用sunny-ngrok穿透??梢灾苯釉L問。怎么接收微信服務(wù)器傳來的GET值并判定?是前端VUE3接收再傳到后端解析?還是直接發(fā)到后端,解析后把值傳到前端嗎?
實現(xiàn)微信授權(quán)流程
<?phpnamespace?app\controller;use?think\Controller;use?think\Request; class?WeChat?extends?Controller{????//?設(shè)置?AppID?和?AppSecret????private?$appId?=?'your_app_id';????private?$appSecret?=?'your_app_secret';????????//?獲取?access_token????public?function?getAccessToken()????{????????$url?=?"https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid={$this->appId}&secret={$this->appSecret}";????????$response?=?json_decode(file_get_contents($url),?true);????????return?$response['access_token'];????} ????//?獲取用戶信息????public?function?getUserInfo($accessToken,?$openid)????{????????$url?=?"https://api.weixin.qq.com/cgi-bin/user/info?access_token={$accessToken}&openid={$openid}&lang=zh_CN";????????$response?=?json_decode(file_get_contents($url),?true);????????return?$response;????} ????//?處理微信回調(diào)????public?function?callback(Request?$request)????{????????$accessToken?=?$this->getAccessToken();????????//?獲取微信返回的?`code`?參數(shù)????????$code?=?$request->param('code');????????????????//?使用?`code`?獲取?`openid`?和?`access_token`????????$url?=?"https://api.weixin.qq.com/sns/oauth2/access_token?appid={$this->appId}&secret={$this->appSecret}&code={$code}&grant_type=authorization_code";????????$response?=?json_decode(file_get_contents($url),?true);????????$openid?=?$response['openid']; ????????//?獲取用戶信息????????$userInfo?=?$this->getUserInfo($accessToken,?$openid);????????return?json($userInfo);????}}
前端 Vue 3 配置
export?default?{??data()?{????return?{??????userInfo:?null,????};??},??methods:?{????getUserInfo()?{??????//?跳轉(zhuǎn)到微信授權(quán)頁面??????window.location.href?=?`https://open.weixin.qq.com/connect/oauth2/authorize?appid=your_app_id&redirect_uri=your_redirect_uri&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect`;????},??},??mounted()?{????//?頁面加載后獲取用戶信息????const?code?=?new?URLSearchParams(window.location.search).get('code');????if?(code)?{??????//?調(diào)用后端接口獲取用戶信息??????this.$axios.get(`/wechat/callback?code=${code}`).then(response?=>?{????????this.userInfo?=?response.data;??????});????}??},};
你測試一下
微信掃碼
關(guān)注PHP中文網(wǎng)服務(wù)號
QQ掃碼
加入技術(shù)交流群
Copyright 2014-2025 http://www.400tele.com.cn/ All Rights Reserved | php.cn | 湘ICP備2023035733號