SmsService.php 2.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. <?php
  2. /**
  3. * Created by PhpStorm.
  4. * User: gevnc
  5. * Date: 2018/5/17
  6. * Time: 14:47
  7. */
  8. namespace App\Services;
  9. use App\Traits\Singleton;
  10. use Aliyun\Core\Config;
  11. use Aliyun\Core\Profile\DefaultProfile;
  12. use Aliyun\Core\DefaultAcsClient;
  13. use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
  14. use Aliyun\Api\Sms\Request\V20170525\SendBatchSmsRequest;
  15. use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
  16. class SmsService
  17. {
  18. static $acsClient = null;
  19. /**
  20. * 取得AcsClient
  21. *
  22. * @return DefaultAcsClient
  23. */
  24. public static function getAcsClient() {
  25. //产品名称:云通信流量服务API产品,开发者无需替换
  26. $product = "Dysmsapi";
  27. //产品域名,开发者无需替换
  28. $domain = "dysmsapi.aliyuncs.com";
  29. // TODO 此处需要替换成开发者自己的AK (https://ak-console.aliyun.com/)
  30. $accessKeyId = env("ALIYUN_ACCESS_KEY_ID"); // AccessKeyId
  31. $accessKeySecret = env("ALIYUN_ACCESS_KEY_SECRET"); // AccessKeySecret
  32. // 暂时不支持多Region
  33. $region = "cn-hangzhou";
  34. // 服务结点
  35. $endPointName = "cn-hangzhou";
  36. if(static::$acsClient == null) {
  37. //初始化acsClient,暂不支持region化
  38. $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
  39. // 增加服务结点
  40. DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
  41. // 初始化AcsClient用于发起请求
  42. static::$acsClient = new DefaultAcsClient($profile);
  43. }
  44. return static::$acsClient;
  45. }
  46. /**
  47. * 发送短信
  48. * @return stdClass
  49. */
  50. public static function sendSms($phone,$code) {
  51. // 初始化SendSmsRequest实例用于设置发送短信的参数
  52. $request = new SendSmsRequest();
  53. //可选-启用https协议
  54. //$request->setProtocol("https");
  55. // 必填,设置短信接收号码
  56. $request->setPhoneNumbers($phone);
  57. // 必填,设置签名名称,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  58. $request->setSignName(env("SMS_SIGN_NAME"));
  59. // 必填,设置模板CODE,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  60. $request->setTemplateCode(env("SMS_TEMPLATE_CODE"));
  61. // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项
  62. $request->setTemplateParam(json_encode(array( // 短信模板中字段的值
  63. "code"=>$code
  64. ), JSON_UNESCAPED_UNICODE));
  65. // 发起访问请求
  66. $acsResponse = static::getAcsClient()->getAcsResponse($request);
  67. return $acsResponse;
  68. }
  69. }