<?php

namespace App\Libs\Pay\Merchants;

use GuzzleHttp\Client;
use Log;

/**
 *
 *
 * commit e0bb38efab0b546f00ffd8f5f485032b7cda4ad9
Author: zz <524914631@qq.com>
Date:   Thu Aug 3 18:00:57 2017 +0800

    dist

commit 90a52f5073dac91e58487d9966faf55b55cf849f
Author: zz <524914631@qq.com>
Date:   Thu Aug 3 17:33:32 2017 +0800

    dist

commit 6e84098457780a2d0e57510eca4cfaf8a5b65ba5
Author: zz <524914631@qq.com>
Date:   Wed Aug 2 13:39:44 2017 +0800

    apple online check
 */
class Youluo {

	private $merchant_key;
	private $merchant_id;
	private $appId;
	function __construct()
	{
		$this->merchant_key = 'bc9f9ad017460b5ccb6d237dca39d5b9';//'d014da1ab33d8f3ddfaf7e5a81724f1a';
		$this->merchant_id = '26102295';//'26104515';
		$this->appId = 'wxcccc8abc4b42abab';//'26104515';
	}

	//生成订单
	function send($trade_no,$fee=1,$ip="192.168.1.21",$return_url)
	{
		$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'=>$fee*100,
			'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 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;
	}

	

}