server { listen 80; //監聽的端口號 server_name wxh5.beta.hqjy.com; 本地訪問的域名(host文件也要配置) location /{ proxy_pass http://wxh5.beta.hqjy.com:8080/; 代理的域名加本地項目啟用的端口號->nginx服務會代理本地起的服務從而可以在wx開發者工具上調試,因為你的目的就是為了在工具調試本地的微信授權登錄的流程 } location /sns{ # return 666; proxy_pass https://api.weixin.qq.com;微信公眾號的域名 } # location /api/ { # proxy_pass http://10.0.99.32:8093/; # } }
host文件配置
127.0.0.1 wxh5.beta.hqjy.com
// 微信登陸 goWxLogin() { // TODO const url = encodeURIComponent(location.href.split('#')[0]); //獲取#之前的當前路徑 window.location.href = 'http://open.weixin.qq.com/connect/oauth2/authorize?appid='+this.appid+'&redirect_uri='+url+'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect' }, mounted() { if (this.$route.query.code) { // 獲取code var code = this.$route.query.code // 通過code 獲取access_token&openid this.$axios.get('/sns/oauth2/access_token?appid='+this.appid+'&secret='+this.secret+'&code='+code+'&grant_type=authorization_code').then((res) => { console.log(JSON.parse(JSON.stringify(res)), '通過code 獲取access_token&openid') var res = JSON.parse(JSON.stringify(res)) var access_token = res.data.access_token var openid = res.data.openid var refresh_token = res.data.refresh_token // 刷新access_token this.$axios.get('/sns/oauth2/refresh_token?appid='+this.appid+'&grant_type=refresh_token&refresh_token='+refresh_token).then((res) => { console.log(JSON.parse(JSON.stringify(res)), '刷新token延長失效時間') }) // 獲取unionid this.$axios.get('/sns/userinfo?access_token='+access_token+'&openid='+openid+'&lang=zh_CN').then((res) =>{ console.log(JSON.parse(JSON.stringify(res)), '獲取unionid') var res = JSON.parse(JSON.stringify(res)) // res = decodeURIComponent(encodeURIComponent(res)) //兼容微信昵稱中文亂碼問題 var unionid = res.data.unionid // 拿模數 this.$api.getRsaPublicKey().then(res => { if (res.code === 200) { var modulus = res.data.modulus // 拿模數和獲取微信unionid登陸 const data = { clientType: 'h5', modulus: '', // 模數 unionId: '', versionCode: 1 } if (unionid) { this.$api.getWeChatLogin(data).then(res =>{ if (res.code === 200) { // 登陸成功-設置token到cookie this.$router.push({name:'textualResearch'}) } }) } } }) }) }) } },
記得線上也需要配置nginx代理,不然訪問wx提供的接口肯定會報錯的。
參考網站
https://blog.csdn.net/yuan_life/article/details/91820618
官方文檔
https://developers.weixin.qq.com/doc/offiaccount/OA_Web_Apps/Wechat_webpage_authorization.html
