2021-02-19 laravel + EasyWechat + jwt 小程序 授权登录

857次阅读
没有评论
  1. 安装必要的第三方包

$ composer require tymon/jwt-auth
$ composer require overtrue/wechat:~5.0 -vvv

注意: 第一次安装jwt包后需要执行

$ php artisan jwt:secret
  1. 在控制器中添加用户验证方法

    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是否过期
        if (isset($data['errcode'])) {
            return ['code' => 404, 'massage' => 'code已过期或不正确'];
        }
        $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'); # 设置token 过期时间

//        if (!$token = Auth::guard('api')->setTTL($ttl)->tokenById($user->id)) {
//            return ['code' => 500, 'massage' => 'token 过期'];
//        }

//        return apiJson($this->respondWithToken($token));

        return ['code' => 200, 'token' => $token];
    }
  1. 添加创建中间件CheckMemberToken

$ php artisan make:middleware CheckMemberToken

4.在创建的中间件中完善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' => '用户异常']);
                }

                //如果想向控制器里传入用户信息,将数据添加到$request里面
                $request->attributes->add(['memberId' => $user->id]); //添加参数
            }
            //其他地方获取用户值
//            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无效', 'token' => '']);
            }
        }
    }
  1. App\Http\Kernel中注册中间件路由

    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.设置路由

// 授权登录
Route::any('wechat/auth', 'WechatController@auth');

Route::group([
    'middleware' => 'jwt.user',
    'prefix' => 'orders',
], function (Router $router) {
    // 创建订单
    $router->post('create', 'OrderController@create');
    // 核销订单
    $router->post('verification/{id}', 'OrderController@verification');
    // 订单详情页
    $router->get('{id}/detail', 'OrderController@orderDetail');
    // 确认订单页
    $router->get('confirm_order', 'OrderController@confirmOrder');
    // 订单支付
    $router->any('pay', 'OrderController@payOrder');
});
  1. 小程序端测试代码

    // 微信授权登陆
    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));
              //   }
              // })
            }
          })
        
      }
    })

2021-02-19 laravel + EasyWechat + jwt 小程序 授权登录

授权登录成功

2021-02-19 laravel + EasyWechat + jwt 小程序 授权登录

创建订单成功

正文完
可以使用微信扫码关注公众号(ID:xzluomor)
post-qrcode
 
评论(没有评论)