Detailed example of node.js implementing WeChat payment refund function
WeChat development is becoming more and more popular. We know that there are payment and refund functions in WeChat. Such functions are very common. This article mainly introduces node.js to implement the WeChat payment refund function. Friends who need it can refer to it. , hope it can help everyone.
Origin
There will be a refund if payment is made
Note that refunds support partial refunds
The money from the left pocket will be returned to the right pocket
The refund request of 0.01 yuan initiated this time is received in real time. Therefore, the refund initiated by the user on the mini program is just a request to the backend, which will be reviewed by the backend reviewer. Only after everything is correct will WeChat initiate the refund operation.
Introduce third-party module
Add "weixin-pay": "^1.1.7" to package.json
Code directory structure
Enter the parameters
{ transaction_id: '4200000005201712165508745023', // 交易 out_trade_no: '5b97cba0ae164bd58dfe9e77891d3aaf', // 自己这头的交易号 out_refund_no: '6f3240c353934105be34eb9f2d364cec', // 退款订单,自己生成 total_fee: 1, // 退款总额 nonce_str: '1xSZW0op0KcdKoMYxnyxhEuF1fAQefhU', // 随机串 appid: 'wxff154ce14ad59a55', // 小程序 appid mch_id: '1447716902', // 微信支付商户id sign: '416FCB62F9B8F03C82E83052CC77524B' // 签名,weixin-pay这个module帮助生成 }
Then wxpay will generate the remaining fields for us, such as nonce_str, sign, and of course the p12 certificate.
This was selected early in wxpay It has been configured in the initial code, pfx: fs.readFileSync(__dirname + '/../../../cert/apiclient_cert.p12'), //WeChat Merchant Platform Certificate
lib/wechat/ The source code of utils/wxpay.js
const WXPay = require('weixin-pay'); // 引入weixin-pay这个第三方模块 const {weapp} = require('../../../utils/config'); // 我自己的全局配置文件,包括了appid key 等 const fs = require('fs'); const wxpay = WXPay({ appid: weapp.APPID, mch_id: weapp.MCHID, partner_key: weapp.KEY, //微信商户平台 API secret,非小程序 secret pfx: fs.readFileSync(__dirname + '/../../../cert/apiclient_cert.p12'), }); module.exports = wxpay;
There is also a util.js tool class
for verification and error callback
const wxpay = require('./wxpay'); const validateSign = results => { const sign = wxpay.sign(results); if (sign !== results.sign) { const error = new Error('微信返回参数签名结果不正确'); error.code = 'INVALID_RESULT_SIGN'; throw error; }; return results; }; const handleError = results => { if (results.return_code === 'FAIL') { throw new Error(results.return_msg); } if (results.result_code !== 'SUCCESS') { const error = new Error(results.err_code_des); error.code = results.err_code; throw error; } return results; }; module.exports = { validateSign, handleError, };
initiating a refund request
The refund logic is like this. First, find the transaction_id/out_trade_no/total_fee from your Order data table, and then add the out_refund_no refund order number you generated. The partial amount of this refund is refund_fee, and finally weixin -wxpay.refund under the pay module is sufficient. If successful, the order status will be changed to "Refund Successful"
// 退款 router.post('/refund', function(req, res) { Order.findById(req.body._id, (err, order) => { if (err) { console.log(err); } console.log(order); // 生成微信设定的订单格式 var data = { transaction_id: order.transactionId, out_trade_no: order.tradeId, out_refund_no: uuid().replace(/-/g, ''), total_fee: order.amount, refund_fee: order.amount }; console.log(data); // 先查询订单,再退订单 wxpay.refund(data, (err, result) => { if (err) { console.log(err); res.send( utils.json({ code: 500, msg: '退款失败' }) ); } // 返回退款请求成功后,要将订单状态改成REFUNDED if (result.result_code === 'SUCCESS') { console.log(result); order.status = 'REFUNDED'; order.save((err, response) => { res.send( utils.json({ msg: '退款成功' }) ); }); } else { res.send( utils.json({ code: 500, msg: result.err_code_des }) ); } }); }); });
Enter the pit
1. Encountered this time The pitfall is that refund_fee forgets to pass the value, which means that WeChat refund supports partial refund. If it is a full refund, then assign it the same value as total_fee
2. Op_user_id mentioned on the Internet: weapp. The parameter MCHID is optional
3. Just choose one of transaction_id and out_trade_no, so that a refund can be initiated even if the transaction_id is not recorded (for example, a callback for successful payment is not written); the priority is The former is greater than the latter, which was verified in the process of deliberately giving the wrong answer to the former.
4. An error was reported that the appid does not match the merchant number, return_code: 'FAIL', return_msg: 'The merchant number mch_id does not match the appid' It turns out that the mini program has not been bound to the official account WeChat payment. This is really a mistake.
Data returned by WeChat for successful refund
appid:"wxff154ce14ad59a55" cash_fee:"1" cash_refund_fee:"1" coupon_refund_count:"0" coupon_refund_fee:"0" mch_id:"1447716902" nonce_str:"c44wOvB6a4bQJfRk" out_refund_no:"9ace1466432a4d548065dc8df95d904a" out_trade_no:"5b97cba0ae164bd58dfe9e77891d3aaf" refund_channel:"" refund_fee:"1" refund_id:"50000705182017121702756172970" result_code:"SUCCESS" return_code:"SUCCESS" return_msg:"OK" sign:"5C2E67B3250054E8A665BF1AE2E9BDA3" total_fee:"1" transaction_id:”4200000005201712165508745023”
Repeated refunds will be returned as follows
appid:"wxff154ce14ad59a55" err_code:"ERROR" err_code_des:"订单已全额退款" mch_id:"1447716902" nonce_str:"KP1YWlU7a5viZEgK" result_code:"FAIL" return_code:"SUCCESS" return_msg:"OK" sign:”C2A7DED787BEA644C325E37D96E9F41C”
Finally
If What should I do if I don’t have a refund function or don’t want to write a refund function? In fact, I can refund money through the backend of WeChat Pay at pay.weixin.qq.com. I just don’t want to forget to manually set the order status to refund status. .
Related recommendations:
How to implement WeChat applet payment and refund in php
##PHP backend UnionPay payment and refund example
10 recommended articles about refunds
The above is the detailed content of Detailed example of node.js implementing WeChat payment refund function. For more information, please follow other related articles on the PHP Chinese website!

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version
God-level code editing software (SublimeText3)

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Atom editor mac version download
The most popular open source editor