<?php
/**
*
* example目录下为简单的支付样例，仅能用于搭建快速体验微信支付使用
* 样例的作用仅限于指导如何使用sdk，在安全上面仅做了简单处理， 复制使用样例代码时请慎重
* 请勿直接直接使用样例对外提供服务
* 
**/
header("Content-Type: text/html;charset=utf-8");
define('IN_YUNYECMS',true);
require '../../config/const.php';
require YUNYECMS_CORE.'init.php';
$common=core::load_class('common');
core::load_fun('core');
core::load_fun('content');
core::load_fun('tree');
core::load_fun('shop');
require_once "./lib/WxPay.Api.php";
require_once './lib/WxPay.Notify.php';
require_once "WxPay.Config.php";
require_once 'log.php';

//初始化日志
$logHandler= new CLogFileHandler("./logs/".date('Y-m-d').'.log');
$log = Log::Init($logHandler, 15);

class NativeNotifyCallBack extends WxPayNotify
{
	public function unifiedorder($openId, $product_id)
	{
		//统一下单
		$config = new WxPayConfig();
		$input = new WxPayUnifiedOrder();
		$input->SetBody("test");
		$input->SetAttach("test");
		$input->SetOut_trade_no($config->GetMerchantId().date("YmdHis"));
		$input->SetTotal_fee("1");
		$input->SetTime_start(date("YmdHis"));
		$input->SetTime_expire(date("YmdHis", time() + 600));
		$input->SetGoods_tag("test");
		$input->SetNotify_url(DOMAIN."core/extend/wxpay/notify.php");
		$input->SetTrade_type("NATIVE");
		$input->SetOpenid($openId);
		$input->SetProduct_id($product_id);
		try {
			$result = WxPayApi::unifiedOrder($config, $input);
			Log::DEBUG("unifiedorder:" . json_encode($result));
		} catch(Exception $e) {
			Log::ERROR(json_encode($e));
		}
		return $result;
	}

	/**
	*
	* 回包前的回调方法
	* 业务可以继承该方法，打印日志方便定位
	* @param string $xmlData 返回的xml参数
	*
	**/
	public function LogAfterProcess($xmlData)
	{
		Log::DEBUG("call back， return xml:" . $xmlData);
		return;
	}
	
	/**
	 * @param WxPayNotifyResults $objData 回调解释出的参数
	 * @param WxPayConfigInterface $config
	 * @param string $msg 如果回调处理失败，可以将错误信息输出到该方法
	 * @return true回调出来完成不需要继续回调，false回调处理未完成需要继续回调
	 */
	public function NotifyProcess($objData, $config, &$msg)
	{
		$data = $objData->GetValues();
		//echo "处理回调";
		Log::DEBUG("call back:" . json_encode($data));
		//TODO 1、进行参数校验
		if(!array_key_exists("openid", $data) ||
			!array_key_exists("product_id", $data))
		{
			$msg = "回调数据异常";
			Log::DEBUG($msg  . json_encode($data));
			return false;
		}

		//TODO 2、进行签名验证
		try {
			$checkResult = $objData->CheckSign($config);
			if($checkResult == false){
				//签名错误
				Log::ERROR("签名错误...");
				return false;
			}
		} catch(Exception $e) {
			Log::ERROR(json_encode($e));
		}
		 
		$openid = $data["openid"];
		$product_id = $data["product_id"];
		
		//TODO 3、处理业务逻辑
		//统一下单
		$result = $this->unifiedorder($openid, $product_id);
		if(!array_key_exists("appid", $result) ||
			 !array_key_exists("mch_id", $result) ||
			 !array_key_exists("prepay_id", $result))
		{
		 	$msg = "统一下单失败";
		 	Log::DEBUG($msg  . json_encode($data));
		 	return false;
		 }
		
		
       $dataarr=serialize($data);
       $strsql="select * from `#yunyecms_orders` where sn='{$data["out_trade_no"]}'";
       $cur=$this->db->find($strsql);
	   Log::DEBUG("curorder:".json_encode($cur));
	   if($cur['status']==0){
		    $curtime=time();
			$strsql="update `#yunyecms_orders`  set  status=1,wxpaydata='".$dataarr."',paytime='".$curtime."'   where  sn='{$data["out_trade_no"]}'";
			$ret=$this->db->query($strsql);
	   }		
		
		$this->SetData("appid", $result["appid"]);
		$this->SetData("mch_id", $result["mch_id"]);
		$this->SetData("nonce_str", WxPayApi::getNonceStr());
		$this->SetData("prepay_id", $result["prepay_id"]);
		$this->SetData("result_code", "SUCCESS");
		$this->SetData("err_code_des", "OK");
		return true;
	}
}

$config = new WxPayConfig();
Log::DEBUG("begin notify!");
$notify = new NativeNotifyCallBack();
$notify->Handle($config, true);





