<?php
/**
 * @description 发送短信
 * @version 1.0.1
 */
namespace Wd;
class Sms{
	
	public function __construct($config=array()){
    	foreach ($config as $k => $v) {
    		$this->$k=$v;
    	}
    }
	
	/**
	 * @description 阿里云短信
	 * @author 建站宝  QQ 613600010
	 * @param $tplparam array 发送内容参数，注意转换为字符串
	 * @param $mobile string 目标手机号,多条记录可以英文逗号分隔
	 * @param $sign string 签名名称
	 * @param $tpl string 模板CODE
	 * @return json
	 * @example
	 *  $sms=new \Wd\Sms(array(
	 		'accessKeyId'=>'aaaaaa',
	    	'accessKeySecret'=>'bbbbbbbb',
	 	));
		$data=array(
			'mobile'=>'13333333333',
			'sign'=>'问鼎科技',
			'tpl'=>'SMS_12345678',
			'tplparam'=>array('code'=>(string)rand(100000, 999999)),
		);
		$re=$sms->aliyun($data);
	 */
	public function aliyun($data){
		$params = array ();
		
	    $accessKeyId = $data['accessKeyId']?$data['accessKeyId']:'LTAIryeee7IQMLo7';
	    $accessKeySecret = $data['accessKeySecret']?$data['accessKeySecret']:'RZkHlipUBi5kZVK56lNmCiHi82hl7p';
	
	    $params["PhoneNumbers"] = $data['mobile'];
	    $params["SignName"] = $data['sign'];
	    $params["TemplateCode"] = $data['tpl'];
	    $params['TemplateParam'] = $data['tplparam'];
	    if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
	        $params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
	    }
	    $helper = new \aliyun\SignatureHelper();
	    $content = $helper->request(
	        $accessKeyId,
	        $accessKeySecret,
	        "dysmsapi.aliyuncs.com",
	        array_merge($params, array(
	            "RegionId" => "cn-hangzhou",
	            "Action" => "SendSms",
	            "Version" => "2017-05-25",
	        ))
	    );
	    return $content;
	}
	
	function http($url, $param=array(), $data =array(), $method = 'GET',$header=''){
		$opts = array(
	        CURLOPT_TIMEOUT        => 30,
	        CURLOPT_RETURNTRANSFER => 1,
	        CURLOPT_SSL_VERIFYPEER => false,
	        CURLOPT_SSL_VERIFYHOST => false,
	    );
	
	    /* 根据请求类型设置特定参数 */
	    $opts[CURLOPT_URL] = empty($param)?$url:$url . '?' . http_build_query($param);
	
	    if(strtoupper($method) == 'POST'){
	        $opts[CURLOPT_POST] = 1;
	        $opts[CURLOPT_POSTFIELDS] = $data;
	    }
		if($header){
			$header=is_array($header)?$header:array($header);
		    $opts[CURLOPT_HTTPHEADER] = array(
	            'Content-Type: application/json; charset=utf-8',  
	        );
			if(is_string($data)){
			    array_push($opts[CURLOPT_HTTPHEADER],'Content-Length: ' . strlen($data));
			}
			$opts[CURLOPT_HTTPHEADER] = array_merge($opts[CURLOPT_HTTPHEADER], $header);
		}
	    /* 初始化并执行curl请求 */
	    $ch = curl_init();
	    curl_setopt_array($ch, $opts);
	    $data  = curl_exec($ch);
	    $error = curl_error($ch);
	    curl_close($ch);
	
	    return  $data;
	}
}