const appid = "wx3b0e58d4d2dbea9f"; //公众号后台获取 const redirectUri = encodeURIComponent("http://245691q6b5.zicp.vip")//微信会带code码访问这个连接 const url = `https://open.weixin.qq.com/connect/oauth2/authorize?appid=${appid}&redirect_uri=${redirectUri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`
若是不是每次进入页面都要从微信获取code码时(用户信息),建议在前端获取,须要时才改变浏览器连接让用户访问连接获取受权,把code码传给后端获取用户信息。javascript
const querystring = getQueryString() let code = querystring.code; if(!code){ location.href = url; }else{ https.get('http://127.0.0.1:3000/auth',{code}).then(res => { console.log(res) }) } function getQueryString() { const url = location.search; const rs = {} if(url.indexOf('?') === 0){ const querystring = url.substr(1); const kvArr = querystring.split('&'); kvArr.forEach(item => { const temp = item.split('=') const key = temp[0]; const val = temp[1]; rs[key] = val }) } return rs }
若是每次都要获取code码,就让用户只要进入页面就访问接口连接,但这时的redirectUri要配置成后端接口的连接,也就是说微信会带着code码访问后端接口,后端直接获取code码。前端
//后端使用koa2 //Superagent时一个后端的http请求中间件 router.get('/auth', async (ctx, next) => { code = ctx.querystring.split('&')[0].split('=')[1]; // 使用code获取openid和access_token await Superagent .get(`https://api.weixin.qq.com/sns/oauth2/access_token?appid=${appid}&secret=${appsecret}&code=${code}&grant_type=authorization_code`) .then(res => { let result = JSON.parse(res.text) access_token = result.access_token openid = result.openid }) // 使用ACCESS_TOKEN和openid await Superagent .get(`https://api.weixin.qq.com/sns/userinfo?access_token=${access_token}&openid=${openid}&lang=zh_CN`) .then(res => { //userinfo返回给前端 userinfo = JSON.parse(res.text) ctx.body = res.text }) })