Laravel+easywechat 开放平台 PC 端授权登录相关问题请教
有需求做到PC端微信扫码登录,easywechat官方文档对于开放平台的相关运用比较少(最大的可能是我菜(捂脸))。
参考了多种方式,不是报错就是达不到预期效果。
前期准备:
前端blade模板中引入微信js:
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
并且在js中加入代码以获取微信登录二维码:
$(function () {
getLoginqrcode();
});
function getLoginqrcode() {
var obj = new WxLogin({
id: "放二维码的div标签的id",
appid: "开放平台网站应用app_id",
scope: "snsapi_login",
redirect_uri: "{{ url('回调地址') }}",
response_type:"code",
href: '',
state: "<?php echo time(); ?>"
});
微信开放平台配置:
'open_platform' => [
'default' => [
'app_id' => env('WECHAT_OPEN_PLATFORM_APPID', '开放平台网站应用app_id'),
'secret' => env('WECHAT_OPEN_PLATFORM_SECRET', '开放平台网站应用app_secret'),
'token' => env('WECHAT_OPEN_PLATFORM_TOKEN', ''),
'aes_key' => env('WECHAT_OPEN_PLATFORM_AES_KEY', ''),
],
],
尝试1:
微信网页扫码登录的实现
按照原文的代码:
//通过code获得 access_token + openid
$url="https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $appid
"&secret=" . $secret . "&code=" . $code . "&grant_type=authorization_code";
$jsonResult = file_get_contents($url);
$resultArray = json_decode($jsonResult, true);
$access_token = $resultArray["access_token"];
$openid = $resultArray["openid"];
//通过access_token + openid 获得用户所有信息,结果全部存储在$infoArray里,后面再写自己的代码逻辑
$infoUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token . "&openid=" . $openid;
$infoResult = file_get_contents($infoUrl);
$infoArray = json_decode($infoResult, true);
在打印$infoArray的时候报错:
(1/1) InvalidArgumentException
Action Facade\Ignition\Http\Controllers\ShareReportController not defined.
in UrlGenerator.php line 453 at UrlGenerator->action('Facade\\Ignition\\Http\\Controllers\\ShareReportController', array(), true)
in helpers.php line 103
一个方法不成就换第二种方式,使用easywechat的:
尝试2:
EasyWeChat微信开发平台第三方接入(Laravel5+,EasyWeChat3.0/EasyWeChat4.0)
根据原文中的处理授权事件来处理:
$server->push(function ($event) use($openPlatform){
//获取(刷新)授权公众号或小程序的接口调用凭据(令牌)
$res = $openPlatform->handleAuthorize($event->AuthorizationCode);
$appid2 = $res->authorization_info['authorizer_appid'];
$refresh_token = $res->authorization_info['authorizer_refresh_token'];
//获取授权方的帐号基本信息
$data = $openPlatform->getAuthorizer($appid2);
$account = Account::where('appid', $appid2)->first();
$info2 = $data['authorizer_info'];
$info1 = $data['authorization_info'];
...
}, Guard::EVENT_AUTHORIZED);
在打印$res的时候依然还是报尝试一种的错误!
去掉所有代码,在回调的方法中(例如我的回调方法是test)打印所有的信息:
public functiontest(Request $request){
$data = $request->input();
dump($data);
}
得到的结果为前端传过来的code值和state(此处为时间戳)
到了此处,问题应该清楚了,就是怎么处理回调的问题,怎么获取相关信息的问题。
查看官方文档,得到的答案是code去换取access_token,但是这个问题又回归到了尝试1的问题中。
后续想了很多种办法,也尝试了很多,但是还是达不到尝试1,尝试2以及easywechat中关于开放平台使用的效果,所以在此请教各位如果还要使用easywechat公众号开放平台网站应用的扫码授权登录或者是其他方式,怎么能获取到扫码人的信息。
附相关的包以及版本:
"dingo/api": "^2.3",
"encore/laravel-admin": "^1.7",
"hhxsv5/laravel-s": "^3.5",
"laravel/framework": "^6.2",
"overtrue/laravel-wechat": "^5.0",
推荐文章: