TP6实现阿里云短信发送(新版SDK)

ThinkPHP 1799 0 2021-09-03

TP6实现阿里云短信发送(新版SDK)

首页安装SDK,用composer进行下载安装,代码如下:

composer require alibabacloud/client


接着把下载好的vendor目录复制到TP框架项目下的extend目录下,比如:extend/aliyunsms/vendor

以下为实现短信发送代码:

require_once '../extend/aliyunsms/vendor/autoload.php';
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;

class Aliyunsms
{
    public function sendSms(){
		$res=['status'=>false,'msg'=>'err','data'=>[]];
    	$accessKeyId='**********';
    	$accessSecret='**********';
		$pv=input('post.'); //说明:$pv是POST传过来的参数,如:$pv=['PhoneNumbers' =>'189********', 'TemplateCode' => 'SMS_18******', 'TemplateParam'=>'{code:809966}'];
		if(empty($pv) || isNull($pv)){
			$res['msg']='请确认信息是否填写完整';
		}else{
			AlibabaCloud::accessKeyClient($accessKeyId,$accessSecret)->regionId('cn-hangzhou')->asDefaultClient();
			try {
				$query=['RegionId' => "cn-hangzhou", 'SignName' => '海南世云科技' ];
				$query=array_merge($query,$pv);
			    $result =AlibabaCloud::rpc()->product('Dysmsapi')->version('2017-05-25')->action('SendSms')
			    ->method('POST')->host('dysmsapi.aliyuncs.com')->options(['query' =>$query])->request();
					$res['data']=$result->toArray();
					if($res['data']['Code']=='OK'){
						$res['status']=true;
						$res['msg']='短信发送成功';
					}else{
						$res['msg']='短信发送失败';
					}
				} catch (ClientException $e) {
				    $res['msg']=$e->getErrorMessage();
				} catch (ServerException $e) {
				    $res['msg']=$e->getErrorMessage();
				}
		}
		return json($res);
	}
}


上一篇:TP6 常用数据库操作

下一篇:TP6稳定版的安装/多应用模式扩展/常用扩展安装及配置

讨论数量:0

请先登录再发表讨论。 2024-11-24

天涯网魂
3 杠 5 星
TA 的文章
TA 的随言
TA 的资源链