Introduction
============================================
Interface name: WeChat official account payment interface
Version: V3.3
Development language: PHP
========
Configuration instructions
===========================================
1.【Basic information settings】
The merchant submits corporate and bank account information to WeChat. After the merchant function is approved, the basic account information can be obtained. Find the configuration file "WxPay.pub.config.php" for this routine and configure the following information:
appId: WeChat public
作者官网:www.wemallshop.com
2. [代码]SDKRuntimeException.php
?
class SDKRuntimeException extends Exception {
public function errorMessage()
{
return $this->getMessage();
}
}
?>
3. [代码]WxPay.pub.config.php
?
/**
* WeChat payment help library
* ================================================= ===
* There are three types of interfaces:
* 【Request interface】--Wxpay_client_
* Unified payment interface class--UnifiedOrder
* Order query interface--OrderQuery
* Refund application interface--Refund
* Refund query interface--RefundQuery
* Bill interface--DownloadBill
* Short link conversion interface--ShortUrl
* 【Responsive interface】--Wxpay_server_
* Universal notification interface--Notify
* Native payment - Request merchants to obtain product information interface - NativeCall
*【Others】
* Static link QR code--NativeLink
* JSAPI payment--JsApi
* ================================================= ====
*【CommonUtil】Commonly used tools:
* trimString(), the character processing function needed when setting parameters
* createNoncestr(), generates a random string, no longer than 32 bits
* formatBizQueryParaMap(), format parameters, needed for the signature process
* getSign(), generate signature
* arrayToXml(), array to xml
* xmlToArray(), xml to array
* postXmlCurl(), submit xml to the corresponding interface url in post mode
* postXmlSSLCurl(), use the certificate to submit xml to the corresponding interface url in post mode
*/
include_once("SDKRuntimeException.php");
include_once("WxPay.pub.config.php");
/**
* Base class for all interfaces
*/
class Common_util_pub
{
function __construct() {
}
function trimString($value)
{
$ret = null;
if (null != $value)
{
$ret = $value;
if (strlen($ret) == 0)
{
$ret = null;
}
}
return $ret;
}
/**
* Function: Generate a random string, no longer than 32 bits
*/
public function createNoncestr( $length = 32 )
{
$chars = "abcdefghijklmnopqrstuvwxyz0123456789";
$str ="";
for ( $i = 0; $i
$str.= substr($chars, mt_rand(0, strlen($chars)-1), 1);
}
return $str;
}
/**
* Function: Formatting parameters, required for the signature process
*/
function formatBizQueryParaMap($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);
}
return $reqPar;
}
/**
* Function: Generate signature
*/
public function getSign($Obj)
{
foreach ($Obj as $k => $v)
{
$Parameters[$k] = $v;
}
//签名步骤一:按字典序排序参数
ksort($Parameters);
$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】 ".$result_."";
return $result_;
}
/**
* Function: array to xml
*/
function arrayToXml($arr)
{
$xml = "";
foreach ($arr as $key=>$val)
{
if (is_numeric($val))
{
$xml.="".$val."".$key.">";
}
else
$xml.="".$key.">";
}
$xml.="";
return $xml;
}
/**
* Function: Convert xml to array
*/
public function xmlToArray($xml)
{
//Convert XML to array
$array_data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $array_data;
}
/**
* Function: Submit xml to the corresponding interface url in post mode
*/
public function postXmlCurl($xml,$url,$second=30)
{
//Initialize curl
$ch = curl_init();
//Set timeout
curl_setopt($ch, CURLOP_TIMEOUT, $second);
//Set the proxy here, if any
//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);
//Set header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//Require the result to be a string and output it to the screen
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//post submission method
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//Run curl
$data = curl_exec($ch);
curl_close($ch);
//return result
if($data)
{
curl_close($ch);
return $data;
}
else
{
$error = curl_errno($ch);
echo "curl error, error code: $error"."
";
echo "Error cause query";
curl_close($ch);
return false;
}
}
/**
* Function: Use the certificate to submit xml to the corresponding interface url in post mode
*/
function postXmlSSLCurl($xml,$url,$second=30)
{
$ch = curl_init();
//Timeout period
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
//Set the proxy here, if any
//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);
//Set header
curl_setopt($ch,CURLOPT_HEADER,FALSE);
//Require the result to be a string and output it to the screen
curl_setopt($ch,CURLOPT_RETURNTRANSFER,TRUE);
//Set the certificate
//Use certificate: cert and key belong to two .pem files respectively
//The default format is PEM and can be annotated
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLCERT, WxPayConf_pub::SSLCERT_PATH);
//The default format is PEM and can be annotated
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
curl_setopt($ch,CURLOPT_SSLKEY, WxPayConf_pub::SSLKEY_PATH);
//post submission method
curl_setopt($ch,CURLOPT_POST, true);
curl_setopt($ch,CURLOPT_POSTFIELDS,$xml);
$data = curl_exec($ch);
//return result
if($data){
curl_close($ch);
return $data;
}
else {
$error = curl_errno($ch);
echo "curl error, error code: $error"."
";
echo "Error cause query";
curl_close($ch);
return false;
}
}
/**
* Function: Print array
*/
function printErr($wording='',$err='')
{
print_r('
');<br>
echo $wording."";<br>
var_dump($err);<br>
print_r('
Copy after login
');
}
}
/**
* Base class of request interface
*/
class Wxpay_client_pub extends Common_util_pub
{
var $parameters;//Request parameters, type is associative array
public $response; //Response returned by WeChat
public $result;//Return parameter, type is associative array
var $url;//Interface link
var $curl_timeout;//curl timeout
/**
* Function: Set request parameters
*/
function setParameter($parameter, $parameterValue)
{
$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}
/**
* Function: Set standard request parameters, generate signatures, and generate interface parameter xml
*/
function 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);//签名
return $this->arrayToXml($this->parameters);
}
/**
* Function: post request xml
*/
function postXml()
{
$xml = $this->createXml();
$this->response = $this->postXmlCurl($xml,$this->url,$this->curl_timeout);
return $this->response;
}
/**
* Function: Use certificate post to request xml
*/
function postXmlSSL()
{
$xml = $this->createXml();
$this->response = $this->postXmlSSLCurl($xml,$this->url,$this->curl_timeout);
return $this->response;
}
/**
* Function: Get results, certificate is not used by default
*/
function getResult()
{
$this->postXml();
$this->result = $this->xmlToArray($this->response);
return $this->result;
}
}
/**
* Unified payment interface class
*/
class UnifiedOrder_pub extends Wxpay_client_pub
{
function __construct()
{
//设置接口链接
$this->url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
//设置curl超时时间
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter xml
*/
function createXml()
{
try
{
//检测必填参数
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);//签名
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Get prepay_id
*/
function getPrepayId()
{
$this->postXml();
$this->result = $this->xmlToArray($this->response);
$prepay_id = $this->result["prepay_id"];
return $prepay_id;
}
}
/**
* Order query interface
*/
class OrderQuery_pub extends Wxpay_client_pub
{
function __construct()
{
//设置接口链接
$this->url = "https://api.mch.weixin.qq.com/pay/orderquery";
//设置curl超时时间
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter xml
*/
function createXml()
{
try
{
//检测必填参数
if($this->parameters["out_trade_no"] == null &&
$this->parameters["transaction_id"] == null)
{
throw new SDKRuntimeException("In the order query interface, fill in at least one out_trade_no and transaction_id!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
}
/**
* Refund application interface
*/
class Refund_pub extends Wxpay_client_pub
{
function __construct() {
//Set interface link
$this->url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//Set curl timeout
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter xml
*/
function createXml()
{
try
{
//Detect required parameters
if($this->parameters["out_trade_no"] == null && $this->parameters["transaction_id"] == null) {
throw new SDKRuntimeException("In the refund application interface, fill in at least one out_trade_no and transaction_id!"."
");
}elseif($this->parameters["out_refund_no"] == null){
throw new SDKRuntimeException("In the refund application interface, the required parameter out_refund_no is missing!"."
");
}elseif($this->parameters["total_fee"] == null){
throw new SDKRuntimeException("In the refund application interface, the required parameter total_fee is missing!"."
");
}elseif($this->parameters["refund_fee"] == null){
throw new SDKRuntimeException("In the refund application interface, the required parameter refund_fee is missing!"."
");
}elseif($this->parameters["op_user_id"] == null){
throw new SDKRuntimeException("In the refund application interface, the required parameter op_user_id is missing!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Function: Get results and communicate using certificates
*/
function getResult()
{
$this->postXmlSSL();
$this->result = $this->xmlToArray($this->response);
return $this->result;
}
}
/**
* Refund inquiry interface
*/
class RefundQuery_pub extends Wxpay_client_pub
{
function __construct() {
//Set interface link
$this->url = "https://api.mch.weixin.qq.com/pay/refundquery";
//Set curl timeout
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter 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("In the refund query interface, one of the four parameters out_refund_no, out_trade_no, transaction_id, and refund_id is required!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Function: Get results and communicate using certificates
*/
function getResult()
{
$this->postXmlSSL();
$this->result = $this->xmlToArray($this->response);
return $this->result;
}
}
/**
* Billing interface
*/
class DownloadBill_pub extends Wxpay_client_pub
{
function __construct()
{
//Set interface link
$this->url = "https://api.mch.weixin.qq.com/pay/downloadbill";
//Set curl timeout
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter xml
*/
function createXml()
{
try
{
if($this->parameters["bill_date"] == null )
{
throw new SDKRuntimeException("In the statement interface, the required parameter bill_date is missing!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Function: Get results, certificate is not used by default
*/
function getResult()
{
$this->postXml();
$this->result = $this->xmlToArray($this->result_xml);
return $this->result;
}
}
/**
* Short link conversion interface
*/
class ShortUrl_pub extends Wxpay_client_pub
{
function __construct()
{
//Set interface link
$this->url = "https://api.mch.weixin.qq.com/tools/shorturl";
//Set curl timeout
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Generate interface parameter xml
*/
function createXml()
{
try
{
if($this->parameters["long_url"] == null )
{
throw new SDKRuntimeException("In the short link conversion interface, the required parameter long_url is missing!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
return $this->arrayToXml($this->parameters);
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Get prepay_id
*/
function getShortUrl()
{
$this->postXml();
$prepay_id = $this->result["short_url"];
return $prepay_id;
}
}
/**
*Responsive interface base class
*/
class Wxpay_server_pub extends Common_util_pub
{
public $data;//The received data is of type associative array
var $returnParameters;//Return parameters, type is associative array
/**
* Convert WeChat's request xml into an associative array to facilitate data processing
*/
function saveData($xml)
{
$this->data = $this->xmlToArray($xml);
}
function checkSign()
{
$tmpData = $this->data;
unset($tmpData['sign']);
$sign = $this->getSign($tmpData);//Local signature
if ($this->data['sign'] == $sign) {
return TRUE;
}
return FALSE;
}
/**
* Get WeChat request data
*/
function getData()
{
return $this->data;
}
/**
* Set the xml data returned to WeChat
*/
function setReturnParameter($parameter, $parameterValue)
{
$this->returnParameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}
/**
* Generate interface parameter xml
*/
function createXml()
{
return $this->arrayToXml($this->returnParameters);
}
/**
* Return xml data to WeChat
*/
function returnXml()
{
$returnXml = $this->createXml();
return $returnXml;
}
}
/**
* Universal notification interface
*/
class Notify_pub extends Wxpay_server_pub
{
}
/**
* Request merchants to obtain product information interface
*/
class NativeCall_pub extends Wxpay_server_pub
{
/**
* Generate interface parameter xml
*/
function createXml()
{
if($this->returnParameters["return_code"] == "SUCCESS"){
$this->returnParameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->returnParameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant number
$this->returnParameters["nonce_str"] = $this->createNoncestr();//Random string
$this->returnParameters["sign"] = $this->getSign($this->returnParameters);//Signature
}
return $this->arrayToXml($this->returnParameters);
}
/**
* Get product_id
*/
function getProductId()
{
$product_id = $this->data["product_id"];
return $product_id;
}
}
/**
*Static link QR code
*/
class NativeLink_pub extends Common_util_pub
{
var $parameters; //Static link parameters
var $url; //Static link
function __construct()
{
}
/**
* Set parameters
*/
function setParameter($parameter, $parameterValue)
{
$this->parameters[$this->trimString($parameter)] = $this->trimString($parameterValue);
}
/**
* Generate Native payment link QR code
*/
function createLink()
{
try
{
if($this->parameters["product_id"] == null)
{
throw new SDKRuntimeException("The required parameter product_id of the Native payment QR code link is missing!"."
");
}
$this->parameters["appid"] = WxPayConf_pub::APPID;//Public account ID
$this->parameters["mch_id"] = WxPayConf_pub::MCHID;//Merchant ID
$time_stamp = time();
$this->parameters["time_stamp"] = "$time_stamp";//Timestamp
$this->parameters["nonce_str"] = $this->createNoncestr();//Random string
$this->parameters["sign"] = $this->getSign($this->parameters);//Signature
$bizString = $this->formatBizQueryParaMap($this->parameters, false);
$this->url = "weixin://wxpay/bizpayurl?".$bizString;
}catch (SDKRuntimeException $e)
{
die($e->errorMessage());
}
}
/**
* Return link
*/
function getUrl()
{
$this->createLink();
return $this->url;
}
}
/**
* JSAPI payment——H5 web page launches payment interface
*/
class JsApi_pub extends Common_util_pub
{
var $code;//code code to get openid
var $openid;//User’s openid
var $parameters;//jsapi parameters, the format is json
var $prepay_id;//Prepayment ID obtained using the unified payment interface
var $curl_timeout;//curl timeout
function __construct()
{
//Set curl timeout
$this->curl_timeout = WxPayConf_pub::CURL_TIMEOUT;
}
/**
* Function: Generate the url where the code can be obtained
*/
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;
}
/**
* Function: Generate a url that can get openid
*/
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;
}
/**
* Function: Submit code to WeChat through curl to obtain openid
*/
function getOpenid()
{
$url = $this->createOauthUrlForOpenid();
//Initialize curl
$ch = curl_init();
//Set timeout
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('
Copy after login
');
}
}
?>
微信安全支付
6. [Code]index.php
?
WeChat secure payment
7. [Code]js_api_call.php
?
/**
* JS_API payment demo
* ================================================= ===
* Open the H5 webpage in the WeChat browser and execute JS to initiate payment. The input and output data format of the interface is JSON.
* Three steps are required to successfully activate payment:
* Step 1: Obtain user openid via web page authorization
* Step 2: Use the unified payment interface to obtain prepay_id
* Step 3: Use jsapi to initiate payment
*/
include_once("./WxPayPubHelper/WxPayPubHelper.php");
//Use jsapi interface
$jsApi = new JsApi_pub();
//==========Step 1: Obtain user openid via web page authorization============
//Get openid through code
if (!isset($_GET['code']))
{
//Trigger WeChat return code
$url = $jsApi->createOauthUrlForCode(WxPayConf_pub::JS_API_CALL_URL);
Header("Location: $url");
}else
{
//Get the code code to get the openid
$code = $_GET['code'];
$jsApi->setCode($code);
$openid = $jsApi->getOpenId();
}
//==========Step 2: Use the unified payment interface to obtain prepay_id============
//Use unified payment interface
$unifiedOrder = new UnifiedOrder_pub();
//Set unified payment interface parameters
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//spbill_create_ip has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$body = $_GET["body"];
$out_trade_no = $_GET["orderid"];
$total_fee = $_GET["totalprice"];
$url = $_GET["url"];
$unifiedOrder->setParameter("openid","$openid");//Product description
$unifiedOrder->setParameter("body","$body");//Product description
//Customize order number, this is just an example
// $timeStamp = time();
// $out_trade_no = WxPayConf_pub::APPID."$timeStamp";
$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//Merchant order number
$unifiedOrder->setParameter("total_fee","$total_fee");//Total amount
$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//Notification address
$unifiedOrder->setParameter("trade_type","JSAPI");//Transaction type
//Non-required parameters, merchants can choose to fill in according to actual situation
//$unifiedOrder->setParameter("sub_mch_id","XXXX");//Sub-merchant number
//$unifiedOrder->setParameter("device_info","XXXX");//Device number
//$unifiedOrder->setParameter("attach","XXXX");//Additional data
//$unifiedOrder->setParameter("time_start","XXXX");//Transaction start time
//$unifiedOrder->setParameter("time_expire","XXXX");//Transaction end time
//$unifiedOrder->setParameter("goods_tag","XXXX");//Product tag
//$unifiedOrder->setParameter("openid","XXXX");//User ID
//$unifiedOrder->setParameter("product_id","XXXX");//Product ID
$prepay_id = $unifiedOrder->getPrepayId();
//==========Step 3: Use jsapi to initiate payment============
$jsApi->setPrepayId($prepay_id);
$jsApiParameters = $jsApi->getParameters();
//echo $jsApiParameters;
?>
WeChat secure payment
8. [Code]log_.php
?
class Log_
{
// print log
function log_result($file,$word)
{
$fp = fopen($file,"a");
flock($fp, LOCK_EX) ;
fwrite($fp,"Execution date:".strftime("%Y-%m-%d-%H:%M:%S",time())."n".$word."nn");
flock($fp, LOCK_UN);
fclose($fp);
}
}
?>
9. [Code]native_call.php
?
/**
*Native (native) payment mode demo
* ================================================= ===
*Mode 1: The merchant generates a link QR code in a fixed format, and the user scans the code and adjusts WeChat
* The productid and user openid will be sent to the link set by the merchant, and the merchant will receive it
* Request to generate an order, call the unified payment interface to place the order and submit it to WeChat, WeChat will return
* Give merchant prepayid.
* The QR code corresponding to this routine is generated by native_call_qrcode.php;
* The response service corresponding to this routine is native_call.php;
*Requires both to be used together.
*
*/
include_once("./log_.php");
include_once("../WxPayPubHelper/WxPayPubHelper.php");
//Record callback information in the form of a log file for debugging
$log_ = new Log_();
$log_name="./native_call.log";
//Use native notification interface
$nativeCall = new NativeCall_pub();
//Receive WeChat request
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
$log_->log_result($log_name,"[Native notification received]:n".$xml."n");
$nativeCall->saveData($xml);
if($nativeCall->checkSign() == FALSE){
$nativeCall->setReturnParameter("return_code","FAIL");//Return status code
$nativeCall->setReturnParameter("return_msg","Signature failed");//Return information
}else{
//Extract product_id
$product_id = $nativeCall->getProductId();
//Use unified payment interface
$unifiedOrder = new UnifiedOrder_pub();
//Set the corresponding order parameters according to different $product_id. Here is only one example
switch ($product_id)
{
case WxPayConf_pub::APPID."static":// corresponds to the static link QR code in native_call_qrcode.php
//Set unified payment interface parameters
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//spbill_create_ip has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$unifiedOrder->setParameter("body","Contribute a penny");//Product description
//Customize order number, this is just an example
$timeStamp = time();
$out_trade_no = WxPayConf_pub::APPID."$timeStamp";
$unifiedOrder->setParameter("out_trade_no","$out_trade_no");//Merchant order number $unifiedOrder->setParameter("product_id","$product_id");//Product ID
$unifiedOrder->setParameter("total_fee","1");//Total amount
$unifiedOrder->setParameter("notify_url",WxPayConf_pub::NOTIFY_URL);//Notification address
$unifiedOrder->setParameter("trade_type","NATIVE");//Transaction type
$unifiedOrder->setParameter("product_id","$product_id");//User ID
//Non-required parameters, merchants can choose to fill in according to actual situation
//$unifiedOrder->setParameter("sub_mch_id","XXXX");//Sub-merchant number
//$unifiedOrder->setParameter("device_info","XXXX");//Device number
//$unifiedOrder->setParameter("attach","XXXX");//Additional data
//$unifiedOrder->setParameter("time_start","XXXX");//Transaction start time
//$unifiedOrder->setParameter("time_expire","XXXX");//Transaction end time
//$unifiedOrder->setParameter("goods_tag","XXXX");//Goods tag
//$unifiedOrder->setParameter("openid","XXXX");//User ID
//Get prepay_id
$prepay_id = $unifiedOrder->getPrepayId();
//Set return code
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$nativeCall->setReturnParameter("return_code","SUCCESS");//Return status code
$nativeCall->setReturnParameter("result_code","SUCCESS");//Business results
$nativeCall->setReturnParameter("prepay_id","$prepay_id");//Prepayment ID
break;
default:
//Set return code
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$nativeCall->setReturnParameter("return_code","SUCCESS");//Return status code
$nativeCall->setReturnParameter("result_code","FAIL");//Business results
$nativeCall->setReturnParameter("err_code_des","This product is invalid");//Business results
break;
}
}
//Return the result to WeChat
$returnXml = $nativeCall->returnXml();
$log_->log_result($log_name,"[Return to WeChat's native response]:n".$returnXml."n");
echo $returnXml;
//Transaction completed
?>
10. [Code]native_call_qrcode.php Jump to [1] [2] [3] [4] [5] [6] [7] [8] [9] [10] [11] [12] [13] [ 14] [15] [16] [Full screen preview]
?
/**
*Native (native) payment mode demo
* ================================================= ===
*Mode 1: The merchant generates a link QR code in a fixed format, and the user scans the code and adjusts WeChat
* The productid and user openid will be sent to the link set by the merchant, and the merchant will receive it
* Request to generate an order, call the unified payment interface to place the order and submit it to WeChat, WeChat will return
* Give merchant prepayid.
* The QR code corresponding to this routine is generated by native_call_qrcode.php;
* The response service corresponding to this routine is native_call.php;
*Requires both to be used together.
*/
include_once("../WxPayPubHelper/WxPayPubHelper.php");
//Set static link
$nativeLink = new NativeLink_pub();
//Set static link parameters
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//time_stamp has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$product_id = WxPayConf_pub::APPID."static";//Customized product id
$nativeLink->setParameter("product_id","$product_id");//product id
//Get link
$product_url = $nativeLink->getUrl();
//Use short link conversion interface
$shortUrl = new ShortUrl_pub();
//Set required parameters
//appid has been filled in, merchants do not need to fill it in again
//mch_id has been filled in, merchants do not need to fill it in again
//noncestr has been filled in, merchants do not need to fill it in again
//sign has been filled in, merchants do not need to fill it in again
$shortUrl->setParameter("long_url","$product_url");//URL link
//Get short link
$codeUrl = $shortUrl->getShortUrl();
?>
WeChat secure payment
<script><br />
var url = "<?php echo $product_url;?>";<br />
//参数1表示图像大小,取值范围1-10;参数2表示质量,取值范围'L','M','Q','H'<br />
var qr = qrcode(10, 'M');<br />
qr.addData(url);<br />
qr.make();<br />
var dom=document.createElement('DIV');<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表示质量,取值范围'L','M','Q','H'<br />
var qr = qrcode(10, 'M');<br />
qr.addData(url);<br />
qr.make();<br />
var wording=document.createElement('p');<br />
wording.innerHTML = "扫我,扫我";<br />
var code=document.createElement('DIV');<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