wechatpay
1.0.0
微信支付SDK,支援刷卡支付、公眾號支付、掃碼支付、APP 支付、H5 支付,以及優惠券,紅包,企業付款,微信代扣
const path = require ( "path" ) ;
const fs = require ( "fs" ) ;
const {
PubPay ,
RequestError ,
CommunicationError ,
utils : { getXMLBody }
} = require ( "@sigodenjs/wechatpay" ) ;
const pay = new PubPay ( {
appId : "wxb80e5bddb2d804f3" ,
key : "6Q9VX4N3WTBM9G9XBL7H1L9PB9ANHLY7" ,
mchId : "1434712502" ,
pfx : fs . readFileSync ( path . resolve ( __dirname , "cert.p12" ) )
} ) ;
// 调用统一下单接口
pay
. unifiedOrder ( {
body : "腾讯充值中心-QQ会员充值" ,
out_trade_no : "1217752501201407033233368018" ,
total_fee : 888 ,
spbill_create_ip : "8.8.8.8" ,
notify_url : "https://example.com/wechatpay/notify" ,
trade_type : "JSAPI" ,
openid : "oUpF8uMuAJO_M2pxb1Q9zNjWeS6o"
} )
. then ( res => {
if ( ! pay . verifySign ( res ) ) {
// 签名校验失败
throw new Error ( "签名校验失败" ) ;
}
if ( res . result_code === "FAIL" ) {
console . log ( res . err_code , res . err_code_des ) ;
} else {
console . log ( res . prepay_id ) ;
}
} )
. catch ( err => {
if ( err instanceof RequestError ) {
// 请求错误
} else if ( err instanceof CommunicationError ) {
// return_code = FAIL
}
} ) ;
// 支付结果通知
router . post ( "/wechatpay/notify" , ( req , res ) => {
const options = {
length : req . headers [ "content-length" ] ,
limit : "1mb" ,
encoding : "utf8"
} ;
getXMLBody ( req , options ) . then ( data => {
pay
. payNotify ( data , async parsedData => {
if ( ! pay . verifySign ( parsedData ) ) {
// 签名校验失败
}
if ( parsedData . result_code === "FAIL" ) {
// 业务逻辑失败
}
// ...
return {
return_code : "SUCCESS" ,
return_msg : "OK"
} ;
} )
. then ( returnData => {
res . set ( "Content-Type" , "application/xml; charset=utf-8" ) ;
res . end ( returnData ) ;
} ) ;
} ) ;
} ) ;
如果你只使用了某一項支付,請使用業務類別。但如果涉及多種支付,使用綜合類別更便捷。
Copyright (c) 2018 sigoden
Licensed under the MIT license.