- 安裝必要的第三方包
$ composer require tymon/jwt-auth
$ composer require overtrue/wechat:~5.0 -vvv
注意: 第一次安裝jwt包后需要執(zhí)行
$ php artisan jwt:secret
- 在控制器中添加用戶驗(yàn)證方法
public function auth(Request $request)
{
$code = $request->get('code');
$rawData = $request->get('rawData');
$config = Configs::first()->toArray();
$config = [
'app_id' => $config['app_id'] ?? env('WECHAT_APP_ID'), // 這里需要自行修改
'secret' => $config['secret'] ?? env('WECHAT_APP_SECRET'), // 這里需要自行修改
];
$app = Factory::miniProgram($config);
$data = $app->auth->session($code);
//判斷code是否過(guò)期
if (isset($data['errcode'])) {
return ['code' => 404, 'massage' => 'code已過(guò)期或不正確'];
}
$weappOpenid = $data['openid'];
$weixinSessionKey = $data['session_key'];
$wechat = json_decode($rawData, true);
$user = Members::UpdateOrCreate(['openid' => $weappOpenid], [
'openid' => $weappOpenid,
'nickname' => $wechat['nickName'],
// 'gender' => $wechat['gender'],
// 'city' => $wechat['city'], // 'Wenzhou',
// 'province' => $wechat['province'], // 'Zhejiang',
// 'country' => $wechat['country'], // 'China',
'avatar' => $wechat['avatarUrl'],
'session_key' => $weixinSessionKey,
'mobile' => $wechat['mobile'] ?? '--',
'created_at' => date('Y-m-d H:i:s'),
'updated_at' => date('Y-m-d H:i:s'),
]);
$customClaims = ['sub' => ["openid" => $user->openid, 'session_key' => $user->session_key]];
$payload = JWTFactory::customClaims($customClaims)->make();
if (!$token = JWTAuth::encode($payload)->get()) {
return ['code' => 401, 'massage' => 'Unauthorized'];
}
// $ttl = $request->out_time ?? config('jwt.ttl'); # 設(shè)置token 過(guò)期時(shí)間
// if (!$token = Auth::guard('api')->setTTL($ttl)->tokenById($user->id)) {
// return ['code' => 500, 'massage' => 'token 過(guò)期'];
// }
// return apiJson($this->respondWithToken($token));
return ['code' => 200, 'token' => $token];
}
- 添加創(chuàng)建中間件
CheckMemberToken
$ php artisan make:middleware CheckMemberToken
4.在創(chuàng)建的中間件中完善handle代碼
public function handle($request, Closure $next)
{
try {
$token = JWTAuth::getToken();
if (empty($token)) {
return response()->json(['status_code' => 40 1, 'message' => '未登錄']);
}
$user_info = JWTAuth::setToken($token)->getPayload()->get('sub');
if ($user_info) {
$user = Members::where('openid', $user_info->openid)->first();
if (!$user) {
response()->json(['status_code' => 402, 'message' => '用戶異常']);
}
//如果想向控制器里傳入用戶信息肠虽,將數(shù)據(jù)添加到$request里面
$request->attributes->add(['memberId' => $user->id]); //添加參數(shù)
}
//其他地方獲取用戶值
// var_dump($request->attributes->get('memberId'));exit();
return $next($request);
} catch (TokenExpiredException $e) {
try {
$token = JWTAuth::refresh();
if ($token) {
return response()->json(['status_code' => 403, 'message' => '新token', 'token' => $token]);
}
} catch (JWTException $e) {
return response()->json(['status_code' => 404, 'message' => 'token無(wú)效', 'token' => '']);
}
}
}
- 在
App\Http\Kernel
中注冊(cè)中間件路由
protected $routeMiddleware = [
'auth' => \App\Http\Middleware\Authenticate::class,
'auth.basic' => \Illuminate\Auth\Middleware\AuthenticateWithBasicAuth::class,
'bindings' => \Illuminate\Routing\Middleware\SubstituteBindings::class,
'cache.headers' => \Illuminate\Http\Middleware\SetCacheHeaders::class,
'can' => \Illuminate\Auth\Middleware\Authorize::class,
'guest' => \App\Http\Middleware\RedirectIfAuthenticated::class,
'password.confirm' => \Illuminate\Auth\Middleware\RequirePassword::class,
'signed' => \Illuminate\Routing\Middleware\ValidateSignature::class,
'throttle' => \Illuminate\Routing\Middleware\ThrottleRequests::class,
'verified' => \Illuminate\Auth\Middleware\EnsureEmailIsVerified::class,
'wechat.auth' => \Overtrue\LaravelWeChat\Middleware\OAuthAuthenticate::class,
// 添加這一行
'jwt.user' => \App\Http\Middleware\CheckMemberToken::class
];
6.設(shè)置路由
// 授權(quán)登錄
Route::any('wechat/auth', 'WechatController@auth');
Route::group([
'middleware' => 'jwt.user',
'prefix' => 'orders',
], function (Router $router) {
// 創(chuàng)建訂單
$router->post('create', 'OrderController@create');
// 核銷訂單
$router->post('verification/{id}', 'OrderController@verification');
// 訂單詳情頁(yè)
$router->get('{id}/detail', 'OrderController@orderDetail');
// 確認(rèn)訂單頁(yè)
$router->get('confirm_order', 'OrderController@confirmOrder');
// 訂單支付
$router->any('pay', 'OrderController@payOrder');
});
- 小程序端測(cè)試代碼
// 微信授權(quán)登陸
wx.login({
success:function (res){
var code = res.code;
wx.request({
url: 'http://fiveyears.cc/wechat/auth',
header: {
'content-type': 'application/json'
},
data: {
code: code,
rawData: rawData
},
success(res) {
console.log(res)
}
})
var token = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJodHRwOlwvXC9maXZlLmdhb3lhbmFuLnRvcFwvd2VjaGF0XC9hdXRoIiwiaWF0IjoxNjEzNzI0ODA2LCJleHAiOjE2MTM3Mjg0MDYsIm5iZiI6MTYxMzcyNDgwNiwianRpIjoic3haaUV4Y1Bhb0pIa29VUiIsInN1YiI6eyJvcGVuaWQiOiJvVnZLVjVEN1hvRFFlM2c3M2V2Yk5kczJka05ZIiwic2Vzc2lvbl9rZXkiOm51bGx9fQ.y5PrJH1lPHCSNy7EqKGM6qhMRcdqeaBqu8JGIhMf07k';
wx.request({
url: 'http://fiveyears.cc/orders/create',
header: {
'content-type': 'application/json'
},
data: {
token: token,
id: 1,
type: 1,
},
method: 'post',
success(res) {
console.log(res)
console.log(res.data)
console.log(res.data.data.timestamp)
// 微信支付
// wx.requestPayment({
// 'timeStamp':res.data.data.timestamp,//
// 'nonceStr': res.data.data.nonceStr,
// 'package': res.data.data.package,
// 'signType': 'MD5',
// 'paySign': res.data.data.paySign,
// 'success':function(res){
// console.log(res);
// },
// 'fail':function(res){
// console.log('fail:'+JSON.stringify(res));
// }
// })
}
})
}
})