Aliyun.php 2.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. <?php
  2. namespace app\common\library\sms\engine;
  3. use app\common\library\sms\package\aliyun\SignatureHelper;
  4. /**
  5. * 阿里云短信模块引擎
  6. */
  7. class Aliyun extends Server
  8. {
  9. private $config;
  10. /**
  11. * 构造方法
  12. */
  13. public function __construct($config)
  14. {
  15. $this->config = $config;
  16. }
  17. /**
  18. * 发送短信通知
  19. */
  20. public function sendSms($mobile, $template_code, $templateParams)
  21. {
  22. if(empty($template_code)){
  23. return false;
  24. }
  25. $params = [];
  26. // *** 需用户填写部分 ***
  27. // 必填: 短信接收号码
  28. $params["PhoneNumbers"] = $mobile;
  29. // 必填: 短信签名,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  30. $params["SignName"] = $this->config['sign'];
  31. // 必填: 短信模板Code,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  32. $params["TemplateCode"] = $template_code;
  33. // 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
  34. $params['TemplateParam'] = $templateParams;
  35. // 可选: 设置发送短信流水号
  36. // $params['OutId'] = "12345";
  37. // 可选: 上行短信扩展码, 扩展码字段控制在7位或以下,无特殊需求用户请忽略此字段
  38. // $params['SmsUpExtendCode'] = "1234567";
  39. // *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
  40. if (!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
  41. $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
  42. }
  43. // 初始化SignatureHelper实例用于设置参数,签名以及发送请求
  44. $helper = new SignatureHelper;
  45. // 此处可能会抛出异常,注意catch
  46. $response = $helper->request(
  47. $this->config['AccessKeyId']
  48. , $this->config['AccessKeySecret']
  49. , "dysmsapi.aliyuncs.com"
  50. , array_merge($params, [
  51. "RegionId" => "cn-hangzhou",
  52. "Action" => "SendSms",
  53. "Version" => "2017-05-25",
  54. ])
  55. // 选填: 启用https
  56. , true
  57. );
  58. // 记录日志
  59. log_write([
  60. 'config' => $this->config,
  61. 'params' => $params
  62. ]);
  63. log_write($response);
  64. $this->error = $response->Message;
  65. return $response->Code === 'OK';
  66. }
  67. }