请教一个关于微信登录的问题
需求:微信公众号或者微信小程序加入外链页面,访问该页面的时候,使用微信的 openid 进行用户注册(如果 openid 不存在的话),然后进行登录。现在获取微信用户信息,通过 openid 创建用户已经完成,就是进行登录的时候不知道怎么处理,以下是代码:
// 微信外链页面
public function weixin()
{
$appid = $this->weixin_app_id;
$callback = $this->weixin_call_back;
$url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid='.$appid.'&redirect_uri='.$callback.'&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect';
return redirect($url);
}
// 回调页面
public function weixinCallback(Request $request)
{
// http://xxx/login/weixin/callback?code=001Y4lPA0ShYCk2N51MA0xkkPA0Y4lPh&state=STATE
$code = $request->code;
$appid = $this->weixin_app_id;
$secret = $this->weixin_app_secret;
// 获取 access_token
$url = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code';
$ret = json_decode(_curl_get($url));
$access_token = isset($ret->access_token) ? $ret->access_token : '';
$openid = isset($ret->openid) ? $ret->openid : '';
if ( $openid == '' ) return;
// 获取个人信息
$url = 'https://api.weixin.qq.com/sns/userinfo?access_token='.$access_token.'&openid='.$openid.'&lang=zh_CN';
// 获取微信用户信息
$ret = json_decode(_curl_get($url));
$user = User::where('weixin_openid', $openid)->first();
// 没有用户,默认创建一个用户
if (!$user) {
$user = User::create([
'name' => isset($ret->nickname) ? $ret->nickname : '',
'email' => $openid . '@qq.com',
'password' => bcrypt($openid),
'weixin_openid' => $openid,
]);
}
// 本地登录(不知道怎么处理了)
return redirect('/home');
}
用户系统使用的是 Laravel 自带的用户认证功能:
php artisan ui:auth
我希望的是获取微信信息后,怎么实现用户的登录,而不需要通过这个页面输入邮箱、密码进行登录:
我尝试过以下的方式模拟登录,但是貌似都只是当前页面有效而已:
Auth::attempt(['email' => $email, 'password' => $password]);
Auth::loginUsingId($userid, $remember = false);
请问这个问题该如何解决呢?
推荐文章: