需要到商戶平臺(tái)下載兩個(gè)證書
登錄https://pay.weixin.qq.com進(jìn)入微信商戶平臺(tái)-->賬戶設(shè)置-->API安全-->證書下載
下載后需要用到里面的兩個(gè)證書:apiclient_key.pem歹垫,apiclient_cert.pem
使用的一個(gè)類庫(kù)
<?php
class wechatAppPay
{
//接口API URL前綴
const API_URL_PREFIX = 'https://api.mch.weixin.qq.com';
//下單地址URL
const UNIFIEDORDER_URL = "/pay/unifiedorder";
//查詢訂單URL
const ORDERQUERY_URL = "/pay/orderquery";
//關(guān)閉訂單URL
const CLOSEORDER_URL = "/pay/closeorder";
//公眾賬號(hào)ID
private $appid;
//商戶號(hào)
private $mch_id;
//隨機(jī)字符串
private $nonce_str;
//簽名
private $sign;
//商品描述
private $body;
//商戶訂單號(hào)
private $out_trade_no;
//支付總金額
private $total_fee;
//終端IP
private $spbill_create_ip;
//支付結(jié)果回調(diào)通知地址
private $notify_url;
//交易類型
private $trade_type;
//支付密鑰
private $key;
//證書路徑
private $SSLCERT_PATH;
private $SSLKEY_PATH;
//所有參數(shù)
private $params = array();
public function __construct($appid, $mch_id, $notify_url, $key)
{
$this->appid = $appid;
$this->mch_id = $mch_id;
$this->notify_url = $notify_url;
$this->key = $key;
}
/**
* 下單方法
* @param $params 下單參數(shù)
*/
public function unifiedOrder( $params ){
$this->body = $params['body'];
$this->out_trade_no = $params['out_trade_no'];
$this->total_fee = $params['total_fee'];
$this->trade_type = $params['trade_type'];
$this->nonce_str = $this->genRandomString();
$this->spbill_create_ip = $_SERVER['REMOTE_ADDR'];
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->nonce_str;
$this->params['body'] = $this->body;
$this->params['out_trade_no'] = $this->out_trade_no;
$this->params['total_fee'] = $this->total_fee;
$this->params['spbill_create_ip'] = $this->spbill_create_ip;
$this->params['notify_url'] = $this->notify_url;
$this->params['trade_type'] = $this->trade_type;
//獲取簽名數(shù)據(jù)
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::UNIFIEDORDER_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
if( !empty($result['result_code']) && !empty($result['err_code']) ){
$result['err_msg'] = $this->error_code( $result['err_code'] );
}
return $result;
}
/**
* 小程序 下單方法
* @param $params
* @return bool|mixed
*/
public function unifiedOrder2( $params ){
$this->body = $params['body'];
$this->out_trade_no = $params['out_trade_no'];
$this->total_fee = $params['total_fee'];
$this->trade_type = $params['trade_type'];
$this->nonce_str = $this->genRandomString();
$this->spbill_create_ip = $_SERVER['REMOTE_ADDR'];
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->nonce_str;
$this->params['body'] = $this->body;
$this->params['out_trade_no'] = $this->out_trade_no;
$this->params['total_fee'] = $this->total_fee;
$this->params['spbill_create_ip'] = $this->spbill_create_ip;
$this->params['notify_url'] = $this->notify_url;
$this->params['trade_type'] = $this->trade_type;
$this->params['openid'] = $params['openid'];
//獲取簽名數(shù)據(jù)
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::UNIFIEDORDER_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
if( !empty($result['result_code']) && !empty($result['err_code']) ){
$result['err_msg'] = $this->error_code( $result['err_code'] );
}
return $result;
}
/**
* 查詢訂單信息
* @param $out_trade_no 訂單號(hào)
* @return array
*/
public function orderQuery( $out_trade_no ){
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//獲取簽名數(shù)據(jù)
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::ORDERQUERY_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
if( !empty($result['result_code']) && !empty($result['err_code']) ){
$result['err_msg'] = $this->error_code( $result['err_code'] );
}
return $result;
}
/**
* 關(guān)閉訂單
* @param $out_trade_no 訂單號(hào)
* @return array
*/
public function closeOrder( $out_trade_no ){
$this->params['appid'] = $this->appid;
$this->params['mch_id'] = $this->mch_id;
$this->params['nonce_str'] = $this->genRandomString();
$this->params['out_trade_no'] = $out_trade_no;
//獲取簽名數(shù)據(jù)
$this->sign = $this->MakeSign( $this->params );
$this->params['sign'] = $this->sign;
$xml = $this->data_to_xml($this->params);
$response = $this->postXmlCurl($xml, self::API_URL_PREFIX.self::CLOSEORDER_URL);
if( !$response ){
return false;
}
$result = $this->xml_to_data( $response );
return $result;
}
/**
*
* 獲取支付結(jié)果通知數(shù)據(jù)
* return array
*/
public function getNotifyData(){
//獲取通知的數(shù)據(jù)
$xml = $GLOBALS['HTTP_RAW_POST_DATA'];
//$xml = file_get_contents('php://input');
$data = array();
if( empty($xml) ){
return false;
}
$data = $this->xml_to_data( $xml );
if( !empty($data['return_code']) ){
if( $data['return_code'] == 'FAIL' ){
return false;
}
}
return $data;
}
/**
* 接收通知成功后應(yīng)答輸出XML數(shù)據(jù)
* @param string $xml
*/
public function replyNotify(){
/* ksort($data);
$buff = '';
foreach ($data as $k => $v){
if($k != 'sign'){
$buff .= $k . '=' . $v . '&';
}
}
$stringSignTemp = $buff . 'key=a1M5s4s6a4r8t4g2h3Md36AlJ8s7f5sd';//key為證書密鑰
$sign = strtoupper(md5($stringSignTemp));
//判斷算出的簽名和通知信息的簽名是否一致
if($sign == $data['sign']){
//處理完成之后偿渡,告訴微信成功結(jié)果
echo '<xml>
<return_code><![CDATA[SUCCESS]]></return_code>
<return_msg><![CDATA[OK]]></return_msg>
</xml>';
exit();
}
*/
$data['return_code'] = 'SUCCESS';
$data['return_msg'] = 'OK';
$xml = $this->data_to_xml( $data );
echo $xml;
die();
}
/**
* 生成APP端支付參數(shù)
* @param $prepayid 預(yù)支付id
*/
public function getAppPayParams( $prepayid ){
$data['appid'] = $this->appid;
$data['partnerid'] = $this->mch_id;
$data['prepayid'] = $prepayid;
$data['package'] = 'Sign=WXPay';
$data['noncestr'] = $this->genRandomString();
$data['timestamp'] = time();
$data['sign'] = $this->MakeSign( $data );
return $data;
}
/**
* 生成簽名
* @return 簽名
*/
public function MakeSign( $params ){
//簽名步驟一:按字典序排序數(shù)組參數(shù)
ksort($params);
$string = $this->ToUrlParams($params);
//簽名步驟二:在string后加入KEY
$string = $string . "&key=".$this->key;
//簽名步驟三:MD5加密
$string = md5($string);
//簽名步驟四:所有字符轉(zhuǎn)為大寫
$result = strtoupper($string);
return $result;
}
/**
* 將參數(shù)拼接為url: key=value&key=value
* @param $params
* @return string
*/
public function ToUrlParams( $params ){
$string = '';
if( !empty($params) ){
$array = array();
foreach( $params as $key => $value ){
$array[] = $key.'='.$value;
}
$string = implode("&",$array);
}
return $string;
}
/**
* 輸出xml字符
* @param $params 參數(shù)名稱
* return string 返回組裝的xml
**/
public function data_to_xml( $params ){
if(!is_array($params)|| count($params) <= 0)
{
return false;
}
$xml = "<xml>";
foreach ($params as $key=>$val)
{
if (is_numeric($val)){
$xml.="<".$key.">".$val."</".$key.">";
}else{
$xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
}
}
$xml.="</xml>";
return $xml;
}
/**
* 將xml轉(zhuǎn)為array
* @param string $xml
* return array
*/
public function xml_to_data($xml){
if(!$xml){
return false;
}
//將XML轉(zhuǎn)為array
//禁止引用外部xml實(shí)體
libxml_disable_entity_loader(true);
$data = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
return $data;
}
/**
* 獲取毫秒級(jí)別的時(shí)間戳
*/
private static function getMillisecond(){
//獲取毫秒的時(shí)間戳
$time = explode ( " ", microtime () );
$time = $time[1] . ($time[0] * 1000);
$time2 = explode( ".", $time );
$time = $time2[0];
return $time;
}
/**
* 產(chǎn)生一個(gè)指定長(zhǎng)度的隨機(jī)字符串,并返回給用戶
* @param type $len 產(chǎn)生字符串的長(zhǎng)度
* @return string 隨機(jī)字符串
*/
private function genRandomString($len = 32) {
$chars = array(
"a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
"l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
"w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
"H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
"S", "T", "U", "V", "W", "X", "Y", "Z", "0", "1", "2",
"3", "4", "5", "6", "7", "8", "9"
);
$charsLen = count($chars) - 1;
// 將數(shù)組打亂
shuffle($chars);
$output = "";
for ($i = 0; $i < $len; $i++) {
$output .= $chars[mt_rand(0, $charsLen)];
}
return $output;
}
/**
* 以post方式提交xml到對(duì)應(yīng)的接口url
*
* @param string $xml 需要post的xml數(shù)據(jù)
* @param string $url url
* @param bool $useCert 是否需要證書邮丰,默認(rèn)不需要
* @param int $second url執(zhí)行超時(shí)時(shí)間,默認(rèn)30s
* @throws WxPayException
*/
private function postXmlCurl($xml, $url, $useCert = false, $second = 30){
$ch = curl_init();
//設(shè)置超時(shí)
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,FALSE);
curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,2);
//設(shè)置header
curl_setopt($ch, CURLOPT_HEADER, FALSE);
//要求結(jié)果為字符串且輸出到屏幕上
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
if($useCert == true){
//設(shè)置證書
//使用證書:cert 與 key 分別屬于兩個(gè).pem文件
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
//curl_setopt($ch,CURLOPT_SSLCERT, WxPayConfig::SSLCERT_PATH);
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
//curl_setopt($ch,CURLOPT_SSLKEY, WxPayConfig::SSLKEY_PATH);
}
//post提交方式
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
//運(yùn)行curl
$data = curl_exec($ch);
//返回結(jié)果
if($data){
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
curl_close($ch);
return false;
}
}
/**
* 錯(cuò)誤代碼
* @param $code 服務(wù)器輸出的錯(cuò)誤代碼
* return string
*/
public function error_code( $code ){
$errList = array(
'NOAUTH' => '商戶未開通此接口權(quán)限',
'NOTENOUGH' => '用戶帳號(hào)余額不足',
'ORDERNOTEXIST' => '訂單號(hào)不存在',
'ORDERPAID' => '商戶訂單已支付轴咱,無(wú)需重復(fù)操作',
'ORDERCLOSED' => '當(dāng)前訂單已關(guān)閉汛蝙,無(wú)法支付',
'SYSTEMERROR' => '系統(tǒng)錯(cuò)誤!系統(tǒng)超時(shí)',
'APPID_NOT_EXIST' => '參數(shù)中缺少APPID',
'MCHID_NOT_EXIST' => '參數(shù)中缺少M(fèi)CHID',
'APPID_MCHID_NOT_MATCH' => 'appid和mch_id不匹配',
'LACK_PARAMS' => '缺少必要的請(qǐng)求參數(shù)',
'OUT_TRADE_NO_USED' => '同一筆交易不能多次提交',
'SIGNERROR' => '參數(shù)簽名結(jié)果不正確',
'XML_FORMAT_ERROR' => 'XML格式錯(cuò)誤',
'REQUIRE_POST_METHOD' => '未使用post傳遞參數(shù) ',
'POST_DATA_EMPTY' => 'post數(shù)據(jù)不能為空',
'NOT_UTF8' => '未使用指定編碼格式',
);
if( array_key_exists( $code , $errList ) ){
return $errList[$code];
}
}
}
退款方法
$wechatAppPay = new wechatAppPay($PAYAPPID, $PAYMCHID, $NOTIFY_URL, $PAYKEY);
//小程序的appid
$param['appid'] = $PAYAPPID;
//商戶號(hào)
$param['mch_id'] = $PAYMCHID;
//隨機(jī)字符串
$nonce_str = $this->random(15);//隨機(jī)數(shù)生成
$param['nonce_str'] = $nonce_str;
//商戶訂單號(hào)
$param['out_trade_no'] = $out_trade_no;
//商戶退款單號(hào)
$out_refund_no = $this->random(15);//生成隨機(jī)數(shù)
$param['out_refund_no'] = $out_refund_no;
//訂單金額
$param['total_fee'] = 1 * 100;
//退款金額
$param['refund_fee'] =1* 100;
//退款原因
$param['refund_desc'] = '拼團(tuán)失敗';
$stringSignTemp = $wechatAppPay->MakeSign($param);
$param['sign'] = $stringSignTemp;
$xml_data = $wechatAppPay->data_to_xml($param);
$data = $this->curl_post_ssl('https://api.mch.weixin.qq.com/secapi/pay/refund', $xml_data, '../../' . $cert_pem, '../../' . $key_pem);
// '../../wxcertificate/apiclient_cert.pem','../../wxcertificate/apiclient_key.pem'
$res = $wechatAppPay->xml_to_data($data);
退款成功狀態(tài):
if ($res['result_code'] == 'SUCCESS') {//退款成功
}
引用的方法
//file_cert_pem,file_key_pem兩個(gè)退款必須的文件
function curl_post_ssl($url, $vars,$file_cert_pem,$file_key_pem, $second = 30, $aHeader = array())
{
$ch = curl_init();
//超時(shí)時(shí)間
curl_setopt($ch, CURLOPT_TIMEOUT, $second);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//這里設(shè)置代理烈涮,如果有的話
//curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
//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);
//以下兩種方式需選擇一種
//第一種方法,cert 與 key 分別屬于兩個(gè).pem文件
//默認(rèn)格式為PEM窖剑,可以注釋
curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
// curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/cert.pem');
curl_setopt($ch,CURLOPT_SSLCERT,$file_cert_pem);
//默認(rèn)格式為PEM坚洽,可以注釋
curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
// curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/private.pem');
curl_setopt($ch,CURLOPT_SSLKEY,$file_key_pem);
//第二種方式,兩個(gè)文件合成一個(gè).pem文件
// curl_setopt($ch, CURLOPT_SSLCERT, getcwd() . '/all.pem');
if (count($aHeader) >= 1) {
curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
}
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $vars);
$data = curl_exec($ch);
if ($data) {
curl_close($ch);
return $data;
} else {
$error = curl_errno($ch);
// echo "call faild, errorCode:$error\n";
curl_close($ch);
return false;
}
}