天天看點

ECSHOP 微信支付 二維碼支付 PC php

<?php
/**
 * ECSHOP 微信掃碼支付
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

		
// 包含配置檔案
$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/wxpay_native.php';

if (file_exists($payment_lang))
{
    global $_LANG;

    include_once($payment_lang);
}

/* 子產品的基本資訊 */
if (isset($set_modules) && $set_modules == TRUE)
{
    $i = isset($modules) ? count($modules) : 0;

    /* 代碼 */
    $modules[$i]['code']    = basename(__FILE__, '.php');

    /* 描述對應的語言項 */
    $modules[$i]['desc']    = 'wxpay_native_desc';

    /* 是否支援貨到付款 */
    $modules[$i]['is_cod']  = '0';

    /* 是否支援線上支付 */
    $modules[$i]['is_online']  = '1';

    /* 作者 */
    $modules[$i]['author']  = 'qq:472995301';

    /* 網址 */
    $modules[$i]['website'] = 'qq:472995301';

    /* 版本号 */
    $modules[$i]['version'] = '3.3.0';

    /* 配置資訊 */
       $modules[$i]['config'] = array(
        // 微信公衆号身份的唯一辨別
        array(
            'name' => 'wxpay_native_appid',
            'type' => 'text',
            'value' => ''
        ),
        // JSAPI接口中擷取openid,稽核後在公衆平台開啟開發模式後可檢視
        array(
            'name' => 'wxpay_native_appsecret',
            'type' => 'text',
            'value' => ''
        ),
        // 商戶支付密鑰Key
        array(
            'name' => 'wxpay_native_key',
            'type' => 'text',
            'value' => ''
        ),
        // 受理商ID
        array(
            'name' => 'wxpay_native_mchid',
            'type' => 'text',
            'value' => ''
        )
    );

    return;
}

require_once ( dirname(__FILE__).'/wxpay/WxPay.Config.php' );
require_once ( dirname(__FILE__).'/wxpay/WxPay.Api.php' );
require_once ( dirname(__FILE__).'/wxpay/WxPay.Notify.php' );
require_once ( dirname(__FILE__).'/wxpay/WxPay.PayNotifyCallBack.php' );
require_once ( dirname(__FILE__).'/wxpay/log.php' );

/**
 * 類
 */
class wxpay_native
{
	private $dir  ;
	private $site_url;


	function _config( $payment )
	{
		WxPayConfig::set_appid( $payment['wxpay_native_appid'] );
		WxPayConfig::set_mchid( $payment['wxpay_native_mchid'] );
		WxPayConfig::set_key( $payment['wxpay_native_key'] );
		WxPayConfig::set_appsecret( $payment['wxpay_native_appsecret']);	
	}
	
	/**
     * 生成支付代碼
     * @param   array   $order  訂單資訊
     * @param   array   $payment    支付方式資訊
     */
	function get_code($order, $payment)
	{
		
		$this->_config($payment);
		$root_url = str_replace('mobile/', '', $GLOBALS['ecs']->url());
		$notify_url = $root_url.'wxpay_native_notify.php';
		
		$out_trade_no = $order['order_sn'].'O'.$order['log_id'].'-'.time();
		
		$input = new WxPayUnifiedOrder();
		$input->SetBody( $order['order_sn'] );
		$input->SetAttach( $order['log_id'] );		//商戶支付日志
		$input->SetOut_trade_no($out_trade_no);		//商戶訂單号 
		$input->SetTotal_fee( strval(($order['order_amount']*100)) ); //總金額
		$input->SetTime_start(date("YmdHis"));
		//$input->SetTime_expire(date("YmdHis", time() + 600));
		//$input->SetGoods_tag("test");
		$input->SetNotify_url( $notify_url );	//通知位址 
		$input->SetTrade_type("NATIVE");	//交易類型
		$input->SetProduct_id($order['order_sn']);

		$result = $this->GetPayUrl($input);
		$url2 = null;
		$err = '出錯了'; 
		if( $result["return_code"] == 'FAIL'){
			$err = $result["return_msg"]; 
		}else{
			$url2 = $result["code_url"];
		}
		
        $html = '<button type="button" οnclick="javascript:alert(\''. $err .'\')">微信支付</button>';
        if($url2 != NULL)
        {
            $code_url = $url2;
            $html = '<div class="wx_qrcode" style="text-align:center">';
            //$html .= $this->getcode($code_url);
			$html .= '<img alt="掃碼支付" src="http://paysdk.weixin.qq.com/example/qrcode.php?data='.urlencode($url2).'" style="width:150px;height:150px;"/>';
            $html .= "</div>";

            $html .= "<div style=\"text-align:center\">支付後點選<a href=\"user.php?act=order_list\" style=\"color:red\">此處檢視我的訂單</a></div>";
			
		
			
			
			$html = "<div style=\"text-align:center;color:#A00000;\"><b>掃描下方二維碼支付訂單</b></div>";
			$html .= '<div class="wx_qrcode" style="text-align:center">';
            $html .= $this->getcode($code_url);
            $html .= "</div>";
            $html .= "<div style=\"text-align:center\">支付後點選<a href=\"user.php?act=order_list\">此處</a>檢視我的訂單</div>";
       	  $html .='<script type="text/javascript">
				function get_wxpay_native_status( id ){
					/*$.get("user.php", "act=wxpay_native_query&id="+id,function( result ){
						if ( result.error == 0 && result.is_paid == 1 ){
							window.location.href = result.url;
						}
					}, "json");
					*/
					Ajax.call("user.php", "act=wxpay_native_query&id="+id, return_wxpay_order_status, "GET", "JSON");
					
				}
				function return_wxpay_order_status(  result ){
					if ( result.error == 0 && result.is_paid == 1 ){
						window.location.href = result.url;
					}
				}
				window.setInterval(function(){ get_wxpay_native_status("'. $order['log_id'] .'"); }, 2000); 
			</script>';
			
        }
        
        return $html;
	}
	

    function respond()
    {
		$payment  = get_payment('wxpay_native');
		$this->_config($payment);

		$lib_path	= dirname(__FILE__).'/wxpay/';
		$logHandler= new CLogFileHandler($lib_path."logs/".date('Y-m-d').'.log');
		$log = Log::Init($logHandler, 15);
		
		Log::DEBUG("begin notify");
		$notify = new PayNotifyCallBack( );
		$notify->Handle(true);
		
		$data = $notify->data;
		
		//判斷簽名
			if ($data['result_code'] == 'SUCCESS') {
				
					$transaction_id = $data['transaction_id'];
				 // 擷取log_id
                    $out_trade_no	= explode('O', $data['out_trade_no']);
                    $order_sn		= $out_trade_no[0];
					$log_id			= (int)$out_trade_no[1]; // 訂單号log_id
					$payment_amount = $data['total_fee']/100;
					
					/* 檢查支付的金額是否相符 */
					if (!check_money($log_id, $payment_amount))
					{
						 echo 'fail';
					}
							
					$action_note = 'result_code' . ':' 
					. $data['result_code']
					. ' return_code:'
					. $data['return_code']
					. ' orderId:'
					. $data['out_trade_no']		
					. ' openid:'
					. $data['openid']
					. ' '.$GLOBALS['_LANG']['wxpay_native_transaction_id'] . ':' 
					. $transaction_id;
					// 完成訂單。
					order_paid($log_id, PS_PAYED, $action_note);
					return true;
			}else{
				 echo 'fail';
			}
			
		return false;
		
    }


    function getcode($url){
        if(file_exists(ROOT_PATH . 'includes/phpqrcode.php')){
            include(ROOT_PATH . 'includes/phpqrcode.php');
        }
        // 糾錯級别:L、M、Q、H 
        $errorCorrectionLevel = 'Q';  
        // 點的大小:1到10 
        $matrixPointSize = 5;
        // 生成的檔案名
        $tmp = ROOT_PATH .'images/qrcode/';
        if(!is_dir($tmp)){
            @mkdir($tmp);
        }
        $filename = $tmp . $errorCorrectionLevel . $matrixPointSize . '.png';
        QRcode::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 2);
        return '<img src="'.$GLOBALS['ecs']->url(). 'images/qrcode/'.basename($filename).'" />';
    }
    
    function log($file,$txt)
    {
       $fp =  fopen($file,'ab+');
       fwrite($fp,'-'.local_date('Y-m-d H:i:s').'---');
       fwrite($fp,$txt);
       fwrite($fp,"\r\n");
       fclose($fp);
    }
	
/**
	 * 
	 * 生成掃描支付URL,模式一
	 * @param BizPayUrlInput $bizUrlInfo
	 */
	public function GetPrePayUrl($productId)
	{
		$biz = new WxPayBizPayUrl();
		$biz->SetProduct_id($productId);
		$values = WxpayApi::bizpayurl($biz);
		$url = "weixin://wxpay/bizpayurl?" . $this->ToUrlParams($values);
		return $url;
	}
	
	/**
	 * 
	 * 參數數組轉換為url參數
	 * @param array $urlObj
	 */
	private function ToUrlParams($urlObj)
	{
		$buff = "";
		foreach ($urlObj as $k => $v)
		{
			$buff .= $k . "=" . $v . "&";
		}
		
		$buff = trim($buff, "&");
		return $buff;
	}
	
	/**
	 * 
	 * 生成直接支付url,支付url有效期為2小時,模式二
	 * @param UnifiedOrderInput $input
	 */
	public function GetPayUrl($input)
	{
		if($input->GetTrade_type() == "NATIVE")
		{
			$result = WxPayApi::unifiedOrder($input);
			return $result;
		}
	}
	

}

?>