最新消息:欢迎访问刘磊博客

新版短信接口

PHP编程 飞翔的mouse 524浏览

1.申请短信签名和模板,短信签名不能带有”测试”,否则通过不了.

2. composer require alibabacloud/sdk

3. 代码部分

<?php
namespace alisms;

use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

// Download:https://github.com/aliyun/openapi-sdk-php
// Usage:https://github.com/aliyun/openapi-sdk-php/blob/master/README.md
class alisms
{
    //密钥账号
    static $accessKeyId = '*****';
    //密钥密码
    static $accessSecret = '*****';

    //发送短信,$phone为接收短信的手机号码
    //国内短信:11位手机号码,例如15951955195,国际/港澳台消息:国际区号+号码,例如85200000000
    public static function sendSms($phone)
    {
        //验证码
        $code = mt_rand(100000, 999999);
        AlibabaCloud::accessKeyClient(static::$accessKeyId, static::$accessSecret)
            ->regionId('cn-hangzhou')              // replace regionId (地区) as you need
            ->asDefaultClient();
        $code_arr = ['code' => $code];
        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phone,                      //手机号码
                        'SignName' => "*****",                        //短信签名名称(必须和签名管理的签名名字一致)
                        'TemplateCode' => "*****",            //短信模板ID
                        'TemplateParam' => json_encode($code_arr),      //短信模板变量对应的实际值,JSON格式
                    ],
                ])
                ->request();
            return $result->toArray();                                   //对象转数组
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return [];
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
            return [];
        }
    }

    //返回结果例子
    /*
     * Array ( [Message] => OK [RequestId] => F144F01A-EB4E-48F9-9E90-D3D775B2D2E4 [BizId] => 799010660648933410^0 [Code] => OK )
     */
}

4. 说明:新版短信接口代码于19年4月底更新了,抛弃了以前写法,这里是最新写法,

5. 注意:价格0.045-0.055/条(国内), 为了防止盗刷,建议加上图形验证码、拖动验证等.,

6. 为了代码的高度复用,建议封装.

7. 请求接口网址说明: https://help.aliyun.com/document_detail/101414.html?spm=a2c4g.11186623.6.616.e1473e2cHaBVB5

转载请注明:ONE'S 博客 » 新版短信接口