public function oauthCallback(Request $request)
 {
     if ($request->get('state') == session('state')) {
         $auth = new Auth(config('wechat.appid'), config('wechat.secret'));
         $ouser = $auth->user();
         if (!$ouser) {
             abort('微信授权错误 #13101');
         }
         $sa = SocialAccount::where('openid', $ouser->get('openid'))->where('platform', 'wechat')->first();
         if ($sa) {
             \Auth::loginUsingId($ouser->user_id);
         } else {
             \DB::transaction(function () use($ouser, $auth) {
                 $user = User::create(['name' => $ouser->get('nickname', ''), 'username' => $ouser->get('platform') . '_' . $ouser->get('openid', ''), 'avatar' => $ouser->get('headimgurl')]);
                 SocialAccount::create(['user_id' => $user->id, 'access_token' => $auth->access_token, 'refresh_token' => $auth->refresh_token, 'platform' => 'wechat', 'openid' => $ouser->get('openid'), 'user_info' => json_encode($ouser), 'union_id' => $ouser->get('union_id', '')]);
                 \Auth::loginUsingId($user->id);
             });
         }
         return redirect(route('home'));
     } else {
         abort('403', '服务器授权state不正确');
     }
 }
Example #2
0
 /**
  * @return \yii\db\ActiveQuery
  */
 public function getSocialAccounts()
 {
     return $this->hasMany(SocialAccount::className(), ['user_id' => 'id']);
 }