SmsSend.php 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. namespace common\libs\api\sms\meilian;
  3. use yii\helpers\Json;
  4. use yii\httpclient\Client;
  5. class SmsSend
  6. {
  7. private $_username;
  8. private $_password;
  9. private $_apikey;
  10. private $_url='https://m.5c.com.cn/api/send/index.php';
  11. private $_encode='UTF-8';
  12. private $_client;
  13. private $_response;
  14. private $_error = [];
  15. private $_errorCode;
  16. public function __construct($username, $password, $apikey) {
  17. $this->_username = $username;
  18. $this->_password = $password;
  19. $this->_apikey = $apikey;
  20. $this->_errorCode = require \Yii::getAlias('@common/libs/api/sms/meilian/') . 'errorCode.php';
  21. }
  22. public function getError(){
  23. return $this->_error;
  24. }
  25. public function send(array $params) {
  26. $this->_error = null;
  27. if($this->_client === null) {
  28. $this->_client = new Client();
  29. }
  30. $data = [
  31. 'type' => 'send',
  32. 'apikey' => $this->_apikey,
  33. 'username' => $this->_username,
  34. 'password_md5' => md5($this->_password),
  35. 'encode' => $this->_encode,
  36. 'mobile' => $params['mobiles'],
  37. 'content' => urlencode($params['content']),
  38. ];
  39. $sendData = [
  40. 'format' => 'json',
  41. 'data' => Json::encode($data),
  42. ];
  43. $this->_response = $this->_client->createRequest()
  44. ->setMethod('post')
  45. ->setUrl($this->_url)
  46. ->setData($sendData)
  47. ->send();
  48. if(!$this->_response->isOk){
  49. $this->_error[] = '网络错误,短信发送失败';
  50. return false;
  51. }
  52. if($this->_response->data['status'] == 'error'){
  53. $errKey = $this->_response->data['msg'];
  54. if(isset($this->_errorCode[$errKey])){
  55. $this->_error[] = $this->_errorCode[$errKey];
  56. } else {
  57. $this->_error[] = $errKey;
  58. }
  59. return false;
  60. }
  61. unset($data);
  62. return true;
  63. }
  64. }