PHP阿里云短信服务

今天是对接阿里云短信的案例

先用composer安装插件包

composer require alibabacloud/client

简单封装一下

<?php


namespace app\tools;

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

class Alisms
{
    //配置
    protected $config = [];

    public function __construct($config)
    {
        $this->config = $config;
    }

    /**
     * 发送
     * @param string $phone 接收短信的手机号码
     * @param string $content 短信内容(json)
     * @return array
     * @throws ClientException
     */
    public function send($template, $phone = '', $content = '')
    {
        AlibabaCloud::accessKeyClient($this->config['AccessKeyId'], $this->config['accessSecret'])
            ->regionId('cn-hangzhou')
            ->asDefaultClient();

        try {
            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'PhoneNumbers' => $phone,
                        'SignName' => $this->config['SignName'],
                        'TemplateCode' => $template,
                        'TemplateParam' => $content,
                        'RegionId' => $this->config['RegionId'],
                    ],
                ])
                ->request();
            if ($result['Code'] == 'OK' || $result['Message'] == 'ok') {
                return ['code' => 0, 'msg'=>'发送成功'];
            } else {
                return ['code' => 4003, 'msg'=>$result['Message']];
            }
        } catch (ClientException $e) {
            return ['code' => 500, 'msg'=>$e->getErrorMessage()];
        } catch (ServerException $e) {
            return ['code' => 500, 'msg'=>$e->getErrorMessage()];
        }
    }
}

调用

//配置
$config = [
    'AccessKeyId' => '',
    'accessSecret' => '',
    'SignName' => '',
    'RegionId' => ''
];

//生成验证码
$auth_code = rand(1000,9999);

//短信模板
$template = '';

//发送内容,要根据实际的模板内容(验证码)
$content = json_encode(['code'=>$auth_code]);

$sms = new Alisms($config);
$result = $sms->send($template, $phone, $content);

if ($result['code'] != 0) {
    return api_json_return(500, '发送短信失败,请联系管理员');
}

return api_json_return(0, '发送成功');
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值