Skip to content

Commit 9e9cc01

Browse files
committed
扫一扫登录
1 parent 5ac569e commit 9e9cc01

File tree

4 files changed

+154
-1
lines changed

4 files changed

+154
-1
lines changed

CNAME

Lines changed: 0 additions & 1 deletion
This file was deleted.

README.md

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,5 +19,8 @@
1919
* [nvm安装node](./Node/nvm安装node.md)
2020
# python
2121
* [python控制台输出颜色字体](./python控制台输出颜色.md)
22+
# webChat
23+
24+
* [扫一扫登录](./webChat/扫一扫登录.md)
2225

2326

webChat/扫一扫登录.md

Lines changed: 151 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,151 @@
1+
个人网站是无法接入微信扫一扫登录的,只能使用曲线救国的方式,采用小程序了,小程序是可以获取到微信用户的 `UnionID` 的。
2+
3+
首先第一步要注册一个小程序应用,很简单的,用邮箱申请即可,[点击注册](https://mp.weixin.qq.com/wxopen/waregister?action=step1)
4+
5+
注册完成之后就可以进行开发了,我后台服务使用的是node来写的
6+
7+
8+
9+
# 生成小程序二维码
10+
11+
要做扫一扫登录,二维码是不可少的,官方也提供了几种生成二维码的方式。[查看生成方式](https://developers.weixin.qq.com/miniprogram/dev/framework/open-ability/qr-code.html)
12+
13+
我使用的是[A接口](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/qr-code/wxacode.get.html),详细信息可查看官方文档。
14+
15+
16+
17+
```
18+
POST https://api.weixin.qq.com/wxa/getwxacode?access_token=ACCESS_TOKEN
19+
```
20+
21+
从api上可以看出,调用这个接口需要传入成一个 `ACCESS_TOKEN` ,这个不是我们生成的,需要调用小程序的服务来获取到。
22+
23+
[ACCESS_TOKEN](https://developers.weixin.qq.com/miniprogram/dev/api-backend/open-api/access-token/auth.getAccessToken.html)
24+
25+
获取 `ACCESS_TOKEN` 示例
26+
27+
28+
29+
``` JavaScript
30+
const getWebChatAccessToken = () => {
31+
return new Promise((resolve, reject) => {
32+
let url = `https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=${appId}&secret=${secretKey}`
33+
axios.get(url).then(res => {
34+
resolve(res.data)
35+
}).catch(e => {
36+
errorlog.error(e)
37+
resolve(Common.unifyResponse("获取微信token失败", 500))
38+
})
39+
}
40+
})
41+
}
42+
```
43+
>token过期的时间是由微信服务控制的,拿到之后可以存到redis中,不需要每次都去获取新的
44+
45+
获取到token之后就可以调用生成二维码的方法了
46+
47+
调用示例
48+
```javascript
49+
const getQRCode = (access_token) => {
50+
return new Promise((resolve, reject) => {
51+
let fileName = Common.randomNumber()
52+
let url = `https://api.weixin.qq.com/cgi-bin/wxaapp/createwxaqrcode?access_token=${access_token}`
53+
axios.request({
54+
method: 'post',
55+
responseType: 'arraybuffer',
56+
url,
57+
data: {
58+
path: 'pages/login/login?clientId='+fileName
59+
}
60+
}).then(res => {
61+
fs.writeFile(Common.config("qrCode") + fileName + ".jpeg", res.data, "binary", function (err) {
62+
resolve(fileName)
63+
});
64+
}).catch(e => {
65+
errorlog.error(e)
66+
resolve(Common.unifyResponse("获取二维码失败", 500))
67+
})
68+
})
69+
}
70+
```
71+
返回的是二维码的文件名称
72+
73+
74+
```javascript
75+
LoginRouter.post("/qrlogin/:clientId", (req, res) => {
76+
let userId = req["userId"];
77+
let clientId = req.params.clientId
78+
let token = makeToken(userId);
79+
axios.post(apiConfig.socketUrl, {
80+
clientId,
81+
message: token
82+
})
83+
res.send(true)
84+
85+
})
86+
```
87+
处理登录请求,在小程序完成授权之后,调用`webSocket`服务通知页面授权成功,跳转到首页
88+
# 页面显示二维码
89+
```javascript
90+
$.ajax({
91+
url: api,
92+
type: 'get',
93+
success: function (data) {
94+
$('#qrcode').attr("src","/"+data + ".jpeg")
95+
webSocketConnect(data)
96+
97+
}
98+
})
99+
100+
function webSocketConnect(clientId) {
101+
if ('WebSocket' in window) {
102+
ws = new WebSocket(SOCKET_URL + clientId);
103+
} else if ('MozWebSocket' in window) {
104+
ws = new WebSocket(SOCKET_URL + clientId);
105+
} else {
106+
alert("该浏览器不支持websocket");
107+
}
108+
ws.onmessage = function (evt) {
109+
localStorage.setItem("accessToken", evt.data)
110+
window.location.href = 'me.html'
111+
112+
};
113+
}
114+
115+
```
116+
117+
登录页面调用服务器端生成二维码并显示在页面上,并且连接`webSocket`服务,等待服务器确认登录。
118+
# 小程序
119+
120+
login.js
121+
```javascript
122+
Page({
123+
onLoad: function (options) {
124+
const scene = decodeURIComponent(options.clientId);
125+
wx.setStorage({
126+
key: "clientId",
127+
data: scene
128+
})
129+
},
130+
login: async function (e) {
131+
let result = await util.getLoginInfo()
132+
if (result) {
133+
let clientId = wx.getStorageSync('clientId')
134+
await util.httpRequest({
135+
method: 'post',
136+
url: 'api/wx/qrlogin/' + clientId
137+
})
138+
wx.switchTab({
139+
url: '../index/index'
140+
})
141+
}
142+
}
143+
})
144+
```
145+
login.wxml
146+
```html
147+
<button open-type="getUserInfo" bindgetuserinfo="login">授权登录</button>
148+
```
149+
[github](https://github.com/lizeze/express-leancloud)
150+
151+
[体验地址](http://xx996.cn/jzb/index.html)

webchat.jpg

99.1 KB
Loading

0 commit comments

Comments
 (0)