authorize.js 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  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. // 没有code,就重定向到地址https://www.xyyxt.net?ask_type=https://api.xyyxt.net/pages2/order/confirm_pay 去获取code,授权后就会把code带上然后访问域名
  27. // ?fromCart=&code=061F5a1w3aolh03SLe1w3sMsCF4F5a16&state=STATE
  28. getMobileConfig().then((res) => {
  29. if (JSON.parse(res.mobileConfig).gzhSelfLicense) {
  30. getWxConfig().then((res) => {
  31. location.replace(
  32. `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${
  33. res.gzhAppId
  34. }&redirect_uri=${encodeURIComponent(
  35. "https://" + url
  36. )}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
  37. );
  38. });
  39. } else {
  40. url = url.split("//")[1];
  41. location.replace("https://www.xyyxt.net/home/index2?ask_type=" + url);
  42. }
  43. });
  44. }
  45. export function bindCode(code) {
  46. if (!uni.getStorageSync("user_account")) {
  47. return;
  48. }
  49. OfficialLogin({
  50. code,
  51. }).then((res) => {});
  52. }
  53. export function backCode(cb = bindCode) {
  54. let code = getQueryString("code");
  55. if (!code) {
  56. return;
  57. }
  58. cb(code);
  59. }
  60. export function backOpenId(cb) {
  61. let openid = uni.getStorageSync("openid");
  62. if (openid) {
  63. cb && cb(openid);
  64. return;
  65. }
  66. let code = getQueryString("code");
  67. if (!code) {
  68. return;
  69. }
  70. getOpenId({ code }).then((res) => {
  71. uni.setStorageSync("openid", res.openid);
  72. uni.setStorageSync("unionid", res.unionid);
  73. cb && cb(res.openid);
  74. });
  75. }
  76. export function isWechat() {
  77. var ua = window.navigator.userAgent.toLowerCase();
  78. return ua.match(/micromessenger/i) == "micromessenger";
  79. }