天天看点

腾讯云短信发送及记录

1、安装腾讯云提供的拓展包:

composer require qcloudsms/qcloudsms_php      

2、代码,指定模板单条发送:

...
use Qcloud\Sms\SmsSingleSender;
...
public function sendSingleMessage($data)
{
    $customer_id = $data['customer_id'];
    $nationCode = $data['nationCode'];
    $phoneNumber = $data['phoneNumber'];
    $templId = $data['templId'];
    $params = $data['params'];
    
    $appid = config('bcc_kid.tencent_app_id', '');
    $appkey = config('bcc_kid.tencent_app_key', '');

    $status_code = 200;
    $status = 1;
    $err_message = '发送短信失败!';
    try {
        $sender = new SmsSingleSender($appid, $appkey);
        // 假设模板内容为:测试短信,{1},{2},{3},上学。
        $result = $sender->sendWithParam($nationCode, $phoneNumber, $templId,
            $params, $sign);
        $rsp = json_decode($result);
        if ($rsp->result != 0) {
            $status_code = 500;
            $err_message = json_encode($rsp, 320);
            $status = 2;
        }
    } catch (\Exception $e) {
        $err_message = $e;
        $status_code = 500;
        $status = 2;
    }
    $creator = auth()->id();

    //准备写入日志的数据
    $attributes = [
        'customer_id' => $customer_id ?? 0,
        'message_type' => 1,
        'message_params' => json_encode($params, 320),
        'send_type' => 2,
        'sms_template_id' => $templId,
        'message_type_value' => '(+' . $nationCode . ')' . $phoneNumber,
        'status_code' => $status_code,
        'status' => $status,
        'creator' => $creator,
        'updator' => $creator,
    ];
    $this->createMessageLog($attributes);
    //如果状态码错误,那么返回错误消息,否则返回1;
    return $status_code == 500 ? $err_message : 1;
}