<?php
/**
 * 微信支付接口类库   
 */
defined('IN_YUNYECMS') or exit('No permission.');
core::load_class('base',false);
core::load_fun('content');
core::load_fun('tree');
core::load_fun('shop');
class wxpay extends base {
	    public $db;
	    public $orderdata;
       //在类初始化方法中，引入相关类库    
		function __construct() {
		 $this->db = core::load_model('content_model');
		 parent::__construct();
		 islogin(); 
			require_once YUNYECMS_EXTEND.'wxpay'.DIRECTORY_SEPARATOR.'lib'.DIRECTORY_SEPARATOR.'WxPay.Api.php'; 
			require_once YUNYECMS_EXTEND.'wxpay'.DIRECTORY_SEPARATOR.'log.php'; 
		 }
	
         public function jsapi($orderdata){
			require_once YUNYECMS_EXTEND.'wxpay'.DIRECTORY_SEPARATOR.'WxPay.JsApiPay.php'; 
			require_once YUNYECMS_EXTEND.'wxpay'.DIRECTORY_SEPARATOR.'WxPay.Config.php'; 
			//初始化日志
			$logHandler= new CLogFileHandler("./logs/".date('Y-m-d').'.log');
			$log = Log::Init($logHandler, 15);
					//①、获取用户openid
			try{
				$tools = new JsApiPay();
				$openId = $tools->GetOpenid();
				//②、统一下单
				$input = new WxPayUnifiedOrder();
				$input->SetBody($orderdata['body']);
				$input->SetAttach($orderdata['attach']);
				$input->SetOut_trade_no($orderdata['out_trade_no']);
				$input->SetTotal_fee($orderdata['total_fee']);
				$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("JSAPI");
				$input->SetOpenid($openId);
				$config = new WxPayConfig();
				$order = WxPayApi::unifiedOrder($config, $input);
				$jsApiParameters = $tools->GetJsApiParameters($order);
				//获取共享收货地址js函数参数
				$editAddress = $tools->GetEditAddressParameters();
				$retarr["jsApiParameters"]=$jsApiParameters;
				$retarr["editAddress"]=$editAddress;
				return $retarr;
			   }catch(Exception $e) {
				 Log::ERROR(json_encode($e));
			   }
			//③、在支持成功回调通知中处理成功之后的事宜，见 notify.php
			/**
			 * 注意：
			 * 1、当你的回调地址不可访问的时候，回调通知会失败，可以通过查询订单来确认支付是否成功
			 * 2、jsapi支付时需要填入用户openid，WxPay.JsApiPay.php中有获取openid流程 （文档可以参考微信公众平台“网页授权接口”，
			 * 参考http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html）
			 */
	}
	
	
    /**
     * 异步通知
     * @param $data
     * @return mixed
     */
    public function notify($data)
    {
        $inputdata = file_get_contents("php://input");
        if (!empty($inputdata)) {
            $payment = model('Payment')->get_payment($data['code']);
            $postdata = json_decode(json_encode(simplexml_load_string($inputdata, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
            /* 检查插件文件是否存在，如果存在则验证支付是否成功，否则则返回失败信息 */
            // 微信端签名
            $wxsign = $postdata['sign'];
            unset($postdata['sign']);

            // 微信附加参数
            $attach = $postdata['attach'];

            foreach ($postdata as $k => $v) {
                $Parameters[$k] = $v;
            }
            // 签名步骤一：按字典序排序参数
            ksort($Parameters);

            $buff = "";
            foreach ($Parameters as $k => $v) {
                $buff .= $k . "=" . $v . "&";
            }
            $String = '';
            if (strlen($buff) > 0) {
                $String = substr($buff, 0, strlen($buff) - 1);
            }
            // 签名步骤二：在string后加入KEY
            $String = $String . "&key=" . $payment['wxpay_key'];
            // 签名步骤三：MD5加密
            $String = md5($String);
            // 签名步骤四：所有字符转为大写
            $sign = strtoupper($String);
            // 验证成功
            if ($wxsign == $sign) {
                // 交易成功
                if ($postdata['result_code'] == 'SUCCESS') {
                    // 获取log_id
                    $out_trade_no = explode('B', $postdata['out_trade_no']);
                    $log_id = $out_trade_no[1]; // 订单号log_id
                    $order_trade_no = explode('A', $out_trade_no[0]);
                    // 改变订单状态
                    if ($attach == 'drp') {
                        model('Payment')->drp_order_paid($log_id, 2);
                    } elseif ($attach == 'crowd') {
                        model('Payment')->crowd_order_paid($log_id, 2);
                    } else {
                        model('Payment')->order_paid($log_id, 2);
                    }
                    // 修改订单信息(openid，tranid)
                    model('Base')->model->table('pay_log')
                        ->data('openid = "' . $postdata['openid'] . '", transid = "' . $postdata['transaction_id'] . '"')
                        ->where('log_id = ' . $log_id)
                        ->update();
                }
                $returndata['return_code'] = 'SUCCESS';
            } else {
                $returndata['return_code'] = 'FAIL';
                $returndata['return_msg'] = '签名失败';
            }
        } else {
            $returndata['return_code'] = 'FAIL';
            $returndata['return_msg'] = '无数据返回';
        }
        // 数组转化为xml
        $xml = "<xml>";
        foreach ($returndata as $key => $val) {
            if (is_numeric($val)) {
                $xml .= "<" . $key . ">" . $val . "</" . $key . ">";
            } else {
                $xml .= "<" . $key . "><![CDATA[" . $val . "]]></" . $key . ">";
            }
        }
        $xml .= "</xml>";

        exit($xml);
    }	
	
	
	
	//打印输出数组信息
	function printf_info($data)
	{
		foreach($data as $key=>$value){
			echo "<font color='#00ff55;'>$key</font> :  ".htmlspecialchars($value, ENT_QUOTES)." <br/>";
		}
	}

	
	
   
}
?>