1. Webhook của PayPal cho Refund
PayPal cung cấp webhook sự kiện "PAYMENT.SALE.REFUNDED"
, bạn có thể đăng ký webhook này để nhận thông báo khi có refund xảy ra.
2. Cấu hình Webhook trong PayPal
- Truy cập PayPal Developer Dashboard: https://developer.paypal.com/
- Chọn ứng dụng của bạn trong My Apps & Credentials.
- Trong phần Webhook, thêm một webhook URL trỏ đến website của bạn.
- Chọn sự kiện
"PAYMENT.SALE.REFUNDED"
.
3. Xử lý Webhook trong WooCommerce
Bạn cần tạo một endpoint để nhận dữ liệu webhook từ PayPal và cập nhật trạng thái đơn hàng trong WooCommerce.
Ví dụ code xử lý webhook Refund từ PayPal
Thêm đoạn code này vào file functions.php
hoặc tạo một plugin riêng:
add_action('rest_api_init', function () { register_rest_route('custom-api/v1', '/paypal-webhook/', [ 'methods' => 'POST', 'callback' => 'handle_paypal_refund_webhook', 'permission_callback' => '__return_true', ]); }); function handle_paypal_refund_webhook(WP_REST_Request $request) { $body = $request->get_json_params(); if (!isset($body['event_type']) || $body['event_type'] !== 'PAYMENT.SALE.REFUNDED') { return new WP_REST_Response(['message' => 'Invalid event'], 400); } $sale_id = $body['resource']['sale_id']; $order_id = wc_get_order_id_by_transaction_id($sale_id); if (!$order_id) { return new WP_REST_Response(['message' => 'Order not found'], 404); } $order = wc_get_order($order_id); $order->update_status('refunded', 'Refunded via PayPal Webhook'); return new WP_REST_Response(['message' => 'Order updated successfully'], 200); }