TP5框架使用腾讯短信验证码类库
接到美国客户需求,在商城添加地址时候添加手机号需要进行短信校验,客户想使用腾讯云国际短信,看了下官方文档,总的来说太繁琐了,一些功能和api都不是我所需要的,
以下是整理出来的精简版api供框架使用,tp laravel等框架均可使用,放在公共文件定义好命名空间即可调用。
提供下载官方API文档出提取出来的仅短信发送类:https://www.lanzous.com/i8skomh
将下载的API放在一个文件夹中,将下面的类也放在这个文件夹中用来调用
<?php namespace app\common\library\sms\tencent_sms; // 腾讯云短信DEMO use Qcloud\Sms\SmsSingleSender; class tencentApi{ // 短信应用SDK AppID private $appid = ""; // 短信应用SDK AppKey private $appkey = ""; // 国家码 中国的国家码为86 美国为1 private $country = "1"; /* * @param int $phone 手机号 * @param int $temID 模版ID */ public function send($phone,$temID){ require_once __DIR__ . "/smsutil.php"; require_once __DIR__ . "/smssend.php"; // 生成短信验证码 $code = mt_rand(1000,9999); try { $ssender = new SmsSingleSender($this->appid, $this->appkey); $result = $ssender->sendWithParam($this->country, $phone, $temID, array($code), "", "", ""); $rsp = json_decode($result,true); return \json_encode(['codeyz'=> $code,'result'=> $rsp]); // 返回短信验证码 和发送状态信息 } catch (\Exception $e) { return \json_encode(['code'=>500,'msg'=>$e]); // 抛出异常 } } } ?>
开始使用:
引入命名空间和tp的缓存类
use app\common\library\sms\tencent_sms\tencentApi; use think\Cache;
创建短信发送类:
/** * 短信验证码发送(腾讯接口) * Class Sms * @package app\api\controller */ class Sms extends Controller { /** * 短信验证码发送 * @param int 用户id * @param int 要发送验证码的手机号 * @return json */ public function index($user_id = '',$phone) { if($user_id == ''){ return json(['code'=>301, 'msg' => '用户不存在!']); // 用户不存在 } if(!is_numeric($phone) || strlen($phone)!=10){ // 校验手机号格式是否正确 return json(['code'=>305,'msg'=>'手机号格式不正确!']); } $tencentApi = new tencentApi; $data = json_decode($tencentApi->send($phone,'模版ID'),true); if($data['result']['result'] ==0){ // 短信发送成功,将验证码存入缓存用于后续校验 Cache::set('address'. $user_id, $data['codeyz'], 120); return json(['code'=>200,'msg'=>'验证码发送成功!']); }else{ return json(['code'=>302,'msg'=>'验证码发送失败!']); } } /** * 短信验证码校验 * @param int 用户id * @param int 用户输入的验证码 * @return json */ public function check($user_id = '',$code = ''){ if($user_id=='' && $code==''){ return json(['code' => 301, 'msg' => '用户不存在!']); // 用户不存在 } // 对比用户输入的验证码与缓存中是否一致 if($code == Cache::get('address' . $user_id, '')){ // 判断验证码是否相同 return json(['code'=>200,'msg'=>'验证码正确!']); }else{ return json(['code'=>301,'msg'=>'验证码不正确!']); } } /** * 信用卡消费通知 * @param int 用户id * @param int 用户输入的验证码 * @return json */ public function creditCard() { $tencentApi = new tencentApi; return json_decode($tencentApi->send('手机号', '模版ID'), true); } }
这样下来就完成了精简版的腾讯短信验证接口!
评论