在做微信支付退款时,为了确切的知道退款是否成功,往往需要在参数中添加notify_url,以便接收微信退款成功之后的回调。在过程中有两个问题:
回调参数的传递问题
回调的文档中没有明确的指明怎么接收回调的结果,通过普通的交互请求对象request/body来获取参数往往获取不到参数,后经测试,其实它是通过流数据来传递,示例代码:
//egg版
const { req } = this.ctx
let xml = ''
req.on('data', chunk => {
xml += chunk
})
const onEnd = () => {
const data = this.helper.xml.parseXml(xml) //解析XML函数
this.logger.warn('receiveRepoStreamForWx::', JSON.stringify(data))
}
req.on('end', onEnd)
解密req_info问题
同时,在接收到传递参数后,req_info是密文发送,文档有介绍加密、解密的过程,但没给出示例,而网上大多是JAVA版的解析,参考意义不大。经摸索与测试,nodejs版解密代码如下:
const crypto = require("crypto")
function md5(str) {
const md5 = crypto.createHash("md5")
return md5.update(str).digest("hex")
}
const req_info=
"T2tAmlnsUo4LJ60gLfgp1DY6LuYiKSNV99dVrts1iAYXz8UvuXqhlt7BaEprj354U7fu5KaDl30uwgJa5FuJqexGOXWfC2K94/BrASzGI877eviLuC/XPic+bgpW5HnHz7lLhUQkGVw09/QFvwvt+FubyMg5WReDg1czsoE+IlaR2MVW77we1eQXxtNxY7moQjMWL7Be7p14W8CCgAtHkU8r7Vk2/lK67o9Y7luZ4ls/hHoDdKlrepcqo80PF/eXikQiWGbVx4p3L1h1Dt5Zey5Bx2X72dVeI43ExRKIWIV88453CwSGa/q2ICL6ApwrUFcydMydO9GG+J7YHeDcTugdBhPAhESrqUG8Acrq7gGvaolOhPvogxH44LfJFwIJK37e8t18KU2N2jJj6Aokv0g9TV7qC2iUapeqw3TZqDDWpr2wNPAerD4REVZcGJ9dCpr10e952H+v9+IquB7Zkrs/wPJzZ1B68g+PIe7jakBuy58+wV9UcYzimrjp9ZosFB1fd1eFuJf1pSEK1VGo4+nAowaPcI1qUW1HL/f2JxgRRH3zp37nX3GwzOeD4/HjYtFp5lb3BAIc7UG26NsRjA1GERGfbmBMkaJY3QHxdYYV+IBKlzJyDqMjDm+1wzj9srtx0g1W5Zso8e0cacp3z9UM9uf5zLJncw4CIJiivUoEC1kEIxdlXjrNVdlBoxiYdMW/eNsOtF8PSNiBjgaMSXu7XyjOyOYfG2A5P7kAF6ZHgVid9G8ehsIvK+k/x619DrTIQuCNrU/m5wQOTOiVHOj6LT48cYFcsa34+4uzR3RfRwUGQQQMI2iTQOk0lajnxFXCHJJbbH+dy49+StHDMtizGLjzSp6le6Y2WsXxecYC38XjB6/apBl3qqFZOQ8LBaeE2SrUbLhzeDoWIFheMmdXRVsRA2n0Q6Rfm3qZipKe5zeWbTIQBhAFDI29X2NXBWfBzPhqytZaMOTy8ytgNqNmVDYZVss/c5GLFUjAkvLn4jq0No17ryoa/Lqfy/SVG1E5Qiv8qgp1CykS6xBVb6NIVhu7iiFrxzfAEnplZgbw2uqQ7Ee6n/oCGu6O5UKp"
const key = "你在微信平台配置的KEY"
const decipher = crypto.createDecipheriv("aes-256-ecb", md5(key), null)
const decryptedSecret = decipher.update(req_info, "base64", "utf8") + decipher.final("utf8")
console.log(decryptedSecret)
解析出XML数据结构(decryptedSecret打印结果)
<root>
<out_refund_no><![CDATA[xxcgS2hep2D8xBhQmggWxx]]></out_refund_no>
<out_trade_no><![CDATA[xxc94gS2hep2D8xBhQmggW]]></out_trade_no>
<refund_account><![CDATA[REFUND_SOURCE_RECHARGE_FUNDS]]></refund_account>
<refund_fee><![CDATA[30]]></refund_fee>
<refund_id><![CDATA[50301702032022053121111521122]]></refund_id>
<refund_recv_accout><![CDATA[支付用户零钱]]></refund_recv_accout>
<refund_request_source><![CDATA[API]]></refund_request_source>
<refund_status><![CDATA[SUCCESS]]></refund_status>
<settlement_refund_fee><![CDATA[30]]></settlement_refund_fee>
<settlement_total_fee><![CDATA[30]]></settlement_total_fee>
<success_time><![CDATA[2022-05-31 19:15:53]]></success_time>
<total_fee><![CDATA[30]]></total_fee>
<transaction_id><![CDATA[42000015212022053180070xxx]]></transaction_id>
</root>