微信扫码支付PHP接入总结

微信扫码支付分为两种模式,
模式一比较复杂,需要公众号配置回调地址。

模式二比较简单,只需要在代码中配置回调地址就可以了。

我这次使用的是模式二。

需要配置参数,

const APPID = 'xxx';
const MCHID = 'xxx';
const KEY = 'xxx';
const APPSECRET = 'xxx';

配置公众号的appid,appsecret。以及微信支付的mchid与key。

生成二维码,这个页面需要自己去美化,不像支付宝那样自带效果。

require_once "./phpcms/plugin/weixinpay/lib/WxPay.Api.php";
require_once "./phpcms/plugin/weixinpay/example/WxPay.NativePay.php";
require_once './phpcms/plugin/weixinpay/example/log.php';

$input = new WxPayUnifiedOrder();
$input->SetBody('预订'.$product_info['name'].'订单');
$input->SetAttach('预订'.$product_info['name'].'订单');
$input->SetOut_trade_no($order_info['orderno']);
$input->SetTotal_fee($order_info['payprice'] * 100);
$input->SetTime_start(date("YmdHis"));
$input->SetTime_expire(date("YmdHis", time() + 600));
$input->SetGoods_tag("");
$input->SetNotify_url("http://www.ayuanduanzu.com/wxpay/notify.php"); // 地址是外网能访问的,且不能包含参数
$input->SetTrade_type("NATIVE");
$input->SetProduct_id($product_info['id']);
$notify = new NativePay();
$result = $notify->GetPayUrl($input);
$code_url = $result["code_url"];
<img alt="扫码支付" src="http://paysdk.weixin.qq.com/example/qrcode.php?data={urlencode($code_url)}" style="width:150px;height:150px;"/>

这里的回调地址很有讲究,扫码支付成功后,微信会自动调用这个地址。这个地址不能包含任何参数,否则调用失败。啥都看不到!

微信调用的时候,会传递xml类型的参数。

<?php
include_once "../phpcms/base.php";

// 处理回调数据
ini_set('date.timezone','Asia/Shanghai');
error_reporting(E_ERROR);

require_once "../phpcms/plugin/weixinpay/lib/WxPay.Api.php";
require_once '../phpcms/plugin/weixinpay/lib/WxPay.Notify.php';
require_once '../phpcms/plugin/weixinpay/example/log.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;
		}
		return true;
	}
}

Log::DEBUG("begin notify");
$notify = new PayNotifyCallBack();

$ilog_db = pc_base::load_model('ilog_model');
$order_db = pc_base::load_model('order_model');
$postXml = $GLOBALS["HTTP_RAW_POST_DATA"];
$postArr = xmlToArray($postXml);
$ilog_db->addLog(json_encode($postArr));

// 查询是否支付成功
$r = $notify->Queryorder($postArr['transaction_id']);
if ($r) {
	// 获取订单信息
	$order_info  = $order_db->get_one(array('orderno'=>$postArr['out_trade_no']));

	if ($order_info['pay_status'] != '1') {
		$data['pay_status'] = '1';
		$data['pay_type']   = 'weixinpay';
		$data['pay_code']   = $postArr['transaction_id'];
		$data['paytime']    = time();
		$data['order_status']= 3; // 已支付
		$order_db->update($data,array('orderno'=>$postArr['out_trade_no']));
	}
}

?>

通过

$GLOBALS["HTTP_RAW_POST_DATA"];

可以获取微信端传入的参数

{
    "appid": "wxed7996e9ad58345d",
    "attach": "u9884u8ba2u5bbfu8fc1u00b7u592au53e4u91ccu7f8eu5f0fu5957u623fu8ba2u5355",
    "bank_type": "CFT",
    "cash_fee": "1",
    "fee_type": "CNY",
    "is_subscribe": "Y",
    "mch_id": "1283301801",
    "nonce_str": "20xn5e0lbk2u1u6pes2uonape2sdyfs4",
    "openid": "oR8C7wsknwVELIRrzTlZX2eONWeY",
    "out_trade_no": "2016091455521024608",
    "result_code": "SUCCESS",
    "return_code": "SUCCESS",
    "sign": "95C2C532D095E7BF7588522C579758C4",
    "time_end": "20160914135518",
    "total_fee": "1",
    "trade_type": "NATIVE",
    "transaction_id": "4009602001201609143926590576"
}

查询是否已支付,支付完成的话,进行订单数据处理。

这里的一切都是异步的,二维码页面啥都看不到。

只能通过异步获取订单状态来判断是否操作成功。

// 检测是否支付成功
$(document).ready(function () {
	setInterval("ajaxstatus()", 3000);    
});
	
function ajaxstatus() {
	var orderno = $("#out_trade_no").val();
    if (orderno != 0) {
        $.ajax({
            url: "?m=home&c=order&a=ajax",
            type: "GET",
            dataType:"json",
            data: {
	            todo: 'ajaxCheckWxPay',
	            orderno: orderno,
	        },
            success: function (json) {
                if (json.status == 1) { //订单状态为1表示支付成功
                	layer.msg('支付成功',{icon:1,time: 2000},function(){
                		window.location.href = "?m=home&c=order&a=payDone&orderno="+json.info['orderno'];
                	});
                   // window.location.href = "wxScanSuccessUrl.action"; //页面跳转
                }
            }
        });
    }
} 

三秒执行一次,如果成功,进行跳转处理。

赠送函数

/**
 * 	作用:array转xml
 */
function arrayToXml($arr)
{
    $xml = "<xml>";
    foreach ($arr as $key=>$val)
    {
    	 if (is_numeric($val))
    	 {
    	 	$xml.="<".$key.">".$val."</".$key.">"; 

    	 }
    	 else
    	 	$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";  
    }
    $xml.="</xml>";
    return $xml; 
}
	
/**
 * 	作用:将xml转为array
 */
function xmlToArray($xml)
{		
    //将XML转为array        
    $array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);		
	return $array_data;
}

赠送小窍门

对于异步的调用,如果看不到效果。可以建一个日志表,把操作的数据记录在表中。便于测试。支付回调都是异步的,可以通过日志表中的数据来判断是否支付成功,是否调用了回调,调用了几次。

小结:
微信扫码支付不如支付宝扫码支付便捷。需要自己做很多处理。

posted @ 2016-09-14 16:29  TBHacker  阅读(17090)  评论(0编辑  收藏  举报