authorize.js 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. import { getWxConfig, getMobileConfig, OfficialLogin } from "@/utils/user";
  2. import { getOpenId } from "@/utils/login";
  3. export function getQueryString(name) {
  4. const url = location.search; //获取url中"?"符后的字串
  5. let theRequest = new Object();
  6. if (url.indexOf("?") != -1) {
  7. let str = url.substr(1);
  8. let strs = str.split("&");
  9. for (let i = 0; i < strs.length; i++) {
  10. theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
  11. }
  12. }
  13. if (name) {
  14. return theRequest[name];
  15. }
  16. return theRequest;
  17. }
  18. // 授权
  19. export function authorize(url = window.location.href) {
  20. if (!isWechat()) {
  21. return;
  22. }
  23. if (uni.getStorageSync("openid")) {
  24. return;
  25. }
  26. if (getQueryString("code")) {
  27. return;
  28. }
  29. // 没有code,就重定向到地址https://www.xyyxt.net?ask_type=https://api.xyyxt.net/pages2/order/confirm_pay 去获取code,授权后就会把code带上然后访问域名
  30. // ?fromCart=&code=061F5a1w3aolh03SLe1w3sMsCF4F5a16&state=STATE
  31. getMobileConfig().then((res) => {
  32. if (JSON.parse(res.mobileConfig).gzhSelfLicense) {
  33. getWxConfig().then((res) => {
  34. location.replace(
  35. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
  36. res.gzhAppId
  37. }&redirect_uri=${encodeURIComponent(
  38. "https://" + url
  39. )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  40. );
  41. });
  42. } else {
  43. url = url.split("//")[1];
  44. location.replace("https://www.xyyxt.net/home/index2?ask_type=" + url);
  45. // location.replace("https://www.xyyxt.net/?ask_type=" + url);
  46. }
  47. });
  48. }
  49. export function bindCode(code) {
  50. if (!uni.getStorageSync("seller_account")) {
  51. return;
  52. }
  53. OfficialLogin({
  54. code,
  55. }).then((res) => {});
  56. }
  57. export function backCode(cb = bindCode) {
  58. let code = getQueryString("code");
  59. if (!code) {
  60. return;
  61. }
  62. cb(code);
  63. }
  64. export function backOpenId(cb) {
  65. let openid = uni.getStorageSync("openid");
  66. if (openid) {
  67. cb && cb(openid);
  68. return;
  69. }
  70. let code = getQueryString("code");
  71. if (!code) {
  72. return;
  73. }
  74. getOpenId({ code }).then((res) => {
  75. uni.setStorageSync("openid", res.openid);
  76. uni.setStorageSync("unionid", res.unionid);
  77. cb && cb(res.openid);
  78. });
  79. }
  80. export function isWechat() {
  81. var ua = window.navigator.userAgent.toLowerCase();
  82. return ua.match(/micromessenger/i) == "micromessenger";
  83. }