官方文档:网页授权 | 微信开放文档
其实实现网页授权只需要走三步:
我这里前端只需要将code码发给后端,剩下步骤由后端来返回用户信息,我这里使用的是非静默授权,只需要将appid和回调的地址写好然后引导用户跳转到此页面即可
scope为snsapi_userinfo:
https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxf0e81c3bee622d60&redirect_uri=http%3A%2F%2Fnba.bluewebgame.com%2Foauth_response.php&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect
<a
class="subbtn"
href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=*****&redirect_uri=****&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"
>开始答题</a>
然后在回调的页面的url里去截取code码
var url = window.location.href;
var newurl = url.split("=")[1];
var code = newurl.split("&")[0];
var res = await axios.post("/api/login/register", {
code: code,
});
补充:
这里上线vue3项目的时候需要修改路由模式,将history修改为hash模式,否则无法正常显示页面
// router/index.js
import { createRouter, createWebHistory,createWebHashHistory } from 'vue-router'
const router = createRouter({
history: createWebHashHistory(process.env.BASE_URL),
routes
})
还有部署到宝塔(apache)后访问后端接口出现问题,需要在配置文件中修改后端接口,修改线上的前端跨域
ProxyPass /api http://127.0.0.1:8021
ProxyPassReverse /api http://127.0.0.1:8021