首先下载
安装阿里云短信SDK
composer require alibabacloud/sdk
安装 Alibaba Cloud SDK for PHP 作为依赖项
composer require alibabacloud/darabonba-openapi
最后安装对应的包
composer require alibabacloud/dysmsapi-20170525
上面3个都下载了,官方网站并没有说明下载sdk,这个没有下载,查询资料花了几个小时,掉坑了
这里要添加配制文件信息,阿里云的信息,包含短信的信息等。自行准备
<?php
namespace services\alisms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class AliSmsService
{
/**
* 阿里云发送短信
* @param string $phone
* @param int $code
* @return bool
* @throws ClientException
*/
public static function sendCodeServer(string $phone, int $code) : bool {
if(empty($phone) || empty($code)){
return false;
}
AlibabaCloud::accessKeyClient(config("aliyun.access_key_id"), config("aliyun.access_secret"))
->regionId(config("aliyun.region_id"))
->asDefaultClient();
$templateParam = [
"code" => $code
];
try {
$result = AlibabaCloud::rpc()
->product('Dysmsapi')
// ->scheme('https') // https | http
->version('2017-05-25')
->action('SendSms')
->method('POST')
->host(config("aliyun.host"))
->options([
'query' => [
'RegionId' => config("aliyun.region_id"),
'PhoneNumbers' => $phone,
'SignName' => config("aliyun.sign_name"),
'TemplateCode' => config("aliyun.template_code"),
'TemplateParam' => json_encode($templateParam),
],
])
->request();
// print_r($result->toArray());
} catch (ClientException $e) {
return false;
// echo $e->getErrorMessage() . PHP_EOL;
} catch (ServerException $e) {
return false;
// echo $e->getErrorMessage() . PHP_EOL;
}
return true;
}
function sendCode( string $phone) : bool {
$code = rand(100000, 999999);
$sms = self::sendCodeServer($phone, $code);
if($sms){
// 需要记录redis及失效时间1分钟
}
return true;
}
}
这是控制器代码
<?php
namespace app\api\controller;
/**
* 发送短信
* Class Code
* @package app\api\controller
*/
use services\alisms\AliSmsService;
class Code
{
public function send_code(){
$phone=input('phone');
if (empty($phone)){
return error_json('手机号码不能为空');
}
/*try {
validate(User::class)->scene("send_code")->check($data);
}catch (ValidateException $e){
return show(config("status.error"), $e->getError());
}*/
if($this->getAliSmsService()->sendCode($phone)){
return success_json("发送验证码成功");
}
return error_json("发送验证码失败");
}
function getAliSmsService(){
return app(AliSmsService::class);
}
}
bug
部署到服务器上的阿里云SDK会报错,如下
这是报错信息 Class 'AlibabaCloud\Client\AlibabaCloud' not found 代码里已经引用了,但是会报错,测试发现,原来是阿里云SDK造成的,昨天修复好了,第二天又出现同样的问题,我先把解决方法给大家看一看
代码中引用的,如图下
解决方案如下,直接更新阿里云SDK
文章来源地址https://www.toymoban.com/news/detail-565075.html
需要用composer安装
1.切换阿里云镜像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
2.安装阿里云SDK
composer require alibabacloud/sdk
文章来源:https://www.toymoban.com/news/detail-565075.html
到了这里,关于TP6 对接阿里云短信接口2.0的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!