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

Tips for implementing WeChat applet SMS verification code using PHP

WBOY
WBOYOriginal
2023-06-01 09:42:052573browse

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'];

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);

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."×tamp=".$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);

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);

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."×tamp=".$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);
}

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:
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