亲宝软件园·资讯

展开

小程序 Token生成与验证

红尘炼炼心 人气:0

流程

每次请求接口携带token,进行验证
1.验证成功则返回接口数据
2.验证失败(token过期),小程序重新请求生成新的token,然后请求之前的接口

key值: 随机数+时间戳+盐
value值: id+session_key+openid

演示

小程序端

<view>
  <button bindtap="loadToeknData">携带token请求数据</button>
</view>
Page({
  data: {
  },
 
  onLoad:function(){
    // this._loadData();
  },
 
  //生成token
  setToken:function(callback){
    // wx.setStorageSync('token', "sfspx64w8x47w14x3zX4x4wf4")
    var that = this;
    wx.request({
      url: 'http://2021xcx-api.com/api/gettoken',
      method: 'POST',
      success: function(res){
        console.log(res.data);
        var data = res.data;
        if(data.code==1){
          //更新新获取的token值
          wx.setStorageSync('token', data.token);
          // 执行回调函数
          callback&&callback()
        }else{
          that.setToken();
        }
      }
    })
  },
 loadToeknData:function(){
   var that = this;
    wx.request({
      url: 'http://2021xcx-api.com/api/orders',
      method: 'POST',
      header: {
        'content-type': 'application/json',
        'token': wx.getStorageSync('token')
      },
      success: function(res){
        var data = res.data;
        console.log(data)
        if(data.code==903){
          // token过期,重新请求设置
          // 携带回调函数,token重新获取后继续执行此方法。
          that.setToken(that.loadToeknData)
        }
      }
    })
  },
})

  

后端接口

路由配置

<?php
Route::post("api/orders", "api/index/getOrders");
// Token
Route::post("api/gettoken", "api/token/createToken");

Index.php

<?php
namespace app\api\controller;
use app\api\controller\Token;
use think\Cache;
 
class Index extends Token
{
    public function getOrders(Token $token){
        $token->verifyToken();
 
        $data['orders'] = [
            'id' => 1,
            'title' => 'apple',
            'time' => time()
        ];
        echo json_encode($data);
 
    }
}

Token.php

<?php
namespace app\api\controller;
use think\Controller;
 
class Token extends Controller
{
    protected $returnParam = [
        'code' => 1,
        'msg' => '请求失败'
    ];
 
    /**
     * [verifyToken 验证Token是否携带并存在]
     * @return [type] [description]
     */
    public function verifyToken(){
        $token = request()->header()['token'];
        $isSetToken = cache($token);
        // dump($isSetToken);die;
        if(!$isSetToken){
            $this->returnParam['code'] = 903;
            $this->returnParam['msg'] = "Token验证失败";
            echo json_encode( $this->returnParam );die;
        }
    }
    
    /**
     * [createToken Token生成]
     * tip:token中记录用户ID/session_kye/openid
     * @return [type] [description]
     */
    public function createToken()
    {
        $randStr = rand(1,9999);
        $time = time();
        $sale = "xixi2021";
 
        // * 此处模拟--未请求微信接口进行sessionkey及openid的获取
        $tokenValue = [
            'uid' => 1,
            'session_key' => '84848aasa',
            'openid' => '20oxl65wc4d4s5x7hwc',
            'code' => 'sssaaeee'
        ];
        $tokenKey = md5($randStr.$time.$sale);
        //缓存存储token数据
        cache($tokenKey, json_encode($tokenValue), 1);
 
        $returnParam = [
            'code' => 1,
            'token' => $tokenKey
        ];
        echo json_encode($returnParam);
    }
   
}

加载全部内容

相关教程
猜你喜欢
用户评论