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

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

#阿里云免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 云服务 短信服务

推荐文章

php常用的正则表达式
2024-11-19 03:48:35 +0800 CST
淘宝npm镜像使用方法
2024-11-18 23:50:48 +0800 CST
Vue3中的Scoped Slots有什么改变?
2024-11-17 13:50:01 +0800 CST
jQuery `$.extend()` 用法总结
2024-11-19 02:12:45 +0800 CST
前端代码规范 - 图片相关
2024-11-19 08:34:48 +0800 CST
Vue3中的Store模式有哪些改进?
2024-11-18 11:47:53 +0800 CST
robots.txt 的写法及用法
2024-11-19 01:44:21 +0800 CST
API 管理系统售卖系统
2024-11-19 08:54:18 +0800 CST
微信内弹出提示外部浏览器打开
2024-11-18 19:26:44 +0800 CST
如何使用go-redis库与Redis数据库
2024-11-17 04:52:02 +0800 CST
前端如何一次性渲染十万条数据?
2024-11-19 05:08:27 +0800 CST
Go语言中的`Ring`循环链表结构
2024-11-19 00:00:46 +0800 CST
ElasticSearch简介与安装指南
2024-11-19 02:17:38 +0800 CST
JavaScript 策略模式
2024-11-19 07:34:29 +0800 CST
Rust 中的所有权机制
2024-11-18 20:54:50 +0800 CST
Go语言中的mysql数据库操作指南
2024-11-19 03:00:22 +0800 CST
Elasticsearch 的索引操作
2024-11-19 03:41:41 +0800 CST
Vue3 组件间通信的多种方式
2024-11-19 02:57:47 +0800 CST
MySQL数据库的36条军规
2024-11-18 16:46:25 +0800 CST
一些实用的前端开发工具网站
2024-11-18 14:30:55 +0800 CST
程序员茄子在线接单