<?php

class Sms
{
    private $api_url, $auth_key, $errorMsg;

    function __construct($api_url, $auth_key)
    {
        $this->api_url = $api_url;
        $this->auth_key = $auth_key;
    }

    /**
     * 实现短信验证码接口
     *
     */
    public function sendSms($mobile, $code)
    {
        $send = array(
            'apikey' => $this->auth_key,
            'mobile' => $mobile,
            'text' => $code
        );
        $data = http_build_query($send);
        $res = json_decode($this->_httpClient($this->api_url, $data));
        $resArr = $this->objectToArray($res);
        if (!empty($resArr) && $resArr["code"] == 0) {
            return true;
        } else {
            if (empty($this->errorMsg)) $this->errorMsg = isset($resArr["msg"]) ? $resArr["msg"] : '未知错误';
            return false;
        }
    }

    //对象转数组,使用get_object_vars返回对象属性组成的数组
    function objectToArray($array)
    {
        if (is_object($array)) {
            $array = (array)$array;
        }
        if (is_array($array)) {
            foreach ($array as $key => $value) {
                $array[$key] = $this->objectToArray($value);
            }
        }
        return $array;
    }

    /**
     * POST方式访问短信接口
     * @param string $data
     * @return mixed
     */
    private function _httpClient($api_url, $data)
    {
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept:text/plain;charset=utf-8', 'Content-Type:application/x-www-form-urlencoded', 'charset=utf-8'));
            curl_setopt($ch, CURLOPT_URL, $api_url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, 1);
            curl_setopt($ch, CURLOPT_TIMEOUT, 10);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
            $res = curl_exec($ch);
            curl_close($ch);
            return $res;
        } catch (Exception $e) {
            $this->errorMsg = $e->getMessage();
            return false;
        }
    }

    /**
     * POST方式访问短信接口
     * @param string $data
     * @return mixed
     */
    public function getErrors()
    {
        return $this->errorMsg;
    }
}