一、获取微信access_token
在使用微信api之前,需要先获取access_token。access_token是微信api的调用凭证,每次调用微信api时都需要在请求头中携带access_token。具体获取方式如下:
在微信公众平台中创建小程序,然后在小程序开发设置中查看appid和appsecret。根据appid和appsecret发送http get请求,获取access_token。具体代码如下:$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'];
二、生成随机验证码
生成随机验证码的过程非常简单,使用php内置的rand函数即可。具体代码如下:
$code = rand(1000, 9999);
三、调用短信api发送验证码
在获取access_token和生成随机验证码后,就可以调用短信api发送验证码了。这里以腾讯云短信为例,其他短信服务商类似。
在腾讯云短信控制台中创建应用,并获取应用id、应用key和短信模板id。根据应用id和应用key生成签名,并根据短信模板id和随机验证码生成短信内容。使用腾讯云短信api发送短信。具体代码如下:// 生成签名$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中,设置一个有效期。具体代码如下:
$redis = new redis();$redis->connect('127.0.0.1', 6379);$redis->setex($mobile, 300, $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);}
六、总结
本文介绍了如何使用php实现微信小程序短信验证码的技巧,包括获取access_token、生成随机验证码、调用短信api发送验证码和保存验证码到redis。这些技巧不仅适用于微信小程序,也可以用于其他类型的应用程序。希望本文对大家有所帮助。
以上就是php实现微信小程序短信验证码技巧的详细内容。
