uni-app开发微信公众号H5授权获取code并登录

微信公众号是微信生态系统中重要的组成部分,各类官网中也经常会看到H5页面进行微信授权登录等操作。

本篇文章就来介绍在uni-app开发中如何通过url自动授权获取code进行微信登录。

一、微信授权登录封装方法

wxAuthorize(appid) {
let _this = this
// 在微信公众号中定义的回调地址url
let local = '';
let code = (this.getUrlCode()).code; // 截取url上携带的code
// 获取之前的code
let oldCode = uni.getStorageSync('wechatCode')
//判断是否存在code,不存在或者过期将重新授权
if (code == null || code === '' || code == 'undefined' || code == oldCode) {
//转码
let uri = encodeURIComponent(local)
// 设置旧的code为0,避免死循环
uni.setStorageSync('wechatCode',0)
window.location.href =
`https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${uri}&response_type=code&scope=snsapi_base&state=123#wechat_redirect`
} else {
console.log('存在code,使用code换取用户信息')
// 保存最新code
uni.setStorageSync('wechatCode',code)
//在这里写使用获取到code,进行后续操作,如登录
}
}

二、获取url携带参数封装方法

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;
}

通过调用wxAuthorize()封装方法,即可实现微信公众号H5授权获取code并进行登录微信操作。

六月初字帖坊小程序 你想要的字帖模板及工具,这里都有!