首頁  >  文章  >  php教程  >  微商城程式碼片段--微信公眾號支付接口

微商城程式碼片段--微信公眾號支付接口

WBOY
WBOY原創
2016-08-04 08:56:191256瀏覽

簡介
============================================
介面名稱:微信公眾號支付介面
版本:V3.3
開發語言:PHP

========
配置說明
===========================================

1.【基本資訊設定】
商家向微信提交企業以及銀行帳戶資料,商家功能審核通過後,可以獲得帳戶基本信息,找到本例程的配置文件“WxPay.pub.config.php”,配置好如下信息:
appId:微信公
作者官網:www.wemallshop.com
2. [程式碼]SDKRuntimeException.php

類別 SDKRuntimeException 擴充了 Exception {
公用函數 errorMessage()
{
返回 $this->getMessage();
}
}
? >
3. [程式碼]WxPay.pub.config.php

/**
* 微信支付幫助庫
* =================================================== ===
* 介面分三種:
* 【請求型介面】--Wxpay_client_
* 統一支付介面類別--UnifiedOrder
* 訂單查詢介面--OrderQuery
* 退款申請書--Refund
* 退款查詢介面--RefundQuery
* 對帳單介面--DownloadBill
* 短連結轉換介面--ShortUrl
* 【響應型介面】--Wxpay_server_
* 通用通知介面--Notify
* Native支付-請求商家取得商品資訊介面--NativeCall
* 【其他】
* 靜態連結二維碼--NativeLink
* JSAPI支付--JsApi
* =================================================== ====
* 【CommonUtil】常用工具:
* trimString(),設定參數時需要用到的字元處理函數
* createNoncestr(),產生隨機字串,不長於32位元
* formatBizQueryParaMap(),格式化參數,簽章過程需要用到
* getSign(),產生簽名
* arrayToXml(),array轉xml
* xmlToArray(),xml轉 array
* postXmlCurl(),以post方式提交xml到對應的介面url
* postXmlSSLCurl(),使用證書,以post方式提交xml到對應的介面url
*/
include_once("SDKRuntimeException.php");
include_once("WxPay.pub.config.php");
/**
* 所有介面的基底類別
*/
Common_util_pub 類別
{
函數 __construct() {
}
函數trimString($value)
{
$ret = null;
if (null != $value)
{
$ret = $value;
if (strlen($ret) == 0)
{
$ret = null;
}
}
返回$ret;
}

/**
* 作用:產生隨機字串,不長於32位元
*/
公用函數 createNoncestr( $length = 32 )
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str="";
for ( $i = 0; $i $str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
返回 $str;
}

/**
* 作用:格式化參數,簽章過程需要使用
*/
函數格式BizQueryParaMap($paraMap, $urlencode)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v)
{
if($urlencode)
{
$v = urlencode($v);
}
//$buff .= strtolower($k) . “=”。 $v。 「&」;
$buff .= $k 。 “=”。 $v。 「&」;
}
$reqPar;
if (strlen($buff) > 0)
{
$reqPar = substr($buff, 0, strlen($buff)-1);
}
返回 $reqPar;
}

/**
* 作用:產生簽名
*/
公用函數 getSign($Obj)
{
foreach ($Obj as $k => $v)
{
$參數[$k] = $v;
}
//簽章步驟一:依字典排序排序參數
ksort($參數);
$String = $this->formatBizQueryParaMap($Parameters, false);
//echo '【string1】'.$String.'';
//簽章步驟二:在string後加入KEY
$String = $String."&key=".WxPayConf_pub::KEY;
//echo "【string2】".$String."";
//簽章步驟三:MD5加密
$String = md5($String);
//echo "【string3】 ".$String."";
//簽章步驟四:所有字元轉為大寫
$result_ = strtoupper($String);
//echo "【結果】 ".$result_."";
回傳$結果_;
}

/**
* 作用:array轉xml
*/
函數 arrayToXml($arr)
{
$xml = "";
foreach ($arr as $key=>$val)
{
if (is_numeric($val))
{
$xml.="".$val."".$key.">";
}
其他
$xml.="".$key.">";
}
$xml.="
";
返回$xml;
}

/**
* 作用:將xml轉為array
*/
public function xmlToArray($xml)
{
//將XML轉為array
$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $array_data;
}
/**
* 作用:以post方式提交xml到對應的介面url
*/
public function postXmlCurl($xml,$url,$second=30)
{
//初始化curl
$ch = curl_init();
//設定超時
curl_setopt($ch, CURLOP_TIMEOUT, $second);
//這裡設定代理,如果有的話
//curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
//設定header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求結果為字串且輸出到螢幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//運行curl
$data = curl_exec($ch);
curl_close($ch);
//回傳結果
if($data)
{
curl_close($ch);
return $data;
}
else
{
$error = curl_errno($ch);
echo "curl出錯,錯誤碼:$error"."
";
echo "錯誤原因查詢";
curl_close($ch);
return false;
}
}
/**
* 作用:使用證書,以post方式提交xml到對應的介面url
*/
function postXmlSSLCurl($xml,$url,$second=30)
{
$ch = curl_init();
//超時時間
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
//這裡設定代理,如果有的話
//curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
//curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
//設定header
curl_setopt($ch,CURLOPT_HEADER,FALSE);
//要求結果為字串且輸出到螢幕上
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
//設定證書
//使用憑證:cert 與 key 分別屬於兩個.pem檔
//預設格式為PEM,可以註解
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, WxPayConf_pub::SSLCERT_PATH);
//預設格式為PEM,可以註解
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, WxPayConf_pub::SSLKEY_PATH);
//post提交方式
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
$data = curl_exec($ch);
//回傳結果
if($data){
curl_close($ch);
return $data;
}
else {
$error = curl_errno($ch);
echo "curl出錯,錯誤碼:$error"."
";
echo "錯誤原因查詢";
curl_close($ch);
return false;
}
}

/**
* 作用:列印數組
*/
function printErr($wording='',$err='')
{
print_r('

');<br>
        echo $wording."";<br>
        var_dump($err);<br>
        print_r('
');
}
}
/**
* 請求型介面的基底類別
*/
class Wxpay_client_pub extends Common_util_pub
{
var $parameters;//請求參數,類型為關聯數組
public $response;//微信回傳的回應
public $result;//回傳參數,類型為關聯數組
var $url;//介面連結
var $curl_timeout;//curl超時時間

/**
* 作用:設定請求參數
*/
function setParameter($parameter, $parameterValue)
{
$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}

/**
* 作用:設定標配的請求參數,產生簽名,產生介面參數xml
*/
函數createXml()
{
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
返回 $this->arrayToXml($this->parameters);
}

/**
* 作用:post請求xml
*/
函數 postXml()
{
$xml = $this->createXml();
$this->response = $this->postXmlCurl($xml,$this->url,$this->curl_timeout);
返回 $this->response;
}

/**
* 作用:使用憑證post請求xml
*/
函數 postXmlSSL()
{
$xml = $this->createXml();
$this->response = $this->postXmlSSLCurl($xml,$this->url,$this->curl_timeout);
返回 $this->response;
}
/**
* 作用:取得結果,預設不使用憑證
*/
函數 getResult()
{
$this->postXml();
$this->結果 = $this->xmlToArray($this->response);
回傳 $this->結果;
}
}
/**
* 統一支付介面類別
*/
UnifiedOrder_pub 類別擴充了 Wxpay_client_pub
{
函數 __construct()
{
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}

/**
* 產生介面參數xml
*/
函數createXml()
{
試試
{
//偵測必填參數
if($this->parameters["out_trade_no"] == null)
{
throw new SDKRuntimeException("短缺統一支付介面必填參數out_trade_no!"."
");
}elseif($this->parameters["body"] == null){
throw new SDKRuntimeException("缺少統一支付介面必填參數body!"."
");
}elseif ($this->parameters["total_fee"] == null ) {
throw new SDKRuntimeException("短缺統一支付介面必填參數total_fee!"."
");
}elseif ($this->parameters["notify_url"] == null) {
throw new SDKRuntimeException("缺少統一支付介面必填參數notify_url!"."
");
}elseif ($this->parameters["trade_type"] == null) {
throw new SDKRuntimeException("短缺統一支付介面必填參數trade_type!"."
");
}elseif ($this->parameters["trade_type"] == "JSAPI" &&
$this->parameters["openid"] == NULL){
throw new SDKRuntimeException("統一支付介面中,缺少必填參數openid!trade_type為JSAPI時,openid為必填參數!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["spbill_create_ip"] = $_SERVER['REMOTE_ADDR'];//終止ip
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
返回 $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
死($e->errorMessage());
}
}

/**
* 獲取prepay_id
*/
函數 getPrepayId()
{
$this->postXml();
$this->結果 = $this->xmlToArray($this->response);
$prepay_id = $this->result["prepay_id"];
回傳 $prepay_id;
}

}
/**
* 訂單查詢介面
*/
OrderQuery_pub 類別擴充了 Wxpay_client_pub
{
函數 __construct()
{
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/pay/orderquery";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* 產生介面參數xml
*/
函數createXml()
{
試試
{
//偵測必填參數
if($this->parameters["out_trade_no"] == null &&
$this->parameters["transaction_id"] == null)
{
throw new SDKRuntimeException("訂單查詢介面中,out_trade_no、transaction_id至少填一個!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
}
/**
* 退款申請書
*/
class Refund_pub extends Wxpay_client_pub
{

function __construct() {
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}

/**
* 產生介面參數xml
*/
function createXml()
{
try
{
//偵測必填參數
if($this->parameters["out_trade_no"] == null && $this->parameters["transaction_id"] == null) {
throw new SDKRuntimeException("退款申請介面中,out_trade_no、transaction_id至少填一個!"."
");
}elseif($this->parameters["out_refund_no"] == null){
throw new SDKRuntimeException("退款申請介面中,缺少必填參數out_refund_no!"."
");
}elseif($this->parameters["total_fee"] == null){
throw new SDKRuntimeException("退款申請介面中,缺少必填參數total_fee!"."
");
}elseif($this->parameters["refund_fee"] == null){
throw new SDKRuntimeException("退款申請介面中,缺少必填參數refund_fee!"."
");
}elseif($this->parameters["op_user_id"] == null){
throw new SDKRuntimeException("退款申請介面中,缺少必填參數op_user_id!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* 作用:取得結果,使用證書通訊
*/
function getResult()
{
$this->postXmlSSL();
$this->result = $this->xmlToArray($this->response);
return $this->result;
}

}
/**
* 退款查詢介面
*/
class RefundQuery_pub extends Wxpay_client_pub
{

function __construct() {
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/pay/refundquery";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}

/**
* 產生介面參數xml
*/
function createXml()
{
try
{
if($this->parameters["out_refund_no"] == null &&
$this->parameters["out_trade_no"] == null &&
$this->parameters["transaction_id"] == null &&
$this->parameters["refund_id "] == null)
{
throw new SDKRuntimeException("退款查詢介面中,out_refund_no、out_trade_no、transaction_id、refund_id四個參數必填一個!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* 作用:取得結果,使用證書通訊
*/
function getResult()
{
$this->postXmlSSL();
$this->result = $this->xmlToArray($this->response);
return $this->result;
}
}
/**
* 對帳單介面
*/
class DownloadBill_pub extends Wxpay_client_pub
{
function __construct()
{
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* 產生介面參數xml
*/
function createXml()
{
try
{
if($this->parameters["bill_date"] == null )
{
throw new SDKRuntimeException("對帳單介面中,缺少必填參數bill_date!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}

/**
* 作用:取得結果,預設不使用憑證
*/
function getResult()
{
$this->postXml();
$this->result = $this->xmlToArray($this->result_xml);
return $this->result;
}


}
/**
* 短連結轉換介面
*/
class ShortUrl_pub extends Wxpay_client_pub
{
function __construct()
{
//設定介面連結
$this->url = "https://api.mch.weixin.qq.com/tools/shorturl";
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}

/**
* 產生介面參數xml
*/
function createXml()
{
try
{
if($this->parameters["long_url"] == null )
{
throw new SDKRuntimeException("短鏈結轉換介面中,缺少必填參數long_url!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}

/**
* 獲取prepay_id
*/
function getShortUrl()
{
$this->postXml();
$prepay_id = $this->result["short_url"];
return $prepay_id;
}

}
/**
* 響應型介面基底類
*/
class Wxpay_server_pub extends Common_util_pub
{
public $data;//接收的數據,型別為關聯數組
var $returnParameters;//返回參數,類型為關聯數組

/**
* 將微信的請求xml轉換成關聯數組,以方便資料處理
*/
function saveData($xml)
{
$this->data = $this->xmlToArray($xml);
}

function checkSign()
{
$tmpData = $this->data;
unset($tmpData['sign']);
$sign = $this->getSign($tmpData);//本地簽名
if ($this->data['sign'] == $sign) {
return TRUE;
}
return FALSE;
}

/**
* 取得微信的請求資料
*/
function getData()
{
return $this->data;
}

/**
* 設定回傳微信的xml資料
*/
function setReturnParameter($parameter, $parameterValue)
{
$this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}

/**
* 產生介面參數xml
*/
function createXml()
{
return $this->arrayToXml($this->returnParameters);
}

/**
* 將xml資料回傳微信
*/
function returnXml()
{
$returnXml = $this->createXml();
return $returnXml;
}
}
/**
* 通用通知介面
*/
class Notify_pub extends Wxpay_server_pub
{
}
/**
* 請求商家取得商品資訊介面
*/
class NativeCall_pub extends Wxpay_server_pub
{
/**
* 產生介面參數xml
*/
function createXml()
{
if($this->returnParameters["return_code"] == "SUCCESS"){
$this->returnParameters["appid"] = WxPayConf_pub::APPID;//公用帳號ID
$this->returnParameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$this->returnParameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->returnParameters["sign"] = $this->getSign($this->returnParameters);//簽名
}
return $this->arrayToXml($this->returnParameters);
}

/**
* 取得product_id
*/
function getProductId()
{
$product_id = $this->data["product_id"];
return $product_id;
}

}
/**
* 靜態連結二維碼
*/
class NativeLink_pub extends Common_util_pub
{
var $parameters;//靜態鏈結參數
var $url;//靜態連結
function __construct()
{
}

/**
* 設定參數
*/
function setParameter($parameter, $parameterValue)
{
$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}

/**
* 產生Native支付連結二維碼
*/
function createLink()
{
try
{
if($this->parameters["product_id"] == null)
{
throw new SDKRuntimeException("缺少Native支付二維碼連結必填參數product_id!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//公有帳號ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//商家號碼
$time_stamp = time();
$this->parameters["time_stamp"] = "$time_stamp";//時間戳記
$this->parameters["nonce_str"] = $this->createNoncestr();//隨機字串
$this->parameters["sign"] = $this->getSign($this->parameters);//簽名
$bizString = $this->formatBizQueryParaMap($this->parameters, false);
$this->url = "weixin://wxpay/bizpayurl?".$bizString;
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}

/**
* 返回連結
*/
function getUrl()
{
$this->createLink();
return $this->url;
}
}
/**
* JSAPI支付-H5網頁端調起支付介面
*/
class JsApi_pub extends Common_util_pub
{
var $code;//code碼,用以取得openid
var $openid;//使用者的openid
var $parameters;//jsapi參數,格式為json
var $prepay_id;//使用統一支付介面所得到的預付id
var $curl_timeout;//curl超時時間
function __construct()
{
//設定curl超時時間
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}

/**
* 作用:產生可以獲得code的url
*/
function createOauthUrlForCode($redirectUrl)
{
$urlObj["appid"] = WxPayConf_pub::APPID;
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_base";
$urlObj["state"] = "STATE"."#wechat_redirect";
$bizString = $this->formatBizQueryParaMap($urlObj, false);
return "https://open.weixin.qq.com/connect/oauth2/authorize?".$bizString;
}
/**
* 作用:產生可以獲得openid的url
*/
function createOauthUrlForOpenid()
{
$urlObj["appid"] = WxPayConf_pub::APPID;
$urlObj["secret"] = WxPayConf_pub::APPSECRET;
$urlObj["code"] = $this->code;
$urlObj["grant_type"] = "authorization_code";
$bizString = $this->formatBizQueryParaMap($urlObj, false);
return "https://api.weixin.qq.com/sns/oauth2/access_token?".$bizString;
}


/**
* 作用:透過curl向微信提交code,以取得openid
*/
function getOpenid()
{
$url = $this->createOauthUrlForOpenid();
//初始化curl
$ch = curl_init();
//設定超時
curl_setopt($ch, CURLOP_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//运行curl,结果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res,true);
$this->openid = $data['openid'];
return $this->openid;
}
/**
* 作用:设置prepay_id
*/
function setPrepayId($prepayId)
{
$this->prepay_id = $prepayId;
}
/**
* 作用:设置code
*/
function setCode($code_)
{
$this->code = $code_;
}
/**
* 作用:设置jsapi的参数
*/
public function getParameters()
{
$jsApiObj["appId"] = WxPayConf_pub::APPID;
$timeStamp = time();
$jsApiObj["timeStamp"] = "$timeStamp";
$jsApiObj["nonceStr"] = $this->createNoncestr();
$jsApiObj["package"] = "prepay_id=$this->prepay_id";
$jsApiObj["signType"] = "MD5";
$jsApiObj["paySign"] = $this->getSign($jsApiObj);
$this->parameters = json_encode($jsApiObj);

return $this->parameters;
}
}
?>
5. [代码]download_bill.php
?
/**
* 对账单接口demo
* ====================================================
* 商户可以通过该接口下载历史交易清单。
*/
include_once("../WxPayPubHelper/WxPayPubHelper.php");
//对账单日期
if (!isset($_POST["bill_date"])){
$bill_date = "20140814";
}
else{
$bill_date = $_POST["bill_date"];

//使用对账单接口
$downloadBill = new DownloadBill_pub();
//设置对账单接口参数
//设置必填参数
//appid已填,商户无需重复填写
//mch_id已填,商户无需重复填写
//noncestr已填,商户无需重复填写
//sign已填,商户无需重复填写
$downloadBill->setParameter("bill_date","$bill_date");//对账单日期
$downloadBill->setParameter("bill_type","ALL");//账单类型
//非必填参数,商户可根据实际情况选填
//$downloadBill->setParameter("device_info","XXXX");//设备号

//对账单接口结果
$downloadBillResult = $downloadBill->getResult();
echo $downloadBillResult['return_code'];

if ($downloadBillResult['return_code'] == "FAIL") {
echo "通信出错:".$downloadBillResult['return_msg'];
}else{
print_r('
');<br>
             echo "【对账单详情】"."";<br>
             print_r($downloadBill->response);<br>
             print_r('
');
}
}

?>





微信安全支付





对账单查询


日期(格式:20140101):






返回首页


?>



6. [代碼]index.php
?




微信安全支付








7. [程式碼]js_api_call.php
?
/**
* JS_API支付demo
* =================================================== ===
* 在微信瀏覽器裡面開啟H5網頁執行JS調起付款。介面輸入輸出資料格式為JSON。
* 成功調起付款需要三個步驟:
* 步驟1:網頁授權取得使用者openid
* 步驟2:使用統一支付接口,取得prepay_id
* 步驟3:使用jsapi調起付款
*/
include_once("./WxPayPubHelper/WxPayPubHelper.php");

//使用jsapi介面
$jsApi = new JsApi_pub();
//=========步驟1:網頁授權取得使用者openid============
//透過code取得openid
if (!isset($_GET['code']))
{
//觸發微信回傳code碼
$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
Header("Location: $url");
}else
{
//取得code碼,以取得openid
$code = $_GET['code'];
$jsApi->setCode($code);
$openid = $jsApi->getOpenId();
}

//=========步驟2:使用統一支付接口,取得prepay_id============
//使用統一支付介面
$unifiedOrder = new UnifiedOrder_pub();

//設定統一支付介面參數
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//spbill_create_ip已填入,商家無須重複填入
//sign已填,商家無須重複填入
$body = $_GET["body"];
$out_trade_no = $_GET["orderid"];
$total_fee = $_GET["totalprice"];
$url = $_GET["url"];
$unifiedOrder->setParameter("openid","$openid");//商品描述
$unifiedOrder->setParameter("body","$body");//商品描述
//自訂訂單號,此處僅作舉例
// $timeStamp = time();
// $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商家訂單號碼
$unifiedOrder->setParameter("total_fee","$total_fee");//總金額
$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址
$unifiedOrder->setParameter("trade_type","JSAPI");//交易類型

//非必填參數,商家可依實際情況選填
//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商家號碼
//$unifiedOrder->setParameter("device_info","XXXX");//裝置號碼
//$unifiedOrder->setParameter("attach","XXXX");//附加資料
//$unifiedOrder->setParameter("time_start","XXXX");//交易起始時間
//$unifiedOrder->setParameter("time_expire","XXXX");//交易結束時間
//$unifiedOrder->setParameter("goods_tag","XXXX");//商品標記
//$unifiedOrder->setParameter("openid","XXXX");//使用者標識
//$unifiedOrder->setParameter("product_id","XXXX");//商品ID
$prepay_id = $unifiedOrder->getPrepayId();
//=========步驟3:使用jsapi調起支付============
$jsApi->setPrepayId($prepay_id);
$jsApiParameters = $jsApi->getParameters();
//echo $jsApiParameters;
?>




微信安全支付






8. [程式碼]log_.php
?
class Log_
{
// 列印log
function log_result($file,$word)
{
$fp = fopen($file,"a");
flock($fp, LOCK_EX) ;
fwrite($fp,"執行日期:".strftime("%Y-%m-%d-%H:%M:%S",time())."n".$word."nn");
flock($fp, LOCK_UN);
fclose($fp);
}
}
?>
9. [程式碼]native_call.php
?
/**
* Native(原生)支付模式一demo
* =================================================== ===
* 模式一:商家依固定格式產生連結二維碼,使用者掃碼後調微信
* 會將productid和使用者openid傳送到商家設定的連結上,商家收到
* 請求產生訂單,呼叫統一支付介面下單提交至微信,微信會回傳
* 給商家prepayid。
* 本例程對應的二維碼由native_call_qrcode.php產生;
* 本例程對應的回應服務為native_call.php;
* 需兩者配合使用。
*
*/
include_once("./log_.php");
include_once("../WxPayPubHelper/WxPayPubHelper.php");

//以log檔案形式記錄回調訊息,用於調試
$log_ = new Log_();
$log_name="./native_call.log";
//使用native通知介面
$nativeCall = new NativeCall_pub();
//接收微信請求
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$log_->log_result($log_name,"【收到的native通知】:n".$xml."n");
$nativeCall->saveData($xml);

if($nativeCall->checkSign() == FALSE){
$nativeCall->setReturnParameter("return_code","FAIL");//返回狀態碼
$nativeCall->setReturnParameter("return_msg","簽章失敗");//回傳訊息
}else{
//提取product_id
$product_id = $nativeCall->getProductId();

//使用統一支付介面
$unifiedOrder = new UnifiedOrder_pub();

//根據不同的$product_id設定對應的下單參數,此處只舉例一種
switch ($product_id)
{
case WxPayConf_pub::APPID."static"://與native_call_qrcode.php中的靜態連結二維碼對應
//設定統一支付介面參數
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//spbill_create_ip已填入,商家無須重複填入
//sign已填,商家無須重複填入
$unifiedOrder->setParameter("body","貢獻一分錢");//商品描述
//自訂訂單號,此處僅作舉例
$timeStamp = time();
$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商家訂單編號 $unifiedOrder->setParameter("product_id","$product_id");//商品ID
$unifiedOrder->setParameter("total_fee","1");//總金額
$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址
$unifiedOrder->setParameter("trade_type","NATIVE");//交易類型
$unifiedOrder->setParameter("product_id","$product_id");//使用者識別
//非必填參數,商家可依實際情況選填
//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商家號碼
//$unifiedOrder->setParameter("device_info","XXXX");//裝置號碼
//$unifiedOrder->setParameter("attach","XXXX");//附加資料
//$unifiedOrder->setParameter("time_start","XXXX");//交易起始時間
//$unifiedOrder->setParameter("time_expire","XXXX");//交易結束時間
//$unifiedOrder->setParameter("goods_tag","XXXX");//商品標記
//$unifiedOrder->setParameter("openid","XXXX");//使用者標識

//取得prepay_id
$prepay_id = $unifiedOrder->getPrepayId();
//設定回傳碼
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//sign已填,商家無須重複填入
$nativeCall->setReturnParameter("return_code","SUCCESS");//返回狀態碼
$nativeCall->setReturnParameter("result_code","SUCCESS");//業務成果
$nativeCall->setReturnParameter("prepay_id","$prepay_id");//預付ID

break;
default:
//設定回傳碼
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//sign已填,商家無須重複填入
$nativeCall->setReturnParameter("return_code","SUCCESS");//返回狀態碼
$nativeCall->setReturnParameter("result_code","FAIL");//業務成果
$nativeCall->setReturnParameter("err_code_des","此商品無效");//業務成果
break;
}
}

//將結果回傳微信
$returnXml = $nativeCall->returnXml();
$log_->log_result($log_name,"【傳回微信的native回應】:n".$returnXml."n");
echo $returnXml;

//交易完成
?>
10. [代碼]native_call_qrcode.php 跳至[1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [ 14] [15] [16] [全螢幕預覽]
?
/**
* Native(原生)支付模式一demo
* =================================================== ===
* 模式一:商家依固定格式產生連結二維碼,使用者掃碼後調微信
* 會將productid和使用者openid傳送到商家設定的連結上,商家收到
* 請求產生訂單,呼叫統一支付介面下單提交至微信,微信會回傳
* 給商家prepayid。
* 本例程對應的二維碼由native_call_qrcode.php產生;
* 本例程對應的回應服務為native_call.php;
* 需兩者配合使用。
*/
include_once("../WxPayPubHelper/WxPayPubHelper.php");
//設定靜態連結
$nativeLink = new NativeLink_pub();

//設定靜態連結參數
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//time_stamp已填,商家無須重複填寫
//sign已填,商家無須重複填入
$product_id = WxPayConf_pub::APPID."static";//自訂商品id
$nativeLink->setParameter("product_id","$product_id");//商品id
//取得連結
$product_url = $nativeLink->getUrl();
//使用短連結轉換介面
$shortUrl = new ShortUrl_pub();
//設定必填參數
//appid已填,商家無須重複填寫
//mch_id已填,商家無須重複填寫
//noncestr已填,商家無需重複填寫
//sign已填,商家無須重複填入
$shortUrl->setParameter("long_url","$product_url");//URL連結
//取得短連結
$codeUrl = $shortUrl->getShortUrl();

?>





微信安全支付



掃我,掃我




回首頁



<script><br /> var url = "<?php echo $product_url;?>";<br /> //参数1表示图像大小,取值范围1-10;参数2表示质量,取值范围&#039;L&#039;,&#039;M&#039;,&#039;Q&#039;,&#039;H&#039;<br /> var qr = qrcode(10, &#039;M&#039;);<br /> qr.addData(url);<br /> qr.make();<br /> var dom=document.createElement(&#039;DIV&#039;);<br /> dom.innerHTML = qr.createImgTag();<br /> var element=document.getElementById("qrcode");<br /> element.appendChild(dom);<br /> </script>

11. [代码]native_dynamic_qrcode.php
?
/**
* Native(原生)支付-模式二-demo
* ====================================================
* 商户生成订单,先调用统一支付接口获取到code_url,
* 此URL直接生成二维码,用户扫码后调起支付。
*
*/
include_once("../WxPayPubHelper/WxPayPubHelper.php");
//使用统一支付接口
$unifiedOrder = new UnifiedOrder_pub();

//设置统一支付接口参数
//设置必填参数
//appid已填,商户无需重复填写
//mch_id已填,商户无需重复填写
//noncestr已填,商户无需重复填写
//spbill_create_ip已填,商户无需重复填写
//sign已填,商户无需重复填写
$unifiedOrder->setParameter("body","贡献一分钱");//商品描述
//自定义订单号,此处仅作举例
$timeStamp = time();
$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//商户订单号
$unifiedOrder->setParameter("total_fee","1");//总金额
$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//通知地址
$unifiedOrder->setParameter("trade_type","NATIVE");//交易类型
//非必填参数,商户可根据实际情况选填
//$unifiedOrder->setParameter("sub_mch_id","XXXX");//子商户号
//$unifiedOrder->setParameter("device_info","XXXX");//设备号
//$unifiedOrder->setParameter("attach","XXXX");//附加数据
//$unifiedOrder->setParameter("time_start","XXXX");//交易起始时间
//$unifiedOrder->setParameter("time_expire","XXXX");//交易结束时间
//$unifiedOrder->setParameter("goods_tag","XXXX");//商品标记
//$unifiedOrder->setParameter("openid","XXXX");//用户标识
//$unifiedOrder->setParameter("product_id","XXXX");//商品ID

//获取统一支付接口结果
$unifiedOrderResult = $unifiedOrder->getResult();

//商户根据实际情况设置相应的处理流程
if ($unifiedOrderResult["return_code"] == "FAIL")
{
//商户自行增加处理流程
echo "通信出错:".$unifiedOrderResult['return_msg']."
";
}
elseif($unifiedOrderResult["result_code"] == "FAIL")
{
//商户自行增加处理流程
echo "错误代码:".$unifiedOrderResult['err_code']."
";
echo "错误代码描述:".$unifiedOrderResult['err_code_des']."
";
}
elseif($unifiedOrderResult["code_url"] != NULL)
{
//从统一支付接口获取到code_url
$code_url = $unifiedOrderResult["code_url"];
//商户自行增加处理流程
//......
}
?>






微信安全支付





订单号:





















返回首页



<script><br /> if(<?php echo $unifiedOrderResult["code_url"] != NULL; ?>)<br /> {<br /> var url = "<?php echo $code_url;?>";<br /> //参数1表示图像大小,取值范围1-10;参数2表示质量,取值范围&#039;L&#039;,&#039;M&#039;,&#039;Q&#039;,&#039;H&#039;<br /> var qr = qrcode(10, &#039;M&#039;);<br /> qr.addData(url);<br /> qr.make();<br /> var wording=document.createElement(&#039;p&#039;);<br /> wording.innerHTML = "扫我,扫我";<br /> var code=document.createElement(&#039;DIV&#039;);<br /> code.innerHTML = qr.createImgTag();<br /> var element=document.getElementById("qrcode");<br /> element.appendChild(wording);<br /> element.appendChild(code);<br /> }<br /> </script>

12. [代码]notify_url.php
?
/**
* 通用通知接口demo
* ====================================================
* 支付完成后,微信会把相关支付和用户信息发送到商户设定的通知URL,
* 商户接收回调信息后,根据需要设定相应的处理流程。
*
* 这里举例使用log文件形式记录回调信息。
*/
include_once("./log_.php");
include_once("./WxPayPubHelper/WxPayPubHelper.php");
include_once('../../Public/Conf/config.php');

//使用通用通知接口
$notify = new Notify_pub();
//存储微信的回调
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$notify->saveData($xml);

//验证签名,并回应微信。
//对后台通知交互时,如果微信收到商户的应答不是成功或超时,微信认为通知失败,
//微信会通过一定的策略(如30分钟共8次)定期重新发起通知,
//尽可能提高通知的成功率,但微信不保证通知最终能成功。
if($notify->checkSign() == FALSE){
$notify->setReturnParameter("return_code","FAIL");//返回状态码
$notify->setReturnParameter("return_msg","签名失败");//返回信息
}else{
$notify->setReturnParameter("return_code","SUCCESS");//设置返回码
}
$returnXml = $notify->returnXml();
echo $returnXml;
//==商户根据实际情况设置相应的处理流程,此处仅作举例=======

//以log文件形式记录回调信息
$log_ = new Log_();
$log_name="./notify_url.log";//log文件路径
$log_->log_result($log_name,"【接收到的notify通知】:\n".$xml."\n");
if($notify->checkSign() == TRUE)
{
if ($notify->data["return_code"] == "FAIL") {
//此处应该更新一下订单状态,商户自行增删操作
$log_->log_result($log_name,"【通信出错】:\n".$xml."\n");
}
elseif($notify->data["result_code"] == "FAIL"){
//此处应该更新一下订单状态,商户自行增删操作
$log_->log_result($log_name,"【业务出错】:\n".$xml."\n");
}
else{
//此处应该更新一下订单状态,商户自行增删操作
$log_->log_result($log_name,"【支付成功】:\n".$xml."\n");
}
//商户自行增加处理流程,
//例如:更新订单状态
//例如:数据库操作
//例如:推送支付完成信息
$xml = $notify->xmlToArray($xml);
// 商户订单号
$out_trade_no = $xml ['out_trade_no'];
$total_fee = $xml ['total_fee'];
$uid = $xml ['openid'];
$log_->log_result($log_name,"【订单号】:\n".$out_trade_no."\n");
// 判断该笔订单是否在商户网站中已经做过处理
// 如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序
// 如果有做过处理,不执行商户的业务程序
if (! empty ( $out_trade_no )) {
$sql = "update " . DB_PREFIX . "order set pay_status=1 where orderid='" . $out_trade_no . "'";
mysql_query ( $sql, $conn );
}
}
?>
13. [代码]order_query.php
?
/**
* 订单查询-demo
* ====================================================
* 该接口提供所有微信支付订单的查询。
* 当支付通知处理异常或丢失的情况,商户可以通过该接口查询订单支付状态。
*
*/
include_once("../WxPayPubHelper/WxPayP
陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn