sms.php 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. <?php
  2. class Sms
  3. {
  4. private $api_url, $auth_key, $errorMsg;
  5. function __construct($api_url, $auth_key)
  6. {
  7. $this->api_url = $api_url;
  8. $this->auth_key = $auth_key;
  9. }
  10. /**
  11. * 实现短信验证码接口
  12. *
  13. */
  14. public function sendSms($mobile, $code)
  15. {
  16. $send = array(
  17. 'apikey' => $this->auth_key,
  18. 'mobile' => $mobile,
  19. 'text' => $code
  20. );
  21. $data = http_build_query($send);
  22. $res = json_decode($this->_httpClient($this->api_url,$data));
  23. $resArr = $this->objectToArray($res);
  24. if (!empty($resArr) && $resArr["code"] == 0) return true;
  25. else {
  26. if (empty($this->errorMsg)) $this->errorMsg = !empty($resArr["msg"]) ? $resArr["msg"] : '未知错误';
  27. return false;
  28. }
  29. }
  30. //对象转数组,使用get_object_vars返回对象属性组成的数组
  31. function objectToArray($array)
  32. {
  33. if (is_object($array)) {
  34. $array = (array)$array;
  35. }
  36. if (is_array($array)) {
  37. foreach ($array as $key => $value) {
  38. $array[$key] = $this->objectToArray($value);
  39. }
  40. }
  41. return $array;
  42. }
  43. /**
  44. * POST方式访问短信接口
  45. * @param string $data
  46. * @return mixed
  47. */
  48. private function _httpClient($api_url, $data)
  49. {
  50. try {
  51. $ch = curl_init();
  52. curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
  53. curl_setopt($ch, CURLOPT_URL, $api_url);
  54. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  55. curl_setopt($ch, CURLOPT_POST, 1);
  56. curl_setopt($ch, CURLOPT_TIMEOUT, 10);
  57. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
  58. curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
  59. $res = curl_exec($ch);
  60. curl_close($ch);
  61. return $res;
  62. } catch (Exception $e) {
  63. $this->errorMsg = $e->getMessage();
  64. return false;
  65. }
  66. }
  67. /**
  68. * POST方式访问短信接口
  69. * @param string $data
  70. * @return mixed
  71. */
  72. public function getErrors()
  73. {
  74. return $this->errorMsg;
  75. }
  76. }