php短信提醒,PHP腾讯云短信服务

最近做的几个项目都用到了短信验证码的功能,频繁的找代码我也觉得繁琐了,今天把代码写到博客,方便粘贴复制。今天是对接腾讯云的代码示例。

先使用 composer 安装 tencent SDK

composer require tencentcloud/tencentcloud-sdk-php

简单封装一下

namespace app\extend;

use TencentCloud\Common\Credential;

use TencentCloud\Common\Profile\ClientProfile;

use TencentCloud\Common\Profile\HttpProfile;

use TencentCloud\Common\Exception\TencentCloudSDKException;

use TencentCloud\Sms\V20190711\SmsClient;

use TencentCloud\Sms\V20190711\Models\SendSmsRequest;

class SmsTencent

{

public $config = [];

public function __construct($appid, $secret_id, $secret_key)

{

$this->config = [

'appid' => $appid,

'secret_id' => $secret_id,

'secret_key' => $secret_key

];

}

public function send($template_id, $sign, $phone, $auth_code)

{

$return = [

'code' => 0,

'msg' => 'success',

'data' => []

];

try {

$cred = new Credential($this->config['secret_id'], $this->config['secret_key']);

$httpProfile = new HttpProfile();

$httpProfile->setEndpoint("sms.tencentcloudapi.com");

$clientProfile = new ClientProfile();

$clientProfile->setHttpProfile($httpProfile);

$client = new SmsClient($cred, "ap-guangzhou", $clientProfile);

$req = new SendSmsRequest();

$params = array(

"PhoneNumberSet" => array(

'86' . $phone

),

"TemplateID" => $template_id,

"Sign" => $sign,

"TemplateParamSet" => array(

(string)$auth_code

),

"SmsSdkAppid" => $this->config['appid']

);

$req->fromJsonString(json_encode($params));

$resp = $client->SendSms($req);

$result = $resp->toJsonString();

$result = json_decode($result, true);

} catch (TencentCloudSDKException $e) {

$return['code'] = 500;

$return['msg'] = $e->getMessage();

return $return;

}

if (isset($result['SendStatusSet'][0]['Code'])&&$result['SendStatusSet'][0]['Code']=='Ok') {

$return['code'] = 0;

$return['msg'] = 'success';

} else {

$return['code'] = 500;

$return['msg'] = $result['SendStatusSet'][0]['Message'] ?? '发送失败';

}

return $return;

}

}

调用

//生成验证码

$auth_code = rand(1000,9999);

$phone = $post['phone'];

//签名

$sign = Config::get('sms.sign');

//appid

$appid = Config::get('sms.appid');

//secret_id

$secret_id = Config::get('sms.secret_id');

//secret_key

$secret_key = Config::get('sms.secret_key');

//模板ID

$auth_code_template_id = Config::get('sms.auth_code_template_id');

$sms = new SmsTencent($appid, $secret_id, $secret_key);

$result = $sms->send($auth_code_template_id, $sign, $phone, $auth_code);

if ($result['code'] != 0) {

return api_json_return(500, $result['msg'] ?? '发送失败');

}

return api_json_return(0, '发送成功');

so easy

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值