- 安装必要的第三方包
$ composer require overtrue/wechat:~5.0 -vvv
2.修改config/auth.php
中的 providers
'providers' => [
'users' => [
'driver' => 'eloquent',
'model' => App\Models\Member\Members::class,
// 这个根据项目设置, 我这里的用户表用的是member所以这里的模型需要换成对应的Members类
],
// 'users' => [
// 'driver' => 'database',
// 'table' => 'users',
// ],
],
- 在控制器中添加用户验证方法
public function officialAccounts(Request $request)
{
// 已登录
if (Auth::check()) {
return redirect(route('user'));
}
$config = [
'app_id' => Configs::where('key', 'APP_ID')->value('value'),
'secret' => Configs::where('key', 'SECRET')->value('value'),
'response_type' => 'array',
'oauth' => [
'scopes' => ['snsapi_base'],
// 静默获取 snsapi_base 点击按钮用户信息 snsapi_userinfo
'callback' => route('auth.official_account_to_notify'),
],
];
$app = Factory::officialAccount($config);
$oauth = $app->oauth;
return $oauth->redirect();
}
- 在控制器中写入回调方法
public function officialAccountToNotify(Request $request)
{
$config = [
'app_id' => Configs::where('key', 'APP_ID')->value('value'),
'secret' => Configs::where('key', 'SECRET')->value('value'),
'response_type' => 'array',
];
$app = Factory::officialAccount($config);
$user = $app->oauth->user()->toArray();
$openid = $user['original']['openid'];
// 拿到静默获取的openid, 静默获取只能获取openid 点击按钮可以获取详细信息
$user = $app->user->get($openid);
// 通过openid获取用户信息, 若是显性按钮获取可省略这一步
$user = Members::UpdateOrCreate(['openid' => $openid], [
'openid' => $openid,
'nickname' => $user['nickname'],
// 'gender' => $user['gender'],
// 'city' => $user['city'], // 'Wenzhou',
// 'province' => $user['province'], // 'Zhejiang',
// 'country' => $user['country'], // 'China',
'avatar' => $user['headimgurl'],
// 'subscribe_time' => $user['subscribe_time'],
'mobile' => '--',
'login_time' => date('Y-m-d H:i:s'),
]);
\Auth::login($user);
return redirect(route('member'));
}
5.在路由文件中添加对应路由
Router::get('/wechat/official_accounts', 'WechatController@officialAccounts');
Router::any('/wechat/official_account_to_notify', 'WechatController@officialAccountToNotify')
->name('auth.official_account_to_notify');