首先下載
安裝阿里云短信SDK
composer require alibabacloud/sdk
安裝 Alibaba Cloud SDK for PHP 作為依賴項
composer require alibabacloud/darabonba-openapi
最后安裝對應(yīng)的包
composer require alibabacloud/dysmsapi-20170525?
上面3個都下載了,官方網(wǎng)站并沒有說明下載sdk,這個沒有下載,查詢資料花了幾個小時,掉坑了
這里要添加配制文件信息,阿里云的信息,包含短信的信息等。自行準(zhǔn)備?
<?php
namespace services\alisms;
use AlibabaCloud\Client\AlibabaCloud;
use AlibabaCloud\Client\Exception\ClientException;
use AlibabaCloud\Client\Exception\ServerException;
class AliSmsService
{
/**
* 阿里云發(fā)送短信
* @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;
/**
* 發(fā)送短信
* 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('手機(jī)號碼不能為空');
}
/*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("發(fā)送驗證碼成功");
}
return error_json("發(fā)送驗證碼失敗");
}
function getAliSmsService(){
return app(AliSmsService::class);
}
}
bug
部署到服務(wù)器上的阿里云SDK會報錯,如下
這是報錯信息 Class 'AlibabaCloud\Client\AlibabaCloud' not found? 代碼里已經(jīng)引用了,但是會報錯,測試發(fā)現(xiàn),原來是阿里云SDK造成的,昨天修復(fù)好了,第二天又出現(xiàn)同樣的問題,我先把解決方法給大家看一看
?代碼中引用的,如圖下
解決方案如下,直接更新阿里云SDK
?文章來源地址http://www.zghlxwxcb.cn/news/detail-565075.html
需要用composer安裝
1.切換阿里云鏡像
composer config -g repo.packagist composer https://mirrors.aliyun.com/composer/
2.安裝阿里云SDK
composer require alibabacloud/sdk
?文章來源:http://www.zghlxwxcb.cn/news/detail-565075.html
?
到了這里,關(guān)于TP6 對接阿里云短信接口2.0的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!