<?php
namespace app\index\controller;
use think\facade\Request;
use think\facade\View;
use think\facade\Session;

class Sms extends Base{
	
	//腾讯短信接口str
	function send_tx(){		
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();
		
		if(strlen($tdata['phone'])!="11" or is_numeric($tdata['phone'])==false) {
			$data =['type' =>1,'msg' =>'手机号码错误!'];
			return json($data);
		}

        $appid =1400625657;  //自己的短信appid
        $appkey = "3ac0fdcb6ec6123902ee1a4e93faac5b"; //自己的短信appkey
		$sign = "北京银符";//模板签名信息
		$templId =1282955; //自己短信模板id
		
		$nationCode=86;//地区
		$phoneNumber=$tdata['phone'];
        $random = rand(100000, 999999);//生成随机数

		Session::set('sms_sjh',$phoneNumber);
		Session::set('sms_yzm',$random);
				
		$params[0] = $random;//参数,一般为随机码
        $curTime = time();
        $wholeUrl = "https://yun.tim.qq.com/v5/tlssmssvr/sendsms". "?sdkappid=" . $appid . "&random=" . $random;
		
        // 按照协议组织 post 包体
        $data = new \stdClass();//创建一个没有成员方法和属性的空对象
        $tel = new \stdClass();
        $tel->nationcode = "".$nationCode;
        $tel->mobile = "".$phoneNumber;
        $data->tel = $tel;
        $data->sig=hash("sha256", "appkey=".$appkey."&random=".$random."&time=".$curTime."&mobile=".$phoneNumber);// 生成签名
        $data->tpl_id = $templId;
        $data->params = $params;
        $data->sign = $sign;
        $data->time =time();
        $data->extend ='';
        $data->ext ='';
		
		$this->sendCurlPost($wholeUrl, $data);		
		$data =['type' =>'OK','msg' =>'发送成功!'];
		return json($data);
	}

	function sendCurlPost($url, $dataObj){
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
        curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($dataObj));
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        $ret = curl_exec($curl);
        if (false == $ret) {
            // curl_exec failed
            $result = "{ \"result\":" . -2 . ",\"errmsg\":\"" . curl_error($curl) . "\"}";
        } else {
            $rsp = curl_getinfo($curl, CURLINFO_HTTP_CODE);
            if (200 != $rsp) {
                $result = "{ \"result\":" . -1 . ",\"errmsg\":\"". $rsp
                        . " " . curl_error($curl) ."\"}";
            } else {
                $result = $ret;
            }
        }
        curl_close($curl);
        return $result;
	}
	//腾讯短信接口end


	//天晴中乎短信接口str
	function send_tq(){		
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();

		Session::delete('sms_phone');
		Session::delete('sms_rand');
		
		if($tdata['b']==''){
			if(strlen($tdata['phone'])!="11" or is_numeric($tdata['phone'])==false) {
				$data =['type' =>1,'msg' =>'手机号码错误!'];
				return json($data);
			}
		}
		
		if($tdata['b']!=''){
			$map['name']=$tdata['name'];
			$map['password']=pass_encrypt($tdata['password']);
			$is_phone=\app\index\model\User::where($map)->field('id,is_effect,phone')->select();
			if($is_phone[0]['id']==''){
				$data =['type' =>1,'msg' =>'账号或密码错误,请重新输入!'];
				return json($data);
			}
		}
		
		$is_true=\app\index\model\User::where('phone',$tdata['phone'])->field('phone')->find();
		if($is_true!='' and $tdata['b']==''){
			$data =['type' =>1,'msg' =>'该号码已注册!'];
			return json($data);
		}

		if($tdata['b']!=''){
			$Destinations=$is_phone[0]['phone'];
		}else{
			$Destinations=$tdata['phone'];
		}
		

		$post_data = array();
		$post_data['action'] ="send";//账号
		$post_data['userid'] ="335";//账号
		$post_data['account'] ="zscq";//账号
		$post_data['password'] ="zscq4821085";//密码
		$post_data['mobile'] =$Destinations;//手机
		$sms_rand=rand(100000,999999);
		$post_data['content'] ="【工行杯大赛】您的2022工行杯全国大学生金融科技创新大赛验证码为：".$sms_rand."，请您不要泄露给其他人，若非本人操作请忽略该短信。";
		
		Session::set('sms_rand',$sms_rand);
		Session::set('sms_phone',$Destinations);
		
		$post_data['sendtime'] =''; //不定时发送，值为0，定时发送，输入格式YYYYMMDDHHmmss的日期值
		//$url='http://smshttp.k400.cc/SendSMS.aspx';
		$url='http://maiyuan.400work.com:8888/sms.aspx';
		$o='';
		
		foreach ($post_data as $k=>$v){
			$o.="$k=".urlencode($v).'&';
		}
		
		$post_data=substr($o,0,-1);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
		$result = curl_exec($ch);
		
		$list=json_decode($result,true);
		$return_code=explode(':',$list['Result']);
		$xml = simplexml_load_string($result);
		$json = json_encode($xml);
		//由json转化为数组类型
		$new_xml = json_decode($json,true);
		$data =['type' =>1,'msg' =>$new_xml['message']];
		return json($data);
		
	}
	//天晴中乎短信接口end



	//阿里云短信接口str
	function aly_request($accessKeyId, $accessKeySecret, $domain, $params, $security=false) {
		$apiParams = array_merge(array (
			"SignatureMethod" => "HMAC-SHA1",
			"SignatureNonce" => uniqid(mt_rand(0,0xffff), true),
			"SignatureVersion" => "1.0",
			"AccessKeyId" => $accessKeyId,
			"Timestamp" => gmdate("Y-m-d\TH:i:s\Z"),
			"Format" => "JSON",
		), $params);
		ksort($apiParams);
		$sortedQueryStringTmp = "";
		foreach ($apiParams as $key => $value) {
			$sortedQueryStringTmp .= "&" . $this->encode($key) . "=" . $this->encode($value);
		}
		$stringToSign = "GET&%2F&" . $this->encode(substr($sortedQueryStringTmp, 1));
		$sign = base64_encode(hash_hmac("sha1", $stringToSign, $accessKeySecret . "&",true));
		$signature = $this->encode($sign);
		$url = ($security ? 'https' : 'http')."://{$domain}/?Signature={$signature}{$sortedQueryStringTmp}";
		try {
			$content = $this->fetchContent($url);
			return json_decode($content);
		} catch( \Exception $e) {
			return false;
		}
	}
	
	function encode($str){
		$res = urlencode($str);
		$res = preg_replace("/\+/", "%20", $res);
		$res = preg_replace("/\*/", "%2A", $res);
		$res = preg_replace("/%7E/", "~", $res);
		return $res;
	}
	
	function fetchContent($url) {
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $url);
		curl_setopt($ch, CURLOPT_TIMEOUT, 5);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("x-sdk-client" => "php/2.0.0"));

		if(substr($url, 0,5) == 'https') {
			curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
			curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
		}

		$rtn = curl_exec($ch);

		if($rtn === false) {
			trigger_error("[CURL_" . curl_errno($ch) . "]: " . curl_error($ch), E_USER_ERROR);
		}
		curl_close($ch);

		return $rtn;
	}

	function send_aliyun(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();

		Session::delete('sms_phone');
		Session::delete('sms_rand');
		
		if($tdata['b']==''){
			if(strlen($tdata['phone'])!="11" or is_numeric($tdata['phone'])==false) {
				$data =['type' =>1,'msg' =>'手机号码错误!'];
				return json($data);
			}
		}
		
		if($tdata['b']!=''){
			$map['name']=$tdata['name'];
			$map['password']=pass_encrypt($tdata['password']);
			$is_phone=\app\index\model\User::where($map)->field('id,is_effect,phone')->select();
			if($is_phone[0]['id']==''){
				$data =['type' =>1,'msg' =>'账号或密码错误,请重新输入!'];
				return json($data);
			}
		}
		
		$is_true=\app\index\model\User::where('phone',$tdata['phone'])->field('phone')->find();
		if($is_true!='' and $tdata['b']==''){
			$data =['type' =>1,'msg' =>'该号码已注册!'];
			return json($data);
		}

		if($tdata['b']!=''){
			$mobile=$is_phone[0]['phone'];
		}else{
			$mobile=$tdata['phone'];
		}
		$sms_rand=rand(100000,999999);
		
		$TemplateParam=array();
		$TemplateCode = 'SMS_153815075';
		$params=array();
		// *** 需用户填写部分 ***
		// fixme 必填: 请参阅 https://ak-console.aliyun.com/ 取得您的AK信息
		$accessKeyId = "LTAI5tLyFzczycmJRYB4Rpp6";
		$accessKeySecret = "YeejVRFAz3qL53usUmuSi7bFcMz2Wd";

		// fixme 必填: 短信接收号码
		$params["PhoneNumbers"] = $mobile;
		// fixme 必填: 短信签名，应严格按"签名名称"填写，请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/sign
		$params["SignName"] = "内蒙古知识产权保护中心";
		// fixme 必填: 短信模板Code，应严格按"模板CODE"填写, 请参考: https://dysms.console.aliyun.com/dysms.htm#/develop/template
		$params["TemplateCode"] = $TemplateCode;
	
		// fixme 可选: 设置模板参数, 假如模板中存在变量需要替换则为必填项
		$params['TemplateParam'] = Array (
			"code" => $sms_rand,
		);

		// fixme 可选: 设置发送短信流水号
		$params['OutId'] = "";

		// fixme 可选: 上行短信扩展码, 扩展码字段控制在7位或以下，无特殊需求用户请忽略此字段
		$params['SmsUpExtendCode'] = "";

		// *** 需用户填写部分结束, 以下代码若无必要无需更改 ***
		if(!empty($params["TemplateParam"]) && is_array($params["TemplateParam"])) {
			$params["TemplateParam"] = json_encode($params["TemplateParam"], JSON_UNESCAPED_UNICODE);
		}
		// 初始化SignatureHelper实例用于设置参数，签名以及发送请求

		// 此处可能会抛出异常，注意catch
		$content = $this->aly_request(
			$accessKeyId,
			$accessKeySecret,
			"dysmsapi.aliyuncs.com",
			array_merge($params, array(
				"RegionId" => "cn-hangzhou",
				"Action" => "SendSms",
				"Version" => "2017-05-25",
			))
			// fixme 选填: 启用https
			// ,true
		);
		
		//error_log(print_r($content,1)."\r\n",3,'smsdata.log');
		
		Session::set('sms_rand',$sms_rand);
		Session::set('sms_phone',$mobile);
		$data =['type' =>$content->Code,'msg' =>$content->Message];
		return json($data);
		
	}
	//阿里云短信接口end


	//天晴新短信接口str
	function send_tq1(){
		IS_AJAX(Request::isAjax());
		$tdata=Request::param();

		$Destinations=$tdata['phone'];
		Session::delete('sms_phone');
		Session::delete('sms_rand');

		if(strlen($tdata['phone'])!="11" or is_numeric($tdata['phone'])==false) {
			$data =['type' =>1,'msg' =>'手机号码错误!'];
			return json($data);
		}
		$is_true=\app\index\model\User::is_true($tdata['phone']);
		if($is_true['id']!='' and $tdata['b']==''){
			$data =['type' =>1,'msg' =>'该号码已注册!'];
			return json($data);
		}
		if($is_true['id']=='' and $tdata['b']!=''){
			$data =['type' =>1,'msg' =>'号码错误请输入正确的手机号码!'];
			return json($data);
		}

		$post_data = array();
		$post_data['uid'] ="tqcy_ghb";//账号
		$post_data['pwd'] ="tqcy4821085";//账号
		$post_data['tos'] =$Destinations;//手机
		$sms_rand=rand(100000,999999);
		$post_data['msg'] ="【工行杯大赛】您的2022工行杯全国大学生金融科技创新大赛验证码为：".$sms_rand."，请您不要泄露给其他人，若非本人操作请忽略该短信。";
		$post_data['otime'] ='';
		//不定时发送，值为0，定时发送，输入格式YYYYMMDDHHmmss的日期值
		
		Session::set('sms_rand',$sms_rand);
		Session::set('sms_phone',$Destinations);
		
		$one=substr ($Destinations,0,1);//等于0为港澳台
		if($one==8){
			$url='http://service2.winic.org/service.asmx/SendInternationalMessages?';
		}else{
			$url='http://service2.winic.org/service.asmx/SendMessages?';
		}
		$o='';
		
		foreach ($post_data as $k=>$v){
			$o.="$k=".urlencode($v).'&';
		}
		$post_data=substr($o,0,-1);
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_URL,$url);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); //如果需要将结果直接返回到变量里，那加上这句。
		$result = curl_exec($ch);
		$xml = simplexml_load_string($result);
		$json = json_encode($xml);
		//由json转化为数组类型
		$new_xml = json_decode($json,true);
		$type=strlen($new_xml[0]);
		if($type>11){
			$type=1;
		}else{
			$type=0;
		}
		
		$data =['type' =>$type,'msg' =>$new_xml[0]];
		return json($data);
	}
	//天晴新短信接口end		
		
}