stripe_test.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. //go:build unit
  2. package provider
  3. import (
  4. "bytes"
  5. "context"
  6. "testing"
  7. "github.com/Wei-Shaw/sub2api/internal/payment"
  8. "github.com/stretchr/testify/require"
  9. stripe "github.com/stripe/stripe-go/v85"
  10. )
  11. type stripeRefundBackend struct {
  12. params []*stripe.RefundCreateParams
  13. }
  14. func (b *stripeRefundBackend) Call(_ string, _ string, _ string, params stripe.ParamsContainer, v stripe.LastResponseSetter) error {
  15. b.params = append(b.params, params.(*stripe.RefundCreateParams))
  16. refund := v.(*stripe.Refund)
  17. refund.ID = "re_123"
  18. refund.Status = stripe.RefundStatusSucceeded
  19. return nil
  20. }
  21. func (*stripeRefundBackend) CallStreaming(string, string, string, stripe.ParamsContainer, stripe.StreamingLastResponseSetter) error {
  22. return nil
  23. }
  24. func (*stripeRefundBackend) CallRaw(string, string, string, []byte, *stripe.Params, stripe.LastResponseSetter) error {
  25. return nil
  26. }
  27. func (*stripeRefundBackend) CallMultipart(string, string, string, string, *bytes.Buffer, *stripe.Params, stripe.LastResponseSetter) error {
  28. return nil
  29. }
  30. func (*stripeRefundBackend) SetMaxNetworkRetries(int64) {}
  31. func TestStripeRefundUsesStableAmountSpecificIdempotencyKey(t *testing.T) {
  32. backend := &stripeRefundBackend{}
  33. client := stripe.NewClient("sk_test", stripe.WithBackends(&stripe.Backends{API: backend}))
  34. provider := &Stripe{
  35. config: map[string]string{"currency": "CNY"},
  36. initialized: true,
  37. sc: client,
  38. }
  39. refund := func(amount string) {
  40. _, err := provider.Refund(context.Background(), payment.RefundRequest{
  41. TradeNo: "pi_123",
  42. OrderID: "sub2_order_456",
  43. Amount: amount,
  44. })
  45. require.NoError(t, err)
  46. }
  47. refund("12.34")
  48. refund("12.34")
  49. refund("12.35")
  50. require.Len(t, backend.params, 3)
  51. require.Equal(t, int64(1234), *backend.params[0].Amount)
  52. require.Equal(t, "re-sub2_order_456-1234", *backend.params[0].IdempotencyKey)
  53. require.Equal(t, backend.params[0].IdempotencyKey, backend.params[1].IdempotencyKey)
  54. require.Equal(t, int64(1235), *backend.params[2].Amount)
  55. require.Equal(t, "re-sub2_order_456-1235", *backend.params[2].IdempotencyKey)
  56. require.NotEqual(t, *backend.params[0].IdempotencyKey, *backend.params[2].IdempotencyKey)
  57. }