【uniapp】h5微信公众号授权登录

步骤

  • 前端根据微信提供的 oauth2 地址获取code
  • 调用后端微信登录接口传参:code,返回token(后端可通过code、access_token和微信提供的接口等,完成与系统用户的绑定等操作)
  • 前端获取到token后与其他登录一样,登录完成后完成业务

注意

前端调用微信提供的 oauth2 地址获取code时,所传的参数:redirect_uri (此地址域名必须与微信公众号后台配置的网页授权域名一致)

官方地址:https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html

示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
export default {
data() {
return {
appid: "xxxxxxxxxxxxxxx"
}
},
onLoad() {
this.getWxCode()
},
methods: {
/**
* 获取微信code
*/
getWxCode() {
const code = ""
let local = window.location.href; // 微信授权重定向的 url
code = this.getUrlParams().code
// 如果没有code,则去微信服务器请求
if (!code) {
window.location.href = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${this.appid}&redirect_uri=${encodeURIComponent(local)}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
} else {
this.wxLogin(code)
}
},
/**
* wx登录
*/
wxLogin(code) {
// 已经拿到code,写登录逻辑......
},
/**
* 获取url中的参数
*/
getUrlParams() {
var url = location.search
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
},
}
}