Home WeChat Applet Mini Program Development About node.js implementing the function of WeChat payment refund

About node.js implementing the function of WeChat payment refund

Jun 27, 2018 am 10:11 AM
node.js nodejs WeChat pay

This article mainly introduces node.js to implement the refund function of WeChat payment. In WeChat development, there will be a refund if there is a payment. Such a function is very common. Friends who need it can refer to it

Origin

There will be a refund if payment is made

Note that the refund supports partial refund

The money in the left pocket Return to the right pocket Luo

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 only a request. In the background, the refund operation will be initiated on WeChat only after the background reviewer has reviewed everything correctly.

Introduce third-party module

Add "weixin-pay": "^1.1.7" to package.json

Code directory structure

Input 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帮助生成 }
Copy after login

Then wxpay will generate the remaining fields for us, such as nonce_str, sign, and of course the p12 certificate,

This early selection has been configured in the wxpay initial code, pfx: fs.readFileSync(__dirname '/../../../cert/apiclient_cert.p12'), //WeChat merchant platform certificate

lib/wechat/utils/wxpay.js source code

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;
Copy after login

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,
};
Copy after login

Initiated Refund request

The refund logic is as follows. First, find transaction_id/out_trade_no/total_fee from your own Order data table, and then add the out_refund_no refund form you generated. No., the partial amount of this refund is refund_fee, and finally it can be adjusted by wxpay.refund under the weixin-pay module. 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
     })
    );
   }

  });
 });
});
Copy after login

The pitfalls of entry

1. The pitfall encountered this time is that refund_fee forgets to pass the value, which means that WeChat refund The payment supports partial refund. If it is a full refund, then assign it the same value as total_fee

2. The op_user_id mentioned on the Internet: weapp.MCHID is a non-required parameter

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 a successful payment is not written); the priority of the former is greater than that of the latter, so I have to distinguish between the two. The process of intentionally giving errors was verified.

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”
Copy after login

Repeat 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”
Copy after login

last

What to do if you don’t have a refund function or don’t want to write a refund function? In fact, you can refund money from the backend of WeChat Pay at pay.weixin.qq.com, but you just don’t want to forget it. You need to manually set the order status to refund status.

The above is the entire content of this article. I hope it will be helpful to everyone's study. For more related content, please pay attention to the PHP Chinese website!

Related recommendations:

How to use JS to implement the WeChat payment pop-up function

How to implement it in the WeChat applet Custom toast

The above is the detailed content of About node.js implementing the function of WeChat payment refund. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

deepseek image generation tutorial deepseek image generation tutorial Feb 19, 2025 pm 04:15 PM

DeepSeek: A powerful AI image generation tool! DeepSeek itself is not an image generation tool, but its powerful core technology provides underlying support for many AI painting tools. Want to know how to use DeepSeek to generate images indirectly? Please continue reading! Generate images with DeepSeek-based AI tools: The following steps will guide you to use these tools: Launch the AI ​​Painting Tool: Search and open a DeepSeek-based AI Painting Tool (for example, search "Simple AI"). Select the drawing mode: select "AI Drawing" or similar function, and select the image type according to your needs, such as "Anime Avatar", "Landscape"

gateio Chinese official website gate.io trading platform website gateio Chinese official website gate.io trading platform website Feb 21, 2025 pm 03:06 PM

Gate.io, a leading cryptocurrency trading platform founded in 2013, provides Chinese users with a complete official Chinese website. The website provides a wide range of services, including spot trading, futures trading and lending, and provides special features such as Chinese interface, rich resources and community support.

List of handling fees for okx trading platform List of handling fees for okx trading platform Feb 15, 2025 pm 03:09 PM

The OKX trading platform offers a variety of rates, including transaction fees, withdrawal fees and financing fees. For spot transactions, transaction fees vary according to transaction volume and VIP level, and adopt the "market maker model", that is, the market charges a lower handling fee for each transaction. In addition, OKX also offers a variety of futures contracts, including currency standard contracts, USDT contracts and delivery contracts, and the fee structure of each contract is also different.

Ouyi Exchange app domestic download tutorial Ouyi Exchange app domestic download tutorial Mar 21, 2025 pm 05:42 PM

This article provides a detailed guide to safe download of Ouyi OKX App in China. Due to restrictions on domestic app stores, users are advised to download the App through the official website of Ouyi OKX, or use the QR code provided by the official website to scan and download. During the download process, be sure to verify the official website address, check the application permissions, perform a security scan after installation, and enable two-factor verification. During use, please abide by local laws and regulations, use a safe network environment, protect account security, be vigilant against fraud, and invest rationally. This article is for reference only and does not constitute investment advice. Digital asset transactions are at your own risk.

gateio exchange app old version gateio exchange app old version download channel gateio exchange app old version gateio exchange app old version download channel Mar 04, 2025 pm 11:36 PM

Gateio Exchange app download channels for old versions, covering official, third-party application markets, forum communities and other channels. It also provides download precautions to help you easily obtain old versions and solve the problems of discomfort in using new versions or device compatibility.

The difference between H5 and mini-programs and APPs The difference between H5 and mini-programs and APPs Apr 06, 2025 am 10:42 AM

H5. The main difference between mini programs and APP is: technical architecture: H5 is based on web technology, and mini programs and APP are independent applications. Experience and functions: H5 is light and easy to use, with limited functions; mini programs are lightweight and have good interactiveness; APPs are powerful and have smooth experience. Compatibility: H5 is cross-platform compatible, applets and APPs are restricted by the platform. Development cost: H5 has low development cost, medium mini programs, and highest APP. Applicable scenarios: H5 is suitable for information display, applets are suitable for lightweight applications, and APPs are suitable for complex functions.

Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Sesame Open Door Login Registration Entrance gate.io Exchange Registration Official Website Entrance Mar 04, 2025 pm 04:51 PM

Gate.io (Sesame Open Door) is the world's leading cryptocurrency trading platform. This article provides a complete tutorial on spot trading of Gate.io. The tutorial covers steps such as account registration and login, KYC certification, fiat currency and digital currency recharge, trading pair selection, limit/market transaction orders, and orders and transaction records viewing, helping you quickly get started on the Gate.io platform for cryptocurrency trading. Whether a beginner or a veteran, you can benefit from this tutorial and easily master the Gate.io trading skills.

What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? What should I do if the company's security software conflicts with applications? How to troubleshoot HUES security software causes common software to fail to open? Apr 01, 2025 pm 10:48 PM

Compatibility issues and troubleshooting methods for company security software and application. Many companies will install security software in order to ensure intranet security. However, security software sometimes...

See all articles