1.首先公众号进行配置,必须要https域名
还有个txt文件,有弹框提示需要下载放在服务器上
前端处理code的代码封装
// 微信公众号授权
export function wxAuthorize(calback) {// 非静默授权,第一次有弹框 这里的回调页面就是放在服务器上微信会跳转回来反值如openid的页面let redirect_uri =config.redirect_uri || window.location.host; // 重定向地址console.log(redirect_uri, '重定向地址')let appid = config.appid // 公众号appidlet code = getUrlCode().code; // 截取code// 获取之前的codelet oldCode = uni.getStorageSync('wechatCode')if (code == null || code === '' || code == 'undefined' || code == oldCode) {// 如果没有code,就去请求获取codeconsole.log('当前没有code,进入授权页面')let uri = encodeURIComponent(redirect_uri)// 设置旧的code为0,避免死循环uni.setStorageSync('wechatCode', 0)const urll =`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_userinfo&state=State#wechat_redirect`console.log(urll, '------------urll-------------------');window.location.href = urll} else {console.log('存在code,使用code换取用户信息',code)// 保存最新codeuni.setStorageSync('wechatCode', code)wxCallback(`?code=${code}&state=123`).then(res => {// 成功data为tokencalback && calback({success: true,data:res})}).catch((err) => {if(err.code == '9997'){ //code失效重新进入window.location.reload()}else if(err.code == '9999'){ // 手机号未绑定calback && calback(err)}})}
}export 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];}}console.log(theRequest,'spdspdop')return theRequest;
}export function getParams(url) {const searchParams = new URLSearchParams(url.split("?")[1]);const params = {};for (const [key, value] of searchParams.entries()) {params[key] = value;}return params;
}