laravel6 微信公众号获取用户信息
发表时间:2020-10-18
发布人:葵宇科技
浏览次数:50
创建控制器
php artisan make:controller WeChatController
获取code和token
public function wxcode()
{
//一定要按照参数的顺序进行排列,否则接口将无法访问
$params = http_build_query([
'appid' => '微信公众号的appid',
'redirect_uri' => '自己的域名/wxtoken',
'response_type' => 'code',
'scope' => 'snsapi_userinfo'
]);
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?'.$params .'#wechat_redirect';
return redirect($url);
}
public function wxtoken(Request $request)
{
$code = $request->input('code');
$params = http_build_query([
'appid' => '微信公众号的appid',
'secret'=> '微信公众号的appsecret',
'code' => $code,
'grant_type' => 'authorization_code'
]);
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?'.$params;
$result = json_decode(file_get_contents($url));
// dd($result);
$params = http_build_query([
'access_token' => $result->access_token,
'openid' => $result->openid,
'lang' => 'zh_CN',
]);
$url = 'https://api.weixin.qq.com/sns/userinfo?'.$params;
$UserInfo = json_decode(file_get_contents($url));
dd($UserInfo);
}
配置路由
Route::get('wxcode','WeChatController@wxcode');
Route::get('wxtoken','WeChatController@wxtoken');
在微信开发者工具上访问 域名/wxcode 就可以获取到用户信息了
微信测试号地址
http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index