const req = require("./request.js"); const api = require('./api.js'); const utils = require('./util.js'); // 微信公众号授权 export function wxAuthorize(parentId, merchantId,scopeType) { // 非静默授权,第一次有弹框 let local = window.location.href; // 获取页面url let appid = req.public.weixinGzAppid // 公众号appid let code = getUrlCode().code; // 截取code // 获取之前的code let oldCode = uni.getStorageSync('wechatCode') console.log('$$$$$$$$$$$$$$$$$wxAuthorize', local); //判断是否存在code,不存在或者过期将重新授权 if (code == null || code === '' || code == 'undefined' || code == oldCode) { // 如果没有code,就去请求获取code console.log('$$$$$$$$$$$$$$$当前没有code,进入授权页面') //转码 let uri = encodeURIComponent(local) // 设置旧的code为0,避免死循环 uni.setStorageSync('wechatCode', 0) // snsapi_base 静默 snsapi_userinfo 非静默 window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=${scopeType}&state=1&connect_redirect=1#wechat_redirect` } else { console.log('$$$$$$$$$$$$$$$$$$存在code,使用code换取用户信息,code====', code); // 保存最新code uni.setStorageSync('wechatCode', code); getWechatLogin(code, parentId, merchantId); // uni.request({ // method: 'GET', // url: this.userUrl + '/sys/getOpenId', // 你的接口地址 // data: { // code: code // }, // success: res => { // console.log(res) // //根据后端返回的结果和需求自行修改,这里直接讲openid本地存储了 // uni.setStorageSync('OPEN_ID', res.data.openid) //正式 // }, // fail: (err) => { // window.alert('请求失败') // console.log(err) // } // }); } } function getWechatLogin(code, parentId, merchantId) { console.log('code>>>' + code + '//parentId>>>>>' + parentId + '//merchantId>>>' + merchantId); req.postRequest(api.wechat_loginV2, { code: code, parentId: parentId ? parentId : '', merchantId: merchantId ? merchantId : '' }, data => { if (data.token){ req.setStorage('AUTH_TOKEN', data.token); } req.setStorage('userInfo', data); }); } function getUrlCode() { // 截取url中的code方法 var url = location.search; // this.winUrl = url; var theRequest = new Object(); if (url.indexOf('?') != -1) { var str = url.substr(1); var strs = str.split('&'); for (var i = 0; i < strs.length; i++) { theRequest[strs[i].split('=')[0]] = strs[i].split('=')[1]; } } return theRequest; }