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

1,690次阅读
没有评论
  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
 0
评论(没有评论)

文心AIGC

2023 年 10 月
 1
2345678
9101112131415
16171819202122
23242526272829
3031  
文心AIGC
文心AIGC
人工智能ChatGPT,AIGC指利用人工智能技术来生成内容,其中包括文字、语音、代码、图像、视频、机器人动作等等。被认为是继PGC、UGC之后的新型内容创作方式。AIGC作为元宇宙的新方向,近几年迭代速度呈现指数级爆发,谷歌、Meta、百度等平台型巨头持续布局
文章搜索
热门文章
潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026

潞晨尤洋:日常办公没必要上私有模型,这三类企业才需要 | MEET2026 Jay 2025-12-22 09...
面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25

面向「空天具身智能」,北航团队提出星座规划新基准丨NeurIPS’25 鹭羽 2025-12-13 22:37...
商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1

商汤Seko2.0重磅发布,合作短剧登顶抖音AI短剧榜No.1 十三 2025-12-15 14:13:14 ...
跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026

跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026

跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026 一水 2025-1...
10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了

10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了

10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了 一水 2025-12-12 13:56:19 ...
最新评论
ufabet ufabet มีเกมให้เลือกเล่นมากมาย: เกมเดิมพันหลากหลาย ครบทุกค่ายดัง
tornado crypto mixer tornado crypto mixer Discover the power of privacy with TornadoCash! Learn how this decentralized mixer ensures your transactions remain confidential.
ดูบอลสด ดูบอลสด Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Pretty! This has been a really wonderful post. Many thanks for providing these details.
ดูบอลสด ดูบอลสด Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
Obrazy Sztuka Nowoczesna Obrazy Sztuka Nowoczesna Thank you for this wonderful contribution to the topic. Your ability to explain complex ideas simply is admirable.
ufabet ufabet Hi there to all, for the reason that I am genuinely keen of reading this website’s post to be updated on a regular basis. It carries pleasant stuff.
ufabet ufabet You’re so awesome! I don’t believe I have read a single thing like that before. So great to find someone with some original thoughts on this topic. Really.. thank you for starting this up. This website is something that is needed on the internet, someone with a little originality!
ufabet ufabet Very well presented. Every quote was awesome and thanks for sharing the content. Keep sharing and keep motivating others.
热评文章
跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026

跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026

跳过“逐字生成”!蚂蚁集团赵俊博:扩散模型让我们能直接修改Token | MEET2026 一水 2025-1...
10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了

10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了

10亿美元OpenAI股权兑换迪士尼版权!米老鼠救Sora来了 一水 2025-12-12 13:56:19 ...
IDC MarketScape: 容联云位居“中国AI赋能的联络中心”领导者类别

IDC MarketScape: 容联云位居“中国AI赋能的联络中心”领导者类别

IDC MarketScape: 容联云位居“中国AI赋能的联络中心”领导者类别 量子位的朋友们 2025-1...