您现在的位置是:首页 > ThinkPHP

李清波 2020-05-27 ThinkPHP 1336 复制当前网址

Thinkphp使用阿里云短信服务器接口

Alibaba Cloud SDK for PHP

地址:https://github.com/aliyun/openapi-sdk-php


composer安装

composer require alibabacloud/sdk


Thinkphp6.0实例

创建Model

AlibabaCloudModel.php

<?php
declare (strict_types = 1);

namespace app\common\model;

use think\Db;
use think\facade\Request;
use think\Model;

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

/**
 * @mixin think\Model
 */
class AlibabaCloudModel extends Model
{

    public static $SignName = '签名';
    public static $AccessKeyId = '阿里云key';
    public static $AccessKeySecret = '阿里云secret';


    public static function sendSms($phone,$code=''){
        AlibabaCloud::accessKeyClient(self::$AccessKeyId, self::$AccessKeySecret)
            ->regionId('cn-hangzhou')
            ->asDefaultClient();
        try {
        	if(empty($code)){
		        $code = rand(1000,9999);
	        }
            $param = [
                'code' => $code
            ];

            $insertData = [
                'code' => $code,
                'phone' => $phone,
                'ip' => get_client_ip(),
                'send_time' => time(),
                'flag' => 1,
                'type' => 1,
                'isuse' => 0,
                'status' => 1
            ];
            SmsModel::create($insertData);

            $result = AlibabaCloud::rpc()
                ->product('Dysmsapi')
                // ->scheme('https') // https | http
                ->version('2017-05-25')
                ->action('SendSms')
                ->method('POST')
                ->host('dysmsapi.aliyuncs.com')
                ->options([
                    'query' => [
                        'RegionId' => "cn-hangzhou",
                        'PhoneNumbers' => $phone,
                        'SignName' => self::$SignName,
                        'TemplateCode' => "SMS_182666989",
                        'TemplateParam' => json_encode($param),
                    ],
                ])
                ->request();
            return $result->toArray();
        } catch (ClientException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        } catch (ServerException $e) {
            echo $e->getErrorMessage() . PHP_EOL;
        }

    }
}

sendSms方法中需要注意的参数有:

PhoneNumbers:发送的手机号码

SignName:签名

TemplateCode:短信模板

TemplateParam:发送短信参数

文章来源:http://liqingbo.com/blog-1705.html

评论