Laravel8 Token验证

composer require firebase/php-jwt
<?php
namespace App\Service;
use Firebase\JWT\JWT;

class Token
{
    protected $key;
    public function __construct()
    {
        $this->key = 'lizichen';
    }
    /**
     * 生成token
     */
    public function createToken($uid)
    {
        $time = time();
        $payload = array(
            "iss" => "",
            "aud" => "",
            "iat" => $time,
            "nbf" => $time,
            "exp" => $time+7200,
            "uid" => $uid
        );

        $token = JWT::encode($payload,$this->key);

        return $token;
    }

    /**
     * 验证token
     */
    public function validateToken($token)
    {
        try {
            $decoded = JWT::decode($token, $this->key, array('HS256'));
            return $decoded->uid;
        }catch (\Exception $e){
            return 'token过期';
        }
    }
}

   

<?php
namespace App\Http\Middleware;
use App\Service\Token;
use Closure;
use Illuminate\Http\Request;

class JwtToken
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle(Request $request, Closure $next)
    {
        $token = $request->header('token');
        if(empty($token)){
            return response()->json(['code'=>40001,'msg'=>'请先登录','data'=>'']);
        }
        $res = (new Token())->validateToken($token);
        if(!is_numeric($res)){
            return response()->json(['code'=>40002,'msg'=>$res,'data'=>'']);
        }
        $request['uid'] = $res;
        return $next($request);
    }
}
<?php


namespace App\Service;


class Curl
{
    public static function getCurl($url)
    {
        $headerArray =array("Content-type:application/json;","Accept:application/json");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch,CURLOPT_HTTPHEADER,$headerArray);
        $output = curl_exec($ch);
        curl_close($ch);
        $output = json_decode($output,true);
        return $output;
    }

}
<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Models\Admin\Userdo;
use App\Service\Phone;
use App\Service\Token;
use Illuminate\Http\Request;
use App\Service\Curl;
use Illuminate\Support\Facades\Cache;

class LoginController extends Controller
{
    //微信小程序登录
    public function wxLogin(Request $request)
    {
        $params = $request->post();
        $captcha = Cache::get($params['phone'].'_code');
        if ($captcha != $params['code1']){
            Cache::get($params['phone'].'_code',null);
            return ['code'=>403,'msg'=>'验证码错误','data'=>[]];
        }else{
            $stdData = array();
            //获取code码
            $code = $request->get('code');
            //获取微信授权url
            $url = sprintf(config('wx.wxLoginUrl'),config('wx.AppID'),config('wx.AppSecret'),$code);
            //获取openid
            $data = Curl::getCurl($url);
            //查询数据表中是否有数据  若没有 则新增
            $user = Userdo::where('openid',$data['openid'])->first();
            //若表中没有数据则添加openid进数据库
            if(empty($user)){
                $user = Userdo::create(['openid'=>$data['openid'],'session_key'=>$data['session_key'],'phone'=>$params['phone']]);
            }
            //生成token
            $token = (new Token())->createToken($user->uid);
            $stdData = [
                'code' => 200,
                'msg' => '操作成功',
                'token' => $token
            ];
            return json_encode($stdData);
        }
    }

    //微信发送验证码
    public function sendCode(Request $request)
    {
        $phone = $request->get('phone');
        if(empty($phone)){
            return ['code'=>10001, 'msg' => '手机号不能为空', 'data'=> []];
        }
        $cache = Cache::get($phone.date("Y:m:d"));
        if($cache > 5){
            return ['code' => 10003, 'msg' => '每天只能发送五条短信', 'data' => []];
        }
        $captcha = (new Phone())->sendSms($phone);
        Cache::put($phone,$captcha,60*15);
        $num = $cache + 1;
        Cache::put($phone.date("Y:m:d"),$num,60*60*24);
        return ['code' => 200, 'msg' => '短信发送成功', 'data' => $captcha];
    }
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值