4.5. 登录 API 获取 JWT 令牌:"Undefined variable: token",
学到《登录 API 获取 JWT 令牌》一章,全部按照教程走。
<?php
namespace App\Http\Controllers\Api;
use App\User;
use Illuminate\Support\Arr;
use Illuminate\Http\Request;
use Overtrue\Socialite\AccessToken;
use Illuminate\Auth\AuthenticationException;
use App\Http\Requests\Api\AuthorizationRequest;
use App\Http\Requests\Api\SocialAuthorizationRequest;
class AuthorizationsController extends Controller
{
public function store(AuthorizationRequest $request)
{
$username = $request->username;
filter_var($username, FILTER_VALIDATE_EMAIL) ?
$credentials['email'] = $username :
$credentials['phone'] = $username;
$credentials['password'] = $request->password;
if (!$token = \Auth::guard('api')->attempt($credentials)) {
throw new AuthenticationException('用户名或密码错误');
}
return $this->respondWithToken($token)->setStatusCode(201);
}
public function socialStore($type, SocialAuthorizationRequest $request)
{
$driver = \Socialite::driver($type);
try {
if ($code = $request->code) {
$accessToken = $driver->getAccessToken($code);
} else {
$tokenData['access_token'] = $request->access_token;
// 微信需要增加 openid
if ($type == 'wechat') {
$tokenData['openid'] = $request->openid;
}
$accessToken = new AccessToken($accessData);
}
$oauthUser = $driver->user($accessToken);
} catch (\Exception $e) {
throw new AuthenticationException('参数错误,未获取用户信息');
}
switch ($type) {
case 'wechat':
$unionid = $oauthUser->getOriginal()['unionid'] ?? null;
if ($unionid) {
$user = User::where('weixin_unionid', $unionid)->first();
} else {
$user = User::where('weixin_openid', $oauthUser->getId())->first();
}
// 没有用户,默认创建一个用户
if (!$user) {
$user = User::create([
'name' => $oauthUser->getNickname(),
'avatar' => $oauthUser->getAvatar(),
'weixin_openid' => $oauthUser->getId(),
'weixin_unionid' => $unionid,
]);
}
break;
}
return $this->respondWithToken($token)->setStatusCode(201);
}
protected function respondWithToken($token)
{
return response()->json([
'access_token' => $token,
'token_type' => 'Bearer',
'expires_in' => auth('api')->factory()->getTTL() * 60
]);
}
}
可是第三方登陆,返回的是:”Undefined variable: token”。
"message": "Undefined variable: token",
"exception": "ErrorException",
"file": "/www/wwwroot/qzzz111.net/app/Http/Controllers/Api/AuthorizationsController.php",
"line": 77,
普通登陆,没问题,能返回token。这是为什么?折腾了一天,跪求大神大哥解答
推荐文章: