loginAgent.html 4.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. <!DOCTYPE html>
  2. <html>
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>百度登录</title>
  6. </head>
  7. <body>
  8. <script>
  9. var GWC = {
  10. version: '1.0.0',
  11. urlParams: {},
  12. appendParams: function(url, params) {
  13. if (params) {
  14. var baseWithSearch = url.split('#')[0];
  15. var hash = url.split('#')[1];
  16. for (var key in params) {
  17. var attrValue = params[key];
  18. if (attrValue !== undefined) {
  19. var newParam = key + "=" + attrValue;
  20. if (baseWithSearch.indexOf('?') > 0) {
  21. var oldParamReg = new RegExp('^' + key + '=[-%.!~*\'\(\)\\w]*', 'g');
  22. if (oldParamReg.test(baseWithSearch)) {
  23. baseWithSearch = baseWithSearch.replace(oldParamReg, newParam);
  24. } else {
  25. baseWithSearch += "&" + newParam;
  26. }
  27. } else {
  28. baseWithSearch += "?" + newParam;
  29. }
  30. }
  31. }
  32. if (hash) {
  33. url = baseWithSearch + '#' + hash;
  34. } else {
  35. url = baseWithSearch;
  36. }
  37. }
  38. return url;
  39. },
  40. getUrlParams: function() {
  41. var pairs = location.search.substring(1).split('&');
  42. for (var i = 0; i < pairs.length; i++) {
  43. var pos = pairs[i].indexOf('=');
  44. if (pos === -1) {
  45. continue;
  46. }
  47. GWC.urlParams[pairs[i].substring(0, pos)] = decodeURIComponent(pairs[i].substring(pos + 1));
  48. }
  49. },
  50. doRedirect: function() {
  51. var code = GWC.urlParams['code'];
  52. var appId = GWC.urlParams['client_id'];
  53. var response_type = GWC.urlParams['response_type'];
  54. var redirectUri;
  55. var scope = GWC.urlParams['scope'];
  56. var state = GWC.urlParams['state'];
  57. var display = GWC.urlParams['display'];
  58. var force_login = GWC.urlParams['force_login'];
  59. var confirm_login = GWC.urlParams['confirm_login'];
  60. var login_type = GWC.urlParams['login_type'];
  61. if (!code) {
  62. //第一步,没有拿到code,跳转至授权页面获取code
  63. redirectUri = GWC.appendParams('https://openapi.baidu.com/oauth/2.0/authorize', {
  64. client_id: appId,
  65. response_type: response_type,
  66. redirect_uri: encodeURIComponent(GWC.appendParams(location.href.split('?')[0], {
  67. 'redirect_uri': encodeURIComponent(GWC.urlParams['redirect_uri']),
  68. })),
  69. scope: scope,
  70. state: state,
  71. display: display,
  72. force_login: force_login,
  73. confirm_login: confirm_login,
  74. login_type: login_type
  75. });
  76. } else {
  77. //第二步,从授权页面跳转回来,已经获取到了code,再次跳转到实际所需页面
  78. redirectUri = GWC.appendParams(GWC.urlParams['redirect_uri'], {
  79. code: code,
  80. state: state,
  81. });
  82. }
  83. location.href = redirectUri;
  84. }
  85. };
  86. GWC.getUrlParams();
  87. GWC.doRedirect();
  88. </script>
  89. </body>
  90. </html>