代码 php腾讯云发送短信

2024-11-18 13:50:11 +0800 CST views 523

该代码实现了一个名为Tensms的类,用于通过腾讯云发送短信。它包含配置、请求方法、签名生成和CURL请求等功能。类构造函数初始化配置,提供了设置请求协议、方法和选项的功能,并实现了发送短信的请求逻辑。通过生成签名和设置请求头,确保请求的安全性和有效性。

<?php
declare (strict_types = 1);
namespace system\sms;

class Tensms {
    /**
     * @var array
     */
    public $config = [];
    /**
     * @var array
     */
    public $options = [];
    /**
     * @var string
     */
    public $version = '2019-07-11';
    /**
     * @var string
     */
    public $action = 'SendSms';
    /**
     * @var string
     */
    public $protocol = 'https://';
    /**
     * @var string
     */
    public $host = 'sms.tencentcloudapi.com';
    /**
     * @var string
     */
    public $algorithm = "TC3-HMAC-SHA256";
    /**
     * @var string
     */
    public $method = 'POST';
    /**
     * @var string
     */
    public $service = 'sms';
    /**
     * @var string
     */
    public $timestamp = 0;
    /**
     * @var object 对象实例
     */
    protected static $instance = null;

    /**
     * 类构造函数
     * class constructor.
     */
    public function __construct(array $config)
    {
        $this->config = $config;
        $this->timestamp = time();
    }

    /**
     * 初始化
     * @access public
     * @param array $options 参数
     * @return static
     */
    public static function instance(array $options = [])
    {
        if (is_null(self::$instance)) {
            self::$instance = new static($options);
        }
        return self::$instance;
    }

    /**
     * @param string $action
     *
     * @return $this
     */
    public function action($action)
    {
        $this->action = $action;
        return $this;
    }

    /**
     * @param array $options
     *
     * @return $this
     */
    public function options(array $options)
    {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        return $this;
    }

    /**
     * @param string $method
     *
     * @return $this
     */
    public function method($method)
    {
        $this->method = $method;
        return $this;
    }

    /**
     * 设置请求协议
     * @param string $protocol 请求协议(https://  http://)
     */
    public function setProtocol($protocol) 
    {
        $this->protocol = $protocol;
    }

    /**
     * 短信发送函数
     * @return array|false
     */
    public function request() 
    {
        $this->options = is_array($this->options) ? json_encode($this->options, JSON_UNESCAPED_UNICODE) : $this->options;
        $hashedRequestPayload = $this->RequestPayload($this->options);

        // 拼接字符串
        $canonicalRequest = $this->method."\n"."/\n"."\n"."content-type:application/json\n"
            ."host:".$this->host."\n\n"."content-type;host\n".$hashedRequestPayload;           
        // 获取时间戳
        $date = gmdate("Y-m-d", $this->timestamp);
        $credentialScope = $date."/".$this->service."/tc3_request";
        $stringToSign = $this->stringToSign($canonicalRequest, $credentialScope);

        // 获取真实签名
        $signature = $this->signature($stringToSign, $date);
        $authorization = $this->authorization($credentialScope, $signature);

        // 使用 CURL 发送请求
        $result = $this->curlPost($this->protocol.$this->host, $this->options, $this->header($authorization));

        if ($result === false) {
            return false;
        }
        return json_decode($result, true);
    }

    /**
     * 返回数据哈希值
     * @access protected
     * @param mixed $payload   
     */
    protected function RequestPayload($payload) 
    {   
        return hash("SHA256", $payload);
    }

    /**
     * 返回待签名字符串
     * @access protected
     * @param mixed $sign   
     * @param mixed $param
     */
    protected function stringToSign($canonicalRequest, $credentialScope)
    {
        $hashedCanonicalRequest = hash("SHA256", $canonicalRequest);
        return $this->algorithm."\n".$this->timestamp."\n".$credentialScope."\n".$hashedCanonicalRequest;
    }

    /**
     * 返回真实签名
     * @access protected
     * @param mixed $stringToSign   
     * @param mixed $date
     */
    protected function signature($stringToSign, $date)
    {
        $secretDate = hash_hmac("SHA256", $date, "TC3".$this->config['secret_key'], true);
        $secretService = hash_hmac("SHA256", $this->service, $secretDate, true);
        $secretSigning = hash_hmac("SHA256", "tc3_request", $secretService, true);
        return hash_hmac("SHA256", $stringToSign, $secretSigning);
    }

    /**
     * 返回数据签名串
     * @access protected
     * @param string $credentialScope   
     * @param string $signature
     */    
    protected function authorization($credentialScope, $signature)
    {
        return $this->algorithm." Credential=".$this->config['secret_id']."/".$credentialScope .", SignedHeaders=content-type;host, Signature=".$signature;
    }

    /**
     * 设置头部信息
     * @access protected
     * @param string $authorization
     */
    protected function header($authorization)
    {
        return [
            'Content-Type: application/json',
            'X-TC-Action: SendSms',
            'X-TC-Timestamp: '.$this->timestamp,
            'X-TC-Version: 2019-07-11',
            'X-TC-Language: zh-CN',
            'Authorization: '.$authorization,
        ];
    }

    /**
     * 使用 CURL 发送 POST 请求
     * @param string $url
     * @param string $postData
     * @param array $headers
     * @return string|false
     */
    protected function curlPost($url, $postData, $headers)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
    }
}

#案例

$config = [
    'secret_id' => 'your_secret_id',
    'secret_key' => 'your_secret_key',
];

$tensms = new \system\sms\Tensms($config);
$tensms->options([
    'PhoneNumberSet' => ['+8613711112222'],  // 设置发送短信的号码
    'TemplateID' => '123456',  // 短信模板ID
    'Sign' => 'YourSign',  // 短信签名
    'TemplateParamSet' => ['验证码', '1234'],  // 模板参数
]);
$response = $tensms->request();
var_dump($response);
复制全文 生成海报 编程 API 短信服务 腾讯云

推荐文章

php获取当前域名
2024-11-18 00:12:48 +0800 CST
Golang - 使用 GoFakeIt 生成 Mock 数据
2024-11-18 15:51:22 +0800 CST
一文详解回调地狱
2024-11-19 05:05:31 +0800 CST
支付页面html收银台
2025-03-06 14:59:20 +0800 CST
2025年,小程序开发到底多少钱?
2025-01-20 10:59:05 +0800 CST
Linux 常用进程命令介绍
2024-11-19 05:06:44 +0800 CST
解决 PHP 中的 HTTP 请求超时问题
2024-11-19 09:10:35 +0800 CST
如何配置获取微信支付参数
2024-11-19 08:10:41 +0800 CST
php指定版本安装php扩展
2024-11-19 04:10:55 +0800 CST
基于Flask实现后台权限管理系统
2024-11-19 09:53:09 +0800 CST
Nginx 状态监控与日志分析
2024-11-19 09:36:18 +0800 CST
PHP 的生成器,用过的都说好!
2024-11-18 04:43:02 +0800 CST
XSS攻击是什么?
2024-11-19 02:10:07 +0800 CST
向满屏的 Import 语句说再见!
2024-11-18 12:20:51 +0800 CST
程序员茄子在线接单