Current Location: Home> Latest Articles> PHP Tutorial: Easily Implement WeChat Payment Refund Function

PHP Tutorial: Easily Implement WeChat Payment Refund Function

gitbox 2025-07-28

Introduction

The WeChat refund function allows merchants to return the funds already paid by users through the WeChat payment API. This feature is especially important in cases of order cancellation or returns, improving user experience and merchant service quality. This article guides you step-by-step through implementing the WeChat refund function using PHP examples.

Preparation

Obtain Merchant ID

Before using WeChat Pay, you need to register and pass the review to obtain a WeChat merchant ID. The merchant ID is a unique identifier for the merchant on the WeChat payment platform, and only approved merchants can call the refund API.

Download WeChat Payment SDK

WeChat Pay offers official SDKs that make it easier for developers to integrate payment and refund functions. You can log in to the WeChat Pay Merchant Platform and download the PHP SDK in the developer center.

Implement Refund Function

Configure Refund Parameters

Before processing a refund, you need to prepare parameters such as merchant ID, refund amount, and order ID. In PHP code, you can define them as follows:


$merchant_id = 'your_merchant_id'; // Merchant ID
$refund_amount = '100'; // Refund amount (in cents)
$order_id = 'your_order_id'; // Order ID

Initiate Refund Request

After configuring the parameters, use the WeChat payment SDK to send the refund request:


require_once 'path_to_wechat_sdk/autoload.php';
use WeChatPay\Builder\Refund\TradeRefundBuilder;

$refundBuilder = new TradeRefundBuilder();
$refundBuilder->setOutTradeNo($order_id)
    ->setOutRefundNo('refund_' . $order_id)
    ->setTotalFee($refund_amount)
    ->setRefundFee($refund_amount)
    ->setNotifyUrl('your_notify_url')
    ->setOpUserId('your_op_user_id')
    ->setIdempotencyKey($order_id);

$wechatPay = new \WeChatPay\WeChatPay();
$response = $wechatPay->refund($refundBuilder->getRequestParams(), $merchant_id);

Handle Refund Result

After sending the refund request, you will receive a response from the API. You can check and handle it with the following code:


if ($response['return_code'] === 'SUCCESS' && $response['result_code'] === 'SUCCESS') {
    // Refund successful, proceed with related business logic
    echo 'Refund successful';
} else {
    // Refund failed, output error details
    echo 'Refund failed: ' . $response['err_code'] . ' ' . $response['err_code_des'];
}

Conclusion

This article introduced how to use PHP to implement the WeChat refund function, including obtaining the merchant ID, downloading the SDK, configuring parameters, initiating refund requests, and handling results. You can adjust the parameters according to your specific business needs to ensure a smooth refund process. Hope this guide helps you successfully develop the WeChat payment refund feature.