<?php

namespace App\Libs\Pay\Merchants;

use GuzzleHttp\Client;

class XiaoxiaoPay {

	private $merchant_key;
	private $merchant_id;
	private $appId;
	function __construct()
	{
		$this->merchant_key = '5wMfGYxF92XN7cL';
		$this->merchant_id = '10001034';
	}

	//生成订单
	function send($trade_no,$fee=1,$ip="192.168.1.21",$return_url)
	{
		global $orderUrl, $appkey, $platpkey,$merchantID,$md5key;
		#请求参数
		$SignArr = array(
			'merchantID'=>	$this->merchant_id,							//商户号
			'waresname'	=>	'充值',									//商品名称
			'cporderid'	=>	$trade_no,							//商家订单号，请确保订单号唯一
			'price'		=>	$fee/100,									//订单金额，单位：元
			'returnurl'	=>	$return_url,			//同步通知地址，支付成功之后跳转地址
			'notifyurl'	=>	'http://pay.iycdm.com/callback/xiaoxiaoPay',			//异步通知地址，请保证为完整链接，通知地址后不带任何参数
			'paytype'	=>	10003,									//支付方式
			//'ext'		=>	$openid,								//授权登录获取的openid
			'ip'		=>	$ip										//用户ip
		);	
		//组装请求报文  对数据签名		
		 $reqData = composeMd5($SignArr, $md5key);	//生成含md5签名的请求数据
		//$reqData		=	composeRsa($SignArr, $appkey);	//生成含rsa签名的请求数据
		
		$reqData .= '&iscashier=1';//公众号独立通道需添加此参数
		
		//发送到小小贝服务后台请求调起支付
		$paymentData  	= 	HttpPost($orderUrl,$reqData);
		//验签数据并且解析返回报文
		if(!parseRespRsa($paymentData,$platpkey)) {
			echo $paymentData;
		}else{
			//解析返回报文
			$callback 		=	json_decode($paymentData);	
			//支付调起成功之后获取 支付链接
			$url			=	$callback->info->payurl;
			//此页面必须在申请时填写的支付授权目录下
			echo '<script>
					function onBridgeReady(){
					   WeixinJSBridge.invoke(
						   "getBrandWCPayRequest",'.$url.',
						   function(res){	   
							   if(res.err_msg == "get_brand_wcpay_request:ok" ) {
								   alert("支付成功");
							   }
						   }
					   ); 
					}
						if (typeof WeixinJSBridge == "undefined"){
					   if( document.addEventListener ){
						   document.addEventListener("WeixinJSBridgeReady", onBridgeReady, false);
					   }else if (document.attachEvent){
						   document.attachEvent("WeixinJSBridgeReady", onBridgeReady); 
						   document.attachEvent("onWeixinJSBridgeReady", onBridgeReady);
					   }
					}else{
					   onBridgeReady();
					}
					document.ontouchstart = function(){onBridgeReady();};
				</script>';	
		}






		$client = new client(['base_uri'=>'http://api.ulopay.com/','timeout'=>20]);
		$data = [
			'trade_type'=>'trade.weixin.jspay',
			'mch_id'=>$this->merchant_id,
			'out_trade_no'=>$trade_no,
			'body'=>'充值',
			'total_fee'=>1,
			'spbill_create_ip'=>$ip,
			'notify_url'=>env('PAY_NOFITY_URL'),
			'nonce_str'=>md5(time()),
			'return_url'=>$return_url
		];
		$data['sign'] = $this->sign($data);
		$response = $client->request('POST',"pay/unifiedorder",['body'=>arrayToXml($data)])->getBody()->getContents();
		return $this->getPayInfo($response);
	}

	function sign($params) 
	{
		$signPars = "";
		ksort($params);
		foreach($params as $k => $v) {
			if("" != $v && "sign" != $k) {
				$signPars .= $k . "=" . $v . "&";
			}
		}
		$signPars .= "key=".$this->merchant_key;
		$sign = strtoupper(md5($signPars));
		return $sign;
	}	

	function composeMd5($para, $md5key) {
		ksort($para);
		$arg  = "";
		while (list ($key, $val) = each ($para)) {
			$arg.=$key."=".$val."&";
		}
		$arg = substr($arg,0,count($arg)-2);
		if(get_magic_quotes_gpc()){$arg = stripslashes($arg);}
		
		$content = $arg;
		$content .= '&key='.$this->merchant_key;
	    $sign = md5($content);
		if(isset($reqJson['psw'])) unset($reqJson['psw']);

		$content = json_encode($reqJson);
	    $reqData = "transdata=".urlencode(trim($content))."&sign=".$sign."&signtype=MD5";
	    return $reqData;
	}
	function getPayInfo($response)
	{
		$return_info = (array)simplexml_load_string($response, null, LIBXML_NOCDATA);
		$nonceStr = md5(time());
		$timeStamp = time();
		$pay_info = [
			'appId'     =>  $this->appId,
	        'package'   =>  'prepay_id='.$return_info['prepay_id'],
	        'nonceStr'  =>  $nonceStr,
	        'timeStamp' =>  $timeStamp,
	        'signType'  =>  'MD5'
		];
		$pay_info['paySign'] = $this->sign($pay_info);
		$pay_info['prepay_url'] = $return_info['prepay_url'];
		return $pay_info;
	}

	

}