微信公众号H5用户授权
其实不是很难,总结起来就是:
1.微信公众号管理后台设置redirect_uri。
2.然后发起一个请求去重定向获取code,然后把获取到code之后重定向的URL放在获取code的URL中
3.获取到code之后就可以获取到openid一些之类的信息了
上代码:
const express = require('express') const router = express.Router() router.get('/oauth2/snsapi_base', function (req, res, next) { const redirectUrl = 'beta.weixin.douanquan.com/weixin/oauth2/snsapi_base_cb?sourceurl=' + encodeURIComponent((req.query.sourceurl || '/personal')) console.log("mmm----------", redirectUrl) console.log('/oauth2/snsapi_base', hospitalId, redirectUrl) res.redirect('https://open.weixin.qq.com/connect/oauth2/authorize?' + 'appid=' + "wxf1a4bbd24d59f858" + '&redirect_uri=' + encodeURIComponent(redirectUrl) + '&response_type=code' + '&scope=snsapi_base' + '&state=' + hospitalId + '#wechat_redirect' ) }) router.get('/oauth2/snsapi_base_cb', async function (req, res, next) { const hospitalId = req.session.hospitalId const wxConfig = config.wxAppidList[hospitalId] res.cookie("qqq","jjj") console.log('/oauth2/snsapi_base_cb', hospitalId, req.query.code, wxConfig) const { data } = await axios.get('https://api.weixin.qq.com/sns/oauth2/access_token', { params: { appid: wxConfig.appId, secret: wxConfig.appSecret, code: req.query.code, grant_type: 'authorization_code' } }) res.cookie('openid', data.openid) })
这种是静默授权的方式,换成弹框的把scope改成snsapi_userinfo