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 }) })