Home Backend Development PHP Tutorial Tips for implementing WeChat applet SMS verification code using PHP

Tips for implementing WeChat applet SMS verification code using PHP

Jun 01, 2023 am 09:42 AM
php WeChat applet SMS verification code

With the popularity of WeChat mini programs, more and more developers are beginning to use WeChat mini programs as a development platform to provide users with a more convenient experience. Among them, SMS verification code is an indispensable part in user registration, login and other scenarios. This article mainly introduces how to use PHP to implement SMS verification codes for WeChat mini programs.

1. Obtain WeChat access_token

Before using WeChat API, you need to obtain access_token first. Access_token is the calling credential for WeChat API. Every time you call WeChat API, access_token needs to be carried in the request header. The specific acquisition method is as follows:

  1. Create a mini program in the WeChat public platform, and then view the appId and appSecret in the mini program development settings.
  2. Send an HTTP GET request based on appId and appSecret to obtain access_token. The specific code is as follows:
$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$secret;
$res = json_decode(file_get_contents($url), true);
$access_token = $res['access_token'];
Copy after login

2. Generate a random verification code

The process of generating a random verification code is very simple, just use PHP's built-in rand function. The specific code is as follows:

$code = rand(1000, 9999);
Copy after login

3. Call the SMS API to send the verification code

After obtaining the access_token and generating a random verification code, you can call the SMS API to send the verification code. Here we take Tencent Cloud SMS as an example, and other SMS service providers are similar.

  1. Create an application in the Tencent Cloud SMS console and obtain the application ID, application key and SMS template ID.
  2. Generate a signature based on the application ID and application key, and generate SMS content based on the SMS template ID and random verification code.
  3. Use Tencent Cloud SMS API to send text messages. The specific code is as follows:
// 生成签名
$timestamp = time();
$sig = md5("appkey=".$appkey."&timestamp=".$timestamp);

// 生成短信内容
$content = "【签名】验证码为:".$code.",有效期5分钟,请勿泄露。如非本人操作,请忽略本短信。";

// 发送短信
$url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=".$sdkappid."&random=".rand();
$data = array(
    "tel" => array("nationcode" => "86", "mobile" => $mobile),
    "type" => 0,
    "msg" => $content
);
$data = json_encode($data);
$header = array(
    "Content-type: application/json",
    "Authorization: ".$sig,
    "Timestamp: ".$timestamp
);
$options = array(
    "http" => array(
        "method" => "POST",
        "header" => implode("
", $header),
        "content" => $data
    )
);
$res = json_decode(file_get_contents($url, false, stream_context_create($options)), true);
Copy after login

4. Save the verification code to Redis

In order to ensure the validity period of the verification code, you need to save the generated random verification code to Redis and set a validity period. The specific code is as follows:

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->setex($mobile, 300, $code);
Copy after login

5. Complete code

function send_sms($mobile, $appid, $appsecret, $sdkappid, $appkey, $templateid)
{
    // 获取access_token
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appid."&secret=".$appsecret;
    $res = json_decode(file_get_contents($url), true);
    $access_token = $res['access_token'];

    // 生成随机验证码
    $code = rand(1000, 9999);

    // 发送短信
    $timestamp = time();
    $sig = md5("appkey=".$appkey."&timestamp=".$timestamp);
    $content = "【签名】验证码为:".$code.",有效期5分钟,请勿泄露。如非本人操作,请忽略本短信。";
    $url = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms?sdkappid=".$sdkappid."&random=".rand();
    $data = array(
        "tel" => array("nationcode" => "86", "mobile" => $mobile),
        "type" => 0,
        "msg" => $content
    );
    $data = json_encode($data);
    $header = array(
        "Content-type: application/json",
        "Authorization: ".$sig,
        "Timestamp: ".$timestamp
    );
    $options = array(
        "http" => array(
            "method" => "POST",
            "header" => implode("
", $header),
            "content" => $data
        )
    );
    $res = json_decode(file_get_contents($url, false, stream_context_create($options)), true);

    // 保存验证码到Redis
    $redis = new Redis();
    $redis->connect('127.0.0.1', 6379);
    $redis->setex($mobile, 300, $code);

    return array("code" => $code);
}
Copy after login

6. Summary

This article introduces how to use PHP to implement SMS verification codes for WeChat mini programs, including obtaining access_token , generate a random verification code, call the SMS API to send the verification code and save the verification code to Redis. These tips not only apply to WeChat mini programs, but can also be used for other types of applications. Hope this article is helpful to everyone.

The above is the detailed content of Tips for implementing WeChat applet SMS verification code using PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

CakePHP Project Configuration CakePHP Project Configuration Sep 10, 2024 pm 05:25 PM

In this chapter, we will understand the Environment Variables, General Configuration, Database Configuration and Email Configuration in CakePHP.

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

CakePHP Date and Time CakePHP Date and Time Sep 10, 2024 pm 05:27 PM

To work with date and time in cakephp4, we are going to make use of the available FrozenTime class.

CakePHP File upload CakePHP File upload Sep 10, 2024 pm 05:27 PM

To work on file upload we are going to use the form helper. Here, is an example for file upload.

CakePHP Routing CakePHP Routing Sep 10, 2024 pm 05:25 PM

In this chapter, we are going to learn the following topics related to routing ?

Discuss CakePHP Discuss CakePHP Sep 10, 2024 pm 05:28 PM

CakePHP is an open-source framework for PHP. It is intended to make developing, deploying and maintaining applications much easier. CakePHP is based on a MVC-like architecture that is both powerful and easy to grasp. Models, Views, and Controllers gu

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

CakePHP Creating Validators CakePHP Creating Validators Sep 10, 2024 pm 05:26 PM

Validator can be created by adding the following two lines in the controller.

See all articles