<?php

namespace App\Libs\Pay\Merchants;

use GuzzleHttp\Client;

/**
 *
 *
 * 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 Swiftpass {

	private $merchant_key;
	private $merchant_id;
	function __construct()
	{
		$this->merchant_key = '9d101c97133837e13dde2d32a5054abb';//$merchant_key;
		$this->merchant_id = '7551000001';
	}

	//生成订单
	function generateOrder($appid='',$notify_url='',$fee=100,$ip="192.168.1.21")
	{
		$client = new client(['base_uri'=>'https://pay.swiftpass.cn/','timeout'=>20]);
		$data = [
			'service'=>'pay.weixin.jspay',
			'mch_id'=>$this->merchant_id,
			'out_trade_no'=>time(),
			'body'=>'充值',
			//'sub_openid'=>'',
			//'sub_appid'=>'wx50bb165fb00ef149',
			'total_fee'=>$fee,
			'mch_create_ip'=>$ip,
			'notify_url'=>$notify_url,
			'nonce_str'=>md5(time()),
			'is_raw'=>1
		];
		$data['sign'] = $this->sign($data);
		$client->request('POST',"https://pay.swiftpass.cn/pay/gateway",['body'=>arrayToXml($data)]);
		$response = $client->getBody()->getContents();
		dd($response);
		return $this->getPayInfo($response);

		// curl_setopt($ch, CURLOPT_URL, "https://pay.swiftpass.cn/pay/gateway");
		// curl_setopt($ch, CURLOPT_POST,1);
		// echo "<pre>";
		// dd(arrayToXml($data));exit;
		// curl_setopt($ch, CURLOPT_POSTFIELDS,$this->toXml($data));
		// curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		// $info = curl_exec($ch);
		// curl_close($ch);
		
		// dump($info);
		// $pay_info = json_decode($return_info->pay_info,1);
		// return $pay_info;

	}

	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 = simplexml_load_string($response, null, LIBXML_NOCDATA);
		$pay_info = json_decode($return_info->pay_info,1);
		return $pay_info;
	}

	

}