一,准备工作:
在阿里云控制台->短信服务中,需完成以下三项的配置,等官方审核通过后,则可以使用接口
二,下载安装php的sdk
1,官方文档地址
https://help.aliyun.com/zh/sms/developer-reference/sdk-product-overview/?spm=a2c4g.11186623.0.0.1db061a5jSzBwS
2,用composer下载安装
liuhongdi@lhdpc:/web/api$ composer require alibabacloud/dysmsapi-20170525 3.0.0
查看安装的版本信息
liuhongdi@lhdpc:/web/api$ composer show alibabacloud/dysmsapi-20170525
name : alibabacloud/dysmsapi-20170525
descrip. : Alibaba Cloud Dysmsapi (20170525) SDK Library for PHP
keywords :
versions : * 3.0.0
released : 2024-06-25, 3 weeks ago
type : library
license : Apache License 2.0 (Apache-2.0) (OSI approved) https://spdx.org/licenses/Apache-2.0.html#licenseText
homepage :
3,安装阿里的openapi库
liuhongdi@lhdpc:/web/api$ composer require alibabacloud/darabonba-openapi
查看安装的版本信息:
liuhongdi@lhdpc:/web/api$ composer show alibabacloud/darabonba-openapi
name : alibabacloud/darabonba-openapi
descrip. : Alibaba Cloud OpenApi Client
keywords :
versions : * 0.2.12
released : 2024-06-21, 1 month ago
type : library
三,代码
1,php代码
namespace App\Http\Controllers;
use Illuminate\Http\Request;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
use \Exception;
use AlibabaCloud\Tea\Exception\TeaError;
use AlibabaCloud\Tea\Utils\Utils;
use Darabonba\OpenApi\Models\Config;
use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
class UserController extends Controller
{
//发送短信息
public function sms(Request $request) {
//设置accesskeyid和accesskeysecret,用自己在阿里云后台的真实的id和secret代替
$config = new Config([
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
"accessKeyId" => getenv("ALIBABA_CLOUD_ACCESS_KEY_ID"),
// 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
"accessKeySecret" => getenv("ALIBABA_CLOUD_ACCESS_KEY_SECRET")
]);
// Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
// 阿里云发送短信的主机
$config->endpoint = "dysmsapi.aliyuncs.com";
//创建client实例
$client = new Dysmsapi($config);
//验证码
$code = rand(1000,9999);
//生成请求
$sendSmsRequest = new SendSmsRequest([
"phoneNumbers" => "138xxxxxxxx", //接收短信的手机号
"signName" => "河北微众信息技术", //签名,要与阿里云后台设置一致
"templateCode" => 'SMS_301234567', //这里是短信的模板id
"templateParam" => json_encode([
'code' => $code
])
]);
try {
// 复制代码运行请自行打印 API 的返回值
$result = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
//var_dump($result);
}
catch (Exception $error) {
if (!($error instanceof TeaError)) {
$error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
}
// 此处仅做打印展示,请谨慎对待异常处理,在工程项目中切勿直接忽略异常。
// 错误 message
var_dump($error->message);
// 诊断地址
var_dump($error->data["Recommend"]);
Utils::assertAsString($error->message);
}
}
四,报错信息的解决:
1, 报错:
["bizId"]=> NULL
["code"]=> string(23) "isp.RAM_PERMISSION_DENY"
["message"]=> string(73) "RAM权限不足,请为当前使用的AccessKey对应RAM用户进行授权"
解决:为api访问权限的用户添加短信授权即可
标签:use,短信,Utils,接口,Dysmsapi,api,error,php,alibabacloud From: https://www.cnblogs.com/architectforest/p/18317534