tp6 加 jwt 实现小程序登录

composer安装jwt

composer require firebase/php-jwt

安装好以后 直接创建一个文件在自己模块下面来调用生成token

写入代码 复制过去改一改命名空间就可以了

 

<?php
namespace app\api\Server;

use Firebase\JWT\JWT;
use Firebase\JWT\Key;


class Token
{

    private  $key = "mini-program-api";

    /**
     * 生成令牌
     * @param $uid
     * @return string
     */
    public static function createToken($uid){
        $payload = [
            'iss' => 'http://example.org',
            'aud' => 'http://example.com',
            'iat' => time(),
            'nbf' => time(),
            'expire' => time() + 86400,
            'uid' => $uid
        ];

        /**
         * IMPORTANT:
         * You must specify supported algorithms for your application. See
         * https://tools.ietf.org/html/draft-ietf-jose-json-web-algorithms-40
         * for a list of spec-compliant algorithms.
         */
        return JWT::encode($payload, (new self())->key, 'HS256');


    }

    /**
     * 验证token
     * @return false|mixed
     */
    public static function verifyToken(){
        try {
            if (!isset($_SERVER["HTTP_AUTHORIZATION"])) {
                return  false;
            }

            $token = $_SERVER["HTTP_AUTHORIZATION"];

            if (is_numeric(strrpos($token,"Bearer"))) {
                $token = trim(str_replace("Bearer"," ",$token));
            }

            if (empty($token)) {
                return  false;
            }
            $decoded = JWT::decode($token, new Key((new self())->key, 'HS256'));

            $decoded = (array)$decoded;
            if (!isset($decoded['uid']) && $decoded['expire'] < time()) {
                return false;
            }
            return $decoded['uid'];
        }catch (\Exception $exception){
            return  false;
        }

    }

}

然后是登录调用获取token

 //小程序登录
    public function login(Request  $request){
        $code=$request->get('code');

        $appid="wx16b33e4050733263";
        $appSecret="3a1ab0ba5e5d2c40159dbf858b67e4bc";
        $url="https://api.weixin.qq.com/sns/jscode2session?appid={$appid}&secret={$appSecret}&js_code={$code}&grant_type=authorization_code";
        $data=file_get_contents($url);
        $data=json_decode($data,true);
        $user = User::where('openid',$data['openid'])->find();

        //如果没有用户进行创建
        if($user){
            $user=User::create(['openid'=>$data['openid']]);
            $uid=$user->id;
        }else{
            $uid=$user->id;
        }
        $token=Token::createToken($uid);

        return json(['code'=>200,'msg'=>'登录成功','token'=>$token]);


    }

找个方法比之前的那个好多简洁

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值