基于koa框架实现微信公众号扫码登录开发中公众号二维码生成
demo的github地址:https://github.com/xuedingmiaojun/koa-demo.git (opens new window)
# 获取微信全局access_token
tip:需要在公众号管理后台预配置一下IP白名单
获取token
// 获取全局token
router.get('/token', async (ctx, next) => {
try {
let appid = 'wx36963a5a84d5ca4d'
let secret = '98431bcb5cac6b46ef132b6f544a11dd'
let opts = {
url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + appid + '&secret=' + secret
}
let res = await rp(opts)
res = JSON.parse(res)
let token = res.access_token
ctx.data = { token: token }
} catch (e) {
console.log(e)
}
await next()
})
# 获取ticket
创建临时二维码ticket
router.get('/qrcode', async (ctx, next) => {
let token = ctx.req.token
let opts = {
method: 'post',
form: '{"expire_seconds": 604800, "action_name": "QR_STR_SCENE", "action_info": {"scene": {"scene_str": 123 }}}',
uri: 'https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=' + token
}
let res = await rp(opts)
console.log(res)
ctx.data = res
await next()
})
# 换取二维码
通过ticket换取二维码
https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=your ticket