<?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 Swiftpass {

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

	//订单发送
	function send($trade_no,$fee=100,$ip="192.168.1.21",$return_url,$open_id)
	{
		$client = new client(['base_uri'=>'https://pay.swiftpass.cn/','timeout'=>20]);
		$data = [
			'service'=>'pay.weixin.jspay',
			'mch_id'=>$this->merchant_id,
			'out_trade_no'=>$trade_no,
			'body'=>'充值',
			'sub_openid'=>$open_id,
			'sub_appid'=>'wxebcb86ec4b80eaca',
			'total_fee'=>$fee*100,
			'mch_create_ip'=>$ip,
			'notify_url'=>env('SWIFT_PAY_NOFITY_URL'),
			'nonce_str'=>md5(time()),
			'is_raw'=>1,
			'callback_url'=>$return_url //交易完成后跳转的URL
		];
		Log::info('client_request_data');
		Log::info($data);
		$data['sign'] = $this->sign($data);
		$response = $client->request('POST',"pay/gateway",['body'=>arrayToXml($data)])->getBody()->getContents();
		Log::info('client_$response');
		Log::info($response);
		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 = simplexml_load_string($response, null, LIBXML_NOCDATA);
		Log::info('$return_info');
		Log::info($return_info->token_id);
		$pay_info = json_decode($return_info->pay_info,1);
		Log::info('origin_pay_info');
		Log::info($pay_info);
		$token = isset($return_info->token_id)?$return_info->token_id:'';
		$prepay_url = "https://pay.swiftpass.cn/pay/jspay?token_id=".$token;
		
		return [
			'appId'     =>  $pay_info['appId'],
	        'package'   =>  $pay_info['package'],
	        'nonceStr'  =>  $pay_info['nonceStr'],
	        'timeStamp' =>  $pay_info['timeStamp'],
	        'signType'  =>  'MD5',
	        'paySign'   =>  $pay_info['paySign'],
	        'prepay_url'   =>  $prepay_url
        ];
	}

	

}