sms.php 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. <?php
  2. class Sms
  3. {
  4. private $api_url, $account, $password, $extno, $errorMsg;
  5. function __construct($api_url, $account,$password,$extno)
  6. {
  7. $this->api_url = $api_url;
  8. $this->account = $account;
  9. $this->password = $password;
  10. $this->extno = $extno;
  11. }
  12. /**
  13. * 实现短信验证码接口
  14. *
  15. */
  16. public function sendSms($mobile, $code)
  17. {
  18. $send = array(
  19. 'action' => 'send',
  20. 'account' => $this->account,
  21. 'password' => $this->password,
  22. 'mobile' => $mobile,
  23. 'content' => $code,
  24. 'extno' => $this->extno
  25. );
  26. $data = http_build_query($send);
  27. $res = simplexml_load_string($this->_httpClient($this->api_url,$data));
  28. $resArr = $this->objectToArray($res);
  29. $resultcode = !empty($resArr) ? explode('#@#',$resArr['resplist']['resp'])[2] : '';
  30. if ($resultcode == '0') return true;
  31. else {
  32. if (empty($this->errorMsg)) $this->errorMsg = !empty($resultcode) ? $this->getErrorMsg($resultcode) : '未知错误';
  33. return false;
  34. }
  35. }
  36. function getErrorMsg($code){
  37. $msg = '';
  38. switch($code){
  39. case 6: $msg = '错误代码:6,请联系我们客服';break;
  40. case 10: $msg = '错误代码:10,请联系我们客服';break;
  41. case 12: $msg = '检查接收短信手机号码格式是否正确';break;
  42. case 15: $msg = '错误代码:15,请联系我们客服';break;
  43. case 16: $msg = '一天时间内同一个手机号码不能太频繁接收短信';break;
  44. case 17: $msg = '错误代码:17,请联系我们客服';break;
  45. default : $msg = '错误代码:400,请联系我们客服';break;
  46. }
  47. return $msg;
  48. }
  49. //对象转数组,使用get_object_vars返回对象属性组成的数组
  50. function objectToArray($array)
  51. {
  52. if (is_object($array)) {
  53. $array = (array)$array;
  54. }
  55. if (is_array($array)) {
  56. foreach ($array as $key => $value) {
  57. $array[$key] = $this->objectToArray($value);
  58. }
  59. }
  60. return $array;
  61. }
  62. /**
  63. * POST方式访问短信接口
  64. * @param string $data
  65. * @return mixed
  66. */
  67. private function _httpClient($api_url, $data)
  68. {
  69. try {
  70. $ch = curl_init();
  71. curl_setopt($ch, CURLOPT_URL,$api_url.$data);
  72. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  73. curl_setopt($ch, CURLOPT_HEADER, 0);
  74. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  75. $res = curl_exec($ch);
  76. curl_close($ch);
  77. return $res;
  78. } catch (Exception $e) {
  79. $this->errorMsg = $e->getMessage();
  80. return false;
  81. }
  82. }
  83. /**
  84. * POST方式访问短信接口
  85. * @param string $data
  86. * @return mixed
  87. */
  88. public function getErrors()
  89. {
  90. return $this->errorMsg;
  91. }
  92. }