代码 阿里云免sdk发送短信代码

2025-01-01 12:22:14 +0800 CST views 538

#阿里云免sdk发送短信代码
该文本提供了一个使用阿里云短信服务的PHP类示例,包含发送短信的功能。类中定义了构造函数、发送短信方法、生成签名、URL编码、生成随机字符串和发送HTTPGET请求的方法。示例展示了如何使用该类发送短信,并处理可能的异常和错误信息。

<?php

class AliyunSms
{
    private $accessKeyId;
    private $accessKeySecret;
    private $signName;
    private $templateCode;
    private $endpoint = "https://dysmsapi.aliyuncs.com/";
    private $apiVersion = "2017-05-25";
    private $regionId = "cn-hangzhou";

    /**
     * 构造函数
     *
     * @param string $accessKeyId
     * @param string $accessKeySecret
     * @param string $signName
     * @param string $templateCode
     */
    public function __construct($accessKeyId, $accessKeySecret, $signName, $templateCode)
    {
        $this->accessKeyId = $accessKeyId;
        $this->accessKeySecret = $accessKeySecret;
        $this->signName = $signName;
        $this->templateCode = $templateCode;
    }
public static function sendSms2($phoneNumber, $templateParam = [])
    {
        $sms = new self();
        return $sms->sendSms($phoneNumber, $templateParam);
    }
    /**
     * 发送短信
     *
     * @param string $phoneNumber 接收短信的手机号码
     * @param array $templateParam 短信模板变量对应的实际值,JSON格式
     * @return array API 返回结果
     * @throws Exception
     */
    public function sendSms($phoneNumber, $templateParam = [])
    {
        $params = [
            "Action" => "SendSms",
            "Version" => $this->apiVersion,
            "RegionId" => $this->regionId,
            "PhoneNumbers" => $phoneNumber,
            "SignName" => $this->signName,
            "TemplateCode" => $this->templateCode,
            "TemplateParam" => json_encode($templateParam, JSON_UNESCAPED_UNICODE),
            "Format" => "JSON",
            "AccessKeyId" => $this->accessKeyId,
            "SignatureMethod" => "HMAC-SHA1",
            "SignatureVersion" => "1.0",
            "SignatureNonce" => $this->generateNonce(),
            "Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
        ];

        // 生成签名
        $signature = $this->generateSignature($params);
        $params["Signature"] = $signature;

        // 构建请求 URL
        $url = $this->endpoint . "?" . http_build_query($params);

        // 发送请求
        $response = $this->httpGet($url);

        // 解析响应
        $result = json_decode($response, true);
        if (!$result) {
            throw new Exception("无法解析API响应");
        }

        return $result;
    }

    /**
     * 生成签名
     *
     * @param array $params
     * @return string
     */
    private function generateSignature($params)
    {
        // 步骤 1:按照字典序排序参数
        ksort($params);

        // 步骤 2:构造规范化的查询字符串
        $canonicalizedQueryString = '';
        foreach ($params as $key => $value) {
            $canonicalizedQueryString .= "&" . $this->percentEncode($key) . "=" . $this->percentEncode($value);
        }
        $canonicalizedQueryString = ltrim($canonicalizedQueryString, '&');

        // 步骤 3:构造字符串待签名
        $stringToSign = "GET&%2F&" . $this->percentEncode($canonicalizedQueryString);

        // 步骤 4:计算签名
        $signingKey = $this->accessKeySecret . "&";
        $signature = base64_encode(hash_hmac('sha1', $stringToSign, $signingKey, true));

        return $signature;
    }

    /**
     * URL编码(符合RFC 3986)
     *
     * @param string $str
     * @return string
     */
    private function percentEncode($str)
    {
        $res = urlencode($str);
        $res = preg_replace('/\+/', '%20', $res);
        $res = preg_replace('/\*/', '%2A', $res);
        $res = preg_replace('/%7E/', '~', $res);
        return $res;
    }

    /**
     * 生成随机字符串(UUID)
     *
     * @return string
     */
    private function generateNonce()
    {
        return uniqid(mt_rand(0, mt_getrandmax()), true);
    }

    /**
     * 发送 HTTP GET 请求
     *
     * @param string $url
     * @return string
     * @throws Exception
     */
    private function httpGet($url)
    {
        $ch = curl_init();

        // 设置选项
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 5);

        // 执行请求
        $response = curl_exec($ch);

        // 错误处理
        if ($response === false) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new Exception("CURL Error: " . $error);
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($httpCode != 200) {
            throw new Exception("HTTP Error Code: " . $httpCode);
        }

        return $response;
    }
}

// 使用示例
try {
    // 替换为您的实际参数
    $accessKeyId = "您的AccessKeyId";
    $accessKeySecret = "您的AccessKeySecret";
    $signName = "您的短信签名";
    $templateCode = "您的模板CODE";

    $sms = new AliyunSms($accessKeyId, $accessKeySecret, $signName, $templateCode);

    $phoneNumber = "15980037210"; // 接收短信的手机号码
    $templateParam = [
        "code" => "123456" // 模板中的变量
    ];

    $result = $sms->sendSms($phoneNumber, $templateParam);

    if (isset($result['Code']) && $result['Code'] === 'OK') {
        echo "短信发送成功!";
    } else {
        echo "短信发送失败,错误信息:" . $result['Message'];
    }
} catch (Exception $e) {
    echo "发生异常:" . $e->getMessage();
}

复制全文 生成海报 编程 API 云服务 短信服务

推荐文章

vue打包后如何进行调试错误
2024-11-17 18:20:37 +0800 CST
Vue3结合Driver.js实现新手指引功能
2024-11-19 08:46:50 +0800 CST
Vue3中如何实现响应式数据?
2024-11-18 10:15:48 +0800 CST
Vue 中如何处理父子组件通信?
2024-11-17 04:35:13 +0800 CST
gin整合go-assets进行打包模版文件
2024-11-18 09:48:51 +0800 CST
# 解决 MySQL 经常断开重连的问题
2024-11-19 04:50:20 +0800 CST
Vue3中如何处理WebSocket通信?
2024-11-19 09:50:58 +0800 CST
Vue3中的v-model指令有什么变化?
2024-11-18 20:00:17 +0800 CST
一些实用的前端开发工具网站
2024-11-18 14:30:55 +0800 CST
JavaScript中设置器和获取器
2024-11-17 19:54:27 +0800 CST
Vue中的`key`属性有什么作用?
2024-11-17 11:49:45 +0800 CST
PHP 压缩包脚本功能说明
2024-11-19 03:35:29 +0800 CST
记录一次服务器的优化对比
2024-11-19 09:18:23 +0800 CST
初学者的 Rust Web 开发指南
2024-11-18 10:51:35 +0800 CST
Gin 与 Layui 分页 HTML 生成工具
2024-11-19 09:20:21 +0800 CST
Web浏览器的定时器问题思考
2024-11-18 22:19:55 +0800 CST
PHP 代码功能与使用说明
2024-11-18 23:08:44 +0800 CST
LangChain快速上手
2025-03-09 22:30:10 +0800 CST
php使用文件锁解决少量并发问题
2024-11-17 05:07:57 +0800 CST
Shell 里给变量赋值为多行文本
2024-11-18 20:25:45 +0800 CST
程序员茄子在线接单