Hwsms.php 3.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  1. <?php
  2. namespace tools;
  3. /**
  4. * 华为IoT云通信短息发送类
  5. */
  6. class Hwsms{
  7. private $account; //账号
  8. private $password; //密码
  9. private $host = ''; //接口域名
  10. private $error;
  11. private $sign = ''; // 短信签名
  12. private $templateId = ''; // 短信模板
  13. public function __construct($config=array())
  14. {
  15. $this->account = isset($config['account'])?$config['account']:'';
  16. $this->password = isset($config['password'])?$config['password']:'';
  17. $this->sign = isset($config['sign'])?$config['sign']:'';
  18. $ip = isset($config['ip'])?$config['ip']:'';
  19. $port = isset($config['port'])?$config['port']:'';
  20. $this->templateId = isset($config['templateId'])?$config['templateId']:'';
  21. if(!$this->account){
  22. $this->error = '未设置账号';
  23. return false;
  24. }
  25. if(!$this->password){
  26. $this->error = '未设置密码';
  27. return false;
  28. }
  29. if(!$ip){
  30. $this->error = '未设置IP';
  31. return false;
  32. }
  33. if(!$port){
  34. $this->error = '未设置端口';
  35. return false;
  36. }
  37. if(!$this->sign){
  38. $this->error = '未设置签名';
  39. return false;
  40. }
  41. if(!$this->templateId){
  42. $this->error = '未设置短信模板';
  43. return false;
  44. }
  45. $this->host = 'https://'.$ip.':'.$port;
  46. }
  47. /**
  48. * 发送短信
  49. * @param $mobiles 手机号多个以逗号隔开,最多1000个
  50. * @param $content 短信内容
  51. * @return bool true=发送成功 false=发送失败
  52. */
  53. public function send($mobiles,$templateParas,$statusCallback=''){
  54. if(!$mobiles){
  55. $this->error = '手机号错误';
  56. return false;
  57. }
  58. $url = $this->host.'/common/sms/sendTemplateMessage';
  59. //必填,全局号码格式(不包含国家码),示例:15123456789,多个号码之间用英文逗号分隔
  60. $mobiles = explode(',',$mobiles);//短信接收人号码
  61. //请求Headers
  62. $headers = [
  63. 'Content-Type: application/json;charset=UTF-8'
  64. ];
  65. $requestLists['mobiles']=$mobiles;
  66. $requestLists['templateId']=$this->templateId;
  67. $requestLists['templateParas']=$templateParas;
  68. $requestLists['signature']=$this->sign;
  69. //请求Body
  70. $data['account']=$this->account;
  71. $data['password']=$this->password;
  72. $data['requestLists']=array($requestLists);
  73. $data['statusCallback']=$statusCallback;
  74. $context_options = [
  75. 'http' => ['method' => 'POST', 'header'=> $headers, 'content' => json_encode($data, JSON_UNESCAPED_UNICODE|JSON_PRETTY_PRINT), 'ignore_errors' => true],
  76. 'ssl' => ['verify_peer' => false, 'verify_peer_name' => false] //为防止因HTTPS证书认证失败造成API调用失败,需要先忽略证书信任问题
  77. ];
  78. $response = file_get_contents($url, false, stream_context_create($context_options));
  79. tplog($response);
  80. return $response;
  81. }
  82. public function getError(){
  83. return $this->error;
  84. }
  85. }