Mini Program to implement Token generation and verification

Mini Program to implement Token generation and verification

process

Each request interface carries a token for verification
1. If verification is successful, the interface data will be returned
2. Verification failed (token expired), the applet re-requests to generate a new token, and then requests the previous interface

key value: random number + timestamp + salt
value: id+session_key+openid

Demo

Mini Program

<view>
  <button bindtap="loadTokenData">Carry token request data</button>
</view>
Page({
  data: {
  },
 
  onLoad:function(){
    // this._loadData();
  },
 
  //Generate 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){
          //Update the newly acquired token value wx.setStorageSync('token', data.token);
          // Execute callback function 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 expires, request to set it again // Carry a callback function and continue to execute this method after token is re-acquired.
          that.setToken(that.loadTokenData)
        }
      }
    })
  },
}) 

Backend interface

Routing Configuration

<?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' => 'Request failed'
    ];
 
    /**
     * [verifyToken verifies whether the Token is carried and exists]
     * @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 verification failed";
            echo json_encode( $this->returnParam );die;
        }
    }
    
    /**
     * [createToken Token generation]
     * tip: record user ID/session_kye/openid in token
     * @return [type] [description]
     */
    public function createToken()
    {
        $randStr = rand(1,9999);
        $time = time();
        $sale = "xixi2021";
 
        // * Simulate here--WeChat interface is not requested to obtain sessionkey and openid $tokenValue = [
            'uid' => 1,
            'session_key' => '84848aasa',
            'openid' => '20oxl65wc4d4s5x7hwc',
            'code' => 'sssaaeee'
        ];
        $tokenKey = md5($randStr.$time.$sale);
        //Cache token data cache($tokenKey, json_encode($tokenValue), 1);
 
        $returnParam = [
            'code' => 1,
            'token' => $tokenKey
        ];
        echo json_encode($returnParam);
    }
   
} 

This is the end of this article about mini program token generation and verification. For more relevant mini program token generation and verification content, please search for previous articles on 123WORDPRESS.COM or continue to browse the following related articles. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • How to handle token expiration in WeChat Mini Programs
  • About WeChat Mini Program crawler token automatic update issue
  • Mini Program Development to Implement Unified Management of Access_Token
  • Tutorial on how to log in to WeChat Mini Program and exchange tokens
  • WeChat applet url and token settings detailed explanation

<<:  About debugging CSS cross-browser style bugs

>>:  Detailed use cases of MySql escape

Recommend

Summary of block-level elements, inline elements, and variable elements

Block element p - paragraph pre - format text tabl...

Sample code for implementing PC resolution adaptation in Vue

Table of contents plan Install Dependencies Intro...

Windows 10 installation vmware14 tutorial diagram

Software Download Download software link: https:/...

A brief discussion on two methods to solve space-evenly compatibility issues

Since its launch in 2009, flex has been supported...

Analysis and solution of MySQL connection throwing Authentication Failed error

[Problem description] On the application side, th...

Detailed examples of ajax usage in js and jQuery

Table of contents Native JS How to send a get req...

Solution to mysql prompt "got timeout reading communication packets"

Error message: user: 'root' host: `localh...

MySQL trigger syntax and application examples

This article uses examples to illustrate the synt...

How to query or obtain images in a private registry

Docker queries or obtains images in a private reg...

SQL uses ROW_NUMBER() OVER function to generate sequence number

Syntax: ROW_NUMBER() OVER(PARTITION BY COLUMN ORD...