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 4 ways to add users to groups in Linux

Preface Linux groups are organizational units use...

Vue + element dynamic multiple headers and dynamic slots

Table of contents 1. Demand 2. Effect 3. All code...

Vue defines private filters and basic usage

The methods and concepts of private filters and g...

CentOS8 installation tutorial of jdk8 / java8 (recommended)

Preface At first, I wanted to use wget to downloa...

Complete steps to install mysql5.7 on Mac (with pictures and text)

I recently used a Mac system and was preparing to...

WeChat Mini Program to Implement Electronic Signature

This article shares the specific code for impleme...

Some questions about hyperlinks

<br />I am very happy to participate in this...

Docker Machine in-depth explanation

Differences between Docker and Docker Machine Doc...

The process of deploying a project to another host using Jenkins

environment Hostname ip address Serve Jenkins 192...

Summary of Vue 3 custom directive development

What is a directive? Both Angular and Vue have th...

Vue shopping cart case study

Table of contents 1. Shopping cart example 2. Cod...

Three Ways to Find the Longest Word in a String in JavaScript (Recommended)

This article is based on the Free Code Camp Basic...

How to modify the firewall on a Linux server to allow remote access to the port

1. Problem Description For security reasons, the ...