<?php
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

require_once "../lib/WxPay.Api.php";
require_once '../lib/WxPay.Notify.php';
require_once 'log.php';
require_once '../lib/Base.php';

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

class PayNotifyCallBack extends WxPayNotify
{
	//查询订单
	public function Queryorder($transaction_id)
	{
		$input = new WxPayOrderQuery();
		$input->SetTransaction_id($transaction_id);
		$result = WxPayApi::orderQuery($input);
		Log::DEBUG("query:" . json_encode($result));
		if(array_key_exists("return_code", $result)
			&& array_key_exists("result_code", $result)
			&& $result["return_code"] == "SUCCESS"
			&& $result["result_code"] == "SUCCESS")
		{
			return true;
		}
		return false;
	}
	
	//重写回调处理函数
	public function NotifyProcess($data, &$msg)
	{
		Log::DEBUG("call back:" . json_encode($data));
		$notfiyOutput = array();
		
		if(!array_key_exists("transaction_id", $data)){
			$msg = "输入参数不正确";
			return false;
		}
		//查询订单，判断订单真实性
		if(!$this->Queryorder($data["transaction_id"])){
			$msg = "订单查询失败";
			return false;
		}else{
			if(!isset($_SESSION)) {
				session_start();
			}
			$tMO = new Model('wxorder');
			$tDatas = $tMO->field('*')->where('out_trade_no = \''.$data['out_trade_no'].'\'')->select();
			//查询卡号
			$tMCMO = new Model('medical_card');
			$tMCDatas = $tMCMO->field('*')->where('med_c_uid = '.$tDatas[0]['uid'].' and med_c_status = 1')->select();
			$tTime = time();
			if(empty($tDatas)) {
				return false;
			}else {
				$tCardNo = $tMCDatas[0]['med_c_card_no'];
				$tRegId = $tDatas[0]['regid'];
				$tRepeiceNo = $tDatas[0]['repeiceno'];
				$tTotalFee = $tDatas[0]['total_fee'];
				$tPatientID = $tDatas[0]['patientid'];
				$tId = $tDatas[0]['id'];

				if($tDatas[0]['prepay_id'] == 1) {//门诊缴费
					Log::DEBUG('call back request:'.json_encode($tDatas));
					$url = 'http://58.20.248.95:4419/apiv1_outpayment/payadm';
					$post = 'cardno='.$tCardNo.'&regid='.$tRegId.'&repeiceno='.$tRepeiceNo.'&total_fee='.$tTotalFee;
					$ch = curl_init();//初始化url
					curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
					curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
					curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
					curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
					$cdata = curl_exec($ch);//运行curl
					// print_r($data);
					$datas = json_decode($cdata, true);
					curl_close($ch);
					if($cdata){//his接口请求成功
						//his接口请求成功，写入日志文件
						$tStr = 'his接口请求成功，请求参数：'.$post.'返回结果：'.json_encode($cdata);
						Log::DEBUG($tStr);
						// $tStr1 = 'test结果：'.$cdata;
						// $tStr1 = 'test结果：'.$datas['repmsg']['Header']['ResultCode'];
						// Log::DEBUG($tStr1);
					
						if(!empty($datas['repmsg']['Header']['ResultCode'])){
							$tReq = array(
								'transaction_id' => $data['transaction_id'],
								'status' => 2,
							);
							$tSql = 'update wxorder set transaction_id = \''.$data['transaction_id'].'\',status = 2 where id='.$tId;
							$tResHis = $tMO->query($tSql);
							if($tResHis) {
								$tStr = 'his请求成功，微信订单表信息更新已支付未更新状态失败，请求参数：'.json_encode($tReq).'门诊缴费支付接口返回结果:'.json_encode($data);
								Log::DEBUG($tStr);
							}else {
								$tStr = 'his请求成功，微信订单表信息更新已支付未更新状态成功，请求参数：'.json_encode($tReq).'门诊缴费支付接口返回结果:'.json_encode($data);
								Log::DEBUG($tStr);
							}

							//his状态更新失败执行退费
							$url = 'http://lyl.medical.91paiyipai.com/wxpay/example/refund.php';
							$post_refund = 'out_trade_no='.$data['out_trade_no'].'&total_fee='.$data['total_fee'].'&refund_fee='.$data['total_fee'];
							$ch = curl_init();//初始化url
							curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
							curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
							curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
							curl_setopt($ch, CURLOPT_POSTFIELDS, $post_refund);
							$cdata_refund = curl_exec($ch);//运行curl
							// print_r($data);
							curl_close($ch);
							$datas_refund = json_decode($cdata_refund, true);

							$tTime = time();

							//判断是否退费成功
							if($datas_refund['data']['result_code'] != 'SUCCESS') {
								$tStr = 'his请求成功，请求参数：'.$post.'微信退费失败，请求参数：'.$post_refund.'返回结果:'.json_encode($datas_refund);
								Log::DEBUG($tStr);
							}else {
								//更新退费信息
								$tRMO = new Model('refund');
								$tData = array(
									'name' => $tMCDatas[0]['med_c_user_name'],
									'total_fee' => $tTotalFee,
									'uid' => $tDatas[0]['uid'],
									'prepay_id' => $tDatas[0]['prepay_id'],
									'out_trade_no' => $data['out_trade_no'],
									'created' => $tTime,
									'status' => 4,
									'refund_id' => $datas_refund['data']['refund_id'],
								);
								if(!$tRMO->insert($tData)) {
									$tStr = 'his请求成功，请求参数：'.$post.'微信退费成功'.$cdata_refund.'，返回结果:'.json_encode($datas_refund).'微信退费表信息插入失败，请求参数：'.json_encode($tData);
									Log::DEBUG($tStr);
								}else{
									$tStr = 'his请求成功，请求参数：'.$post.'微信退费成功'.$cdata_refund.'，返回结果：'.json_encode($datas_refund).'微信退费表信息插入成功，请求参数：'.json_encode($tData);
									Log::DEBUG($tStr);
								}
								//更新订单信息
								$tMO = new Model('wxorder');
								$tSql = 'update wxorder set status = 4 where id = '.$tId;
								$tResRefund = $tMO->query($tSql);
								if($tResRefund) {
									$tStr = 'his请求成功，微信订单退费状态更新失败，返回结果:'.json_encode($tResRefund);
									Log::DEBUG($tStr);
								}else{
									$tStr = 'his请求成功，微信订单退费状态更新成功，返回结果：'.json_encode($tResRefund);
								}
							}
							
						}else{
							$tReq = array(
								'transaction_id' => $data['transaction_id'],
								'status' => 3,
								'uid' => $tDatas[0]['uid'],
							);

							$tSql = 'update wxorder set transaction_id = \''.$data['transaction_id'].'\',status = 3 where id = '.$tId;
							$tResHis = $tMO->query($tSql);
							if($tResHis) {
								$tStr = 'his请求成功，微信订单表信息更新已支付已更新状态失败，请求参数：'.json_encode($tReq).'门诊缴费支付接口返回结果:'.json_encode($data);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his请求成功，微信订单表信息更新已支付已更新状态成功，请求参数：'.json_encode($tReq).'门诊缴费支付接口返回结果:'.json_encode($data);
								Log::DEBUG($tStr);
							}
						}
					}else{//his接口请求失败执行退费
						//his请求失败，写入日志文件
						$tStr = 'his接口请求失败，请求参数：'.$post.'，返回结果：'.json_encode($cdata);
						Log::DEBUG($tStr);

						$url = 'http://lyl.medical.91paiyipai.com/wxpay/example/refund.php';
						$post = 'out_trade_no='.$data['out_trade_no'].'&total_fee='.$data['total_fee'].'&refund_fee='.$data['total_fee'];
						$ch = curl_init();//初始化url
						curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
						curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
						curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
						$cdata_refund = curl_exec($ch);//运行curl
						// print_r($data);
						curl_close($ch);
						$datas_refund = json_decode($cdata_refund, true);

						$tTime = time();

						//判断是否退费成功
						if($datas_refund['data']['result_code'] != 'SUCCESS') {
							$tStr = 'his请求失败，微信退费失败，请求参数：'.$post.'返回结果:'.json_encode($datas_refund);
							Log::DEBUG($tStr);
						}else {
							//更新退费信息
							$tRMO = new Model('refund');
							$tData = array(
								'name' => $tMCDatas[0]['med_c_user_name'],
								'total_fee' => $tTotalFee,
								'uid' => $tMCDatas[0]['med_c_uid'],
								'prepay_id' => $tDatas[0]['prepay_id'],
								'out_trade_no' => $data['out_trade_no'],
								'created' => $tTime,
								'status' => 4,
								'refund_id' => $datas_refund['data']['refund_id'],
							);
							if(!$tRMO->insert($tData)) {
								$tStr = 'his请求失败，微信退费成功，请求参数：'.$post.'返回结果:'.json_encode($datas_refund).'微信退费表信息插入失败，请求参数：'.json_encode($tData);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his请求失败，微信退费成功，请求参数：'.$post.'返回结果：'.json_encode($datas_refund).'微信退费表信息插入成功，请求参数：'.json_encode($tData);
								Log::DEBUG($tStr);
							}
							//更新订单信息
							$tMO = new Model('wxorder');
							$tSql = 'update wxorder set status = 4,name = \''.$tMCDatas[0]['med_c_user_name'].'\' where id = '.$tId;
							$tResRefund = $tMO->query($tSql);
							if($tResRefund) {
								$tStr = 'his请求失败，微信订单退费状态更新失败，返回结果:'.json_encode($tResRefund);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his请求失败，微信订单退费状态更新成功，返回结果:'.json_encode($tResRefund);
								Log::DEBUG($tStr);
							}
						}
					}
					
				}
				if($tDatas[0]['prepay_id'] == 2) {//住院缴费
					$url = 'http://58.20.248.95:4419/apiv1_inpdeposit/recharge';
					$post = 'patientid='.$tPatientID.'&paymt='.$tTotalFee;
					$ch = curl_init();//初始化url
					curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
					curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
					curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
					curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
					curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
					$cdata = curl_exec($ch);//运行curl
					// print_r($data);
					$datas = json_decode($cdata, true);

					curl_close($ch);
					if($cdata){//his接口请求成功
						//his请求成功，写入日志文件
						$tStr = 'his住院缴费接口请求成功，请求参数：'.$post.'返回结果：'.json_encode($cdata);
						Log::DEBUG($tStr);

						if(!empty($datas['repmsg']['Header']['ResultCode'])){//his更新失败执行退费
							//his请求失败，写入日志文件
							$tStr = 'his接口请求失败，请求参数：'.$post.'，返回结果：'.json_encode($cdata);
							Log::DEBUG($tStr);

							$url = 'http://lyl.medical.91paiyipai.com/wxpay/example/refund.php';
							$post_refund = 'out_trade_no='.$data['out_trade_no'].'&total_fee='.$data['total_fee'].'&refund_fee='.$data['total_fee'];
							$ch = curl_init();//初始化url
							curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
							curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
							curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
							curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
							curl_setopt($ch, CURLOPT_POSTFIELDS, $post_refund);
							$cdata_refund = curl_exec($ch);//运行curl
							// print_r($data);
							curl_close($ch);
							$datas_refund = json_decode($cdata_refund, true);

							$tTime = time();

							//判断是否退费成功
							if($datas_refund['data']['result_code'] != 'SUCCESS') {
								$tStr = 'his住院押金请求成功，微信退费失败，请求参数：'.$post.'返回结果:'.json_encode($datas_refund);
								Log::DEBUG($tStr);
							}else {
								//更新退费信息
								$tRMO = new Model('refund');
								$tData = array(
									'name' => $tMCDatas[0]['med_c_user_name'],
									'total_fee' => $tTotalFee,
									'uid' => $tDatas[0]['uid'],
									'prepay_id' => $tDatas[0]['prepay_id'],
									'out_trade_no' => $data['out_trade_no'],
									'created' => $tTime,
									'status' => 4,
									'refund_id' => $datas_refund['data']['refund_id'],
								);
								if(!$tRMO->insert($tData)) {
									$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'返回结果:'.json_encode($datas_refund).'微信退费表信息插入失败，请求参数：'.json_encode($tData);
									Log::DEBUG($tStr);
								}else{
									$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'返回结果：'.json_encode($datas_refund).'微信退费表信息插入成功，请求参数：'.json_encode($tData);
									Log::DEBUG($tStr);
								}
								//更新订单信息
								$tMO = new Model('wxorder');
								$tSql = 'update wxorder set status = 4,name = \''.$tMCDatas[0]['med_c_user_name'].'\' where id = '.$tId;
								$tResRefund = $tMO->query($tSql);
								if($tResRefund) {
									$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'微信订单退费状态更新失败，返回结果:'.json_encode($tResRefund);
									Log::DEBUG($tStr);
								}else{
									$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'微信订单退费状态更新成功，返回结果:'.json_encode($tResRefund);
									Log::DEBUG($tStr);
								}
							}
							$tReq = array(
								'transaction_id' => $data['transaction_id'],
								'status' => 2,
							);
							$tSql = 'update wxorder set transaction_id = \''.$data['transaction_id'].'\',status = 2 where id='.$tId;
							$tResHis = $tMO->query($tSql);
							if($tResHis) {
								$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'微信订单更新已支付未更新状态失败，返回结果：'.json_encode($tResHis);
								Log::DEBUG($tStr);
							}else {
								$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信退费成功，请求参数：'.$post_refund.'微信订单更新已支付未更新状态成功，返回结果：'.json_encode($tResHis);
								Log::DEBUG($tStr);
							}
						}else{//his更新成功
							$tReq = array(
								'transaction_id' => $data['transaction_id'],
								'status' => 3,
							);

							$tSql = 'update wxorder set transaction_id = \''.$data['transaction_id'].'\',status = 3 where id = '.$tId;
							$tResHis = $tMO->query($tSql);
							if($tResHis) {
								$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信缴费成功，微信订单更新已支付已更新状态失败，返回结果：'.json_encode($tResHis);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his住院押金请求成功，请求参数：'.$post.'，微信缴费成功，微信订单更新已支付已更新状态成功，返回结果：'.json_encode($tResHis);
								Log::DEBUG($tStr);
							}
						}
					}else{//his请求失败，执行自动退费
						//his请求失败，写入日志文件
						$tStr = 'his住院押金接口请求失败，请求参数：'.$post.'，返回结果：'.json_encode($cdata);
						Log::DEBUG($tStr);

						$url = 'http://lyl.medical.91paiyipai.com/wxpay/example/refund.php';
						$post = 'out_trade_no='.$data['out_trade_no'].'&total_fee='.$data['total_fee'].'&refund_fee='.$data['total_fee'];
						$ch = curl_init();//初始化url
						curl_setopt($ch, CURLOPT_URL,$url);//抓取指定网页
						curl_setopt($ch, CURLOPT_HEADER, 0);//设置header
						curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//要求结果为字符串且输出到屏幕上
						curl_setopt($ch, CURLOPT_POST, 1);//post提交方式
						curl_setopt($ch, CURLOPT_POSTFIELDS, $post);
						$cdata_refund = curl_exec($ch);//运行curl
						// print_r($data);
						curl_close($ch);
						$datas_refund = json_decode($cdata_refund, true);

						$tTime = time();

						//判断是否退费成功
						if($datas_refund['data']['result_code'] != 'SUCCESS') {
							$tStr = 'his住院押金请求失败，微信退费失败，请求参数：'.$post.'返回结果:'.json_encode($datas_refund);
							Log::DEBUG($tStr);
						}else {
							//更新退费信息
							$tRMO = new Model('refund');
							$tData = array(
								'name' => $tMCDatas[0]['med_c_user_name'],
								'total_fee' => $tTotalFee,
								'uid' => $tMCDatas[0]['med_c_uid'],
								'prepay_id' => $tDatas[0]['prepay_id'],
								'out_trade_no' => $data['out_trade_no'],
								'created' => $tTime,
								'status' => 4,
								'refund_id' => $datas_refund['data']['refund_id'],
							);
							if(!$tRMO->insert($tData)) {
								$tStr = 'his住院押金请求失败，微信退费成功，请求参数：'.$post.'返回结果:'.json_encode($datas_refund).'微信退费表信息插入失败，请求参数：'.json_encode($tData);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his住院押金请求失败，微信退费成功，请求参数：'.$post.'返回结果：'.json_encode($datas_refund).'微信退费表信息插入成功，请求参数：'.json_encode($tData);
								Log::DEBUG($tStr);
							}
							//更新订单信息
							$tMO = new Model('wxorder');
							$tSql = 'update wxorder set status = 4,name = \''.$tMCDatas[0]['med_c_user_name'].'\' where id = '.$tId;
							$tResRefund = $tMO->query($tSql);
							if($tResRefund) {
								$tStr = 'his住院押金请求失败，微信订单退费状态更新失败，返回结果:'.json_encode($tResRefund);
								Log::DEBUG($tStr);
							}else{
								$tStr = 'his住院押金请求失败，微信订单退费状态更新成功，返回结果:'.json_encode($tResRefund);
								Log::DEBUG($tStr);
							}
						}
					}	
				}
			}
			Log::DEBUG('call 跳转页面:'.json_encode($data));
			return '<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>';
		}
		return true;
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();
$notify->Handle(true);
