AliyunSMS.php 3.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. <?php
  2. /**
  3. * Author: 芸众商城 www.yunzshop.com
  4. * Date: 2017/8/29
  5. * Time: 下午7:07
  6. */
  7. namespace app\common\services\aliyun;
  8. use app\common\services\aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
  9. use app\common\services\aliyun\Core\Config;
  10. use app\common\services\aliyun\Core\DefaultAcsClient;
  11. use app\common\services\aliyun\Core\Profile\DefaultProfile;
  12. // 加载区域结点配置
  13. Config::load();
  14. class AliyunSMS
  15. {
  16. /**
  17. * 构造器
  18. *
  19. * @param string $accessKeyId 必填,AccessKeyId
  20. * @param string $accessKeySecret 必填,AccessKeySecret
  21. */
  22. public function __construct($accessKeyId, $accessKeySecret)
  23. {
  24. // 短信API产品名
  25. $product = "Dysmsapi";
  26. // 短信API产品域名
  27. $domain = "dysmsapi.aliyuncs.com";
  28. // 暂时不支持多Region
  29. $region = "cn-hangzhou";
  30. // 服务结点
  31. $endPointName = "cn-hangzhou";
  32. // 初始化用户Profile实例
  33. $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
  34. // 增加服务结点
  35. DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
  36. // 初始化AcsClient用于发起请求
  37. $this->acsClient = new DefaultAcsClient($profile);
  38. }
  39. /**
  40. * 发送短信范例
  41. *
  42. * @param string $signName <p>
  43. * 必填, 短信签名,应严格"签名名称"填写,参考:<a href="https://dysms.console.aliyun.com/dysms.htm#/sign">短信签名页</a>
  44. * </p>
  45. * @param string $templateCode <p>
  46. * 必填, 短信模板Code,应严格按"模板CODE"填写, 参考:<a href="https://dysms.console.aliyun.com/dysms.htm#/template">短信模板页</a>
  47. * (e.g. SMS_0001)
  48. * </p>
  49. * @param string $phoneNumbers 必填, 短信接收号码 (e.g. 12345678901)
  50. * @param array|null $templateParam <p>
  51. * 选填, 假如模板中存在变量需要替换则为必填项 (e.g. Array("code"=>"12345", "product"=>"阿里通信"))
  52. * </p>
  53. * @param string|null $outId [optional] 选填, 发送短信流水号 (e.g. 1234)
  54. * @return stdClass
  55. */
  56. public function sendSms($signName, $templateCode, $phoneNumbers, $templateParam = null, $outId = null) {
  57. // 初始化SendSmsRequest实例用于设置发送短信的参数
  58. $request = new SendSmsRequest();
  59. // 必填,设置雉短信接收号码
  60. $request->setPhoneNumbers($phoneNumbers);
  61. // 必填,设置签名名称
  62. $request->setSignName($signName);
  63. //$request->setRegionId('cn-hangzhou');
  64. // 必填,设置模板CODE
  65. $request->setTemplateCode($templateCode);
  66. // 可选,设置模板参数
  67. if($templateParam) {
  68. $request->setTemplateParam(json_encode($templateParam));
  69. }
  70. // 可选,设置流水号
  71. if($outId) {
  72. $request->setOutId($outId);
  73. }
  74. // 发起访问请求
  75. $acsResponse = $this->acsClient->getAcsResponse($request);
  76. // 打印请求结果
  77. // var_dump($acsResponse);
  78. return $acsResponse;
  79. }
  80. }