Aliyunsms.php 3.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. require_once 'api_sdk/vendor/autoload.php';
  3. use Aliyun\Core\Config;
  4. use Aliyun\Core\Profile\DefaultProfile;
  5. use Aliyun\Core\DefaultAcsClient;
  6. use Aliyun\Api\Sms\Request\V20170525\SendSmsRequest;
  7. use Aliyun\Api\Sms\Request\V20170525\SendBatchSmsRequest;
  8. use Aliyun\Api\Sms\Request\V20170525\QuerySendDetailsRequest;
  9. // 加载区域结点配置
  10. Config::load();
  11. /**
  12. * Class Aliyunsms
  13. *
  14. * 阿里云短信发送
  15. */
  16. class Aliyunsms
  17. {
  18. private $CI;
  19. private $setting;
  20. static $acsClient = null;
  21. function __construct()
  22. {
  23. $this->CI = & get_instance();
  24. $this->CI->load->driver('cache', array('adapter' => 'apc', 'backup' => 'file'));
  25. $this->setting = $this->CI->cache->get('setting');
  26. }
  27. /**
  28. * 取得AcsClient
  29. *
  30. * @return DefaultAcsClient
  31. */
  32. private function getAcsClient() {
  33. //产品名称:云通信流量服务API产品,开发者无需替换
  34. $product = "Dysmsapi";
  35. //产品域名,开发者无需替换
  36. $domain = "dysmsapi.aliyuncs.com";
  37. $accessKeyId = $this->setting['access_key_id']; // AccessKeyId
  38. $accessKeySecret = $this->setting['access_key_secret'];; // AccessKeySecret
  39. // 暂时不支持多Region
  40. $region = "cn-hangzhou";
  41. // 服务结点
  42. $endPointName = "cn-hangzhou";
  43. if(static::$acsClient == null) {
  44. //初始化acsClient,暂不支持region化
  45. $profile = DefaultProfile::getProfile($region, $accessKeyId, $accessKeySecret);
  46. // 增加服务结点
  47. DefaultProfile::addEndpoint($endPointName, $region, $product, $domain);
  48. // 初始化AcsClient用于发起请求
  49. static::$acsClient = new DefaultAcsClient($profile);
  50. }
  51. return static::$acsClient;
  52. }
  53. /**
  54. * 发送短信
  55. * @return stdClass
  56. */
  57. public function sendSms($phone,$template_code,$content) {
  58. if(is_array($content)){
  59. // 初始化SendSmsRequest实例用于设置发送短信的参数
  60. $request = new SendSmsRequest();
  61. //可选-启用https协议
  62. //$request->setProtocol("https");
  63. // 必填,设置短信接收号码
  64. $request->setPhoneNumbers($phone);
  65. // 必填,设置签名名称,应严格按"签名名称"填写,请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
  66. $request->setSignName($this->setting['sign_name']);
  67. // 必填,设置模板CODE,应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
  68. $request->setTemplateCode($template_code);
  69. // 可选,设置模板参数, 假如模板中存在变量需要替换则为必填项
  70. $request->setTemplateParam(json_encode($content), JSON_UNESCAPED_UNICODE);
  71. // 发起访问请求
  72. try {
  73. $acsResponse = $this->getAcsClient()->getAcsResponse($request);
  74. return (array)$acsResponse;
  75. }catch (Exception $e) {
  76. return array("Code"=>"FAILED" , "Message"=>$e->getErrorMessage());
  77. }
  78. }else{
  79. return array("Code"=>"FAILED","Message"=>"参数错误");
  80. }
  81. }
  82. }