1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192 |
- <?php
- declare(strict_types=1);
- namespace App\Master\Framework\Library\AliCloud;
- use AlibabaCloud\SDK\Dysmsapi\V20170525\Dysmsapi;
- use App\Master\Framework\Library\Library;
- use AlibabaCloud\Tea\Exception\TeaError;
- use Darabonba\OpenApi\Models\Config;
- use AlibabaCloud\SDK\Dysmsapi\V20170525\Models\SendSmsRequest;
- use AlibabaCloud\Tea\Utils\Utils\RuntimeOptions;
- class AliSms extends Library
- {
- private string $AccessKeyId;//id
- private string $AccessSecret;//key
- private string $SignName;//短信签名
- private array $type = [
- 1 => 'SMS_469005749',// 验证码 code
- 2 => 'SMS_473780055',// 预约提前三小时提醒 string:name,int:time
- 3 => 'SMS_473155011',// 订单被接单提醒 string:time
- 4 => 'SMS_473005012',// 订单取消通知
- ];
- /**
- * 实例化
- */
- public function __construct()
- {
- // 获取配置信息
- $this->AccessKeyId = (string)site('ali_access_key_id');
- $this->AccessSecret = (string)site('ali_access_secret');
- $this->SignName = (string)site('ali_sign_name');
- }
- /**
- * 使用AK&SK初始化账号Client
- * @return Dysmsapi Client
- */
- public function createClient(){
- // 工程代码泄露可能会导致 AccessKey 泄露,并威胁账号下所有资源的安全性。以下代码示例仅供参考。
- // 建议使用更安全的 STS 方式,更多鉴权访问方式请参见:https://help.aliyun.com/document_detail/311677.html。
- $config = new Config([
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_ID。
- "accessKeyId" => $this->AccessKeyId,
- // 必填,请确保代码运行环境设置了环境变量 ALIBABA_CLOUD_ACCESS_KEY_SECRET。
- "accessKeySecret" => $this->AccessSecret
- ]);
- // Endpoint 请参考 https://api.aliyun.com/product/Dysmsapi
- $config->endpoint = "dysmsapi.aliyuncs.com";
- return new Dysmsapi($config);
- }
- /**
- * 发送短信
- * @param string $mobile
- * @param array $authData
- * @return bool
- */
- public function send(string $mobile, array $authData,int $type = 1): bool
- {
- if (!isset($this->type[$type])){
- return $this->error('短信模板类型有误');
- }
- $client = $this->createClient();
- $sendSmsRequest = new SendSmsRequest([
- "phoneNumbers" => $mobile,
- "signName" => $this->SignName,
- "templateCode" => $this->type[$type],
- "templateParam" => !empty($authData) ? json_encode($authData, JSON_UNESCAPED_UNICODE) : ''
- ]);
- try {
- // 复制代码运行请自行打印 API 的返回值
- $res = $client->sendSmsWithOptions($sendSmsRequest, new RuntimeOptions([]));
- } catch (\Exception $error) {
- if (!($error instanceof TeaError)) {
- $error = new TeaError([], $error->getMessage(), $error->getCode(), $error);
- }
- // 错误 message $error->message
- // 诊断地址 $error->data["Recommend"]
- return $this->error($error->message,$error->data);
- }
- if ($res->body->code != 'OK'){
- return $this->error($res->body->message);
- }
- return $this->success('发送成功');
- }
- }
|