fix: harden payment resume and wxpay webhook routing
This commit is contained in:
@@ -1,6 +1,8 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
@@ -77,9 +79,13 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
|
||||
// This is needed when multiple instances of the same provider exist (e.g. multiple EasyPay accounts).
|
||||
outTradeNo := extractOutTradeNo(rawBody, providerKey)
|
||||
|
||||
provider, err := h.paymentService.GetWebhookProvider(c.Request.Context(), providerKey, outTradeNo)
|
||||
providers, err := h.paymentService.GetWebhookProviders(c.Request.Context(), providerKey, outTradeNo)
|
||||
if err != nil {
|
||||
slog.Warn("[Payment Webhook] provider not found", "provider", providerKey, "outTradeNo", outTradeNo, "error", err)
|
||||
if providerKey == payment.TypeWxpay {
|
||||
c.String(http.StatusBadRequest, "verify failed")
|
||||
return
|
||||
}
|
||||
writeSuccessResponse(c, providerKey)
|
||||
return
|
||||
}
|
||||
@@ -89,7 +95,7 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
|
||||
headers[strings.ToLower(k)] = c.GetHeader(k)
|
||||
}
|
||||
|
||||
notification, err := provider.VerifyNotification(c.Request.Context(), rawBody, headers)
|
||||
resolvedProviderKey, notification, err := verifyNotificationWithProviders(c.Request.Context(), providers, rawBody, headers)
|
||||
if err != nil {
|
||||
truncatedBody := rawBody
|
||||
if len(truncatedBody) > webhookLogTruncateLen {
|
||||
@@ -103,17 +109,17 @@ func (h *PaymentWebhookHandler) handleNotify(c *gin.Context, providerKey string)
|
||||
|
||||
// nil notification means irrelevant event (e.g. Stripe non-payment event); return success.
|
||||
if notification == nil {
|
||||
writeSuccessResponse(c, providerKey)
|
||||
writeSuccessResponse(c, resolvedProviderKey)
|
||||
return
|
||||
}
|
||||
|
||||
if err := h.paymentService.HandlePaymentNotification(c.Request.Context(), notification, providerKey); err != nil {
|
||||
slog.Error("[Payment Webhook] handle notification failed", "provider", providerKey, "error", err)
|
||||
if err := h.paymentService.HandlePaymentNotification(c.Request.Context(), notification, resolvedProviderKey); err != nil {
|
||||
slog.Error("[Payment Webhook] handle notification failed", "provider", resolvedProviderKey, "error", err)
|
||||
c.String(http.StatusInternalServerError, "handle failed")
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccessResponse(c, providerKey)
|
||||
writeSuccessResponse(c, resolvedProviderKey)
|
||||
}
|
||||
|
||||
// extractOutTradeNo parses the webhook body to find the out_trade_no.
|
||||
@@ -131,6 +137,25 @@ func extractOutTradeNo(rawBody, providerKey string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
func verifyNotificationWithProviders(ctx context.Context, providers []payment.Provider, rawBody string, headers map[string]string) (string, *payment.PaymentNotification, error) {
|
||||
var lastErr error
|
||||
for _, provider := range providers {
|
||||
if provider == nil {
|
||||
continue
|
||||
}
|
||||
notification, err := provider.VerifyNotification(ctx, rawBody, headers)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
continue
|
||||
}
|
||||
return provider.ProviderKey(), notification, nil
|
||||
}
|
||||
if lastErr != nil {
|
||||
return "", nil, lastErr
|
||||
}
|
||||
return "", nil, fmt.Errorf("no webhook provider could verify notification")
|
||||
}
|
||||
|
||||
// wxpaySuccessResponse is the JSON response expected by WeChat Pay webhook.
|
||||
type wxpaySuccessResponse struct {
|
||||
Code string `json:"code"`
|
||||
|
||||
@@ -3,11 +3,14 @@
|
||||
package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/Wei-Shaw/sub2api/internal/payment"
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -131,3 +134,70 @@ func TestExtractOutTradeNo(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyNotificationWithProvidersReturnsMatchedProvider(t *testing.T) {
|
||||
firstErr := errors.New("wrong provider")
|
||||
providers := []payment.Provider{
|
||||
webhookHandlerProviderStub{
|
||||
key: payment.TypeWxpay,
|
||||
verifyErr: firstErr,
|
||||
},
|
||||
webhookHandlerProviderStub{
|
||||
key: payment.TypeWxpay,
|
||||
notification: &payment.PaymentNotification{
|
||||
OrderID: "sub2_42",
|
||||
TradeNo: "trade-42",
|
||||
Status: payment.NotificationStatusSuccess,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
providerKey, notification, err := verifyNotificationWithProviders(context.Background(), providers, "{}", map[string]string{"wechatpay-signature": "sig"})
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, payment.TypeWxpay, providerKey)
|
||||
require.NotNil(t, notification)
|
||||
require.Equal(t, "sub2_42", notification.OrderID)
|
||||
}
|
||||
|
||||
func TestVerifyNotificationWithProvidersFailsWhenAllProvidersReject(t *testing.T) {
|
||||
providers := []payment.Provider{
|
||||
webhookHandlerProviderStub{
|
||||
key: payment.TypeWxpay,
|
||||
verifyErr: errors.New("verify failed a"),
|
||||
},
|
||||
webhookHandlerProviderStub{
|
||||
key: payment.TypeWxpay,
|
||||
verifyErr: errors.New("verify failed b"),
|
||||
},
|
||||
}
|
||||
|
||||
_, _, err := verifyNotificationWithProviders(context.Background(), providers, "{}", nil)
|
||||
require.Error(t, err)
|
||||
}
|
||||
|
||||
type webhookHandlerProviderStub struct {
|
||||
key string
|
||||
notification *payment.PaymentNotification
|
||||
verifyErr error
|
||||
}
|
||||
|
||||
func (p webhookHandlerProviderStub) Name() string { return p.key }
|
||||
func (p webhookHandlerProviderStub) ProviderKey() string { return p.key }
|
||||
func (p webhookHandlerProviderStub) SupportedTypes() []payment.PaymentType {
|
||||
return []payment.PaymentType{payment.PaymentType(p.key)}
|
||||
}
|
||||
func (p webhookHandlerProviderStub) CreatePayment(context.Context, payment.CreatePaymentRequest) (*payment.CreatePaymentResponse, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (p webhookHandlerProviderStub) QueryOrder(context.Context, string) (*payment.QueryOrderResponse, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
func (p webhookHandlerProviderStub) VerifyNotification(context.Context, string, map[string]string) (*payment.PaymentNotification, error) {
|
||||
if p.verifyErr != nil {
|
||||
return nil, p.verifyErr
|
||||
}
|
||||
return p.notification, nil
|
||||
}
|
||||
func (p webhookHandlerProviderStub) Refund(context.Context, payment.RefundRequest) (*payment.RefundResponse, error) {
|
||||
panic("unexpected call")
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user