<?php
namespace XYCms;
use think\facade\Cache;
use think\Exception;
use helper\URL;
class Sms{
    private $_key='';
    private $_secret='';
    private $_sendsms_url='https://open.xycms.com/sms/send';
    public $msg='';
    public $phone='';
    /**
     * 构造函数，
     * 读取配置
     */
    function __construct()
    {
        $this->_key         =   Cache::get('xy_xycms.key');
        $this->_secret      =   Cache::get('xy_xycms.secret');
        $this->_time        =   time();
    }
    public function sendSms()
    {
        if (!$this->_key)
            throw new Exception('应用KEY不能为空');
        if (!$this->_secret)
            throw new Exception('应用Secret不能为空');
        $this->_signature       =   md5($this->_key.$this->_time.$this->_secret);
        $data=[
            'key'                   =>  $this->_key,
            'time'                  =>  $this->_time,
            'signature'             =>  $this->_signature,
            'msg'                   =>  $this->msg,
            'phone'                 =>  $this->phone,
        ];
        $ret=URL::post($this->_sendsms_url,json_encode($data));
        $ret=empty($ret)?null:json_decode($ret,true);
        if ($ret&&isset($ret['code'])){
            if ($ret['code']==0)
                return true;
            throw new Exception($ret['msg'].'['.$ret['code'].']');
        }
        throw new Exception('发送失败，请重试');
    }
}