get-weixin-code.html 3.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>微信登录</title>
  6. </head>
  7. <body>
  8. <script>
  9. var GWC = {
  10. version: '1.1.1',
  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['appid'];
  53. var scope = GWC.urlParams['scope'] || 'snsapi_base';
  54. var state = GWC.urlParams['state'];
  55. var isMp = GWC.urlParams['isMp']; //isMp为true时使用开放平台作授权登录,false为网页扫码登录
  56. var baseUrl;
  57. var redirectUri;
  58. if (!code) {
  59. baseUrl = "https://open.weixin.qq.com/connect/oauth2/authorize#wechat_redirect";
  60. if (scope == 'snsapi_login' && !isMp) {
  61. baseUrl = "https://open.weixin.qq.com/connect/qrconnect";
  62. }
  63. //第一步,没有拿到code,跳转至微信授权页面获取code
  64. redirectUri = GWC.appendParams(baseUrl, {
  65. 'appid': appId,
  66. 'redirect_uri': encodeURIComponent(location.href),
  67. 'response_type': 'code',
  68. 'scope': scope,
  69. 'state': state,
  70. });
  71. } else {
  72. //第二步,从微信授权页面跳转回来,已经获取到了code,再次跳转到实际所需页面
  73. redirectUri = GWC.appendParams(GWC.urlParams['redirect_uri'], {
  74. 'code': code,
  75. 'state': state
  76. });
  77. }
  78. location.href = redirectUri;
  79. }
  80. };
  81. GWC.getUrlParams();
  82. GWC.doRedirect();
  83. </script>
  84. </body>
  85. </html>