Payment Processing Architecture: Idempotency, Fraud Detection, PCI
"The easiest way to address inconsistencies in distributed state caused by failures is to implement server endpoints so that they’re idempotent, which means that they can be called any number of times while guaranteeing that side effects only occur once." — Brandur Leach، Designing robust and predictable APIs with idempotency، وبلاگ Stripe، ۲۲ فوریهٔ ۲۰۱۷
خلاصه (Summary): سیستم پرداخت پول را از راه شبکهای جابهجا میکند که ممکن است پاسخ را گم کند. تکرار درخواست، پول جابهجاشده را برنمیگرداند؛ حتی ممکن است دوباره برداشت کند. ارائهدهندهٔ خدمات پرداخت (PSP)، مثل Stripe و Adyen، نتیجه را گاهی بعداً با webhook میگوید. معماری باید برای هر جابهجایی پول اثر دقیقاً یکباره (exactly-once effect) بسازد، آن را در دفترکل دوطرفهٔ فقطافزودنی (append-only double-entry ledger) بنویسد، با فایل تسویهٔ PSP تطبیق دهد، تقلب و اعتراض را مدیریت کند و شمارهٔ کارت را بیرون سیستم نگه دارد. تمرکز (Focus): پول با عدد صحیح در کوچکترین واحد (minor units)، توانهای ISO 4217 و قاعدهٔ صریح گرد کردن ارز (currency rounding)؛ ماشین حالت (state machine) برای قصد پرداخت (payment intent) و وضعیتهای Stripe PaymentIntent؛ authorization، capture، void، refund و partial refund؛ هدر Idempotency-Key و کلید مشتقشدهٔ PSP؛ timeouts و unknown outcome؛ double-entry ledger، journal entry، ledger immutability و audit trail؛ webhook همراه signature verification، Stripe-Signature و Adyen HMAC، replay window، out-of-order webhooks، at-least-once delivery، webhook idempotency table و مسیر dead-letter؛ outbox برای exactly-once effect؛ saga و compensation؛ reconciliation با settlement file و payout؛ chargeback و dispute؛ 3-D Secure، SCA و PSD2؛ PCI DSS v4.0.1، SAQ A، tokenization، network tokens و card vaulting؛ fraud score، velocity rules، device fingerprint، risk engine و manual review queue؛ retries، dunning و smart retries؛ Laravel Cashier، Stripe PHP SDK و stripe-go. هدف یادگیری (Learning goal): سرویس پرداختی طراحی کنید که بعد از timeout دوبار برداشت نکند، webhook را گم نکند، حسابهایش از PSP جدا نشود، شمارهٔ کارت وارد سرورهایش نشود و تصمیم تقلب را در بودجهٔ زمانی checkout بگیرد. بتوانید در مصاحبه هر تصمیم را با رفتار دقیق محصول توضیح دهید.
این فصل نگاه «سیستمهای حوزهای» به پرداخت است: اجزا چطور یک سرویس میسازند و هرکدام چه تضمینی میدهند. جزئیات سازوکارهای عمومی در صفحههای همسایه میماند: ذخیره و lease کلیدها در API Idempotency؛ بودجهٔ retry، backoff و jitter در Timeouts, Retries & Jitter؛ relay در Outbox Pattern؛ orchestration و choreography در Saga Pattern؛ حذف تکرار سمت مصرفکننده در Idempotent Consumer & Inbox؛ تضمین تراکنش و ناهنجاریهای جداسازی در ACID Transactions و Isolation Levels؛ حمله به صفحهٔ پرداخت در OWASP Top 10؛ HMAC، TLS و نگهداری secret در Cryptography in Practice؛ پرداخت بهعنوان مرز سازگاری در Aggregates & Factories؛ و نمونهٔ معماری یک شرکت در Case Study: Amazon.
نقشهٔ صفحه
| دنبال چه هستید | بروید به |
|---|---|
| کل صفحه در سه جدول | همهچیز در یک دقیقه |
| چرا پرداخت از «صدا زدن API» سختتر است | چرا وجود دارد |
| تاریخ شبکهٔ کارت، PSP، PCI DSS، PSD2 و کلیدها | از کجا آمده |
| float، minor units، ISO 4217، گرد کردن و money type | پول |
| issuer، acquirer، شبکهٔ کارت، PSP، Stripe و Adyen | زنجیرهٔ پرداخت |
| وضعیتهای PaymentIntent و state machine | قصد پرداخت و ماشین حالت |
| authorize، capture، void، refund و partial refund | جابهجایی پول |
| Idempotency-Key header و کلید PSP | کلیدهای Idempotency |
| timeout، 5xx، unknown outcome و قواعد failover | Timeout و نتیجهٔ نامعلوم |
| debit، credit، journal entry، append-only و audit trail | دفترکل دوطرفه |
| Stripe-Signature، HMAC، replay window، ترتیب و تکرار | Webhook |
| outbox، at-least-once delivery و exactly-once effect | Outbox |
| checkout چندمرحلهای و void بهعنوان compensation | Saga و جبران |
| settlement file، گزارش payout و کارمزد | تطبیق حسابها |
| chargeback، inquiry، مدرک و کارمزد | اعتراضها |
| 3-D Secure، SCA، PSD2، انتقال مسئولیت و معافیت | 3-D Secure و SCA |
| PCI DSS v4.0.1، SAQ A، token، vault و network tokens | PCI DSS و Tokenization |
| fraud score، velocity rules، device fingerprint و صف بررسی | تقلب و موتور ریسک |
| رد نرم و سخت، dunning و smart retries | رد پرداخت و وصول مجدد |
| دو PSP، مسیریابی و failover | مسیریابی چند PSP |
| Laravel Cashier، Stripe PHP SDK، stripe-go و کتابخانههای Adyen | کتابخانهها |
| جریان درخواست، خطاها، تنظیمها و SQL | سازوکار |
| کد | Go، Laravel |
| یازده خرابی کلاسیک و راهحلشان | حل مسئلههای کلاسیک |
| روش capture، integration و سیاست retry | انتخاب |
| از monolith تا چند region | در معماری |
| برنامههای اجراشدنی و آزمایشهای موردانتظار | آزمایشگاه |
| باور غلط، چکیده، مصاحبه و اصطلاحات | بدفهمیها، چکیده، خودآزمایی، واژهنامه |
همهچیز در یک دقیقه
جابهجاییهای پول (Money movements).
| عملیات | به زبان ساده | Stripe | Adyen | اثر در دفترکل (Ledger) |
|---|---|---|---|---|
| رزرو مبلغ (Authorization) | از issuer میخواهیم مبلغ را روی کارت نگه دارد | تأیید PaymentIntent با capture_method=manual → requires_capture | /payments با manual capture | هنوز هیچ؛ hold درآمد نیست |
| برداشت (Capture) | پول رزروشده را میگیریم | POST /v1/payment_intents/:id/capture، با amount_to_capture کوچکتر در صورت نیاز | /payments/{paymentPspReference}/captures | D دریافتنی از PSP، C فروش |
| لغو رزرو (Void) | hold برداشتنشده را آزاد میکنیم | لغو PaymentIntent (canceled) | /payments/{paymentPspReference}/cancels | هیچ |
| بازپرداخت (Refund) | پول برداشتشده را پس میدهیم | POST /v1/refunds؛ کامل یا جزئی (partial refund) | /payments/{paymentPspReference}/refunds | D بازپرداخت، C دریافتنی از PSP |
| برگشت بانکی (Chargeback) | بانک صاحب کارت پول را پس میگیرد | charge.dispute.created؛ مبلغ و کارمزد کسر میشود | اعلان dispute | D زیان chargeback و کارمزد، C دریافتنی |
| واریز به بانک (Payout) | PSP موجودی را به بانک شما میفرستد | Payout با تطبیق automatic_payout_id | دستهٔ تسویه (Settlement batch) | D وجه بانک، C دریافتنی از PSP |
پنج تضمین و سازوکار هرکدام.
| تضمین | جلوی چه خرابیای را میگیرد | سازوکار این صفحه |
|---|---|---|
| اثر دقیقاً یکباره (Exactly-once effect) برای هر پرداخت | برداشت دوباره بعد از timeout | Idempotency-Key header از کلاینت، کلید مشتقشده برای PSP و قید یکتایی |
| نبود وضعیت غیرمجاز | «بازپرداختشده» پیش از «برداشتشده»؛ بازنویسی succeeded با webhook دیررس | یک state machine با جدول انتقال صریح |
| تراز بودن حسابها | ساخته یا گم شدن پول بر اثر باگ | Double-entry ledger؛ در هر journal entry، debit = credit؛ append-only |
| پردازش هر رویداد | webhook یا ایمیل رسید گمشده | Webhook inbox + صف + dead-letter؛ outbox برای رویدادهای خودمان |
| حسابهای ما = حسابهای PSP | اختلاف خاموش و unknown outcome حلنشده | Reconciliation روزانه با settlement file و payoutها |
تهدیدها و سد دفاعی.
| تهدید | شکل آن | سد دفاعی |
|---|---|---|
| سرقت دادهٔ کارت | PAN و CVV در لاگ یا پایگاهداده | Tokenization در iframe متعلق به PSP؛ ماندن در دامنهٔ SAQ A |
| webhook جعلی | هرکسی payment_intent.succeeded را به POST /webhooks/stripe بفرستد | Signature verification روی raw body و مقایسهٔ constant-time |
| webhook بازپخششده | ارسال دوبارهٔ درخواست معتبر ضبطشده | Replay window؛ پیشفرض کتابخانهٔ Stripe برابر 5 دقیقه، همراه dedup شناسهٔ event |
| آزمایش کارت (Card testing) | صدها برداشت کوچک با کارت سرقتی از یک دستگاه | Velocity rules، device fingerprint، CAPTCHA و مسدودسازی |
| خرید با کارت سرقتی | اولین سفارش بزرگ به آدرس واسطهٔ ارسال | Fraud score، احراز هویت تکمیلی 3-D Secure و انتقال مسئولیت، manual review queue |
| تقلب صاحب کارت (Friendly fraud) | بعد از تحویل میگوید «من نخریدهام» | مدرک نتیجهٔ 3DS و تحویل، پاسخ به dispute |
| تغییر موجودی توسط فرد داخلی یا باگ | UPDATE accounts SET balance = ... | Ledger immutability؛ trigger جلوی UPDATE/DELETE را میگیرد؛ اصلاح با reversal |
تصویر کل فصل را کنار هم گذاشته است. مسیر همگام از چپ به راست است: مرورگر، checkout API، سرویس پرداخت و PSP. حقیقت ناهمگام را از پایین به بالا بخوانید: webhook و settlement file هر دو به همان تراکنش پایگاهداده میرسند که ردیف پرداخت، سطرهای ledger و outbox را با هم مینویسد. شمارهٔ کارت از اولین پیکان عبور نمیکند؛ مرورگر فقط token میفرستد.
چرا وجود دارد
برداشت از کارت ظاهراً یک فراخوانی HTTP است. در عمل تراکنش توزیعشدهای (Distributed transaction) میان پایگاهدادهٔ شما و PSP خارج از کنترل شماست. شبکه ممکن است بعد از جابهجایی پول، پاسخ را گم کند. تلاش مجدد (Retry) میتواند دو بار برداشت کند؛ انجام ندادنش هم ممکن است فروش را از بین ببرد یا مشتری پول بدهد اما سفارش نداشته باشد. نتیجهٔ نهایی PSP اغلب دیرتر میرسد: 3-D Secure به حضور مشتری نیاز دارد، برداشت بانکی SEPA و ACH چند روز طول میکشد و dispute ممکن است ماهها بعد برسد. تیم مالی حسابهایی میخواهد که سطربهسطر با گزارش PSP قابل بررسی باشد. خود شمارهٔ کارت هم دادهٔ تحت مقررات است؛ عبور آن از برنامه، دامنهٔ PCI DSS را گسترش میدهد.
| سادهتر / ارزانتر | قویتر / کنترل بیشتر |
|---|---|
| برداشت فوری (Automatic capture) | رزرو اکنون و برداشت هنگام ارسال (Manual capture)؛ برای کالای ناموجود refund لازم نیست، اما hold منقضی میشود و PSP زمانش را میگوید؛ در Stripe ویژگی payment_method_details.card.capture_before روی charge؛ رزرو آغازشده توسط پذیرندهٔ Visa برابر 5 روز و بیشتر موارد دیگر 7 روز است |
| اعتماد به پاسخ همگام API | Webhook مرجع نتیجهٔ ناهمگام و reconciliation روزانه |
ستون balance قابلویرایش | Double-entry ledger با ثبتهای تغییرناپذیر و موجودی مشتقشده |
| Retry تا موفقیت | فقط همان کلید؛ توقف unknown outcome برای پیگیری؛ بدون failover بعد از خطای مبهم |
| یک PSP | دو PSP با routing؛ دسترسپذیری و نرخ authorization بهتر، reconciliation دوبرابر |
| فرم کارت روی صفحهٔ خودتان | فیلد میزبانیشده یا redirect به PSP؛ SAQ A بهجای صدها کنترل PCI |
| مسدودسازی فقط با rule | Rule + امتیاز ML + 3DS step-up + بررسی انسانی |
تشبیه مشترک این صفحه: رستوران با کارتخوان و دفتر حساب. پیشخدمت، یعنی checkout، از کارتخوان بانکی یا PSP میخواهد صورتحساب را authorize کند. هنوز پرداختی انجام نشده؛ مبلغ فقط روی کارت رزرو شده است. آخر شب مدیر authorizationها را capture میکند. اگر بعد از «تأیید شد» چاپگر گیر کند، پاسخ گم شده است؛ زدن دوبارهٔ پرداخت با همان شمارهٔ صورتحساب نباید دوباره برداشت کند. آن شماره همان idempotency key است. دفتر حساب یا ledger با خودکار نوشته میشود؛ خطا با یک سطر اصلاحی تازه رفع میشود، نه پاک کردن سطر قدیمی. مدیر هر صبح صورتحساب بانک را با دفتر تطبیق میدهد: reconciliation. رسیدهای کارتخوان یا webhook ممکن است دوبار یا بیترتیب برسند؛ پس با شمارهٔ سریال بایگانی میشوند. پیشخدمت هم شمارهٔ کارت را روی صورتحساب نمینویسد: tokenization.
سه بدفهمی رایج، از همین ابتدا
- «PSP خاصیت Idempotency دارد؛ پس retry امن است.» فقط اگر هر بار همان کلید و همان پارامترها را بفرستید و PSP هنوز کلید را نگه داشته باشد. در Stripe API v1 پاکسازی پس از 24 ساعت ممکن است؛ Adyen میگوید "valid for a period of 7 to 14 days". کلید جدید یا منقضیشده یعنی پرداخت دوم.
- «پاسخ
succeededپایان کار است.» فقط authorization و capture تمام شدهاند. Refund، partial refund، dispute، کارمزد و payout به بانک بعداً رخ میدهند؛ بیشترشان از webhook و settlement file معلوم میشوند. سیستم بدون reconciliation وضعیت خودش را نمیداند. - «استفاده از Stripe یعنی انطباق با PCI.» فیلدهای میزبانیشدهٔ Stripe، یعنی Payment Element و Checkout، ممکن است دامنه را به کوتاهترین پرسشنامه یعنی SAQ A کاهش دهند؛ PCI DSS حذف نمیشود. از اجرای الزامات PCI DSS v4.0.1 در ۳۱ مارس ۲۰۲۵، پذیرندهٔ SAQ A باید مطابق PCI SSC تأیید کند سایتش "is not susceptible to attacks from scripts that could affect the merchant’s e-commerce system(s)".
از کجا آمده
حسابداری دوطرفه (Double-entry bookkeeping)، ۱۴۹۴. Martin Fowler در Patterns for Accounting مینویسد این روش "developed in medieval times and first documented by Luca Pacioli, an Italian friar, in 1494". Ledger این صفحه همان فکر است، با پایگاهداده در زیر آن.
شبکهٔ کارت و برگشت بانکی (Chargeback). شبکههای کارت به دارنده حق دادند از راه بانک صادرکننده اعتراض کند؛ پذیرنده با مدرک پاسخ میدهد. پنجرهٔ معمول اعتراض کارت 120 روز است؛ Stripe: "Card networks typically allow cardholders to initiate disputes within 120 days of the original payment".
PCI DSS. شورای PCI SSC استاندارد امنیت داده را منتشر میکند. نسخهٔ v4.0 در مارس ۲۰۲۲ منتشر شد؛ v4.0.1 یک "a limited revision" با "no additional or deleted requirements" است. v4.0 در ۳۱ دسامبر ۲۰۲۴ بازنشسته شد و الزامات دارای مهلت آینده در ۳۱ مارس ۲۰۲۵ لازمالاجرا شدند. در ژانویهٔ ۲۰۲۵، الزامات اسکریپت صفحهٔ پرداخت 6.4.3 و 11.6.1 از SAQ A حذف و با معیار صلاحیت دربارهٔ اسکریپتها جایگزین شدند.
3-D Secure و PSD2. EMVCo نگهدارندهٔ EMV 3-D Secure یا 3DS2 است و آن را "an e-commerce fraud prevention protocol that enables consumer authentication for CNP purchases" مینامد. در منطقهٔ اقتصادی اروپا، PSD2 و استانداردهای فنی آن، یعنی Commission Delegated Regulation (EU) 2018/389 که EBA آن را RTS on SCA and CSC معرفی میکند، احراز هویت قوی مشتری را لازم میکنند. Stripe شروع اجرای SCA را "in effect as of September 14, 2019" میداند.
کلید Idempotency، ۲۰۱۷ و پیشنویس IETF. مقالهٔ Stripe در ۲۰۱۷، هدر Idempotency-Key را به الگوی صنعت تبدیل کرد. کارگروه HTTPAPI در IETF آن را در draft-ietf-httpapi-idempotency-key-header تدوین کرده؛ برای این فصل revision 09 خوانده شده است. پیشنهادش برای تکرار کلید با payload متفاوت 422 و برای نبود کلید اجباری 400 است. تعریف کلاسیک RFC 9110 بخش 9.2.2 این است: "if the intended effect on the server of multiple identical requests with that method is the same as the effect for a single such request". POST جزو این methodها نیست.
Ledger در مقیاس PSP. Stripe دفترکل داخلیاش را "an immutable and auditable log" مبتنی بر حسابداری دوطرفه توصیف میکند که روزانه "sees five billion events".
Year Event What changed in practice
1 1494 Pacioli documents double-entry bookkeeping Debits = credits; ledgers in pen
2 2017 Stripe "Designing robust ... APIs with idempotency" Idempotency-Key header becomes the norm
3 2018 EU RTS 2018/389 on SCA Strong customer authentication defined
4 2019 SCA in effect (Sept 14, per Stripe) 3-D Secure 2 for European card payments
5 2019 Stripe API 2019-02-11 requires_payment_method / requires_action names
6 2022 PCI DSS v4.0 (March) New e-commerce script requirements, future-dated
7 2024 PCI DSS v4.0.1; v4.0 retired 31 Dec 2024 Clarifications only, no new requirements
8 2025 31 Mar 2025: future-dated requirements effective New SAQ A with a script eligibility criterion
9 2026 draft-ietf-httpapi-idempotency-key-header-09 400 missing key, 422 key reuse, 409 in flightردیف 5 از صفحهٔ lifecycle در Stripe است: "Versions of the API before 2019-02-11 show requires_source instead of requires_payment_method". سال ردیف 7 از نوشتهٔ PCI SSC استنباط شده؛ دورهٔ نظرخواهی دسامبر ۲۰۲۳ تا ژانویهٔ ۲۰۲۴ و بازنشستگی v4.0 در ۳۱ دسامبر ۲۰۲۴ بود. ردیف 9 نسخهٔ پیشنویس هنگام پژوهش این فصل، نوامبر ۲۰۲۶، است.
فهرست مفاهیم
ترتیب هر بخش ثابت است: زبان ساده، باور غلط، تعریف، خط زمانی، موقعیت واقعی، رفتار محصول و راهحل. کدهای هر راهحل در Go و Laravel آمدهاند.
پول: minor units، ISO 4217، decimal و currency rounding حیاتی
به زبان ساده: پول را بهصورت عدد صحیح از کوچکترین واحد ارز (Minor units)، همراه کد سهحرفی ارز ذخیره کنید: سنت برای USD، ین برای JPY و فلس برای BHD. عدد ممیزشناور (Floating-point) جای پول نیست.
بدفهمی رایج: «float64 یا DOUBLE کافی است؛ موقع نمایش گرد میکنم.» ممیز شناور دودویی (Binary floating point) نمیتواند 0.1 را دقیق نگه دارد. در before/main.go، جمع 0.1 و 0.2 خروجی 0.30000000000000004 دارد. روی میلیونها ردیف یا در مقایسهٔ == هنگام reconciliation، این دامهای float (float pitfalls) به سنت گمشده و اختلاف بیتوضیح تبدیل میشوند. تصور غلط دوم این است که همهٔ ارزها دو رقم اعشار دارند؛ ISO 4217 برای JPY صفر، BHD و KWD سه و CLF چهار رقم تعیین میکند.
تعریف: نوع پول (Money type) یک value object شامل مقدار صحیح در minor units و کد الفبایی ISO 4217 است. توان minor units از فهرست ISO 4217 میآید که SIX به نمایندگی از ISO منتشر میکند؛ تاریخ نسخهٔ خواندهشده برای این فصل ۱۷ سپتامبر ۲۰۲۶ است. جمع و تفریق فقط برای ارز یکسان مجاز است. تبدیل ارز نرخ و قاعدهٔ گرد کردن صریح میخواهد. تقسیم مبلغ (Allocation) باید باقیمانده را توزیع کند تا جمع سهمها دقیقاً برابر کل شود. برای کسری از minor unit، مثل نرخ FX، مالیات و بهره، نوع دهدهی (Decimal) به کار ببرید: math/big.Rat در Go، NUMERIC در PostgreSQL و brick/money یا bcmath در PHP. سپس فقط یک بار، در نقطهای مستند، به minor units گرد کنید. Currency rounding قاعدهٔ کسبوکار است: half-up برای صورتحساب در بسیاری کشورها و half-even یا گرد کردن بانکی برای بیطرفی آماری.
PSP هم همین قرارداد را با استثناهای خودش دارد. Stripe میگوید "1000 to charge 10 USD (or any other two-decimal currency)" و "to charge 500 JPY, provide an amount value of 500". دربارهٔ ISK و UGX میگوید "transitioned to a zero-decimal currency, but backward compatibility requires you to represent it as a two-decimal value". Payoutهای HUF و TWD باید "evenly divisible by 100" باشند. جدول توان را برای هر PSP نگه دارید، نه فقط بر اساس ISO.
Step float64 int64 minor units (money package)
1 price 0.10 USD 0.1 (0.1000000000000000055) 10
2 + 0.20 USD 0.30000000000000004 30
3 == 0.30 ? false true
4 split 1.00 USD three ways 0.333... x 3 = 0.999... 34, 33, 33 (sum 100)
5 10.00 USD at 0.9235 EUR/USD 9.235 -> 9.23 or 9.24 ? 923.5 -> half-even -> 924 = 9.24 EUR
6 charge 500 JPY amount 500? 50000? exponent 0 -> amount 500سناریوی واقعی: بازارگاهی مبلغ 100.00 را بین 3 فروشنده تقسیم میکند و تا وقتی مالی متوجه اختلاف هفترقمی شود، هر سفارش یک سنت از دست میدهد؛ مشتری کویتی بهخاطر فرض دو رقم اعشار برای KWD ده برابر پرداخت میکند؛ جمع ستونهای DOUBLE هزاران mismatch در reconciliation میسازد؛ موتور مالیات هر سطر را گرد میکند ولی صورتحساب جمع کل را.
چه چیزی فراهمش میکند:
| لایه | نوع minor units | نوع کسر / نرخ | نکته |
|---|---|---|---|
| PostgreSQL | BIGINT + CHAR(3) | NUMERIC(p,s) | REAL/DOUBLE PRECISION دودوییاند؛ برای پول استفاده نکنید |
| MySQL | BIGINT + CHAR(3) | DECIMAL(p,s) | FLOAT/DOUBLE تقریبیاند |
| Go | int64 در ساختار Money | math/big.Rat، github.com/shopspring/decimal؛ وابستگی stripe-go v87 | هرگز float64 |
| PHP / Laravel | int از نوع 64-bit | bcmath، brick/money | Eloquent، cast از نوع decimal:<precision> دارد؛ ستون پول و محاسباتش را صحیح نگه دارید |
| Stripe API | amount صحیح در کوچکترین واحد | کاربرد ندارد | کد ارز درخواست با حروف کوچک |
| Adyen API | amount.value صحیح؛ طبق مستندات capture: "The amount in minor units (without a decimal point)"، همراه amount.currency | کاربرد ندارد | همان قرارداد Stripe |
راهحل / روش استفاده: بستهٔ money شامل Parse بدون float، Add/Sub با کنترل ارز و overflow، Allocate با قاعدهٔ بزرگترین باقیمانده و Convert با نرخ دقیق decimal و half-even است. در SQL schema ستونهای BIGINT + CHAR(3) و در controllerهای Laravel مقدار صحیح total_minor را به کار ببرید.
زنجیرهٔ پرداخت: cardholder، issuer، network، acquirer و PSP حیاتی
به زبان ساده: ارائهدهندهٔ خدمات پرداخت (PSP) واسطهٔ شما و دنیای کارت است. درخواست به بانک پذیرنده (Acquirer)، سپس شبکهٔ کارت (Card network) مثل Visa یا Mastercard، و بعد بانک صادرکنندهٔ کارت (Issuer) میرود. Issuer میگوید بله یا نه.
بدفهمی رایج: «رد پرداخت یعنی PSP قبول نکرد.» تقریباً همیشه issuer رد کرده: موجودی ناکافی، احتمال تقلب یا CVC اشتباه. PSP کد رد را منتقل میکند. موتور تقلب خود PSP، مثل Stripe Radar، هم میتواند مسدود کند، اما کدش فرق دارد؛ highest_risk_level در فهرست hard declineهای Stripe است.
تعریف: PSP دسترسی به acquiring، روشهای پرداخت، tokenization، ابزار تقلب و گزارشها را پشت یک API جمع میکند. Stripe و Adyen هر دو PSP هستند. مجوز رزرو (Authorization) تعهد issuer به پرداخت مبلغ معین است. پایاپای و تسویه (Clearing and settlement) بعداً پول را دستهای جابهجا میکنند؛ سپس PSP موجودی منهای کارمزد را به بانک شما payout میکند.
Customer Your server PSP (Stripe / Adyen) Acquirer / network Issuer
1 enters card in PSP iframe ------> token pm_123
2 confirm(pi_42, pm_123) ->
3 authorization request -> route by BIN ------> check funds, fraud, 3DS
4 <---------------------------------------------- approved (auth code)
5 <- requires_capture or succeeded
6 (later) capture / clearing batch ------------------> money moves (T+1..T+n)
7 (later) <- payout to bank account, settlement file with feesسناریوی واقعی: پرداخت در هلند که issuer از آن 3-D Secure میخواهد؛ تمدید اشتراک آمریکایی با insufficient_funds که سه روز بعد موفق میشود؛ کارت بینالمللی با نرخ تأیید پایین که acquirer دوم تأییدش میکند؛ payout که یک روز بانکی بعد از ارسال PSP به حساب میرسد.
نام هر مفهوم در PSPها:
| مفهوم | Stripe | Adyen |
|---|---|---|
| شیء پرداخت (Payment object) | PaymentIntent (pi_...)، Charge (ch_...) | Payment با pspReference |
| اعلان رویداد (Webhook) | Event (evt_...) به endpoint با هدر Stripe-Signature | Notification / webhook با hmacSignature در additionalData |
| کلید تکرار امن (Idempotency) | هدر Idempotency-Key، تا 255 نویسه | هدر idempotency-key، اعتبار 7 تا 14 روز برای هر حساب شرکت |
| برداشت دستی (Manual capture) | capture_method=manual | تنظیم manual capture یا delayed automatic capture |
| لغو رزرو (Void) | لغو PaymentIntent | /cancels |
| تقلب (Fraud) | Radar؛ امتیاز 0–99، از 65 elevated و از 75 high | Risk management؛ profile، rule و ML rule |
| تطبیق (Reconciliation) | گزارش payout reconciliation و balance | Settlement detail report و settlement reconciliation |
راهحل / روش استفاده: PSP را پشت interface خودتان مدل کنید؛ PSP در payment/service.go. نام وضعیت provider را به نام داخلی نگاشت کنید، reference آن را کنار attempt ذخیره کنید و decline code را برای retry و تحلیل عیناً نگه دارید.
قصد پرداخت و ماشین حالت حیاتی
به زبان ساده: قصد پرداخت (Payment intent) تلاش برای گرفتن یک مبلغ بابت یک سفارش است. ماشین حالت (State machine) فقط حرکت روی پیکانهای نمودار ثابت را مجاز میداند. Webhook کهنه، دوبار کلیک یا باگ نباید بیصدا وضعیت را بازنویسی کند.
بدفهمی رایج: «status یک ستون است؛ مقدار آخرین event را در آن بنویس.» ترتیب رسیدن eventها تضمین ندارد. Stripe میگوید "doesn’t guarantee the delivery of events in the order that they’re generated". اگر payment_intent.processing بعد از payment_intent.succeeded برسد و بیقید نوشته شود، سفارش پرداختشده ناپرداخت به نظر میآید و cron آن را لغو میکند. State machine رویداد دیررس را بیاثر میکند.
تعریف: وضعیتهای Stripe PaymentIntent عبارتاند از requires_payment_method، requires_confirmation، requires_action برای نمونه در 3-D Secure، processing برای روشهای ناهمگام که "can take up to a few days"، requires_capture برای برداشت دستی، succeeded و canceled. تلاش ناموفق "returns to requires_payment_method so that the payment can be retried". لغو "before it reaches a processing or succeeded state" ممکن است و "releases any held funds". همچنین PaymentIntent "might also automatically transition to canceled if they’re confirmed too many times". Refund و dispute شیء جدا دارند و status این شیء را عوض نمیکنند.
تصویر همان جدول انتقال intent/intent.go و PaymentStatus.php است. پیکان خطچین حلقهٔ retry پس از decline است. از دو وضعیت پایانی پیکانی بیرون نمیرود؛ refund حرکت پول تازهای کنار intent است، نه وضعیت تازهٔ آن.
Event (arrival order) Intent status before Transition table says Result
1 confirm (client) requires_confirmation -> requires_action 3DS challenge shown
2 payment_intent.succeeded (evt_2) requires_action -> succeeded ledger + outbox written
3 payment_intent.requires_action succeeded no edge acked, ignored
(evt_1, created earlier, late)
4 payment_intent.succeeded (evt_2) succeeded inbox says: seen acked, ignored
(redelivery)سناریوی واقعی: webhook مربوط به 3-D Secure بعد از webhook موفقیت میرسد؛ دو tab یک intent را confirm میکنند؛ مدیر سفارشی را cancel میکند که همین لحظه capture شده؛ پرداخت SEPA روزها processing میماند و صفحه باید «در انتظار» نشان دهد، نه «ناموفق».
چه چیزی فراهمش میکند:
| محصول | وضعیتها | اجرای محدودیت انتقال |
|---|---|---|
| Stripe PaymentIntent | 7 وضعیت بالا | Stripe اعمال میکند؛ نسخهٔ محلی شما هم باید اعمال کند |
| Adyen | Result codeهای Authorised، Refused، Pending و webhook هر event code | State machine را از event codeها میسازید |
| Go این فصل | intent.Intent و transition map؛ requires_capture همچنین PSPSucceeded تأییدشده با مبلغ capture را میپذیرد؛ Succeed(amount)، با امکان مبلغ جزئی | Apply خطای ErrInvalidTransition میدهد |
| Laravel این فصل | enum به نام PaymentStatus و canBecome()؛ پیکان جدول یا پیشرفت بر اساس رتبه | ProcessStripeEvent رویداد کهنه را ack میکند؛ برای تضاد وضعیتهای پایانی exception میاندازد |
| SQL | CHECK (status IN (...)) و ستون version | قفل خوشبینانه (Optimistic lock): UPDATE ... WHERE version = ? |
راهحل / روش استفاده: یک جدول انتقال و یک تابع اعمال event داشته باشید؛ ستون version برای optimistic locking، مطابق Optimistic & Pessimistic Locking. Intent ریشهٔ aggregate است و مالک attemptها، refundها و مبلغهایش؛ Aggregates & Factories.
جابهجایی پول: authorization، capture، void، refund و partial refund حیاتی
به زبان ساده: رزرو مبلغ (Authorization) پول را نگه میدارد؛ برداشت (Capture) آن را میگیرد؛ لغو رزرو (Void) آزادش میکند؛ بازپرداخت (Refund) پول برداشتشده را پس میدهد. Partial capture کمتر از مبلغ رزرو را میگیرد و بازپرداخت جزئی (Partial refund) فقط بخشی را برمیگرداند.
بدفهمی رایج: «Authorization یعنی پرداخت.» این فقط hold دارای انقضاست. Stripe میگوید "an authorization for an online card payment is valid for 7 days"؛ برای بعضی موارد تمدید هم ممکن است. اما پنجره به برند و نوع پرداخت بستگی دارد: رزرو Visa از نوع merchant-initiated و card-not-present برابر "5 days" است؛ دقیقتر: "The exact authorization window is 4 days and 18 hours". برای Mastercard، American Express و Discover از نوع card-present مدت 2 روز است. مرجع انقضا خود charge است: "the payment_method_details.card.capture_before attribute on the charge indicates when the authorization expires". همچنین "you can only perform one capture on an authorized payment for most payments. If you partially capture a payment, you can’t perform another capture for the difference." فرستادن کالا بدون capture یعنی رایگان تحویل دادن. اشتباه دیگر refund کردن پرداخت captureنشده بهجای void است؛ هزینه و سردرگمی مشتری را بالا میبرد.
تعریف:
| عملیات | پیششرط | اثر روی کارت | برگشتپذیری |
|---|---|---|---|
| رزرو (Authorization) | کارت معتبر و تأیید issuer | Hold روی اعتبار قابلاستفاده | Void یا انقضا |
| برداشت کامل / جزئی (Capture) | requires_capture، مبلغ ≤ hold | Hold به charge تبدیل و باقی آزاد میشود | فقط با refund |
| لغو (Void / cancel) | هنوز capture نشده | Hold آزاد میشود | خیر |
| بازپرداخت کامل / جزئی (Refund / partial refund) | Capture شده؛ جمع refund ≤ capture | اعتبار کارت در "approximately 5-10 business days" طبق Stripe | بعضی refundهای کارت کوتاهمدت قابللغوند؛ refund ممکن است شکست بخورد (refund.failed) |
Hotel booking (manual capture), amounts in cents
1 t0 authorize 10000 intent requires_capture, amount_capturable 10000, ledger: nothing
2 t3d guest checks out: 8250 capture(8250) -> succeeded, amount_received 8250, hold for 1750 released
3 ledger: D psp_receivable 8250 / C sales 8250
4 t5d minibar dispute: refund 1000 with key rf-hotel-7-1
5 ledger: D refunds 1000 / C psp_receivable 1000, amount_refunded 1000
6 t5d client retries refund rf-hotel-7-1 -> no-op (same key)
7 t6d refund 8000 requested 8000 + 1000 > 8250 -> rejected locally, never sent to the PSPسناریوی واقعی: فروشگاه هنگام ارسال capture و برای کالای ناموجود void میکند؛ هتل و اجارهٔ خودرو hold بزرگ و capture کوچکتر دارند؛ ارسال غذا پس از جایگزینی اقلام مبلغ نهایی را capture میکند؛ پشتیبانی چند partial refund روی یک سفارش ثبت میکند.
چه چیزی فراهمش میکند:
| محصول | Partial capture | چند capture | Void | Partial refund |
|---|---|---|---|---|
| Stripe | amount_to_capture | Multicapture فقط برای بعضی پرداختهای کارت | لغو PaymentIntent | بله، چند partial refund |
| Adyen | بله؛ توصیه به علامت pre-authorization | "Multiple partial capture is disabled by default"؛ تماس با پشتیبانی | /cancels؛ اگر "you do not know if the payment has been captured" از /reversals استفاده کنید | بله |
| Laravel Cashier | از Stripe client | کاربرد ندارد | از Stripe client | $user->refund($paymentIntentId) برای کامل، طبق مستندات؛ مقدار جزئی از Cashier::stripe() |
راهحل / روش استفاده: Intent.Capture(amount) مبلغ بیشتر از hold را رد و باقی را آزاد میکند. Service.Capture پیش از تماس با PSP مبلغ را با کلید capture:<intent> ثبت میکند؛ مبلغ متفاوت در درخواست بعدی ErrMismatch است. ثبت در ledger فقط پس از موفقیت PSP انجام میشود و اگر webhook مربوط به capture زودتر رسیده باشد، فقط با مبلغ یکسان پذیرفته میشود. Webhook، amount_received و reference پرداخت PSP را حمل میکند: HandleWebhook(..., amount, pspRef). بنابراین partial capture به مبلغ واقعی ثبت میشود، نه کل hold؛ event هم به attempt صاحب آن reference نسبت داده میشود، پس decline دیررس attempt اول نمیتواند attempt دوم را تغییر دهد. اگر PSP، capture یا refund را تأیید کرده ولی ledger رد کرده باشد، retry از نتیجهٔ ذخیرهشده ثبت را ترمیم میکند و PSP دوباره فراخوانی نمیشود. Service.Refund هر کلید را برای همیشه به پرداخت و مبلغ مقید میکند؛ از لحظهٔ ثبت کلید، مبلغ مصرفشده حساب میشود. رزرو فقط وقتی آزاد میشود که refund ثبت شود یا ثابت شود نخستین ارسال یک کلید تازه رد شده است. هر شکست دیگر، refund را نامعلوم نگه میدارد تا همان کلید موفق شود یا ResolveRefund پس از lookup نتیجه را تعیین کند. هر refund کلید خودش، مثل rf-<order>-<n>، را دارد؛ نه کلید پرداخت.
کلیدهای Idempotency و Idempotency-Key header حیاتی
به زبان ساده: هر درخواست جابهجایی پول کلید یکتا دارد. تکرار همان کلید باید نتیجهٔ اول را برگرداند، نه اجرای دوباره. کلید تکرار امن (Idempotency key) در دو مرز لازم است: از کلاینت به شما و از شما به PSP.
بدفهمی رایج: «برای هر فراخوانی HTTP به PSP یک UUID تازه بساز.» در این صورت هر retry پرداخت جدید است. کلید provider باید از هویت پایدار، یعنی intent id و شمارهٔ attempt، مشتق شود تا worker بعد از crash هم همان کلید را بفرستد. کلید جای قید یکتایی محلی را هم نمیگیرد: کلید از یک API حفاظت میکند؛ UNIQUE (merchant_id, order_id) مانع دو کلید متفاوت برای یک سفارش میشود.
تعریف: Idempotency-Key header در پیشنویس IETF با نام draft-ietf-httpapi-idempotency-key-header کلید ساختهشدهٔ کلاینت را حمل میکند. Stripe طول را "are up to 255 characters long" و پیشنهاد را "we suggest using V4 UUIDs" اعلام میکند. در API v1 پس از شروع endpoint، status code و body اولین پاسخ با کلید ذخیره میشود؛ تکرار همان پاسخ، حتی خطای 500، را برمیگرداند. پاکسازی پس از حداقل 24 ساعت ممکن است: "you can remove keys from the system automatically after they’re at least 24 hours old". لایهٔ کلید پارامترها را هم بررسی میکند: "compares incoming parameters to those of the original request and errors if they’re not the same". Adyen کلید را در سطح حساب شرکت نگه میدارد: "Idempotency keys are valid for a period of 7 to 14 days after first submission". طراحی کامل record، lease و 409/422 در API Idempotency است.
Client (mobile) Payment API (yours) Stripe
1 POST /payments Idempotency-Key: c-7f3a {order 1001, 2500 USD}
2 idempotency_keys (m_1, c-7f3a) -> in_progress
3 payments: pi_0001 created
4 attempt 1: key pi_0001:attempt:1 --------> charge processed
5 <-- x connection reset (answer lost)
6 retry with the SAME key pi_0001:attempt:1 -> saved response: succeeded
7 <-- 201 {pi_0001, succeeded} (key c-7f3a -> completed, response stored)
8 POST /payments Idempotency-Key: c-7f3a (user tapped again)
9 <-- 201 same body, replayed; nothing sent to Stripeسناریوی واقعی: دوبار زدن دکمهٔ پرداخت؛ retry برنامهٔ موبایل بعد از اتصال مجدد؛ crash شدن queue worker پس از فراخوانی PSP؛ پاسخ 504 از load balancer درحالیکه backend کار را تمام کرده است.
چه چیزی فراهمش میکند:
| ارائهدهنده | هدر | نگهداری و رفتار مستند در برابر تکرار |
|---|---|---|
| Stripe API v1 | Idempotency-Key | کلید پس از 24 h قابلپاکسازی است؛ اولین پاسخ ذخیرهشده، حتی 500، بازپخش میشود؛ پارامترها مقایسه و اختلاف رد میشود؛ هنگام اجرای درخواست اول 409: "wait and retry with that key and the same parameters" |
| Adyen | idempotency-key | "valid for a period of 7 to 14 days"، برای هر حساب شرکت؛ میان endpointهای منطقهای بررسی نمیشود؛ تکرار پیش از پایان درخواست اول: 422 یا 409 با کد 704 و "request already processed or in progress"؛ رقابت ممکن است transient-error: true بدهد، با همان کلید retry کنید؛ اگر انبارهٔ idempotency در دسترس نباشد، 503 با کد 703 |
| Square | کلید idempotency یا "a unique string" در درخواست | کلید و درخواست یکسان: "returns the response as the first successful"؛ پارامتر متفاوت: "you get an error indicating that you used the idempotency key previously"؛ رفتار "might vary depending on the API" |
| پیشنویس IETF | Idempotency-Key | مدت نگهداری را سرور تعیین میکند؛ 422 SHOULD برای کلید قبلی با payload دیگر؛ 409 SHOULD هنگام پردازش درخواست اول؛ 400 برای نبود کلید اجباری |
| API شما | Idempotency-Key | حداقل پنجرهٔ PSP؛ 422 برای fingerprint و 409؛ مستقل از کلید، فقط یک پرداخت برای هر merchant و order با ErrDuplicateOrder |
راهحل / روش استفاده: idem.Store با fingerprint، Started/Replay/InFlight و ErrMismatch؛ ستون payment_attempts.psp_idem_key UNIQUE با کلید مشتقشدهٔ pi_...:attempt:N. در Laravel، PaymentIntent با Cashier::stripe()->paymentIntents->create($params, ['idempotency_key' => 'pay_<order>:intent']) ساخته میشود؛ pay() و charge() در Cashier کلید را عرضه نمیکنند. مسیر refund هدر Idempotency-Key خود کلاینت را لازم میداند، روی ردیف refunds ذخیره میکند و در retry همان ردیف را بازپخش میکند.
Timeout، retry و نتیجهٔ نامعلوم حیاتی
به زبان ساده: پایان مهلت (Timeout) تماس با PSP نمیگوید مشتری پول داده یا نه. پیش از هر کار باید نتیجهٔ نامعلوم (Unknown outcome) را با پرسوجو یا همان کلید روشن کنید. تا وقتی PSP اول ممکن است برداشت کرده باشد، PSP دیگری را امتحان نکنید.
بدفهمی رایج: «Timeout یعنی failure؛ بنویس پرداخت ناموفق بود و بگذار دوباره بزند.» شاید پول برداشت شده و مشتری دوباره پرداخت کند. راهنمای Stripe صریح است: "Treat the outcome of a request that returns 500 as indeterminate: the operation might have produced side effects even though you received an error. Don’t retry with a new idempotency key until you’ve resolved the original outcome."
تعریف: unknown outcome یعنی اثر جانبی ممکن است اتفاق افتاده باشد یا نه: timeout کلاینت، reset اتصال پس از ارسال و 5xx. در مقابل، پردازشنشدن اثباتشده (Provably-not-processed) یعنی درخواست وارد پردازش نشده: connection refused، شکست DNS پیش از ارسال یا خطای مستندی که نبود اثر را تضمین میکند. فقط دستهٔ دوم اجازهٔ failover به PSP دیگر میدهد. Stripe میگوید "Limit retries of an unresolved operation to the first 24 hours after the original request, using the same key and parameters"؛ اگر همچنان نامعلوم بود "don’t retry with either the old key or a new one" و reconciliation کنید. هدر Stripe-Should-Retry هم راهنمای retry دارد. نخستین توصیهٔ تیم پرداخت Shopify، "1. Lower Your Timeouts" است؛ پیشفرض Net::HTTP در Ruby برای هر مرحله 60 ثانیه است.
نمودار Service.charge و Service.Confirm در payment/service.go را نشان میدهد. تنها ردیف وسط PSP را عوض میکند؛ ردیف پایین همان PSP و کلید را حفظ میکند. کادر قرمز جای انتظار attempt برای sweep تطبیق است.
Payment service Stripe (primary) Adyen (secondary)
1 Authorize key=pi_2:attempt:1 ----> charge processed
2 ... 200 ms timeout (answer lost)
3 Lookup / resend key=pi_2:attempt:1 -> timeout again (Stripe degraded)
4 attempt 1 state = unknown -- do NOT call Adyen: Stripe may have charged
5 order screen: "payment pending"
6 (5 min later) sweep: resend same key -> saved response: succeeded
7 apply: succeeded, ledger, outbox -> customer charged onceسناریوی واقعی: اختلال PSP که درخواست را اجرا میکند اما پاسخ timeout میشود؛ deploy که worker را وسط تماس میکشد؛ کلاینت موبایل در قطار؛ «router هوشمند» که با هر خطا failover میکند و هنگام افت کیفیت PSP دوبار برداشت میکند.
هر دستهٔ خطا چه اجازهای میدهد:
| خطا | مثال | نتیجه | Retry با همان کلید | Failover به PSP دیگر |
|---|---|---|---|---|
| رد روشن (Clear decline) | card_declined / insufficient_funds | معلوم؛ برداشت نشده | خیر؛ برای این attempt نهایی است | نه برای همان دلیل؛ شاید برای خطای مختص issuer |
| اعتبارسنجی 4xx | پارامتر نامعتبر | معلوم؛ برداشت نشده | خیر؛ درخواست را اصلاح کنید | خیر |
| 409؛ کلید در حال اجرا | تکرار همزمان | نامعلوم؛ هنوز اجرا میشود | بله، پس از انتظار | خیر |
| Timeout پس از ارسال | context.DeadlineExceeded | نامعلوم | بله، پارامتر یکسان | هرگز |
| 5xx | 500 | نامعلوم؛ Stripe همراه کلید cache میکند | اول نتیجه را روشن کنید | هرگز |
| رد retry یک کلید نامعلوم | 503 پس از timeout قبلی | هنوز نامعلوم؛ این رد چیزی دربارهٔ ارسال قبلی ثابت نمیکند | بله، بعداً | هرگز |
| خطای دستهبندینشده | Connection reset، خطای decode پاسخ | نامعلوم؛ توقف امن (Fail closed) | بله | هرگز |
| Connect refused / DNS برای کلید تازه | چیزی ارسال نشده و قبلاً هم ارسال نشده | معلوم؛ برداشت نشده | بله | بله، attempt و کلید جدید |
راهحل / روش استفاده: هر بار فقط یک عملیات روی هر پرداخت اجرا شود؛ Confirm، Capture و Refund توکن مختص پرداخت را میگیرند و فراخوان دوم ErrInFlight، معادل 409 سرویس، میگیرد. Attemptی که حتی یک بار ارسال شده، تا پاسخ روشن یا اثبات نتیجه با reconciliation به همان کلید و PSP مقید میماند. مهلت هر تماس خیلی کمتر از بودجهٔ checkout باشد؛ در آزمایشگاه NewService(200*time.Millisecond, ...). تابع charge اول lookup و بعد retry با همان کلید میکند؛ attemptهای unknown با partial index به نام payment_attempts_open برای پیگیری میمانند. ارسال مجدد فقط داخل ResendWindow مجاز است؛ پیشفرض 23 h، کمتر از نگهداری 24 ساعتهٔ کلید Stripe. پس از آن ErrNeedsReconciliation برمیگردد و بهجای ارسال، تطبیق انجام میشود. بودجه و jitter کلاینت در Timeouts, Retries & Jitter آمده؛ جلوی هر PSP یک Circuit Breaker بگذارید تا هنگام افت کیفیت سریع شکست بخورد.
دفترکل دوطرفه: debit، credit، journal entry و append-only حیاتی
به زبان ساده: هر جابهجایی پول یک ثبت روزنامه (Journal entry) با حداقل دو سطر دارد. مجموع بدهکار (Debit) و بستانکار (Credit) برابر است. هیچ سطری ویرایش نمیشود؛ خطا با ثبت معکوس تازه اصلاح میشود. موجودی از جمع سطرها به دست میآید؛ این دفترکل دوطرفه (Double-entry ledger) است.
بدفهمی رایج: «Debit یعنی منفی و credit یعنی مثبت.» افزایش یا کاهش به نوع حساب بستگی دارد. Modern Treasury: "Debit normal accounts increase with a debit entry and decrease with a credit entry" و "Credit normal accounts increase with a credit entry and decrease with a debit entry". دارایی، مثل وجه نقد و طلب از PSP، و هزینه ماهیت بدهکار دارند. بدهی، مثل کیف پول مشتری یا سهم فروشنده، درآمد و سرمایه ماهیت بستانکار دارند. باور غلط دوم این است که ستون balance همراه audit log همان ledger است. موجودی قابلتغییر ممکن است از log جدا شود؛ موجودی مشتقشده چنین نیست.
تعریف: حساب (Account) طبق Modern Treasury "a discrete pool of value that represents a balance you want to track" است. Journal entry یا journal transaction مجموعهٔ اتمی سطرهاست؛ هر سطر حساب، جهت debit یا credit و مبلغ مثبت در minor units دارد. برای هر ارز، جمع debit و credit برابر است. Fowler میگوید "The value, or balance, of the Account is derived as the sum of all the Accounting Entrys." تغییرناپذیری دفترکل (Ledger immutability) یعنی فقطافزودنی (Append-only): بدون UPDATE و DELETE. اصلاح، journal entry معکوس تازه است تا رد حسابرسی (Audit trail) هم خطا و هم اصلاح را نشان دهد. Stripe Ledger هم میگوید "Transactions previously published into Ledger cannot be deleted or modified, and we can always reconstruct past state by processing all events up to that point." حساب واسط (Clearing account)، اینجا psp_receivable، پول در مسیر را نگه میدارد و با پایان جریان باید صفر شود؛ تشبیه Stripe "intermediate (clearing) pipes" است که در حالت پایدار "empty" هستند.
تصویر مثال هتل در جابهجایی پول را تا بانک دنبال میکند. هر ردیف خودش تراز است. حساب دریافتنی PSP یک بار debit و سه بار credit میشود تا پس از payout صفر شود. ماندهٔ غیرصفر در پایان ماه یعنی ticket برای reconciliation.
Two concurrent postings on the same wallet (liability, balance 100), PostgreSQL READ COMMITTED
T1 (withdraw 80) T2 (withdraw 50)
1 BEGIN; BEGIN;
2 SELECT ... FROM ledger_accounts WHERE id IN
('wallet:u1:USD','cash:USD') ORDER BY id FOR UPDATE; -- locks in id order
3 SELECT ... same rows ORDER BY id FOR UPDATE; -- waits
4 check: 100 - 80 >= 0 -> insert entries, update cached balance
5 COMMIT; -- deferred trigger checks D = C
6 -- wakes, sees balance 20: 20 - 50 < 0 -> ROLLBACK
Without FOR UPDATE both read 100 and the wallet ends at -30 (a lost update, see Isolation Levels).سناریوی واقعی: بازارگاه سهم فروشنده را بدهکار است و کمیسیون را درآمد ثبت میکند؛ کیف پول نباید منفی شود؛ دو پشتیبان همزمان refund میزنند؛ حسابرس میپرسد موجودی ۳۰ ژوئن چه بود و چرا؛ مالی برای بستن ماه کارمزد PSP را بهعنوان هزینه لازم دارد.
چه چیزی فراهمش میکند:
| سیستم | Double-entry | تغییرناپذیری (Immutability) | بررسی تراز |
|---|---|---|---|
| SQL این فصل | سطرهای ledger_entries، سربرگهای journal_transactions | triggerهای BEFORE UPDATE OR DELETE خطا میدهند | Constraint trigger معوق؛ D = C برای هر ارز در COMMIT؛ CHECK (allow_negative OR balance >= 0) |
بستهٔ Go به نام ledger | Post ثبت نامتوازن یا تکسطر را رد میکند | API ویرایش ندارد؛ Post و Journal کپی عمیق میدهند تا فراخواننده نتواند ثبت ذخیرهشده را تغییر دهد؛ Reverse قرینه را ثبت میکند | TrialBalance() همیشه صفر؛ Recompute() برابر cache |
Laravel LedgerService | post() در DB::transaction(..., attempts: 3) | فقط insert | حسابها با ترتیب ثابت و lockForUpdate() قفل میشوند |
| Stripe Ledger داخلی | "based on double-entry bookkeeping" | "immutable log of events" | معیارهای کیفیت داده روی جریان وجوه |
راهحل / روش استفاده: شناسهٔ ثبت را از رویداد کسبوکار بسازید؛ capture:pi_... و refund:<key>، تا idempotent باشد. حسابها را با ترتیب ثابت lock کنید تا deadlock نشود. Cached balance فقط بهینهسازی است و Recompute باید آن را تأیید کند. جزئیات در Isolation Levels و ACID Transactions است.
Webhook: بررسی امضا، replay window، ترتیب و تکرار حیاتی
به زبان ساده: اعلان HTTP یا webhook از PSP میگوید چه اتفاقی افتاده است. اول اصالتش را بررسی کنید، ذخیرهاش کنید و سریع 200 بدهید. کار واقعی را بعداً با اثر یکباره انجام دهید؛ نه یکبار رسیدن تضمین است و نه ترتیب.
بدفهمی رایج: «JSON را parse کن، type را بخوان و سفارش را تغییر بده.» بدون بررسی امضا (Signature verification)، هرکسی با payment_intent.succeeded کالای رایگان میگیرد. بررسی روی JSON دوباره encodeشده هم غلط است: "Stripe requires the raw body of the request to perform signature verification". اجرای کار کسبوکار پیش از پاسخ هم retry میسازد: "Your endpoint must quickly return a successful status code (2xx) before any complex logic that could cause a timeout."
تعریف: Stripe هر تحویل را در هدر Stripe-Signature امضا میکند: t=<timestamp>,v1=<hex HMAC-SHA256>. ورودی HMAC-SHA256 برابر t + "." + raw body و کلید، signing secret همان endpoint است. مستندات میگویند "Our libraries have a default tolerance of 5 minutes between the timestamp and the current time"؛ در stripe-go مقدار DefaultTolerance time.Duration = 300 * time.Second است. همچنین "Don’t use a tolerance value of 0. Using a tolerance value of 0 disables the recency check entirely." این تحمل زمانی همان پنجرهٔ بازپخش (Replay window) است؛ درخواست ضبطشده پس از آن کاربرد ندارد. هنگام چرخش راز (Secret roll)، تا 7 روز "multiple secrets are active for the endpoint. Stripe generates one signature per secret". ورودی v0، "is only present for test events"؛ parser هم "must accept unknown entries and must not depend on a fixed entry count or order". تحویل حداقل یکباره (At-least-once delivery) است: "Webhook endpoints might occasionally receive the same event more than once". در live mode، retry "for up to three days with an exponential back off in live mode" ادامه دارد. حتی دو Event جدا ممکن است تکراری باشند؛ "use the ID of the object in data.object along with the event.type". ترتیب تضمین ندارد؛ این همان out-of-order webhooks است و "Don’t use created to determine event order". Eventها "for 30 days" از API قابلدریافتاند. Adyen هم HMAC-SHA256 روی payload را با کلید HMAC میسازد و Base64 آن را در additionalData.hmacSignature میفرستد.
Stripe Webhook endpoint (yours) Queue worker
1 POST /webhooks/stripe Stripe-Signature: t=1798765432,v1=5257a8...
2 raw body bytes -> HMAC(secret_v2) == v1? -- also try secret_v1 during a roll
3 |now - t| <= 300 s ? -- replay window
4 INSERT webhooks_inbox (stripe, evt_1) ON CONFLICT DO NOTHING
5 processed_at IS NULL -> dispatch job
6 <- 200 {"received": true} (in milliseconds)
7 (retry: our 200 was lost) POST same evt_1, new t and new signature
8 INSERT ... -> 0 rows (duplicate); processed_at still NULL
-> dispatch again (the job is idempotent) -> 200
(had the job already finished: processed_at set -> 200, no job)
9 lock inbox row + payment row
10 state machine allows edge?
11 payment, ledger, outbox, processed_at
12 -- one DB transactionسناریوی واقعی: webhook جعلی succeeded وسط حراج؛ deploy ترتیب middlewareهای JSON را عوض میکند و همهٔ امضاها میشکنند؛ Stripe برای Node میگوید "make sure app.use(express.json()) appears after your webhook route" و همین دام در frameworkهای دیگر هست. Handler سیثانیهای باعث پنج بار ارسال event میشود؛ charge.refunded پیش از payment_intent.succeeded میرسد؛ چرخش secret روی نیمی از سرورها verification را خراب میکند.
چه چیزی فراهمش میکند:
| دغدغه | Stripe | Adyen | Laravel / Cashier | این فصل |
|---|---|---|---|---|
| امضا (Signature) | Stripe-Signature، HMAC-SHA256، hex | HMAC-SHA256، Base64، additionalData.hmacSignature | route متعلق به Cashier با STRIPE_WEBHOOK_SECRET بررسی میکند | webhook.Verifier، StripeWebhookController::verify |
| پنجرهٔ بازپخش (Replay window) | Timestamp در هدر؛ پیشفرض کتابخانه 5 دقیقه | در روش HMAC صفحهٔ Adyen، tolerance برای timestamp وجود ندارد؛ بهجایش dedup کنید | cashier.webhook.tolerance = STRIPE_WEBHOOK_TOLERANCE، پیشفرض 300؛ به WebhookSignature::verifyHeader داده میشود | الزام Tolerance > 0 با ErrBadTolerance |
| چرخش secret (Secret roll) | تا 7 روز، یک v1 برای هر secret | روش "Changing your HMAC key" | یک secret در env | Secrets [][]byte؛ تطبیق یکی کافی است |
| تلاش مجدد (Retries) | تا سه روز، exponential backoff در live | بدون 2xx در 10 ثانیه → صف retry؛ "for up to 30 days" با فاصلههای 30 s، 30 s، 1 min، 2 min تا 8 h؛ alert پس از 5 retry | کاربرد ندارد | پس از ذخیره 200؛ اگر هنوز پردازش نشده دوباره dispatch کنید |
| ترتیب (Order) | تضمین ندارد | "always check the timestamp"؛ بعضی webhookها sequenceNumber دارند | کاربرد ندارد | State machine رویداد کهنه را نادیده میگیرد و پیشرفت را میپذیرد |
| حذف تکرار (Dedup) | Event id؛ object id + type | تکراریها "have the same values in the eventCode and pspReference fields"؛ "use the details from the latest webhook event" | کاربرد ندارد | کلید اصلی webhooks_inbox برابر (psp, event_id) |
راهحل / روش استفاده: raw body، مقایسهٔ constant-time، tolerance و چند secret را بررسی کنید. در جدول idempotency Webhook (Webhook idempotency table) به نام webhooks_inbox بنویسید؛ همان inbox در Idempotent Consumer & Inbox. سپس 200 بدهید و در job صف، داخل یک transaction پردازش کنید. پس از آخرین retry ردیف را پردازشنشده با last_error نگه دارید؛ این رکورد dead-letter برای انسان است؛ Dead Letter Queue. اگر پرداخت هنوز در پایگاهداده نیست، بعداً retry کنید و event را processed نکنید. در production از webhook.ConstructEvent در stripe-go یا \Stripe\Webhook::constructEvent در Stripe PHP SDK استفاده کنید؛ verifier دستی این صفحه برای نشان دادن جزئیات بررسی است.
Outbox: تحویل حداقل یکباره و اثر دقیقاً یکباره حیاتی
به زبان ساده: پس از موفقیت پرداخت، سفارش، ایمیل و تحلیل باید باخبر شوند. رویداد موفقیت را در جدول خروجی (Outbox) و در همان تراکنش پرداخت و ledger بنویسید. Relay بعداً منتشرش میکند؛ مصرفکننده با event id تکراریها را کنار میگذارد.
بدفهمی رایج: «Commit کن، بعد در Kafka منتشر کن؛ اگر نشد log میکنیم.» Crash بین این دو، event را گم میکند؛ مشتری پول داده ولی سفارش ارسال نمیشود. ترتیب معکوس هم پرداختی را اعلام میکند که rollback میشود. تحویل دقیقاً یکباره نداریم؛ اثر دقیقاً یکباره (Exactly-once effect) از تحویل حداقل یکباره (At-least-once delivery) و مصرفکنندهٔ idempotent ساخته میشود.
تعریف: Outbox pattern رویداد را اتمی با تغییر state ذخیره میکند. Relay با polling یا CDC سطرها را منتشر و published علامت میزند. Crash میان publish و mark باعث ارسال دوباره میشود، پس delivery حداقل یکباره است. مصرفکننده هر event id را با inbox فقط یک بار اعمال میکند. برای ترتیب درون هر پرداخت، payment id را partition key قرار دهید. جزئیات در Outbox Pattern است.
Payment service tx Relay Order service
1 BEGIN
2 UPDATE payments SET status='succeeded'...
3 INSERT ledger entries ...
4 INSERT outbox (evt_pi_0001_v3, payments.payment_succeeded)
5 COMMIT
6 SELECT ... WHERE published_at IS NULL
7 publish evt_pi_0001_v3 -> broker
8 (crash before marking published)
9 restart: publish evt_pi_0001_v3 again
10 inbox: evt_pi_0001_v3 new -> ship
11 inbox: seen -> skipسناریوی واقعی: ایمیل رسید دوبار ارسال میشود یا اصلاً نمیرسد؛ fulfilment بهخاطر event مربوط به transaction برگشتخورده کالای ناپرداخت را میفرستد؛ pipeline تحلیل درآمد را دو بار میشمارد.
چه چیزی فراهمش میکند:
| جزء | اینجا | جایگزین |
|---|---|---|
| جدول خروجی (Outbox) | outbox با event_id UNIQUE و partial index روی منتشرنشدهها | Debezium CDC روی جدول |
| ناشر (Relay) | outbox.RelayOnce؛ برای ترتیب هر key روی اولین خطا میایستد | Laravel queued job، Kafka Connect |
| حذف تکرار مصرفکننده (Consumer dedup) | outbox.Inbox / webhooks_inbox | جدول processed-events برای هر مصرفکننده |
| ارسال job در Laravel (Dispatch) | ProcessStripeEvent::dispatch(...)->afterCommit() | گزینهٔ after_commit روی queue connection |
راهحل / روش استفاده: broker را داخل transaction پرداخت صدا نزنید. همان تابع تغییر state، یعنی Service.apply، outbox row را بسازد. شناسهٔ هر event قطعی باشد: evt_<intent>_v<version>.
Saga و جبران: checkout چندمرحلهای حیاتی
به زبان ساده: checkout به موجودی کالا، پرداخت و ارسال دست میزند. تراکنش مشترکی میان این سرویسها نیست؛ مراحل را پشت سر هم اجرا میکنید و اگر مرحلهای شکست خورد، کار قبلی را با عمل جبرانی (Compensation) خنثی میکنید: آزاد کردن کالا و void کردن hold کارت. این زنجیره saga است.
بدفهمی رایج: «جبران پرداخت همیشه refund است.» فقط بعد از capture. پیش از آن void است؛ هزینه ندارد و سطری روی صورتحساب مشتری باقی نمیگذارد. به همین علت بسیاری از checkoutها اول authorize و پس از آخرین مرحلهٔ شکستپذیر capture میکنند. اشتباه دوم این است که compensation شکست نمیخورد؛ void هم timeout میشود و retry و dead-letter لازم دارد.
تعریف: Saga دنبالهای از transactionهای محلی با اعمال جبرانی است؛ orchestrator یا eventها در choreography هماهنگش میکنند. هر مرحله و جبرانش باید idempotent باشد، چون coordinator بعد از crash ممکن است دوباره اجرا کند. مقایسهٔ دو روش در Saga Pattern است.
Orchestrator (order-77) Inventory Payment (PSP) Shipping
1 reserve_stock ----------> reserved
2 authorize ----------------------------> hold 4999
3 book_shipment ----------------------------------------------------> "no slot" (fail)
4 undo authorize ----------------------------> void hold (key order-77:authorize)
5 undo reserve ----------> released
6 order -> canceled; customer sees "could not ship", card statement shows nothing
If step 4 keeps failing: parked on the dead-letter list; the hold expires by itself at its capture_beforeسناریوی واقعی: نبود کالا بعد از authorization معلوم میشود؛ سیستم بلیت همزمان صندلی و مبلغ را نگه میدارد؛ در سفر ترکیبی پرواز و هتل یکی شکست میخورد؛ فروشندهٔ بازارگاه سفارش را رد میکند.
چه چیزی فراهمش میکند:
| مرحله | عمل | جبران (Compensation) | کلید Idempotency |
|---|---|---|---|
| رزرو کالا (Reserve stock) | کاهش موجودی قابلفروش | آزادسازی | order-77:reserve_stock |
| رزرو پول (Authorize) | PaymentIntent با manual capture | Void یا cancel | order-77:authorize |
| رزرو ارسال (Book shipment) | API شرکت حمل | لغو برچسب ارسال | order-77:book_shipment |
| برداشت (Capture) | برداشت hold | Refund؛ نادر، چون capture آخر است | order-77:capture |
راهحل / روش استفاده: checkout.Orchestrator مراحل را اجرا میکند، مراحل تمامشده را معکوس جبران میکند، هر undo را UndoTries بار retry میکند و شکست را در DeadLetter میگذارد. Capture آخرین مرحله است و undo ندارد.
تطبیق حسابها: settlement file، payout و کارمزد حیاتی
به زبان ساده: هر روز تصور خودتان از اتفاقها را سطربهسطر با گفتهٔ PSP مقایسه کنید: charge، refund، chargeback، کارمزد و واریز به بانک. این تطبیق (Reconciliation) هر اختلاف را به باگ یا نتیجهٔ نامعلومی که حالا روشن شده میرساند.
بدفهمی رایج: «Webhookها مطمئناند؛ پس database درست است.» ممکن است بیشتر از پنجرهٔ retry گم شوند، بد پردازش شوند یا برای eventی که هنگام subscription وجود نداشته ارسال نشوند. کارمزد و FX در گزارشها هستند. Payout هم معادل روز تقویمی نیست؛ Stripe میگوید "Match report rows to payouts using automatic_payout_id instead of assuming that report dates coincide with the dates payouts arrive in your bank account".
تعریف: فایل تسویه (Settlement file)، مثل Adyen settlement detail report یا Stripe payout reconciliation report و balance report، هر سطر تسویه را با PSP reference، نوع، gross، fee و net و گروه واریز (Payout یا settlement batch) میآورد. Reconciliation تطبیق سهطرفه است: payments/ledger خودتان ↔ فایل PSP ↔ صورتحساب بانک. خروجی چند فهرست است: matched، missing at PSP پس از cutoff، missing locally یعنی PSP پولی را تسویه کرده که ثبت نکردهاید، اختلاف مبلغ و کارمزد ثبتنشده.
06:00 job loads stripe payout po_77 lines into settlement_lines (insertOrIgnore: rerun-safe)
06:01 join on psp_reference
1 stripe_ch_1 charge 2500 fee 103 ours 2500 -> matched
2 stripe_ch_2 charge 4000 fee 146 ours 4000 -> matched
3 stripe_ch_9 charge 1200 fee 65 ours: none -> missing_locally (an "unknown" attempt that succeeded)
4 fees total 314 -> post D psp_fees / C psp_receivable
5 bank statement: payout po_77 net amount -> post D cash:bank / C psp_receivable; receivable for po_77 = 0سناریوی واقعی: attempt نامعلوم هنگام اختلال موفق بوده و حالا باید fulfil یا refund شود؛ پشتیبانی از dashboard خود PSP refund زده و شما ثبت نکردهاید؛ کارمزد FX پرداخت چندارزی؛ payout شکستخورده که PSP دوباره فرستاده است.
چه چیزی فراهمش میکند:
| منبع | محتوا | کلید تطبیق |
|---|---|---|
| Stripe payout reconciliation report | تراکنشها به تفکیک automatic payout | automatic_payout_id |
| Stripe balance report | حرکت موجودی به تفکیک دسته | جمع دوره |
| Adyen settlement detail report | سطرهای تسویهٔ هر تراکنش در هر batch | pspReference و شمارهٔ batch |
| صورتحساب بانک (Bank statement) | اعتبار payout | شناسهٔ payout در متن reference |
| این فصل | recon.Reconcile و job به نام ReconcileSettlementFile | psp_reference و cutoff time |
راهحل / روش استفاده: بارگذاری فایل idempotent باشد؛ کلید اصلی (psp, batch_id, psp_reference, line_type). مبلغها را صحیح مقایسه کنید، fee و payout را در ledger ثبت کنید، برای هر سطر unmatched ticket باز کنید و missing locally را مسیر حل unknown outcome بدانید.
اعتراض و Chargeback مهم
به زبان ساده: صاحب کارت میتواند از بانک بخواهد پرداخت را پس بگیرد. بانک فوراً مبلغ را کسر میکند، شما کارمزد میدهید و با ارائهٔ مدرک شاید هفتهها بعد پول را پس بگیرید. این پروندهٔ اعتراض (Dispute) و برگشت بانکی (Chargeback) است.
بدفهمی رایج: «Dispute همان refund درخواستی مشتری است.» مبلغ و کارمزد فوراً کم میشود: "Debits the disputed amount, plus a dispute fee, from your Stripe account". معمولاً حتی برد پرونده کارمزد دریافت اعتراض را برنمیگرداند: "Unless otherwise stated in your Stripe contract, we never return the dispute received fee". Refund پس از باز شدن dispute هم میتواند دوبار پول به مشتری بدهد. تصور غلط دیگر این است که 3-D Secure جلوی همهٔ disputeها را میگیرد. فقط مسئولیت تقلب را معمولاً به issuer منتقل میکند: "If a cardholder disputes a 3DS payment as fraudulent, the liability typically shifts from you to the card issuer"؛ اعتراض «کالا نرسیده» باقی است.
تعریف: ابتدا ممکن است درخواست اطلاعات (Inquiry یا retrieval request) برسد. Chargeback اعتراض رسمی است و حساب پذیرنده را بدهکار میکند. فرصت مدرک معمولاً "usually 7-21 days, depending on the card network" و تصمیم issuer "usually 60-75 days" است. نتیجه won یا lost است؛ گاهی برد دیرهنگام و در بعضی شبکهها pre-arbitration هم وجود دارد. پنجرهٔ معمول کارت 120 روز از پرداخت است؛ مشتری SEPA Direct Debit تا 8 هفته "without providing a reason for up to 8 weeks after the debit" میتواند اعتراض کند.
Day Event Ledger (minor units) Dispute status
1 0 payment captured 5000 D receivable 5000 / C sales 5000
2 40 charge.dispute.created D chargeback_losses 5000, D dispute_fees 1500
/ C receivable 6500 needs_response
3 45 evidence submitted (3DS, tracking) under_review
4 100 issuer decides: won D receivable 5000 / C chargeback_losses 5000 won
5 fee 1500 stays an expenseسناریوی واقعی: friendly fraud بعد از دانلود دیجیتال؛ اشتراکی که مشتری فراموش کرده؛ کارت دزدیدهشده بدون 3DS؛ اعتراض mandate مربوط به SEPA در هشت هفته؛ early fraud warning که تحلیل Stripe دربارهاش refund را "most worthwhile on charges at or below your dispute fee" میداند.
چه چیزی فراهمش میکند:
| محصول | سیگنال | مدرک | رفتار کارمزد |
|---|---|---|---|
| Stripe | charge.dispute.created، charge.dispute.closed | ارسال مدرک با dashboard یا API | Received fee برنمیگردد، بهجز مکزیک؛ countered fee در صورت برد برمیگردد |
| این فصل | dispute.Open، SubmitEvidence، Close | کاربرد ندارد | کارمزد هنگام open ثبت و هرگز معکوس نمیشود |
راهحل / روش استفاده: Chargeback را فوری و idempotent با شناسهٔ dispute_opened:<id> ثبت کنید. نتیجهٔ 3DS، IP، دستگاه و اثبات تحویل را کنار پرداخت نگه دارید؛ هم برای مدرک و هم مدل تقلب لازماند. Refund روی پرداختهای مورد اختلاف را مسدود کنید و disputeهای باخته را به ruleهای تقلب برگردانید.
3-D Secure، SCA و PSD2 مهم
به زبان ساده: بانک مشتری برای بسیاری از پرداختهای آنلاین، بهخصوص اروپا، حضور واقعی دارندهٔ کارت را میخواهد؛ تأیید در app، اثرانگشت یا کد یکبارمصرف. 3-D Secure پروتکل درخواست این اثبات است. احراز هویت قوی مشتری (SCA) قاعدهٔ اروپایی الزام آن و PSD2 قانون پشت قاعده است.
بدفهمی رایج: «3-D Secure همیشه pop-up دارد.» در EMV 3DS نسخهٔ 2، جریان بدون تعامل (Frictionless flow) ممکن است؛ Adyen میگوید "the acquirer, issuer, and card scheme exchange all necessary information in the background through passive authentication using the shopper's device fingerprint". فقط جریان چالشی (Challenge flow) از مشتری چیزی میخواهد. اشتباه معکوس این است که پرداخت کمریسک معاف است و پیادهسازی 3DS لازم نیست. Stripe: "banks can still request that the customer complete authentication" و "Exemptions aren’t guaranteed".
تعریف: Strong Customer Authentication برای پرداخت الکترونیکی در EEA دو عامل مستقل میخواهد؛ مبنا PSD2 و Commission Delegated Regulation (EU) 2018/389 یا RTS on SCA and CSC از EBA است. Stripe شروع را ۱۴ سپتامبر ۲۰۱۹ میداند و میگوید "Card payments require you to use 3D Secure to meet SCA requirements". EMVCo: "While EMV 3DS 2.1 supports SCA, EMVCo recommends that v2.2 (or higher) should be considered"؛ فهرست نسخههای خواندهشده شامل v2.4.0.0 است. برداشت از کارت ذخیرهشده بدون حضور مشتری، تراکنش آغازشده توسط پذیرنده (Merchant-Initiated Transaction, MIT) است و "an agreement (also known as a mandate)" لازم دارد. احراز هویت موفق 3DS انتقال مسئولیت (Liability shift) برای dispute تقلب میدهد.
Customer Your server PSP / 3DS server Issuer ACS
1 Pay 120 EUR --> confirm(pi_9) ---> 3DS2 AReq with device data, history -> risk check
2 frictionless? -> ARes "Y" (no UI)
3 <- succeeded (liability shift)
or
2' challenge -> ARes "C"
3' <- requires_action (next_action)
4' bank app approve -----------------------------------------> CRes OK
5' webhook payment_intent.succeededسناریوی واقعی: issuer اروپایی هر خرید اول را challenge میکند؛ تمدید اشتراک off-session MIT با authentication_required رد میشود و مشتری باید on-session برگردد؛ rule تقلب بهجای block، step-up میکند؛ پذیرندهٔ آمریکایی برای انتقال مسئولیت فقط سفارش پرریسک را 3DS میکند.
چه چیزی فراهمش میکند:
| محصول | نمود 3DS | کار توسعهدهنده |
|---|---|---|
| Stripe | PaymentIntent با requires_action؛ Radar میتواند "request 3DS authentication" | مدیریت next_action با Stripe.js و نتیجه از webhook |
| Adyen | Native یا redirect 3D Secure 2؛ frictionless یا challenge | شیء action با Drop-in / Components مدیریت میشود |
| Laravel Cashier | exception به نام IncompletePayment | هدایت به route cashier.payment همراه redirect |
| این فصل | intent.RequiresAction، fraud.Request3D | موتور تقلب برای ریسک متوسط و کارت پشتیبان 3DS، step-up میکند |
راهحل / روش استفاده: همیشه requires_action را مدیریت کنید. کارت را با SetupIntent ذخیره کنید؛ تعریف Stripe "an object that represents your intent to set up a customer’s payment method for future payments" است، تا پرداخت off-session بعدی mandate داشته باشد. 3DS عمل ریسک متوسط موتور تقلب باشد و نتیجه برای مدرک dispute ذخیره شود.
PCI DSS، SAQ A، tokenization، network tokens و card vaulting حیاتی
به زبان ساده: اگر شمارهٔ کارت از سرورهای شما بگذرد، استاندارد امنیتی بزرگی به آنها اعمال میشود. دریافت کارت را به صفحه یا iframe خود PSP بسپارید و بهجایش توکن (Token) بگیرید؛ بیشتر الزامات از دامنهٔ شما بیرون میروند.
بدفهمی رایج: «کارت ذخیره نمیکنیم؛ پس PCI نداریم.» پردازش یا انتقال شمارهٔ اصلی کارت (PAN)، حتی در حافظه یا یک خط لاگ، سیستم را وارد دامنه میکند. Controller در Before.php مقدار card_number را به سرور میفرستد و با CVV لاگ میکند؛ این قلمرو SAQ D یا ارزیابی کامل است و لاگ CVV مجاز نیست. Stripe دربارهٔ PAN بدون token میگوید پذیرنده "might be required to meet more than 300 security controls in PCI DSS".
تعریف: PCI DSS، با نسخهٔ جاری v4.0.1، برای سیستمهای ذخیره، پردازش یا انتقال دادهٔ دارندهٔ کارت است. پرسشنامهٔ خودارزیابی (Self-Assessment Questionnaire یا SAQ) ابزار اعتبارسنجی پذیرنده است. SAQ A "includes only those PCI DSS requirements applicable to merchants with account data functions completely outsourced to PCI DSS validated and compliant third parties"؛ این پذیرندهها "do not store, process, or transmit any account data in electronic form on their systems or premises". از SAQ A ژانویهٔ ۲۰۲۵ باید تأیید کنند "confirm their site is not susceptible to attacks from scripts that could affect the merchant’s e-commerce system(s)". الزامات 6.4.3 و 11.6.1 از SAQ A حذف شدهاند، نه از PCI DSS. روش اعتبارسنجی را "brands, acquirers, payment facilitators" تعیین میکنند، نه خود PCI SSC. جایگزینی با توکن (Tokenization)، PAN را با reference مثل pm_... در Stripe عوض میکند که بیرون PSP کاربرد ندارد. نگهداری کارت (Card vaulting) برای استفادهٔ بعدی است؛ PAN در vault خود PSP میماند و شما token و card fingerprint پایدار را نگه میدارید. توکن شبکه (Network tokens) را شبکهٔ کارت صادر میکند؛ Visa Token Service میگوید "By substituting Visa card numbers with tokens". این tokenها میتوانند بعد از تعویض کارت فیزیکی معتبر بمانند؛ Visa از تازه کردن تاریخ انقضای قدیمی در provisioning میگوید. Stripe هم "is certified annually by an independent PCI Qualified Security Assessor (QSA) as a PCI Level 1 Service Provider".
Browser (your page) PSP iframe (stripe.com origin) Your server PSP
1 loads checkout from your origin + Stripe.js (CSP allowlists only Stripe's origins)
2 customer types PAN, expiry, CVC
3 PAN -> PSP over TLS --------------------------------------> vault
4 <- pm_123 (token)
5 POST /orders/42/charge {payment_method: pm_123} --------> server sees only pm_123
6 confirm(pm_123) ------------> charge
Your servers never see the PAN: SAQ A (if all other eligibility criteria hold)سناریوی واقعی: استارتاپ فرم کارت خودش را ساخته و در اولین قرارداد enterprise با هزینهٔ PCI روبهرو میشود؛ ابزار پشتیبانی تمام request body را لاگ میکند؛ مهاجرت PSP نیازمند انتقال PAN میان vaultهاست که باید مستقیم بین PSPها انجام شود؛ تزریق اسکریپت شبیه Magecart در checkout، علت اضافه شدن معیار اسکریپتهاست؛ OWASP Top 10.
چه چیزی فراهمش میکند:
| روش اتصال (Integration) | دادهٔ کارت روی سرور شما | SAQ معمول | نکته |
|---|---|---|---|
| صفحهٔ PSP؛ Stripe Checkout، Adyen Hosted Checkout | خیر | SAQ A | Redirect؛ کمترین کار |
| فیلد iframe؛ Stripe Payment Element، Adyen Drop-in | خیر | SAQ A با معیار صلاحیت اسکریپت | صفحهٔ شما میزبان iframe است؛ از اسکریپتها محافظت کنید |
| JavaScript از فیلدهای فرم شما مستقیم به PSP میفرستد | ذخیره نمیشود، اما صفحهٔ شما فیلدها را کنترل میکند | SAQ A نیست؛ کارهای دادهٔ حساب "completely outsourced" نیستند؛ SAQ مناسب را از acquirer بپرسید | صفحه قابلدستکاری است |
| فرم کارت به سرور شما POST میکند | بله | SAQ D | پرهیز کنید |
| Network tokens از PSP | خیر | تابع integration | نرخ authorization و بهروزرسانی کارت بهتر؛ ادعای vendor، اینجا اندازهگیری نشده |
راهحل / روش استفاده: کارت فقط در iframe یا صفحهٔ PSP دریافت شود. فقط token به سرور بفرستید؛ checkout دارای Content Security Policy باشد. Request body مسیرهای پرداخت را لاگ نکنید. PSP customer id و payment method id را ذخیره کنید، نه PAN. API key و webhook secret در secret manager باشند؛ Cryptography in Practice.
تقلب و موتور ریسک: fraud score، velocity rules و device fingerprint مهم
به زبان ساده: موتور ریسک (Risk engine) پیش از برداشت به مبلغ، کارت، دستگاه، IP و سابقه نگاه میکند. امتیاز تقلب (Fraud score) و ruleها به یکی از چهار تصمیم میرسند: allow، درخواست 3-D Secure، بررسی انسانی یا block. زمان تصمیم باید داخل بودجهٔ checkout بماند.
بدفهمی رایج: «هر چیز پرریسک را block کن.» مسدود کردن مشتری واقعی درآمد را میگیرد و ticket پشتیبانی میسازد؛ هر review هم وقت انسان میخواهد. هدف کمهزینهترین عمل بهاندازهٔ کافی امن است؛ اغلب 3DS step-up. باور غلط دوم «مدل ML تصمیم میگیرد» است. واقعیتهای قطعی مثل یک کارت روی 20 دستگاه در 10 دقیقه اول با rule بررسی میشوند و هنگام timeout مدل هم باید تصمیمی داشت.
تعریف: Risk engine ویژگیها، شامل card fingerprint، کشور BIN در برابر IP، سن حساب، اثرانگشت دستگاه (Device fingerprint) از SDK پرداخت، ایمیل و سابقه، را ترکیب میکند. قواعد سرعت (Velocity rules) شمارندهٔ کارت، دستگاه، IP و ایمیل در sliding window هستند و جلوی card testing را میگیرند. امتیاز ML، allowlist، blocklist و چهار عمل هم کنار آنها قرار دارند. Stripe Radar میگوید ruleها "take four actions": request 3DS، allow، block و review. امتیاز "ranges from 0–99" و "By default, a score of 65 or above indicates elevated risk, while a score of 75 or above indicates high risk". ریسک elevated ممکن است وارد صف بررسی دستی (Manual review queue) شود: "placed it in your manual review queue". Adyen risk management از risk profile، custom rule، ML rule، post-authorization rule و backtesting استفاده میکند.
Checkout latency budget ~300 ms; model budget 50 ms
1 t=0 features: card fp_a, device dev_bot, IP 203.0.113.7, amount 1.00 USD
2 t=1 velocity: dev_bot has seen 7 distinct cards in 10 min -> rule card_testing: block
3 t=2 model call starts (50 ms budget)
4 t=52 model late -> score = -1, reason model_timeout:rules_only
5 t=52 decision: block, reasons [card_testing..., model_timeout:rules_only]
6 store decision + reasons with the payment (disputes, tuning, audits)سناریوی واقعی: bot با صدها برداشت یکدلاری کارت آزمایش میکند؛ تصاحب حساب با سفارش بزرگ به آدرس جدید؛ آدرس واسطهٔ ارسال مشترک میان کارتهای زیاد؛ مسافر واقعی که کشور IP و کارت او فرق دارد و بهتر است step-up شود نه block؛ صف review حراج سریعتر از ظرفیت تیم رشد میکند.
چه چیزی فراهمش میکند:
| محصول | امتیاز (Score) | قواعد (Rules) | اعمال (Actions) | بررسی (Review) |
|---|---|---|---|---|
| Stripe Radar | 0–99؛ پیشفرض 65+ elevated و 75+ high | Custom rule وابسته به plan و allow/block list | Allow، block، review، request 3DS | Manual review queue وابسته به plan |
| Adyen risk management | ارزیابی ریسک هر پرداخت با تنظیم risk profile | Custom، ML و post-authorization rule؛ backtest | "an action to block, allow, or review the transaction"؛ dynamic 3D Secure | Case management برای "to manually review certain transactions" |
موتور fraud این فصل | Scorer قابلتعویض با بودجهٔ سخت | Rule مرتب و velocity counter | allow، request_3ds، review، block | تصمیم همراه دلیل |
راهحل / روش استفاده: fraud.Engine برای device/card/IP velocity دارد؛ اولویت block > review > 3DS > allow، threshold شبیه Radar، step-up برای کارت پشتیبان 3DS و بودجهٔ مدل 50 ms با fallback فقط-rule. دلیل همهٔ تصمیمها ذخیره میشود. Rate Limiting روی endpoint پرداخت اولین velocity rule است.
رد پرداخت، retry، dunning و smart retries تکمیلی
به زبان ساده: رد تمدید اشتراک گاهی موقت است؛ امروز پول ندارد. گاهی هم با تکرار درست نمیشود؛ کارت دزدیده شده است. وصول مجدد (Dunning) یعنی retry زمانبندیشده برای اولی و درخواست کارت جدید برای دومی.
بدفهمی رایج: «هر تمدید ناموفق را هر ساعت retry کن.» تکرار رد قطعی بیفایده است و رابطه با issuer و شبکه را خراب میکند. تکرار زیاد رد موقت هم شبیه card testing است. Stripe برای hard declineهایش میگوید "can’t automatically retry a payment".
تعریف: رد موقت (Soft decline)، مثل insufficient_funds، try_again_later و processing_error، شاید بعداً موفق شود. رد قطعی (Hard decline) روش پرداخت تازه میخواهد. فهرست hard برای retry اشتراک Stripe این است: incorrect_number، lost_card، pickup_card، stolen_card، revocation_of_authorization، revocation_of_all_authorizations، authentication_required، highest_risk_level و transaction_not_allowed. تلاش مجدد هوشمند (Smart retries) زمان را با مدل انتخاب میکند؛ برای حساب تازه Stripe "enables Smart Retries by default and configures it for up to 8 retries within 2 weeks" و برنامهٔ سفارشی "up to three retries" دارد. Dunning همچنین ایمیل، صفحهٔ بهروزرسانی کارت و عمل نهایی لغو اشتراک یا unpaid کردن را در بر میگیرد.
Day Attempt Decline code Dunning decision (dunning.Default)
1 0 1 insufficient_funds soft -> retry in 1 day, e-mail "please check your card"
2 1 2 insufficient_funds soft -> retry in 2 days
3 3 3 insufficient_funds soft -> retry in 4 days
4 7 4 insufficient_funds soft -> retry in 6 days
5 13 5 insufficient_funds attempt cap reached (5 attempts, inside 14 days) -> exhausted, cancel
Day 0 alternative: stolen_card -> hard -> no retry, ask for a new payment methodسناریوی واقعی: تمدید ماهانهٔ SaaS روی کارت وابسته به روز حقوق؛ کارت منقضی که card updater شبکه یا network token تازهاش میکند؛ تمدید off-session با authentication_required که حضور دوبارهٔ مشتری لازم دارد.
چه چیزی فراهمش میکند:
| محصول | موتور retry | Hard decline | تماس با مشتری |
|---|---|---|---|
| Stripe Billing | Smart Retries با زمان AI یا schedule سفارشی | زمانبندی ادامه دارد ولی اجرا فقط با روش پرداخت جدید | ایمیل revenue recovery، invoice.payment_failed |
| Laravel Cashier | از Stripe Billing استفاده میکند | همان Stripe | IncompletePayment، hasIncompletePayment() |
بستهٔ dunning این فصل | برنامهٔ ثابت با سقف attempt و مدت | Classify برابر فهرست hard در Stripe | پرچم Notify |
راهحل / روش استفاده: decline code را دستهبندی کنید، هم تعداد attempt و هم مدت را محدود کنید، در اولین شکست و پایان برنامه یک ایمیل بفرستید و hard decline را دوباره داخل صف retry نگذارید.
مسیریابی و Failover میان چند PSP تکمیلی
به زبان ساده: بعضی شرکتها دو PSP دارند تا قطعی را تحمل کنند یا هر پرداخت را به provider با احتمال تأیید بیشتر بفرستند. تعویض مسیر (Failover) فقط وقتی امن است که ثابت شده باشد PSP اول کاری نکرده است.
بدفهمی رایج: «روی هر خطا failover کن.» بعد از timeout شاید PSP اول پول را گرفته باشد؛ PSP دوم دوباره میگیرد. Idempotency key کمکی نمیکند، چون این دو PSP کلید مشترک ندارند.
تعریف: مسیریاب (Router) بر اساس ارز، BIN کارت، هزینه و سلامت، PSP را انتخاب میکند. هر تلاش (Attempt) کلید provider خودش را دارد و sent، done یا unknown است. فقط attempt از نوع done بدون اثر اجازهٔ تلاش تازه در جای دیگر میدهد. Tokenها مختص PSP هستند، مگر network token یا vault شخص ثالث داشته باشید؛ این هزینهٔ اصلی multi-PSP است.
Router Stripe Adyen
1 attempt 1 key pi_3:attempt:1 -> connection refused (nothing processed)
2 attempt 1 = done (no effect)
3 attempt 2 key pi_3:attempt:2 -----------------------> approved
4 ledger: D psp_receivable:adyen:GBP / C sales:GBP (booked against the PSP that charged)سناریوی واقعی: قطعی منطقهای PSP هنگام حراج؛ نرخ تأیید پایین acquirer برای یک کشور؛ مذاکرهٔ کارمزد با جابهجایی حجم پرداخت.
چه چیزی فراهمش میکند:
| دغدغه | یک PSP | دو PSP |
|---|---|---|
| قطعی (Outage) | انتظار یا کاهش خدمت | Failover فقط برای پردازشنشدن اثباتشده |
| ذخیرهٔ کارت (Card storage) | Vault خود PSP | Network token، vault شخص ثالث یا vault جدا برای هر PSP |
| تطبیق (Reconciliation) | یک فایل | دو فایل، دو زمانبندی payout و حساب دریافتنی جدا برای هر PSP |
| کد | یک adapter | Interface به نام PSP، ترتیب routing و attempt table |
راهحل / روش استفاده: Service.Confirm و routeFrom در payment/service.go attempt نامعلوم را به PSP خودش مقید نگه میدارند. حساب دریافتنی هم به تفکیک PSP است: psp_receivable:adyen:GBP.
کتابخانهها: Laravel Cashier، Stripe PHP SDK و stripe-go تکمیلی
به زبان ساده: برای فراخوانی API و بررسی امضای webhook از SDK رسمی PSP استفاده کنید. Laravel Cashier پوششی روی Stripe PHP SDK برای مشتری، روش پرداخت، برداشت یکباره و اشتراک است.
بدفهمی رایج: «Cashier همهچیز، از ledger تا idempotency، را مدیریت میکند.» Cashier از webhook برای همگام کردن شیءهای Stripe در جدولهایش استفاده میکند و charge()، pay() و refund() میدهد؛ اما journal entry دوطرفه ثبت نمیکند، settlement file را تطبیق نمیدهد و charge() کلید idempotency نمیگیرد. برای آن از client زیرین استفاده کنید.
تعریف و واقعیتها از مستندات خواندهشده:
| کتابخانه | واقعیتها | استفاده در این صفحه |
|---|---|---|
| Laravel Cashier (Stripe) | composer.json، stripe/stripe-php از ^17.4 تا ^21.0 و illuminate/* با ^12.0|^13.0 میخواهد؛ "Cashier uses the Stripe API version pinned by your installed version of the stripe/stripe-php SDK"؛ نسخهٔ 21.x → API 2026-08-26.dahlia؛ مبلغ "in the lowest denominator"؛ webhook controller در /stripe/webhook، ساخت endpoint با php artisan cashier:webhook؛ IncompletePayment و route cashier.payment برای SCA | CheckoutController |
Stripe PHP SDK (stripe/stripe-php) | \Stripe\Webhook::constructEvent($payload, $sigHeader, $secret, $tolerance = self::DEFAULT_TOLERANCE) با DEFAULT_TOLERANCE = 300؛ گزینهٔ idempotency_key در Util/RequestOptions.php هدر Idempotency-Key میشود؛ README: "even if you locally timeout, the request on Stripe's side can still complete" | Cashier::stripe()->paymentIntents->create($params, ['idempotency_key' => ...]) |
stripe-go (github.com/stripe/stripe-go/v87) | در go.mod مقدار go 1.24 و در README پشتیبانی "Go 1.24+"؛ stripe.NewClient(apiKey) و sc.V1PaymentIntents...؛ retry خودکار "up to two" با کلیدهایی که "always added"؛ MaxNetworkRetries قابلتنظیم؛ webhook.ConstructEvent و DefaultTolerance برابر 300 s | در زاویهٔ Go معرفی شده؛ ماژول این فصل فقط stdlib است تا تست offline باشد |
| Adyen | بررسی HMAC طبق مستندات؛ کتابخانههای سرور Adyen شامل "a validator to verify the HMAC signature" هستند | جدولهای نگاشت |
راهحل / روش استفاده: در production از webhook.ConstructEvent در Go یا \Stripe\Webhook::constructEvent در PHP بهجای verifier دستی استفاده کنید. Retry خودکار SDK و کلید مشتقشدهٔ خودتان هر دو لازماند. نسخهٔ major را pin کنید، چون نسخهٔ Stripe API را تعیین میکند.
سازوکار
جریان دقیق درخواست
Step Where What Failure handling
1 1 checkout API require Idempotency-Key header (400 if missing) client retries with the same key
2 2 payment service idempotency_keys INSERT (merchant, key, fingerprint) replay 2xx / 409 in flight / 422 mismatch
3 3 payment service payments INSERT, UNIQUE (merchant_id, order_id) second key for same order -> conflict
4 4 risk engine decide within 50 ms (rules-only fallback) block -> 402 to client, no PSP call
5 5 payment service payment_attempts INSERT (psp, psp_idem_key, state=sent) crash here: attempt resumed later
6 6 PSP call timeout << checkout budget, provider key unknown -> lookup / same key
7 7 one transaction payments status + version, ledger entries, outbox row deferred D = C check at COMMIT
8 8 response 201 with intent status; key -> completed with body replayed for 24 h+
9 9 webhook verify, inbox, 200, queued job dead-letter after the last try
10 10 reconciliation daily file vs ledger vs bank tickets, fixes as new entriesکد وضعیت و خطاهایی که میبینید
| منبع | کد / پیام | معنی | اقدام |
|---|---|---|---|
| API شما؛ پیشنویس IETF | 400 missing Idempotency-Key | کلید اجباری وجود ندارد | کلاینت کلید اضافه کند |
| API شما؛ پیشنویس IETF | 409 Conflict | همان کلید هنوز در حال پردازش است | انتظار و retry با همان کلید |
| API شما؛ پیشنویس IETF | 422 Unprocessable Content | کلید با payload متفاوت تکرار شده | باگ کلاینت؛ کلید تازه فقط برای intent تازه |
| Stripe | 500؛ در API v1 با کلید cache میشود | "indeterminate" یا نامعلوم | پیش از هر کلید جدید نتیجه را روشن کنید |
| Stripe | هدر Stripe-Should-Retry | راهنمای صریح retry | پیروی کنید |
| Stripe decline | card_declined با decline_code مثل insufficient_funds، do_not_honor، generic_decline | Issuer رد کرده | کارت دیگر بخواهید یا در soft decline بعداً retry کنید |
| Stripe hard decline | stolen_card، lost_card، pickup_card، incorrect_number و غیره | موفق نخواهد شد | روش پرداخت تازه؛ بدون retry خودکار |
| Stripe | authentication_required | Issuer، SCA میخواهد | مشتری را برای 3DS به on-session بیاورید |
| Adyen | 503 از لایهٔ idempotency | "Idempotent processing relies on this data store being available" | طبق Adyen، fallback به پردازش non-idempotent فقط با تصمیم آگاهانه |
| stripe-go | webhook.ErrNoValidSignature، webhook.ErrTooOld | امضای غلط / بیرون tolerance | 400؛ اگر زیاد شد alert |
| این فصل | webhook: timestamp outside tolerance، webhook: no v1 signature matches | همان خطاها در verifier دستی | 400 |
| این فصل | ledger: debits != credits، ledger is append-only (ledger_entries) | ثبت نامتوازن / تلاش UPDATE | باگ؛ کد را اصلاح و reversal ثبت کنید |
| Laravel | DomainException: invalid transition succeeded -> processing | event کهنه در PaymentStatus::to() | Ack و نادیده گرفتن |
| این فصل | payment: another operation on this payment is in progress (ErrInFlight) | Confirm/Capture/Refund دوم هنگام اجرای عملیات دیگر | 409؛ بعداً با همان کلید retry کنید |
| این فصل | payment: PSP result not booked, retry or reconcile (ErrUnbooked) | PSP پول را جابهجا کرده ولی ثبت شکست خورده؛ intent تغییر نکرده | علت را رفع کنید؛ Confirm، Capture یا Refund بعدی با همان کلید نتیجهٔ ذخیرهشده را بدون تماس دوباره با PSP ثبت میکند |
| این فصل | payment: outcome unknown past the resend window, reconcile (ErrNeedsReconciliation) | Attempt، capture یا refund پس از ResendWindow هنوز نامعلوم است | ارسال نکنید؛ از PSP یا settlement file نتیجه را بیابید و سپس تعیین تکلیف کنید |
| این فصل | payment: amount mismatch, needs reconciliation (ErrMismatch) | Webhook و capture، یا دو capture، در مبلغ اختلاف دارند | توقف؛ تصمیم با انسان یا reconciliation |
| این فصل | payment: this order already has a payment (ErrDuplicateOrder) | کلید کلاینت دوم برای یک سفارش | 409؛ پرداخت موجود را استفاده کنید |
تنظیمها
| تنظیم | مقدار این فصل | محل | دلیل |
|---|---|---|---|
| مهلت تماس (PSP call timeout) | 200 ms در تست؛ چند ثانیه در production | NewService(callTimeout) | داخل بودجهٔ checkout و با فرصت lookup |
| نگهداری کلید (Idempotency key retention) | 24 h | idem.New(24*time.Hour)، پیشفرض expires_at | حداقل پنجرهٔ Stripe؛ Adyen برابر 7 تا 14 روز |
| تحمل زمان (Webhook tolerance) | 300 s | Verifier.Tolerance، TOLERANCE_SECONDS | پیشفرض کتابخانهٔ Stripe؛ همیشه > 0 |
| رازهای امضا (Webhook secrets) | فعلی + قبلی | Secrets، services.stripe.webhook_secrets | Secret roll تا 7 روز |
| تلاشهای صف (Queue retries) | #[Tries(8)]، #[Backoff([10, 30, 60, 300])] | ProcessStripeEvent | مقدار آخر برای attemptهای بعدی تکرار میشود |
| بودجهٔ مدل تقلب (Fraud model budget) | 50 ms | Engine.ModelBudget | اگر دیر رسید، تصمیم با rule |
| آستانههای تقلب (Fraud thresholds) | review 65، block 75 | Engine.ReviewAt، BlockAt | پیشفرض مستند Radar |
| پنجرهٔ سرعت (Velocity window) | 10 min | NewVelocity(10 * time.Minute) | Card testing موجی رخ میدهد |
| وصول مجدد (Dunning) | retry پس از 1، 2، 4، 6 روز؛ روزهای 1، 3، 7، 13؛ 5 attempt؛ 14 روز | dunning.Default() | محدودیت هم تعداد و هم مدت |
| تلاش undo در Saga | 3 | Orchestrator.UndoTries | سپس dead-letter |
| اعتبار رزرو (Authorization validity) | مختص هر پرداخت: payments.capture_before از PSP؛ در Stripe برای Visa MIT برابر 4 روز و 18 ساعت، بیشتر online CITها 7 روز | ProcessStripeEvent هنگام requires_capture ذخیره میکند | Capture یا void را با همین timestamp زمانبندی کنید، نه پنجرهٔ ثابت |
تعداد DB::transaction | 3 | LedgerService::post | اجرای مجدد closure هنگام deadlock |
SQL مهم
Schema کامل در Laravel وارد شده است. این دستورها مراحل جریان را در PostgreSQL 16+ پیاده میکنند:
-- 2. claim the client's key (one row wins; the loser reads it and replays or returns 409/422)
INSERT INTO idempotency_keys (merchant_id, key, fingerprint, status)
VALUES ($1, $2, $3, 'in_progress')
ON CONFLICT (merchant_id, key) DO NOTHING
RETURNING key;
-- 5. one attempt row per PSP call; the provider key is unique and reused on every retry
INSERT INTO payment_attempts (payment_id, psp, psp_idem_key, state)
VALUES ($1, 'stripe', $1 || ':attempt:' || $2, 'sent');
-- 7. state change with optimistic locking, ledger and outbox in ONE transaction
BEGIN;
UPDATE payments
SET status = 'succeeded', amount_received = $2, version = version + 1, updated_at = now()
WHERE id = $1 AND version = $3 AND status NOT IN ('succeeded', 'canceled'); -- forward progress only
-- 0 rows: someone else moved it first -> ROLLBACK, reload and re-evaluate
INSERT INTO journal_transactions (id, description) VALUES ('capture:' || $1, 'capture ' || $1)
ON CONFLICT (id) DO NOTHING
RETURNING id; -- 0 rows: already posted -> ROLLBACK, nothing below runs
SELECT id FROM ledger_accounts
WHERE id IN ('psp_receivable:stripe:USD', 'sales:USD') ORDER BY id FOR UPDATE; -- fixed lock order
INSERT INTO ledger_entries (transaction_id, account_id, direction, amount, currency) VALUES
('capture:' || $1, 'psp_receivable:stripe:USD', 'D', $2, 'USD'),
('capture:' || $1, 'sales:USD', 'C', $2, 'USD');
-- the cached normal-side balances move with the entries (asset debit +, revenue credit +);
-- the "cached = derived" query below returns no rows only because of this statement
UPDATE ledger_accounts SET balance = balance + $2, version = version + 1
WHERE id IN ('psp_receivable:stripe:USD', 'sales:USD');
INSERT INTO outbox (event_id, topic, aggregate_id, payload)
VALUES ('evt_' || $1 || '_v' || ($3 + 1), 'payments.payment_succeeded', $1, jsonb_build_object('id', $1));
COMMIT; -- deferred trigger: debits = credits per currency
-- capture/void scheduler: due holds, by the PSP's own expiry (partial index payments_capture_due)
SELECT id, capture_before FROM payments
WHERE status = 'requires_capture' AND capture_before < now() + interval '24 hours'
ORDER BY capture_before;
-- 9. webhook idempotency table: store first, process later
INSERT INTO webhooks_inbox (psp, event_id, event_type, object_id, payload)
VALUES ('stripe', $1, $2, $3, $4)
ON CONFLICT (psp, event_id) DO NOTHING;
-- open attempts for the sweep (partial index payment_attempts_open):
-- unbooked -> book psp_result, never resend; sent/unknown inside the window -> resend the same key;
-- sent/unknown past the window (23 h, below Stripe's 24 h key retention) -> reconcile, never resend
SELECT payment_id, psp, psp_idem_key, state, psp_result,
first_sent_at < now() - interval '23 hours' AS past_resend_window
FROM payment_attempts
WHERE state IN ('sent', 'unknown', 'unbooked') AND first_sent_at < now() - interval '5 minutes';
-- a balance is a sum, and must equal the cached one
SELECT a.id, a.balance AS cached,
sum(CASE e.direction WHEN 'D' THEN e.amount ELSE -e.amount END)
* CASE WHEN a.kind IN ('asset', 'expense') THEN 1 ELSE -1 END AS derived
FROM ledger_accounts a JOIN ledger_entries e ON e.account_id = a.id
GROUP BY a.id, a.balance, a.kind
HAVING a.balance <> sum(CASE e.direction WHEN 'D' THEN e.amount ELSE -e.amount END)
* CASE WHEN a.kind IN ('asset', 'expense') THEN 1 ELSE -1 END; -- must return no rows
-- trial balance: zero per currency, always
SELECT currency, sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) FROM ledger_entries GROUP BY currency;
-- reconciliation: charges settled by the PSP that we never booked, or booked differently
-- (provider identity = psp + intent id; amount, currency and status compared)
SELECT s.psp_reference, s.gross, s.currency, p.id, p.amount_received, p.currency AS our_currency, p.status
FROM settlement_lines s
LEFT JOIN payments p ON p.stripe_payment_intent_id = s.psp_reference AND p.psp = s.psp
WHERE s.psp = $1 AND s.batch_id = $2 AND s.line_type = 'charge'
AND (p.id IS NULL OR p.amount_received <> s.gross OR p.currency <> s.currency OR p.status <> 'succeeded');
-- refunds the PSP settled that we did not book, matched through the refund's payment
SELECT s.psp_reference, s.gross FROM settlement_lines s
LEFT JOIN refunds r ON r.stripe_refund_id = s.psp_reference
LEFT JOIN payments p ON p.id = r.payment_id AND p.psp = s.psp
WHERE s.psp = $1 AND s.batch_id = $2 AND s.line_type = 'refund'
AND (p.id IS NULL OR r.state <> 'succeeded' OR r.amount <> abs(s.gross) OR r.currency <> s.currency);این دستورها با فایل schema تطبیق داده و با خواندن بررسی شدهاند. sql/schema.sql و migration مربوط به Laravel عمداً همگاماند: جدولها، ستونها و وضعیتهای بازیابی یکساناند؛ psp_result، first_sent_at، refused/unbooked و needs_reconciliation. Migration همچنین حسابهای ledger موردنیاز ثبتها را seed میکند؛ پس queryهای اینجا روی هر دو schema کار میکنند. روی ماشین ساخت فصل PostgreSQL نصب نبود؛ بنابراین دستورها اجرا نشدهاند.
Go
ماژول Go با نام academy/payment-processing-architecture و go 1.24 فقط از standard library استفاده میکند. هر ایده یک package دارد و همهٔ تستها offline و با -race اجرا میشوند. stripe-go v87 هم go 1.24 اعلام میکند و میتواند fake مربوط به PSP را با adapter واقعی جایگزین کند؛ اینجا وارد نشده تا تست به شبکه و API key نیاز نداشته باشد.
قبل
پول با float، retry کور که بعد از timeout دوباره برداشت میکند، balance قابلتغییر و ایمیلی که crash گم میکند:
// Package main shows the payment handler most teams write first.
// It compiles and "works" in a demo; every comment marks a production bug.
package main
import (
"errors"
"fmt"
"sync"
)
type gateway struct{ charges int }
// Charge pretends to call the PSP. The second call fails after the money moved,
// which is exactly what a timeout looks like from the caller's side.
func (g *gateway) Charge(amount float64) error {
g.charges++
if g.charges == 1 {
return errors.New("i/o timeout") // the charge happened, the answer was lost
}
return nil
}
type shop struct {
mu sync.Mutex
balance float64 // float money: 0.1 + 0.2 != 0.3
gw *gateway
}
// Pay has no idempotency key, no state machine, no ledger, no outbox.
func (s *shop) Pay(amount float64) error {
for attempt := 0; attempt < 3; attempt++ { // blind retry: a second real charge
if err := s.gw.Charge(amount); err != nil {
continue
}
s.mu.Lock()
s.balance += amount // a mutable balance: no history, no audit, no reconciliation
s.mu.Unlock()
// "send the receipt e-mail" here: lost if the process dies right now
return nil
}
return errors.New("payment failed")
}
func main() {
s := &shop{gw: &gateway{}}
_ = s.Pay(0.1)
_ = s.Pay(0.2)
fmt.Printf("charges sent to PSP: %d (customer paid twice for the first order)\n", s.gw.charges)
fmt.Printf("balance: %.17f (expected 0.3)\n", s.balance)
}خروجی اجرا charges sent to PSP: 3 (customer paid twice for the first order) و balance: 0.30000000000000004 (expected 0.3) است.
بعد
پول (Money) با minor units صحیح، توان ISO 4217، parse سختگیرانه، allocation و تبدیل half-even:
// Package money stores amounts as integers in the currency's minor unit.
// 10.99 USD is Money{Amount: 1099, Currency: "USD"}; 500 JPY is {500, "JPY"}.
package money
import (
"errors"
"fmt"
"math"
"math/big"
"strings"
)
// exponents is the number of minor-unit digits (ISO 4217). Extend from your PSP's table.
var exponents = map[string]int{
"USD": 2, "EUR": 2, "GBP": 2, "CAD": 2, "AUD": 2,
"JPY": 0, "KRW": 0, "VND": 0,
"BHD": 3, "KWD": 3, "OMR": 3, "JOD": 3,
}
var (
ErrUnknownCurrency = errors.New("money: unknown currency")
ErrCurrencyMismatch = errors.New("money: currency mismatch")
ErrOverflow = errors.New("money: int64 overflow")
ErrPrecision = errors.New("money: more decimals than the currency allows")
ErrInvalid = errors.New("money: invalid amount")
)
// Money is an immutable value: never a float.
type Money struct {
Amount int64
Currency string
}
// Exponent returns the minor-unit digits of a currency.
func Exponent(currency string) (int, error) {
e, ok := exponents[currency]
if !ok {
return 0, fmt.Errorf("%w: %q", ErrUnknownCurrency, currency)
}
return e, nil
}
// New validates the currency.
func New(minor int64, currency string) (Money, error) {
if _, err := Exponent(currency); err != nil {
return Money{}, err
}
return Money{Amount: minor, Currency: currency}, nil
}
// Parse turns a decimal string ("10.99") into minor units without floats.
func Parse(s, currency string) (Money, error) {
exp, err := Exponent(currency)
if err != nil {
return Money{}, err
}
neg := strings.HasPrefix(s, "-")
s = strings.TrimPrefix(s, "-")
whole, frac, _ := strings.Cut(s, ".")
if whole == "" || len(frac) > exp {
if len(frac) > exp {
return Money{}, ErrPrecision
}
return Money{}, ErrInvalid
}
if !digits(whole) || !digits(frac) {
return Money{}, ErrInvalid
}
frac += strings.Repeat("0", exp-len(frac))
n, ok := new(big.Int).SetString(whole+frac, 10)
if !ok || !n.IsInt64() {
return Money{}, ErrInvalid
}
v := n.Int64()
if neg {
v = -v
}
return Money{Amount: v, Currency: currency}, nil
}
func digits(s string) bool {
for _, c := range s {
if c < '0' || c > '9' {
return false
}
}
return true
}
// String renders "10.99 USD".
func (m Money) String() string {
exp, _ := Exponent(m.Currency)
sign, a := "", m.Amount
if a < 0 {
sign, a = "-", -a
}
if exp == 0 {
return fmt.Sprintf("%s%d %s", sign, a, m.Currency)
}
p := int64(math.Pow10(exp))
return fmt.Sprintf("%s%d.%0*d %s", sign, a/p, exp, a%p, m.Currency)
}
// Add returns m+o; both must share a currency.
func (m Money) Add(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, ErrCurrencyMismatch
}
s := m.Amount + o.Amount
if (o.Amount > 0 && s < m.Amount) || (o.Amount < 0 && s > m.Amount) {
return Money{}, ErrOverflow
}
return Money{Amount: s, Currency: m.Currency}, nil
}
// Sub returns m-o with checked subtraction (not negate-then-add, which fails for
// o = MinInt64 even when the result fits: -1 - MinInt64 = MaxInt64).
func (m Money) Sub(o Money) (Money, error) {
if m.Currency != o.Currency {
return Money{}, ErrCurrencyMismatch
}
d := m.Amount - o.Amount
if (o.Amount > 0 && d > m.Amount) || (o.Amount < 0 && d < m.Amount) {
return Money{}, ErrOverflow
}
return Money{Amount: d, Currency: m.Currency}, nil
}
// Allocate splits m by ratios so the parts always sum to m (largest remainder:
// leftover minor units go to the first parts). Splitting 100 three ways gives 34, 33, 33.
func (m Money) Allocate(ratios ...int64) ([]Money, error) {
var total int64
for _, r := range ratios {
if r < 0 {
return nil, ErrInvalid
}
total += r
}
if total == 0 {
return nil, ErrInvalid
}
parts := make([]Money, len(ratios))
var used int64
for i, r := range ratios {
share := new(big.Int).Mul(big.NewInt(m.Amount), big.NewInt(r))
share.Quo(share, big.NewInt(total))
parts[i] = Money{Amount: share.Int64(), Currency: m.Currency}
used += parts[i].Amount
}
step := int64(1)
if m.Amount < 0 {
step = -1
}
for i := 0; used != m.Amount; i = (i + 1) % len(parts) {
parts[i].Amount += step
used += step
}
return parts, nil
}
// Convert applies an FX rate given as an exact decimal string ("0.9235" EUR per USD)
// and rounds half-to-even (banker's rounding) into the target minor unit.
func Convert(m Money, to, rate string) (Money, error) {
fromExp, err := Exponent(m.Currency)
if err != nil {
return Money{}, err
}
toExp, err := Exponent(to)
if err != nil {
return Money{}, err
}
r, ok := new(big.Rat).SetString(rate)
if !ok || r.Sign() <= 0 {
return Money{}, ErrInvalid
}
v := new(big.Rat).SetInt64(m.Amount)
v.Mul(v, r)
scale := new(big.Rat).SetFrac(
new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(toExp)), nil),
new(big.Int).Exp(big.NewInt(10), big.NewInt(int64(fromExp)), nil))
v.Mul(v, scale)
out := roundHalfEven(v)
if !out.IsInt64() {
return Money{}, ErrOverflow
}
return Money{Amount: out.Int64(), Currency: to}, nil
}
func roundHalfEven(v *big.Rat) *big.Int {
num, den := new(big.Int).Set(v.Num()), v.Denom()
neg := num.Sign() < 0
num.Abs(num)
q, r := new(big.Int).QuoRem(num, den, new(big.Int))
twice := new(big.Int).Mul(r, big.NewInt(2))
switch twice.Cmp(den) {
case 1:
q.Add(q, big.NewInt(1))
case 0:
if q.Bit(0) == 1 {
q.Add(q, big.NewInt(1))
}
}
if neg {
q.Neg(q)
}
return q
}package money
import (
"errors"
"math"
"testing"
)
func TestParseAndString(t *testing.T) {
cases := []struct {
in, cur, out string
minor int64
}{
{"10.99", "USD", "10.99 USD", 1099},
{"10.9", "USD", "10.90 USD", 1090},
{"500", "JPY", "500 JPY", 500},
{"1.234", "BHD", "1.234 BHD", 1234},
{"-0.05", "EUR", "-0.05 EUR", -5},
}
for _, c := range cases {
m, err := Parse(c.in, c.cur)
if err != nil || m.Amount != c.minor || m.String() != c.out {
t.Fatalf("Parse(%q,%s) = %v %v", c.in, c.cur, m, err)
}
}
if _, err := Parse("10.999", "USD"); !errors.Is(err, ErrPrecision) {
t.Fatalf("want ErrPrecision, got %v", err)
}
for _, bad := range []string{"--5", "1e3", "+5", "1,00", " 5"} {
if _, err := Parse(bad, "USD"); !errors.Is(err, ErrInvalid) {
t.Fatalf("Parse(%q) = %v, want ErrInvalid", bad, err)
}
}
if _, err := Parse("1.5", "JPY"); !errors.Is(err, ErrPrecision) {
t.Fatalf("JPY has no minor unit, got %v", err)
}
}
func TestFloatTrapIsGone(t *testing.T) {
a, _ := Parse("0.10", "USD")
b, _ := Parse("0.20", "USD")
s, _ := a.Add(b)
if s.Amount != 30 {
t.Fatalf("0.10 + 0.20 = %v", s)
}
}
func TestCurrencyMismatch(t *testing.T) {
if _, err := (Money{100, "USD"}).Add(Money{100, "EUR"}); !errors.Is(err, ErrCurrencyMismatch) {
t.Fatalf("got %v", err)
}
}
func TestAllocateNeverLosesACent(t *testing.T) {
m := Money{100, "USD"}
parts, err := m.Allocate(1, 1, 1)
if err != nil || parts[0].Amount != 34 || parts[1].Amount != 33 || parts[2].Amount != 33 {
t.Fatalf("got %v %v", parts, err)
}
for _, total := range []int64{1, 7, 999, 1_000_001, -101} {
parts, _ := Money{total, "USD"}.Allocate(70, 20, 10)
var sum int64
for _, p := range parts {
sum += p.Amount
}
if sum != total {
t.Fatalf("allocate %d: parts sum %d", total, sum)
}
}
}
func TestConvertHalfEven(t *testing.T) {
cases := []struct {
amount int64
from, to string
rate string
want int64
}{
{1000, "USD", "EUR", "0.9235", 924}, // 923.5 -> 924 (4 is even)
{1001, "USD", "EUR", "0.5", 500}, // 500.5 -> 500 (0 is even)
{1003, "USD", "EUR", "0.5", 502}, // 501.5 -> 502
{1000, "USD", "JPY", "151.37", 1514}, // 10.00 USD -> 1513.7 JPY -> 1514
{150000, "JPY", "USD", "0.0066", 99000}, // 990.00 USD
{1000, "USD", "BHD", "0.376", 3760},
}
for _, c := range cases {
got, err := Convert(Money{c.amount, c.from}, c.to, c.rate)
if err != nil || got.Amount != c.want {
t.Fatalf("Convert(%d %s->%s @%s) = %v %v, want %d", c.amount, c.from, c.to, c.rate, got, err, c.want)
}
}
}
// Finding 12: negating MinInt64 overflows; Sub must report it.
func TestSubMinInt64Overflows(t *testing.T) {
if _, err := (Money{0, "USD"}).Sub(Money{math.MinInt64, "USD"}); !errors.Is(err, ErrOverflow) {
t.Fatalf("got %v, want ErrOverflow", err)
}
}
// N14: subtraction is checked as subtraction, not as negate-then-add.
func TestSubMinInt64RepresentableResults(t *testing.T) {
if got, err := (Money{-1, "USD"}).Sub(Money{math.MinInt64, "USD"}); err != nil || got.Amount != math.MaxInt64 {
t.Fatalf("-1 - MinInt64 = %v %v, want MaxInt64", got.Amount, err)
}
if got, err := (Money{math.MinInt64, "USD"}).Sub(Money{math.MinInt64, "USD"}); err != nil || got.Amount != 0 {
t.Fatalf("MinInt64 - MinInt64 = %v %v, want 0", got.Amount, err)
}
if _, err := (Money{math.MaxInt64, "USD"}).Sub(Money{-1, "USD"}); !errors.Is(err, ErrOverflow) {
t.Fatalf("MaxInt64 - (-1): %v, want ErrOverflow", err)
}
}ماشین حالت قصد پرداخت (Payment intent state machine) با نام وضعیتهای Stripe و محدودیت capture و refund:
// Package intent is a payment-intent state machine with Stripe's status names
// (docs.stripe.com/payments/paymentintents/lifecycle). Every change goes through
// one transition table, so an illegal or stale event is an error, not a silent overwrite.
package intent
import (
"errors"
"fmt"
"academy/payment-processing-architecture/money"
)
// Status values copied from the Stripe PaymentIntent lifecycle.
type Status string
const (
RequiresPaymentMethod Status = "requires_payment_method"
RequiresConfirmation Status = "requires_confirmation"
RequiresAction Status = "requires_action"
Processing Status = "processing"
RequiresCapture Status = "requires_capture"
Succeeded Status = "succeeded"
Canceled Status = "canceled"
)
// Event is what happened: a client call or a PSP answer (sync or webhook).
type Event string
const (
AttachMethod Event = "attach_method"
PSPActionReq Event = "psp_requires_action" // 3-D Secure challenge
PSPProcessing Event = "psp_processing" // async rails: SEPA, ACH
PSPAuthorized Event = "psp_authorized" // manual capture: hold placed
PSPSucceeded Event = "psp_succeeded"
PSPDeclined Event = "psp_declined" // back to requires_payment_method, can retry
Cancel Event = "cancel"
AuthExpired Event = "auth_expired" // hold not captured in time
CaptureRequest Event = "capture"
)
var transitions = map[Status]map[Event]Status{
RequiresPaymentMethod: {AttachMethod: RequiresConfirmation, Cancel: Canceled},
RequiresConfirmation: {
PSPActionReq: RequiresAction, PSPProcessing: Processing, PSPAuthorized: RequiresCapture,
PSPSucceeded: Succeeded, PSPDeclined: RequiresPaymentMethod, Cancel: Canceled,
AttachMethod: RequiresConfirmation,
},
RequiresAction: {
PSPProcessing: Processing, PSPAuthorized: RequiresCapture, PSPSucceeded: Succeeded,
PSPDeclined: RequiresPaymentMethod, Cancel: Canceled,
},
Processing: {PSPSucceeded: Succeeded, PSPDeclined: RequiresPaymentMethod},
// PSPSucceeded: the capture happened at the PSP (dashboard, another worker) and a
// verified webhook reports it; the local Capture() path uses CaptureRequest.
RequiresCapture: {CaptureRequest: Succeeded, PSPSucceeded: Succeeded, Cancel: Canceled, AuthExpired: Canceled},
Succeeded: {},
Canceled: {},
}
var (
ErrInvalidTransition = errors.New("intent: invalid transition")
ErrAmount = errors.New("intent: invalid amount")
)
// Intent is one attempt to collect one amount for one order.
type Intent struct {
ID string
Amount int64 // minor units
Currency string
Status Status
AmountCapturable int64
AmountReceived int64
AmountRefunded int64
Version int // optimistic-lock counter, bumped on every change
History []Status
}
// New starts in requires_payment_method.
func New(id string, amount int64, currency string) (*Intent, error) {
if amount <= 0 {
return nil, ErrAmount
}
return &Intent{ID: id, Amount: amount, Currency: currency, Status: RequiresPaymentMethod,
History: []Status{RequiresPaymentMethod}}, nil
}
// Can reports whether ev is legal now.
func (p *Intent) Can(ev Event) bool {
_, ok := transitions[p.Status][ev]
return ok
}
// Apply moves the intent or returns ErrInvalidTransition. Capture uses Capture().
func (p *Intent) Apply(ev Event) error {
if ev == CaptureRequest {
return fmt.Errorf("%w: use Capture(amount)", ErrInvalidTransition)
}
next, ok := transitions[p.Status][ev]
if !ok {
return fmt.Errorf("%w: %s --%s-->", ErrInvalidTransition, p.Status, ev)
}
switch {
case next == RequiresCapture:
p.AmountCapturable = p.Amount
case next == Succeeded && p.Status == RequiresCapture:
// the PSP may have captured less than the hold: only Succeed(amount) knows how much
return fmt.Errorf("%w: use Succeed(amount) from %s", ErrInvalidTransition, p.Status)
case next == Succeeded:
p.AmountReceived = p.Amount
case next == Canceled:
p.AmountCapturable = 0 // the hold is released
}
p.set(next)
return nil
}
// Succeed records a PSP-reported success with the amount the PSP says it received.
// From requires_capture this is the captured amount (partial capture allowed, <= hold);
// from any other state it must be the full amount. Anything else is refused.
func (p *Intent) Succeed(received int64) error {
next, ok := transitions[p.Status][PSPSucceeded]
if !ok {
return fmt.Errorf("%w: %s --%s-->", ErrInvalidTransition, p.Status, PSPSucceeded)
}
if p.Status == RequiresCapture {
if received <= 0 || received > p.AmountCapturable {
return ErrAmount
}
} else if received != p.Amount {
return ErrAmount
}
p.AmountReceived, p.AmountCapturable = received, 0
p.set(next)
return nil
}
// Clone returns an independent copy (the History slice is copied too), so a caller can
// apply a change to the copy and keep it only if the ledger posting succeeds.
func (p *Intent) Clone() *Intent {
c := *p
c.History = append([]Status(nil), p.History...)
return &c
}
// Capture takes amount <= the authorized hold. A partial capture releases the rest:
// for most card payments only one capture is allowed (Stripe "place a hold" docs).
func (p *Intent) Capture(amount int64) error {
if p.Status != RequiresCapture {
return fmt.Errorf("%w: capture in %s", ErrInvalidTransition, p.Status)
}
if amount <= 0 || amount > p.AmountCapturable {
return ErrAmount
}
p.AmountReceived, p.AmountCapturable = amount, 0
p.set(Succeeded)
return nil
}
// Refund is a new money movement on a succeeded intent; the status stays succeeded.
// Refunds are tracked separately and may never exceed what was received.
func (p *Intent) Refund(amount int64) error {
if p.Status != Succeeded {
return fmt.Errorf("%w: refund in %s", ErrInvalidTransition, p.Status)
}
total, err := money.Money{Amount: p.AmountRefunded, Currency: p.Currency}.Add(money.Money{Amount: amount, Currency: p.Currency})
if amount <= 0 || err != nil || total.Amount > p.AmountReceived { // checked: no wrap-around
return ErrAmount
}
p.AmountRefunded = total.Amount
p.Version++
return nil
}
func (p *Intent) set(s Status) {
p.Status = s
p.Version++
p.History = append(p.History, s)
}
// Terminal reports succeeded or canceled.
func (p *Intent) Terminal() bool { return p.Status == Succeeded || p.Status == Canceled }package intent
import (
"errors"
"math"
"testing"
)
func mustNew(t *testing.T) *Intent {
t.Helper()
p, err := New("pi_1", 1099, "USD")
if err != nil {
t.Fatal(err)
}
return p
}
func TestHappyPathWith3DS(t *testing.T) {
p := mustNew(t)
for _, ev := range []Event{AttachMethod, PSPActionReq, PSPSucceeded} {
if err := p.Apply(ev); err != nil {
t.Fatal(err)
}
}
if p.Status != Succeeded || p.AmountReceived != 1099 || p.Version != 3 {
t.Fatalf("got %+v", p)
}
}
func TestDeclineReturnsToRequiresPaymentMethod(t *testing.T) {
p := mustNew(t)
_ = p.Apply(AttachMethod)
if err := p.Apply(PSPDeclined); err != nil || p.Status != RequiresPaymentMethod {
t.Fatalf("got %s %v", p.Status, err)
}
// the customer can retry with another card on the same intent
if err := p.Apply(AttachMethod); err != nil {
t.Fatal(err)
}
}
func TestManualCaptureAndPartialCapture(t *testing.T) {
p := mustNew(t)
_ = p.Apply(AttachMethod)
_ = p.Apply(PSPAuthorized)
if p.Status != RequiresCapture || p.AmountCapturable != 1099 {
t.Fatalf("got %+v", p)
}
if err := p.Capture(2000); !errors.Is(err, ErrAmount) {
t.Fatalf("over-capture must fail, got %v", err)
}
if err := p.Capture(750); err != nil {
t.Fatal(err)
}
if p.Status != Succeeded || p.AmountReceived != 750 || p.AmountCapturable != 0 {
t.Fatalf("got %+v", p)
}
if err := p.Capture(349); !errors.Is(err, ErrInvalidTransition) {
t.Fatalf("second capture must fail, got %v", err)
}
}
func TestVoidAndExpiry(t *testing.T) {
for _, ev := range []Event{Cancel, AuthExpired} {
p := mustNew(t)
_ = p.Apply(AttachMethod)
_ = p.Apply(PSPAuthorized)
if err := p.Apply(ev); err != nil || p.Status != Canceled || p.AmountCapturable != 0 {
t.Fatalf("%s: got %+v %v", ev, p, err)
}
}
}
func TestStaleWebhookIsRejectedNotApplied(t *testing.T) {
p := mustNew(t)
_ = p.Apply(AttachMethod)
_ = p.Apply(PSPSucceeded)
// a late "requires_action" webhook arrives after "succeeded": must not move backwards
if err := p.Apply(PSPActionReq); !errors.Is(err, ErrInvalidTransition) {
t.Fatalf("got %v", err)
}
if p.Status != Succeeded {
t.Fatalf("status changed to %s", p.Status)
}
}
func TestRefundsNeverExceedReceived(t *testing.T) {
p := mustNew(t)
_ = p.Apply(AttachMethod)
_ = p.Apply(PSPSucceeded)
if err := p.Refund(1000); err != nil {
t.Fatal(err)
}
if err := p.Refund(100); !errors.Is(err, ErrAmount) {
t.Fatalf("1000+100 > 1099 must fail, got %v", err)
}
if err := p.Refund(99); err != nil || p.AmountRefunded != 1099 {
t.Fatalf("got %+v %v", p, err)
}
}
func TestEveryStatusHasARow(t *testing.T) {
for _, s := range []Status{RequiresPaymentMethod, RequiresConfirmation, RequiresAction, Processing, RequiresCapture, Succeeded, Canceled} {
if _, ok := transitions[s]; !ok {
t.Fatalf("missing row for %s", s)
}
}
if len(transitions[Succeeded]) != 0 || len(transitions[Canceled]) != 0 {
t.Fatal("terminal states must have no exits")
}
}
// Finding 9: a capture done at the PSP (webhook) completes requires_capture.
func TestPSPSucceededCompletesRequiresCapture(t *testing.T) {
p := mustNew(t)
for _, ev := range []Event{AttachMethod, PSPAuthorized} {
if err := p.Apply(ev); err != nil {
t.Fatal(err)
}
}
if err := p.Apply(PSPSucceeded); err == nil {
t.Fatal("from requires_capture the captured amount is required")
}
if err := p.Clone().Succeed(2000); !errors.Is(err, ErrAmount) {
t.Fatalf("more than the hold: %v", err)
}
if err := p.Succeed(800); err != nil || p.Status != Succeeded || p.AmountReceived != 800 || p.AmountCapturable != 0 {
t.Fatalf("partial capture by webhook: err=%v %+v", err, p)
}
}
// N30: the refund cap uses checked arithmetic.
func TestRefundCapCannotOverflow(t *testing.T) {
p, _ := New("pi_max", math.MaxInt64, "USD")
_ = p.Apply(AttachMethod)
if err := p.Succeed(math.MaxInt64); err != nil {
t.Fatal(err)
}
if err := p.Refund(math.MaxInt64); err != nil {
t.Fatal(err)
}
if err := p.Refund(1); !errors.Is(err, ErrAmount) {
t.Fatalf("refund beyond the captured amount: %v (refunded %d)", err, p.AmountRefunded)
}
}انبارهٔ Idempotency برای Idempotency-Key کلاینت؛ طراحی کامل در API Idempotency:
// Package idem is a minimal idempotency store for the payment API. The full design
// (leases, PostgreSQL and Redis stores, 409/422 semantics) is in the API Idempotency chapter.
package idem
import (
"crypto/sha256"
"encoding/hex"
"errors"
"sync"
"time"
)
// Outcome of Begin.
type Outcome int
const (
Started Outcome = iota // first time: run the operation
Replay // finished before: return the stored result
InFlight // another copy is running: 409
)
var ErrMismatch = errors.New("idem: key reused with a different request") // 422
type record struct {
fingerprint string
done bool
result string
expires time.Time
}
// Store keys records by scope+key (scope = merchant or API client).
type Store struct {
mu sync.Mutex
m map[string]*record
ttl time.Duration
now func() time.Time
}
// New returns a store; Stripe API v1 keeps keys for at least 24 hours, Adyen 7 to 14 days.
func New(ttl time.Duration, now func() time.Time) *Store {
if now == nil {
now = time.Now
}
return &Store{m: map[string]*record{}, ttl: ttl, now: now}
}
// Fingerprint hashes the canonical request body.
func Fingerprint(parts ...string) string {
h := sha256.New()
for _, p := range parts {
h.Write([]byte(p))
h.Write([]byte{0})
}
return hex.EncodeToString(h.Sum(nil))
}
// Begin claims scope/key atomically.
func (s *Store) Begin(scope, key, fp string) (Outcome, string, error) {
s.mu.Lock()
defer s.mu.Unlock()
k := scope + "\x00" + key
r, ok := s.m[k]
if ok && s.now().After(r.expires) {
ok = false
}
if !ok {
s.m[k] = &record{fingerprint: fp, expires: s.now().Add(s.ttl)}
return Started, "", nil
}
if r.fingerprint != fp {
return 0, "", ErrMismatch
}
if !r.done {
return InFlight, "", nil
}
return Replay, r.result, nil
}
// Complete stores the result to replay.
func (s *Store) Complete(scope, key, result string) {
s.mu.Lock()
defer s.mu.Unlock()
if r, ok := s.m[scope+"\x00"+key]; ok {
r.done, r.result = true, result
}
}
// Abandon frees the key so a retry can run again (used when nothing happened).
func (s *Store) Abandon(scope, key string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.m, scope+"\x00"+key)
}دفترکل دوطرفه (Double-entry ledger) با ثبت متوازن، append-only و idempotent، reversal و موجودی قابلبازمحاسبه:
// Package ledger is an append-only double-entry journal. Balances are derived from
// entries (cached for speed, recomputable at any time); nothing is ever updated or deleted.
// A correction is a new, reversing transaction.
package ledger
import (
"errors"
"fmt"
"math"
"sort"
"sync"
"time"
)
// Kind decides the normal side of an account.
type Kind int
const (
Asset Kind = iota // normal debit: cash at bank, PSP receivable
Expense // normal debit: PSP fees, chargeback losses
Liability // normal credit: customer wallet balances, payable to merchants
Revenue // normal credit: sales
Equity // normal credit
)
func (k Kind) debitNormal() bool { return k == Asset || k == Expense }
// Direction of one entry.
type Direction int
const (
Debit Direction = iota
Credit
)
// Account is a named bucket in one currency.
type Account struct {
ID string
Currency string
Kind Kind
AllowNegative bool // false: the normal-side balance may never go below zero
}
// Entry is one line of a transaction.
type Entry struct {
Account string
Direction Direction
Amount int64 // minor units, always > 0
}
// Transaction is an atomic, balanced set of entries.
type Transaction struct {
ID string // also the idempotency key of the posting
Description string
Entries []Entry
PostedAt time.Time
}
var (
ErrUnbalanced = errors.New("ledger: debits != credits")
ErrTooFewLines = errors.New("ledger: a transaction needs at least two entries")
ErrBadAmount = errors.New("ledger: entry amount must be > 0")
ErrNoAccount = errors.New("ledger: unknown account")
ErrInsufficient = errors.New("ledger: balance would go negative")
ErrConflict = errors.New("ledger: transaction id reused with different entries")
ErrExists = errors.New("ledger: account exists")
ErrOverflow = errors.New("ledger: int64 overflow")
)
// Ledger keeps the journal in memory; the SQL schema in this chapter is the durable version.
type Ledger struct {
mu sync.Mutex
accounts map[string]Account
journal []Transaction
byID map[string]int
balance map[string]int64 // signed: debits minus credits
now func() time.Time
}
// New returns an empty ledger.
func New(now func() time.Time) *Ledger {
if now == nil {
now = time.Now
}
return &Ledger{accounts: map[string]Account{}, byID: map[string]int{}, balance: map[string]int64{}, now: now}
}
// Open registers an account.
func (l *Ledger) Open(a Account) error {
l.mu.Lock()
defer l.mu.Unlock()
if _, ok := l.accounts[a.ID]; ok {
return ErrExists
}
l.accounts[a.ID] = a
return nil
}
// Post validates and appends. Re-posting the same ID with the same entries is a no-op
// (idempotent); the same ID with different entries is ErrConflict.
func (l *Ledger) Post(tx Transaction) (Transaction, bool, error) {
l.mu.Lock()
defer l.mu.Unlock()
if i, ok := l.byID[tx.ID]; ok {
if sameEntries(l.journal[i].Entries, tx.Entries) {
return copyTx(l.journal[i]), false, nil
}
return Transaction{}, false, ErrConflict
}
if len(tx.Entries) < 2 {
return Transaction{}, false, ErrTooFewLines
}
perCurrency := map[string]int64{}
delta := map[string]int64{}
for _, e := range tx.Entries {
a, ok := l.accounts[e.Account]
if !ok {
return Transaction{}, false, fmt.Errorf("%w: %s", ErrNoAccount, e.Account)
}
if e.Amount <= 0 {
return Transaction{}, false, ErrBadAmount
}
s := e.Amount
if e.Direction == Credit {
s = -s
}
var ok1, ok2 bool
if perCurrency[a.Currency], ok1 = add(perCurrency[a.Currency], s); !ok1 {
return Transaction{}, false, fmt.Errorf("%w: %s total", ErrOverflow, a.Currency)
}
if delta[a.ID], ok2 = add(delta[a.ID], s); !ok2 {
return Transaction{}, false, fmt.Errorf("%w: %s delta", ErrOverflow, a.ID)
}
}
for cur, sum := range perCurrency {
if sum != 0 {
return Transaction{}, false, fmt.Errorf("%w: %s off by %d", ErrUnbalanced, cur, sum)
}
}
next := map[string]int64{}
for id, d := range delta {
a := l.accounts[id]
b, ok := add(l.balance[id], d)
if !ok || b == math.MinInt64 { // MinInt64 has no normal-side (negated) value
return Transaction{}, false, fmt.Errorf("%w: %s balance", ErrOverflow, id)
}
if !a.AllowNegative && normal(a, b) < 0 {
return Transaction{}, false, fmt.Errorf("%w: %s", ErrInsufficient, id)
}
next[id] = b
}
for id, b := range next {
l.balance[id] = b
}
tx.Entries = append([]Entry(nil), tx.Entries...)
tx.PostedAt = l.now()
l.byID[tx.ID] = len(l.journal)
l.journal = append(l.journal, tx)
return copyTx(tx), true, nil
}
// Reverse posts the mirror image of an existing transaction.
func (l *Ledger) Reverse(id, newID, why string) (Transaction, error) {
l.mu.Lock()
i, ok := l.byID[id]
var orig Transaction
if ok {
orig = l.journal[i]
}
l.mu.Unlock()
if !ok {
return Transaction{}, fmt.Errorf("ledger: no transaction %s", id)
}
rev := Transaction{ID: newID, Description: "reversal of " + id + ": " + why}
for _, e := range orig.Entries {
e.Direction = 1 - e.Direction
rev.Entries = append(rev.Entries, e)
}
tx, _, err := l.Post(rev)
return tx, err
}
// Balance returns the normal-side balance (positive is "has money" for every kind).
func (l *Ledger) Balance(id string) int64 {
l.mu.Lock()
defer l.mu.Unlock()
return normal(l.accounts[id], l.balance[id])
}
// Recompute derives every balance from the journal; it must equal the cache.
func (l *Ledger) Recompute() map[string]int64 {
l.mu.Lock()
defer l.mu.Unlock()
out := map[string]int64{}
for _, tx := range l.journal {
for _, e := range tx.Entries {
s := e.Amount
if e.Direction == Credit {
s = -s
}
out[e.Account] += s
}
}
for id := range out {
out[id] = normal(l.accounts[id], out[id])
}
return out
}
// TrialBalance returns debits minus credits per currency; always zero in a sound ledger.
func (l *Ledger) TrialBalance() map[string]int64 {
l.mu.Lock()
defer l.mu.Unlock()
out := map[string]int64{}
for id, b := range l.balance {
out[l.accounts[id].Currency] += b
}
return out
}
// Journal returns a deep copy of all transactions in posting order: callers cannot
// reach the stored entries, so the journal stays append-only.
func (l *Ledger) Journal() []Transaction {
l.mu.Lock()
defer l.mu.Unlock()
out := make([]Transaction, len(l.journal))
for i, tx := range l.journal {
out[i] = copyTx(tx)
}
return out
}
func copyTx(tx Transaction) Transaction {
tx.Entries = append([]Entry(nil), tx.Entries...)
return tx
}
// add is checked int64 addition: ok is false when the true sum does not fit.
func add(a, b int64) (int64, bool) {
s := a + b
if (b > 0 && s < a) || (b < 0 && s > a) {
return 0, false
}
return s, true
}
func normal(a Account, signed int64) int64 {
if a.Kind.debitNormal() {
return signed
}
return -signed
}
func sameEntries(a, b []Entry) bool {
if len(a) != len(b) {
return false
}
key := func(es []Entry) []string {
out := make([]string, len(es))
for i, e := range es {
out[i] = fmt.Sprintf("%s|%d|%d", e.Account, e.Direction, e.Amount)
}
sort.Strings(out)
return out
}
ka, kb := key(a), key(b)
for i := range ka {
if ka[i] != kb[i] {
return false
}
}
return true
}package ledger
import (
"errors"
"fmt"
"math"
"math/rand/v2"
"sync"
"testing"
)
func setup(t *testing.T) *Ledger {
t.Helper()
l := New(nil)
for _, a := range []Account{
{ID: "psp_receivable", Currency: "USD", Kind: Asset},
{ID: "bank", Currency: "USD", Kind: Asset},
{ID: "psp_fees", Currency: "USD", Kind: Expense},
{ID: "sales", Currency: "USD", Kind: Revenue},
{ID: "wallet:alice", Currency: "USD", Kind: Liability},
{ID: "wallet:bob", Currency: "USD", Kind: Liability},
{ID: "funding", Currency: "USD", Kind: Equity, AllowNegative: true},
} {
if err := l.Open(a); err != nil {
t.Fatal(err)
}
}
return l
}
func TestUnbalancedIsRejected(t *testing.T) {
l := setup(t)
_, _, err := l.Post(Transaction{ID: "t1", Entries: []Entry{
{"psp_receivable", Debit, 1099}, {"sales", Credit, 1000},
}})
if !errors.Is(err, ErrUnbalanced) {
t.Fatalf("got %v", err)
}
if len(l.Journal()) != 0 {
t.Fatal("nothing may be written on failure")
}
}
func TestCaptureThenSettlementWithFee(t *testing.T) {
l := setup(t)
mustPost(t, l, "capture:pi_1", []Entry{{"psp_receivable", Debit, 1099}, {"sales", Credit, 1099}})
// the settlement file says: gross 1099, fee 62, net 1037 paid out to the bank
mustPost(t, l, "settle:po_1:pi_1", []Entry{{"bank", Debit, 1037}, {"psp_fees", Debit, 62}, {"psp_receivable", Credit, 1099}})
if l.Balance("psp_receivable") != 0 || l.Balance("bank") != 1037 || l.Balance("sales") != 1099 {
t.Fatalf("receivable=%d bank=%d sales=%d", l.Balance("psp_receivable"), l.Balance("bank"), l.Balance("sales"))
}
}
func TestWalletCannotGoNegative(t *testing.T) {
l := setup(t)
mustPost(t, l, "fund", []Entry{{"funding", Debit, 500}, {"wallet:alice", Credit, 500}})
_, _, err := l.Post(Transaction{ID: "p2p", Entries: []Entry{{"wallet:alice", Debit, 501}, {"wallet:bob", Credit, 501}}})
if !errors.Is(err, ErrInsufficient) {
t.Fatalf("got %v", err)
}
mustPost(t, l, "p2p-ok", []Entry{{"wallet:alice", Debit, 500}, {"wallet:bob", Credit, 500}})
if l.Balance("wallet:alice") != 0 || l.Balance("wallet:bob") != 500 {
t.Fatal("wrong balances")
}
}
func TestPostIsIdempotentByID(t *testing.T) {
l := setup(t)
e := []Entry{{"psp_receivable", Debit, 100}, {"sales", Credit, 100}}
mustPost(t, l, "capture:pi_9", e)
_, created, err := l.Post(Transaction{ID: "capture:pi_9", Entries: e})
if err != nil || created {
t.Fatalf("replay must be a no-op, created=%v err=%v", created, err)
}
_, _, err = l.Post(Transaction{ID: "capture:pi_9", Entries: []Entry{{"psp_receivable", Debit, 999}, {"sales", Credit, 999}}})
if !errors.Is(err, ErrConflict) {
t.Fatalf("got %v", err)
}
if l.Balance("sales") != 100 {
t.Fatal("double posting")
}
}
func TestReversalNetsToZeroAndKeepsHistory(t *testing.T) {
l := setup(t)
mustPost(t, l, "capture:pi_2", []Entry{{"psp_receivable", Debit, 2500}, {"sales", Credit, 2500}})
if _, err := l.Reverse("capture:pi_2", "rev:pi_2", "posted twice by an old bug"); err != nil {
t.Fatal(err)
}
if l.Balance("sales") != 0 || len(l.Journal()) != 2 {
t.Fatal("reversal must add a row, not delete one")
}
}
// The two invariants under concurrency: the trial balance is zero, and wallets never
// go negative, whatever order 200 random transfers arrive in.
func TestInvariantsUnderConcurrentTransfers(t *testing.T) {
l := setup(t)
mustPost(t, l, "fund-a", []Entry{{"funding", Debit, 10_000}, {"wallet:alice", Credit, 10_000}})
mustPost(t, l, "fund-b", []Entry{{"funding", Debit, 10_000}, {"wallet:bob", Credit, 10_000}})
var wg sync.WaitGroup
for i := 0; i < 200; i++ {
wg.Add(1)
go func(i int) {
defer wg.Done()
from, to := "wallet:alice", "wallet:bob"
if i%2 == 1 {
from, to = to, from
}
amt := int64(rand.IntN(400) + 1)
_, _, _ = l.Post(Transaction{ID: fmt.Sprintf("p2p-%d", i), Entries: []Entry{{from, Debit, amt}, {to, Credit, amt}}})
}(i)
}
wg.Wait()
for cur, v := range l.TrialBalance() {
if v != 0 {
t.Fatalf("trial balance %s = %d", cur, v)
}
}
if l.Balance("wallet:alice") < 0 || l.Balance("wallet:bob") < 0 {
t.Fatal("negative wallet")
}
if l.Balance("wallet:alice")+l.Balance("wallet:bob") != 20_000 {
t.Fatal("money created or destroyed")
}
derived := l.Recompute()
for id, v := range derived {
if l.Balance(id) != v {
t.Fatalf("cache %s=%d, derived=%d", id, l.Balance(id), v)
}
}
}
func mustPost(t *testing.T, l *Ledger, id string, e []Entry) {
t.Helper()
if _, _, err := l.Post(Transaction{ID: id, Entries: e}); err != nil {
t.Fatalf("%s: %v", id, err)
}
}
// Finding 5: values returned by Post and Journal must not alias the stored entries.
func TestReturnedTransactionsCannotMutateTheJournal(t *testing.T) {
l := setup(t)
tx, _, err := l.Post(Transaction{ID: "c1", Entries: []Entry{{"psp_receivable", Debit, 100}, {"sales", Credit, 100}}})
if err != nil {
t.Fatal(err)
}
tx.Entries[0].Amount = 999
l.Journal()[0].Entries[1].Amount = 999
if got := l.Journal()[0].Entries; got[0].Amount != 100 || got[1].Amount != 100 {
t.Fatalf("journal mutated through a returned value: %+v", got)
}
if l.Recompute()["sales"] != l.Balance("sales") {
t.Fatal("recomputed balance no longer equals the cache")
}
}
// N9: totals and deltas use checked arithmetic; a wrapped "balanced" journal is rejected.
func TestOverflowingJournalIsRejected(t *testing.T) {
l := setup(t)
_, _, err := l.Post(Transaction{ID: "wrap", Entries: []Entry{
{"bank", Debit, math.MaxInt64}, {"bank", Debit, math.MaxInt64}, {"bank", Debit, 2},
}})
if !errors.Is(err, ErrOverflow) {
t.Fatalf("got %v, want ErrOverflow", err)
}
if len(l.Journal()) != 0 {
t.Fatal("nothing may be written")
}
}سرویس پرداخت با توقف امن (Fail closed) ساخته شده است: برای هر merchant و order فقط یک پرداخت؛ روی هر پرداخت در هر لحظه فقط یک عملیات. فراخوان دوم ErrInFlight میگیرد؛ اینجا توکن جای row lockی را میگیرد که در طول تماس PSP نگه داشته میشود. Attempt ارسالشده تا اثبات نتیجه با همان کلید تکرار میشود؛ failover فقط برای کلید تازهای مجاز است که PSP قطعاً رد کرده است. خطای دستهبندینشده unknown است. تغییر state روی یک کپی انجام میشود و فقط پس از موفقیت ثبت ledger نگه داشته میشود؛ در غیر این صورت ErrUnbooked برمیگردد و فراخوان بعدی، نتیجهٔ ذخیرهشدهٔ PSP را بدون برداشت مجدد ثبت میکند. مبلغ capture پیش از تماس ثبت میشود، کلید refund به پرداخت و مبلغ مقید است و webhook مبلغ گزارششده را حمل میکند. موفقیت نگهداشتهشده برای ثبت (unbooked) با lookup مشترک retained() پیدا میشود؛ Confirm، Capture و webhook از همان نتیجه ترمیم میکنند و applyLocked و setAttempt اجازهٔ بازنویسی آن را نمیدهند. نسبت دادن webhook به attempt، اعتبارسنجی و اعمالش همگی در یک بخش بحرانی انجام میشود. تطبیق بر اساس PSP reference است؛ موفقیتی که اول با webhook برسد reference خود را نگه میدارد. هر خروجی هنگام نگه داشتن s.mu از intent کپی میگیرد؛ UnknownAttempts هم کپی عمیق میدهد. عملیات unknown فقط داخل ResendWindow و بر اساس FirstSentAt دوباره ارسال میشود؛ PSP جعلی reference پرداخت ناشناخته را رد میکند تا تستها گم شدن آن را کشف کنند. محدودیتهای عمدی در کد و محدودیتهای شناختهشده آمدهاند: توکن در حافظه است و سرویس واقعی row lock یا وضعیت processing در پایگاهداده لازم دارد؛ attemptها و refundهای unknown خودشان حل نمیشوند و با UnknownAttempts، PendingRefunds و ResolveRefund منتظر reconciliation میمانند:
// Package payment is a payment-intent service: idempotent create, confirm against one
// of several PSPs with a derived provider idempotency key, query-then-retry on ambiguous
// outcomes, and ledger postings plus outbox events committed together.
package payment
import (
"context"
"errors"
"fmt"
"sync"
"time"
"academy/payment-processing-architecture/idem"
"academy/payment-processing-architecture/intent"
"academy/payment-processing-architecture/ledger"
"academy/payment-processing-architecture/outbox"
)
// ChargeRequest is what we send to a PSP.
type ChargeRequest struct {
IdempotencyKey string // derived: <intent>:attempt:<n>, identical on every retry
IntentID string
PaymentMethod string // a PSP token (pm_..., a network token), never a PAN
Amount int64
Currency string
ManualCapture bool
}
// Result is the PSP's answer mapped onto our events.
type Result struct {
PSPRef string
Outcome intent.Event // PSPSucceeded, PSPAuthorized, PSPActionReq, PSPProcessing, PSPDeclined
Amount int64 // what the PSP says it received (PSPSucceeded); 0 otherwise
DeclineCode string // e.g. insufficient_funds, do_not_honor
}
// PSP is one provider adapter (Stripe, Adyen, Braintree...).
type PSP interface {
Name() string
Authorize(ctx context.Context, r ChargeRequest) (Result, error)
Lookup(ctx context.Context, idempotencyKey string) (Result, bool, error)
Capture(ctx context.Context, idempotencyKey, pspRef string, amount int64) error
Refund(ctx context.Context, idempotencyKey, pspRef string, amount int64) error
}
var (
// ErrTimeout: the request may or may not have been processed (ambiguous).
ErrTimeout = errors.New("psp: timeout")
// ErrUnavailable: the PSP refused THIS request before processing it. It proves nothing
// about an earlier request with the same key.
ErrUnavailable = errors.New("psp: unavailable")
// ErrKeyReuse: the PSP saw this idempotency key with different parameters.
ErrKeyReuse = errors.New("psp: idempotency key reused with different parameters")
// ErrAmbiguous: we still do not know; the attempt stays "unknown" for reconciliation.
ErrAmbiguous = errors.New("payment: outcome unknown, parked for reconciliation")
// ErrUnbooked: the PSP moved money but the ledger posting failed; the intent is unchanged
// and the result is kept so the next call (or reconciliation) books it.
ErrUnbooked = errors.New("payment: PSP result not booked, retry or reconcile")
// ErrMismatch: two sources disagree about an amount; a human or reconciliation decides.
ErrMismatch = errors.New("payment: amount mismatch, needs reconciliation")
// ErrNeedsReconciliation: an operation whose outcome is unknown is older than the
// resend window (the PSP may have dropped its idempotency key): it is never resent.
ErrNeedsReconciliation = errors.New("payment: outcome unknown past the resend window, reconcile")
ErrInFlight = errors.New("payment: another operation on this payment is in progress") // 409
ErrDuplicateOrder = errors.New("payment: this order already has a payment") // 409
ErrNotFound = errors.New("payment: no such intent")
ErrRefund = errors.New("payment: refund not allowed")
)
// Attempt is one try at one PSP with one key.
//
// sent created, request (maybe) on the wire
// unknown sent at least once, outcome not proven: only the SAME key may be resent
// refused the PSP provably did not process it: a new attempt may follow
// done the PSP's answer is applied and booked
// unbooked the PSP answered (Result kept) but the posting failed: repaired on the next call
type Attempt struct {
IntentID, PSP, Key, PSPRef string
State string
Result *Result
FirstSentAt time.Time // the resend window counts from here
}
type captureRec struct {
key string
amount int64
state string // sent, unknown, unbooked, done
firstSentAt time.Time
}
// RefundRec is one refund key. State: sent, unknown, unbooked, booked.
type RefundRec struct {
IntentID, Key string
Amount int64
State string
FirstSentAt time.Time
}
// DefaultResendWindow stays below Stripe's documented 24 hours of key retention: after it,
// an unresolved operation goes to reconciliation instead of being sent again.
const DefaultResendWindow = 23 * time.Hour
// Service holds state in memory; s.mu stands in for one database transaction, and
// busy[intent] for a row lock held across the PSP call (SELECT ... FOR UPDATE, or a
// status column "processing" set in its own transaction).
type Service struct {
mu sync.Mutex
intents map[string]*intent.Intent
attempts map[string][]*Attempt
byOrder map[string]string // merchant + order -> intent: one payment per order
busy map[string]bool // single flight per payment: a second caller gets ErrInFlight
captures map[string]*captureRec
refunds map[string]*RefundRec // by refund key
idem *idem.Store
Ledger *ledger.Ledger
Outbox *outbox.Outbox
inbox outbox.Inbox
psps []PSP // routing order: primary first
// ResendWindow: how long an operation with an unknown outcome may be resent with its key.
ResendWindow time.Duration
timeout time.Duration
now func() time.Time
seq int
testHook func(point string) // nil in production; tests use it to force interleavings
}
func (s *Service) hook(point string) {
if s.testHook != nil {
s.testHook(point)
}
}
// NewService wires the parts. callTimeout is the per-PSP-call budget.
func NewService(callTimeout time.Duration, psps ...PSP) *Service {
return &Service{
intents: map[string]*intent.Intent{}, attempts: map[string][]*Attempt{},
byOrder: map[string]string{}, busy: map[string]bool{},
captures: map[string]*captureRec{}, refunds: map[string]*RefundRec{},
idem: idem.New(24*time.Hour, nil), Ledger: ledger.New(nil), Outbox: &outbox.Outbox{},
psps: psps, timeout: callTimeout, now: time.Now, ResendWindow: DefaultResendWindow,
}
}
// expired reports whether an operation first sent at t may no longer be resent; s.mu held.
func (s *Service) expired(t time.Time) bool {
return !t.IsZero() && s.now().Sub(t) > s.ResendWindow
}
// Create makes an intent once per (merchant, Idempotency-Key) and at most once per
// (merchant, order): a second client key for the same order is ErrDuplicateOrder.
func (s *Service) Create(merchant, key string, amount int64, currency, orderID string) (*intent.Intent, bool, error) {
fp := idem.Fingerprint(fmt.Sprint(amount), currency, orderID)
out, stored, err := s.idem.Begin(merchant, key, fp)
if err != nil {
return nil, false, err
}
s.mu.Lock()
defer s.mu.Unlock()
switch out {
case idem.Replay:
return s.intents[stored].Clone(), true, nil // copies only: callers never alias state
case idem.InFlight:
return nil, false, ErrInFlight
}
order := merchant + "\x00" + orderID
if _, exists := s.byOrder[order]; exists {
s.idem.Abandon(merchant, key)
return nil, false, fmt.Errorf("%w: %s", ErrDuplicateOrder, orderID)
}
s.seq++
p, err := intent.New(fmt.Sprintf("pi_%04d", s.seq), amount, currency)
if err != nil {
s.idem.Abandon(merchant, key)
return nil, false, err
}
s.intents[p.ID], s.byOrder[order] = p, p.ID
s.idem.Complete(merchant, key, p.ID)
return p.Clone(), false, nil
}
// Get returns a copy of the intent.
func (s *Service) Get(id string) (intent.Intent, error) {
s.mu.Lock()
defer s.mu.Unlock()
p, ok := s.intents[id]
if !ok {
return intent.Intent{}, ErrNotFound
}
return *p.Clone(), nil
}
// begin takes the payment's single-flight token; s.mu must be held.
func (s *Service) begin(id string) error {
if s.busy[id] {
return fmt.Errorf("%w: %s", ErrInFlight, id)
}
s.busy[id] = true
return nil
}
func (s *Service) end(id string) {
s.mu.Lock()
defer s.mu.Unlock()
delete(s.busy, id)
}
// Confirm charges the intent. One caller at a time per payment (others get ErrInFlight).
// An attempt that was ever sent without a proven outcome is resent with the SAME key at
// the SAME PSP until a clear answer arrives; only a fresh attempt that the PSP provably
// refused allows failover. A result whose posting failed is booked again, not re-charged.
func (s *Service) Confirm(ctx context.Context, id, paymentMethod string, manualCapture bool) (intent.Intent, error) {
s.mu.Lock()
p, ok := s.intents[id]
if !ok {
s.mu.Unlock()
return intent.Intent{}, ErrNotFound
}
if err := s.begin(id); err != nil {
cp := *p.Clone()
s.mu.Unlock()
return cp, err
}
defer s.end(id)
last := s.lastAttempt(id)
if r := s.retained(id); r != nil {
defer s.mu.Unlock()
return s.applyLocked(r, *r.Result) // repair: book what the PSP already did
}
if p.Terminal() || p.Status == intent.RequiresCapture || p.Status == intent.RequiresAction || p.Status == intent.Processing {
// finished, or waiting for the customer (3DS) or an async rail: the webhook moves it on
cp := *p.Clone()
s.mu.Unlock()
return cp, nil
}
if p.Status == intent.RequiresPaymentMethod {
_ = p.Apply(intent.AttachMethod)
}
route, fresh := s.psps, true
var att *Attempt
if last != nil && (last.State == "unknown" || last.State == "sent") {
if s.expired(last.FirstSentAt) {
cp := *p.Clone()
s.mu.Unlock()
return cp, fmt.Errorf("%w: attempt %s", ErrNeedsReconciliation, last.Key)
}
att, fresh = last, false // never superseded until its outcome is proven
route = []PSP{s.pspByName(last.PSP)}
} else if len(route) > 0 {
att = s.newAttemptLocked(id, route[0].Name())
}
amount, currency := p.Amount, p.Currency
s.mu.Unlock()
s.hook("confirm:after-lookup")
for i, psp := range route {
if psp == nil {
break
}
if i > 0 {
s.hook("confirm:before-fallback")
s.mu.Lock()
att, fresh = s.newAttemptLocked(id, psp.Name()), true // we still hold the token
s.mu.Unlock()
}
req := ChargeRequest{IdempotencyKey: att.Key, IntentID: id, PaymentMethod: paymentMethod,
Amount: amount, Currency: currency, ManualCapture: manualCapture}
res, err := s.charge(ctx, psp, req, fresh)
switch {
case err == nil:
return s.apply(att, res)
case errors.Is(err, ErrUnavailable):
s.setAttempt(att, "refused") // fresh key, provably not processed
if i+1 < len(route) {
continue
}
cur, _ := s.Get(id)
return cur, err
default:
s.setAttempt(att, "unknown") // never fail over: this PSP may have charged
cur, _ := s.Get(id)
return cur, fmt.Errorf("%w: %v", ErrAmbiguous, err)
}
}
return s.Get(id)
}
// charge = call; on anything but a clear answer ask "did it happen?"; resend the SAME key.
// ErrUnavailable is returned only when no send of this key can have been processed:
// a fresh key whose every send was refused. Every other failure is ambiguous.
func (s *Service) charge(ctx context.Context, psp PSP, req ChargeRequest, fresh bool) (Result, error) {
maybeProcessed := !fresh
for try := 0; try < 2; try++ {
cctx, cancel := context.WithTimeout(ctx, s.timeout)
res, err := psp.Authorize(cctx, req)
cancel()
if err == nil {
return res, nil
}
if errors.Is(err, ErrUnavailable) {
if !maybeProcessed {
return Result{}, ErrUnavailable
}
} else {
maybeProcessed = true // timeout, reset, decode error, unknown 5xx: fail closed
}
lctx, cancel := context.WithTimeout(ctx, s.timeout)
found, ok, lerr := psp.Lookup(lctx, req.IdempotencyKey)
cancel()
if lerr == nil && ok {
return found, nil
}
}
return Result{}, ErrAmbiguous
}
// apply books first and changes state second: the change is made on a clone, posted, and
// only then copied into the intent. A failed posting leaves the intent as it was and keeps
// the PSP result on the attempt ("unbooked") so a retry books it without charging again.
func (s *Service) apply(att *Attempt, res Result) (intent.Intent, error) {
s.mu.Lock()
defer s.mu.Unlock()
return s.applyLocked(att, res)
}
// retained returns the latest attempt of id if it holds a PSP success the ledger has not
// booked yet ("unbooked"); s.mu held. Confirm, Capture and the webhook path all repair from
// this one place, and nothing may overwrite it except its own booking.
func (s *Service) retained(id string) *Attempt {
if a := s.lastAttempt(id); a != nil && a.State == "unbooked" && a.Result != nil {
return a
}
return nil
}
// applyLocked is apply with s.mu held. If the attempt holds a retained success, an incoming
// answer never replaces it: the same success books it, an older answer (authorized, action,
// processing) is stale and the retained success is booked instead, and a decline contradicts
// it (ErrMismatch, retained success untouched).
func (s *Service) applyLocked(att *Attempt, res Result) (intent.Intent, error) {
p := s.intents[att.IntentID]
if att.State == "unbooked" && att.Result != nil {
kept := *att.Result
same := res.Outcome == intent.PSPSucceeded && res.Amount == kept.Amount && (res.PSPRef == "" || res.PSPRef == kept.PSPRef)
if !same && (res.Outcome == intent.PSPDeclined || res.Outcome == intent.PSPSucceeded) {
return *p.Clone(), fmt.Errorf("%w: %s contradicts the retained success of %s", ErrMismatch, res.Outcome, att.Key)
}
res = kept
}
if att.PSPRef != "" && res.PSPRef != "" && att.PSPRef != res.PSPRef {
return *p.Clone(), fmt.Errorf("%w: attempt %s has reference %s, PSP reports %s", ErrMismatch, att.Key, att.PSPRef, res.PSPRef)
}
if att.PSPRef == "" {
att.PSPRef = res.PSPRef // kept in every branch, including the terminal one below
}
if p.Terminal() && !p.Can(res.Outcome) {
if res.Outcome == intent.PSPSucceeded && p.Status == intent.Succeeded && res.Amount != p.AmountReceived {
return *p.Clone(), fmt.Errorf("%w: booked %d, PSP reports %d", ErrMismatch, p.AmountReceived, res.Amount)
}
if att.State != "unbooked" {
att.State, att.Result = "done", nil
}
return *p.Clone(), nil // already applied by another path (webhook or an earlier call)
}
next := p.Clone()
var err error
if res.Outcome == intent.PSPSucceeded {
err = next.Succeed(res.Amount)
} else {
err = next.Apply(res.Outcome)
}
if err != nil {
return *p.Clone(), err
}
if next.Status == intent.Succeeded {
if err := s.postCapture(next, att.PSP, next.AmountReceived); err != nil {
stored := res
att.State, att.Result = "unbooked", &stored
return *p.Clone(), fmt.Errorf("%w: %v", ErrUnbooked, err)
}
}
*p = *next
att.State, att.Result = "done", nil
switch p.Status {
case intent.Succeeded:
s.emit(p, "payments.payment_succeeded", fmt.Sprintf(`{"id":%q,"amount":%d,"psp":%q}`, p.ID, p.AmountReceived, att.PSP))
case intent.RequiresCapture:
s.emit(p, "payments.payment_authorized", fmt.Sprintf(`{"id":%q,"capturable":%d}`, p.ID, p.AmountCapturable))
case intent.RequiresPaymentMethod:
s.emit(p, "payments.payment_failed", fmt.Sprintf(`{"id":%q,"decline_code":%q}`, p.ID, res.DeclineCode))
}
return *p.Clone(), nil
}
// Capture takes a held authorization (full or partial). The amount is recorded with its
// derived key (capture:<intent>) BEFORE the PSP call; a later call with another amount is
// ErrMismatch, never a second capture. Only the PSP's success is booked; if the capture
// webhook booked first, the amounts must agree. A capture the PSP confirmed but the ledger
// rejected ("unbooked") is booked on retry WITHOUT calling the PSP again; an unknown one is
// resent only inside the resend window. Every return clones the intent under s.mu.
func (s *Service) Capture(ctx context.Context, id string, amount int64) (intent.Intent, error) {
s.mu.Lock()
p, ok := s.intents[id]
if !ok {
s.mu.Unlock()
return intent.Intent{}, ErrNotFound
}
if err := s.begin(id); err != nil {
cp := *p.Clone()
s.mu.Unlock()
return cp, err
}
defer s.end(id)
rec := s.captures[id]
if rec != nil && rec.amount != amount {
cp := *p.Clone()
s.mu.Unlock()
return cp, fmt.Errorf("%w: capture key %s already used for %d", ErrMismatch, rec.key, rec.amount)
}
if r := s.retained(id); r != nil && r.Result.Outcome == intent.PSPSucceeded { // the webhook saw the capture
defer s.mu.Unlock()
if r.Result.Amount != amount {
return *p.Clone(), fmt.Errorf("%w: PSP captured %d, capture asks %d", ErrMismatch, r.Result.Amount, amount)
}
got, err := s.applyLocked(r, *r.Result)
if err == nil && rec != nil {
rec.state = "done"
}
return got, err
}
if rec != nil && rec.state == "unbooked" {
defer s.mu.Unlock()
return s.bookCaptureLocked(p, rec, s.lastPSP(id), amount)
}
if p.Status == intent.Succeeded && rec != nil && p.AmountReceived == amount {
cp := *p.Clone()
s.mu.Unlock()
return cp, nil // replay of a booked capture
}
if p.Status != intent.RequiresCapture || amount <= 0 || amount > p.AmountCapturable {
cp := *p.Clone()
s.mu.Unlock()
return cp, fmt.Errorf("%w: capture %d in %s", intent.ErrInvalidTransition, amount, cp.Status)
}
if rec != nil && s.expired(rec.firstSentAt) {
cp := *p.Clone()
s.mu.Unlock()
return cp, fmt.Errorf("%w: capture %s", ErrNeedsReconciliation, rec.key)
}
fresh := rec == nil
if fresh {
rec = &captureRec{key: "capture:" + id, amount: amount, state: "sent", firstSentAt: s.now()}
s.captures[id] = rec
}
pspName := s.lastPSP(id)
psp, ref := s.pspByName(pspName), s.lastRef(id)
key := rec.key
s.mu.Unlock()
if psp == nil {
return s.Get(id)
}
cctx, cancel := context.WithTimeout(ctx, s.timeout)
err := psp.Capture(cctx, key, ref, amount)
cancel()
s.hook("capture:after-psp")
s.mu.Lock()
defer s.mu.Unlock()
if err != nil {
if fresh && errors.Is(err, ErrUnavailable) {
delete(s.captures, id) // provably not captured: the amount may change later
} else {
rec.state = "unknown"
}
return *p.Clone(), err
}
return s.bookCaptureLocked(p, rec, pspName, amount)
}
// bookCaptureLocked books a capture the PSP confirmed; s.mu held.
func (s *Service) bookCaptureLocked(p *intent.Intent, rec *captureRec, pspName string, amount int64) (intent.Intent, error) {
if p.Status == intent.Succeeded { // the capture webhook was faster
if p.AmountReceived != amount {
return *p.Clone(), fmt.Errorf("%w: webhook booked %d, capture %d", ErrMismatch, p.AmountReceived, amount)
}
rec.state = "done"
return *p.Clone(), nil
}
next := p.Clone()
if err := next.Capture(amount); err != nil {
return *p.Clone(), err
}
if err := s.postCapture(next, pspName, amount); err != nil {
rec.state = "unbooked" // captured at the PSP: the retry books it, it never re-captures
return *p.Clone(), fmt.Errorf("%w: %v", ErrUnbooked, err)
}
*p = *next
rec.state = "done"
s.emit(p, "payments.payment_captured", fmt.Sprintf(`{"id":%q,"amount":%d}`, p.ID, amount))
return *p.Clone(), nil
}
func (s *Service) pspByName(name string) PSP {
for _, c := range s.psps {
if c.Name() == name {
return c
}
}
return nil
}
// openRefunds sums refunds of id that are not booked yet (sent, unknown, unbooked):
// that money may already have left, so it is not refundable again.
func (s *Service) openRefunds(id string) int64 {
var n int64
for _, r := range s.refunds {
if r.IntentID == id && r.State != "booked" {
n += r.Amount
}
}
return n
}
// Refund sends a refund with its own key and books it. One operation per payment at a
// time. A key is bound to (payment, amount) forever: any other use is ErrRefund. The amount
// counts as taken from the moment the key is recorded until the refund is booked, or until
// a FRESH key is provably refused (ErrUnavailable on its first send). Every other failure
// leaves the refund "unknown" and its amount taken; the same key resumes it, and
// ResolveRefund (after a lookup at the PSP) is the only other way out.
func (s *Service) Refund(ctx context.Context, id, refundKey string, amount int64) error {
s.mu.Lock()
p, ok := s.intents[id]
if !ok {
s.mu.Unlock()
return ErrNotFound
}
if err := s.begin(id); err != nil {
s.mu.Unlock()
return err
}
defer s.end(id)
rec, seen := s.refunds[refundKey]
switch {
case seen && (rec.IntentID != id || rec.Amount != amount):
s.mu.Unlock()
return fmt.Errorf("%w: key %s belongs to %s / %d", ErrRefund, refundKey, rec.IntentID, rec.Amount)
case seen && rec.State == "booked":
s.mu.Unlock()
return nil // exact replay
case seen && rec.State == "unbooked":
defer s.mu.Unlock()
return s.bookRefund(p, rec, s.lastPSP(id)) // known success: book it, never resend
case seen && s.expired(rec.FirstSentAt):
s.mu.Unlock()
return fmt.Errorf("%w: refund %s", ErrNeedsReconciliation, refundKey)
case !seen:
if p.Status != intent.Succeeded || amount <= 0 || amount > p.AmountReceived-p.AmountRefunded-s.openRefunds(id) {
s.mu.Unlock()
return ErrRefund
}
rec = &RefundRec{IntentID: id, Key: refundKey, Amount: amount, State: "sent", FirstSentAt: s.now()}
s.refunds[refundKey] = rec
}
fresh := !seen
pspName, ref := s.lastPSP(id), s.lastRef(id)
psp := s.pspByName(pspName)
s.mu.Unlock()
var err error
if psp == nil {
err = fmt.Errorf("%w: no PSP attempt recorded for %s", ErrUnavailable, id)
} else {
cctx, cancel := context.WithTimeout(ctx, s.timeout)
err = psp.Refund(cctx, refundKey, ref, amount)
cancel()
}
s.hook("refund:before-booking")
s.mu.Lock()
defer s.mu.Unlock()
if err != nil {
if fresh && errors.Is(err, ErrUnavailable) {
delete(s.refunds, refundKey) // first send refused before processing: nothing left
return err
}
rec.State = "unknown"
return fmt.Errorf("%w: refund %s, amount stays reserved: %v", ErrAmbiguous, refundKey, err)
}
return s.bookRefund(p, rec, pspName)
}
// bookRefund posts the journal entry first and changes the intent second; s.mu held.
func (s *Service) bookRefund(p *intent.Intent, rec *RefundRec, pspName string) error {
next := p.Clone()
if err := next.Refund(rec.Amount); err != nil {
rec.State = "unbooked"
return fmt.Errorf("%w: %v", ErrUnbooked, err)
}
cur := p.Currency
if _, _, err := s.Ledger.Post(ledger.Transaction{ID: "refund:" + rec.Key, Description: "refund " + p.ID, Entries: []ledger.Entry{
{Account: s.acct("refunds", "", cur, ledger.Expense), Direction: ledger.Debit, Amount: rec.Amount},
{Account: s.acct("psp_receivable", pspName, cur, ledger.Asset), Direction: ledger.Credit, Amount: rec.Amount},
}}); err != nil {
rec.State = "unbooked" // refunded at the PSP: the next call with this key books it
return fmt.Errorf("%w: %v", ErrUnbooked, err)
}
*p = *next
rec.State = "booked"
s.emit(p, "payments.payment_refunded", fmt.Sprintf(`{"id":%q,"amount":%d}`, p.ID, rec.Amount))
return nil
}
// ResolveRefund is the reconciliation exit for an unknown refund, after a lookup at the
// PSP (or the settlement file) proved what happened: refunded -> booked, not -> released.
func (s *Service) ResolveRefund(refundKey string, refundedAtPSP bool) error {
s.mu.Lock()
defer s.mu.Unlock()
rec, ok := s.refunds[refundKey]
if !ok || rec.State == "booked" {
return nil
}
if s.busy[rec.IntentID] {
return ErrInFlight
}
if !refundedAtPSP {
delete(s.refunds, refundKey)
return nil
}
return s.bookRefund(s.intents[rec.IntentID], rec, s.lastPSP(rec.IntentID))
}
// PendingRefunds lists refunds that are not booked, for the reconciliation job.
func (s *Service) PendingRefunds() []RefundRec {
s.mu.Lock()
defer s.mu.Unlock()
var out []RefundRec
for _, r := range s.refunds {
if r.State != "booked" {
out = append(out, *r)
}
}
return out
}
// HandleWebhook applies a verified PSP event once; duplicates and stale events are acked.
// The event is attributed by the PSP reference it carries (pspRef), never to "the latest
// attempt": an event for an older attempt is stale (acked) unless it reports a success,
// which means a second charge somewhere and is ErrMismatch. A reference we have not seen
// yet is attached only to the single in-flight attempt without one. amount is what the
// event says was received (PSPSucceeded). A retained (unbooked) success is never overwritten:
// a contradicting event is ErrMismatch, the same or an older event books the retained success.
// Attribution, validation and application run in ONE critical section. The event id is
// claimed first (a concurrent duplicate is skipped) and forgotten again if applying fails,
// so the PSP's next delivery retries it.
func (s *Service) HandleWebhook(eventID, intentID string, ev intent.Event, amount int64, pspRef string) (applied bool, err error) {
if !s.inbox.FirstTime(eventID) {
return false, nil
}
fail := func(e error) (bool, error) { s.inbox.Forget(eventID); return false, e }
s.hook("webhook:window") // before the critical section: nothing can interleave inside it
s.mu.Lock()
defer s.mu.Unlock()
p, ok := s.intents[intentID]
if !ok || pspRef == "" {
return fail(fmt.Errorf("%w: %s / %q", ErrNotFound, intentID, pspRef)) // not ours yet: retry later
}
atts := s.attempts[intentID]
var att *Attempt
for _, a := range atts {
if a.PSPRef == pspRef {
att = a
}
}
if att == nil {
var open []*Attempt
for _, a := range atts {
if a.PSPRef == "" && (a.State == "sent" || a.State == "unknown") {
open = append(open, a)
}
}
if len(open) != 1 {
return fail(fmt.Errorf("%w: no attempt for reference %s", ErrNotFound, pspRef))
}
att = open[0]
}
latest := atts[len(atts)-1] == att
switch {
case !latest && ev == intent.PSPSucceeded:
return fail(fmt.Errorf("%w: success for superseded attempt %s", ErrMismatch, att.Key))
case !latest:
return false, nil // stale: an older attempt's failure says nothing about the current one
case att.State == "unbooked" && (ev == intent.PSPDeclined || (ev == intent.PSPSucceeded && att.Result.Amount != amount)):
return fail(fmt.Errorf("%w: event %s contradicts the unbooked success of %s", ErrMismatch, ev, att.Key))
case att.State == "unbooked": // the same success, or an older event: book the retained success
case att.State != "unbooked" && !p.Can(ev):
mismatch := ev == intent.PSPSucceeded && p.Status == intent.Succeeded && amount != p.AmountReceived
if mismatch {
return fail(fmt.Errorf("%w: booked amount differs, event says %d", ErrMismatch, amount))
}
return false, nil // late or out-of-order: current state already covers it
}
// validation above and application below share ONE critical section: the attempt
// cannot be superseded in between
if _, err = s.applyLocked(att, Result{Outcome: ev, Amount: amount, PSPRef: pspRef}); err != nil {
return fail(err)
}
return true, nil
}
// UnknownAttempts lists attempts for the reconciliation job.
func (s *Service) UnknownAttempts() []Attempt {
s.mu.Lock()
defer s.mu.Unlock()
var out []Attempt
for _, as := range s.attempts {
for _, a := range as {
if a.State == "unknown" || a.State == "unbooked" {
c := *a
if a.Result != nil {
r := *a.Result // deep copy: callers cannot edit recovery state
c.Result = &r
}
out = append(out, c)
}
}
}
return out
}
func (s *Service) postCapture(p *intent.Intent, psp string, amount int64) error {
_, _, err := s.Ledger.Post(ledger.Transaction{ID: fmt.Sprintf("capture:%s", p.ID), Description: "capture " + p.ID, Entries: []ledger.Entry{
{Account: s.acct("psp_receivable", psp, p.Currency, ledger.Asset), Direction: ledger.Debit, Amount: amount},
{Account: s.acct("sales", "", p.Currency, ledger.Revenue), Direction: ledger.Credit, Amount: amount},
}})
return err
}
func (s *Service) acct(name, psp, cur string, k ledger.Kind) string {
id := name + ":" + cur
if psp != "" {
id = name + ":" + psp + ":" + cur
}
_ = s.Ledger.Open(ledger.Account{ID: id, Currency: cur, Kind: k, AllowNegative: name == "psp_receivable"})
return id
}
func (s *Service) emit(p *intent.Intent, topic, payload string) {
s.Outbox.Append(outbox.Event{ID: fmt.Sprintf("evt_%s_v%d", p.ID, p.Version), Topic: topic, Key: p.ID, Payload: payload, CreatedAt: s.now()})
}
func (s *Service) lastAttempt(id string) *Attempt {
if as := s.attempts[id]; len(as) > 0 {
return as[len(as)-1]
}
return nil
}
func (s *Service) newAttemptLocked(id, psp string) *Attempt {
a := &Attempt{IntentID: id, PSP: psp, Key: fmt.Sprintf("%s:attempt:%d", id, len(s.attempts[id])+1), State: "sent", FirstSentAt: s.now()}
s.attempts[id] = append(s.attempts[id], a)
return a
}
// setAttempt records a failure state; it never overwrites a result that is already known
// (done) or retained for booking (unbooked), e.g. by a webhook that arrived meanwhile.
func (s *Service) setAttempt(a *Attempt, st string) {
s.mu.Lock()
defer s.mu.Unlock()
if a.State == "done" || a.State == "unbooked" {
return
}
a.State = st
}
func (s *Service) lastPSP(id string) string {
as := s.attempts[id]
if len(as) == 0 {
return ""
}
return as[len(as)-1].PSP
}
func (s *Service) lastRef(id string) string {
as := s.attempts[id]
if len(as) == 0 {
return ""
}
return as[len(as)-1].PSPRef
}package payment
import (
"context"
"errors"
"fmt"
"sync"
"academy/payment-processing-architecture/intent"
)
// ErrBadRef: the PSP does not know the payment reference (a real PSP answers 404 / 400).
var ErrBadRef = errors.New("psp: unknown payment reference")
// FakePSP behaves like a provider with server-side idempotency keys.
type FakePSP struct {
ID string
mu sync.Mutex
// LoseResponses: the next N Authorize calls process the charge, then return ErrTimeout.
LoseResponses int
// Down: refuse every call before processing (ErrUnavailable).
Down bool
// Decline with this code instead of succeeding.
DeclineCode string
// LookupDown makes the status query fail too (a full PSP outage after the charge).
LookupDown bool
// Require3DS answers requires_action.
Require3DS bool
byKey map[string]Result
reqAmount map[string]int64 // parameters stored with each key, like a PSP's key store
refs map[string]bool // payment references this PSP issued
Charges int // real money movements (distinct keys processed)
// AuthorizeCalls counts every Authorize call that reached the PSP.
AuthorizeCalls int
// BeforeAuthorizeReturn runs (outside the fake's lock) just before a successful
// Authorize returns: tests deliver the webhook "first" from here.
BeforeAuthorizeReturn func(Result)
// LoseCaptureResponses: the next N Capture calls process the capture, then return ErrTimeout.
LoseCaptureResponses int
// BeforeCaptureReturn runs (outside the lock) after a capture was processed.
BeforeCaptureReturn func()
Refunds map[string]int64
// LoseRefundResponses: the next N Refund calls process the refund, then return ErrTimeout.
LoseRefundResponses int
// TimeoutBeforeRefund: the next N Refund calls time out WITHOUT processing.
TimeoutBeforeRefund int
// RefundErr: after processing the refund, return this error (e.g. a connection reset).
RefundErr error
// RefundCalls counts every Refund call that reached the PSP.
RefundCalls int
// Captures records each distinct capture key and its amount.
Captures map[string]int64
}
func (f *FakePSP) Name() string { return f.ID }
func (f *FakePSP) Authorize(ctx context.Context, r ChargeRequest) (Result, error) {
res, err := f.authorize(r)
if err == nil && f.BeforeAuthorizeReturn != nil {
f.BeforeAuthorizeReturn(res)
}
return res, err
}
func (f *FakePSP) authorize(r ChargeRequest) (Result, error) {
f.mu.Lock()
defer f.mu.Unlock()
f.AuthorizeCalls++
if f.Down {
return Result{}, ErrUnavailable
}
if f.byKey == nil {
f.byKey, f.reqAmount, f.refs = map[string]Result{}, map[string]int64{}, map[string]bool{}
}
res, seen := f.byKey[r.IdempotencyKey]
if seen && f.reqAmount[r.IdempotencyKey] != r.Amount {
return Result{}, ErrKeyReuse
}
if !seen {
f.reqAmount[r.IdempotencyKey] = r.Amount
res = Result{PSPRef: fmt.Sprintf("%s_ch_%d", f.ID, len(f.byKey)+1), Outcome: intent.PSPSucceeded, Amount: r.Amount}
switch {
case f.DeclineCode != "":
res.Outcome, res.DeclineCode = intent.PSPDeclined, f.DeclineCode
case f.Require3DS:
res.Outcome = intent.PSPActionReq
case r.ManualCapture:
res.Outcome = intent.PSPAuthorized
}
if res.Outcome != intent.PSPSucceeded {
res.Amount = 0
}
f.byKey[r.IdempotencyKey] = res
f.refs[res.PSPRef] = true
if res.Outcome == intent.PSPSucceeded || res.Outcome == intent.PSPAuthorized {
f.Charges++
}
}
if f.LoseResponses > 0 {
f.LoseResponses--
return Result{}, ErrTimeout
}
return res, nil
}
func (f *FakePSP) Lookup(ctx context.Context, key string) (Result, bool, error) {
f.mu.Lock()
defer f.mu.Unlock()
if f.LookupDown {
return Result{}, false, ErrTimeout
}
r, ok := f.byKey[key]
return r, ok, nil
}
func (f *FakePSP) Capture(ctx context.Context, key, ref string, amount int64) error {
if err := f.capture(key, ref, amount); err != nil {
return err
}
if f.BeforeCaptureReturn != nil {
f.BeforeCaptureReturn()
}
return nil
}
func (f *FakePSP) capture(key, ref string, amount int64) error {
f.mu.Lock()
defer f.mu.Unlock()
if f.Down {
return ErrUnavailable
}
if !f.refs[ref] {
return ErrBadRef
}
if f.Captures == nil {
f.Captures = map[string]int64{}
}
if prev, dup := f.Captures[key]; dup && prev != amount {
return ErrKeyReuse // a real PSP rejects a reused key with different parameters
}
f.Captures[key] = amount
if f.LoseCaptureResponses > 0 {
f.LoseCaptureResponses--
return ErrTimeout
}
return nil
}
func (f *FakePSP) Refund(ctx context.Context, key, ref string, amount int64) error {
f.mu.Lock()
defer f.mu.Unlock()
f.RefundCalls++
if f.Refunds == nil {
f.Refunds = map[string]int64{}
}
if f.Down {
return ErrUnavailable
}
if !f.refs[ref] {
return ErrBadRef // the fake no longer hides a lost reference
}
if f.TimeoutBeforeRefund > 0 {
f.TimeoutBeforeRefund--
return ErrTimeout
}
if prev, dup := f.Refunds[key]; dup && prev != amount {
return ErrKeyReuse
}
f.Refunds[key] = amount
if f.RefundErr != nil {
return f.RefundErr
}
if f.LoseRefundResponses > 0 {
f.LoseRefundResponses--
return ErrTimeout
}
return nil
}
// RefundedTotal is the money this PSP actually sent back.
func (f *FakePSP) RefundedTotal() int64 {
f.mu.Lock()
defer f.mu.Unlock()
var n int64
for _, a := range f.Refunds {
n += a
}
return n
}package payment
import (
"context"
"errors"
"testing"
"time"
"academy/payment-processing-architecture/idem"
"academy/payment-processing-architecture/intent"
"academy/payment-processing-architecture/outbox"
)
func newSvc(psps ...PSP) *Service { return NewService(200*time.Millisecond, psps...) }
func TestCreateIsIdempotent(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe"})
a, replayed, err := s.Create("m_1", "order-77", 1099, "USD", "order-77")
if err != nil || replayed {
t.Fatal(err)
}
b, replayed, err := s.Create("m_1", "order-77", 1099, "USD", "order-77")
if err != nil || !replayed || a.ID != b.ID {
t.Fatalf("want the same intent, got %s vs %s", a.ID, b.ID)
}
if _, _, err := s.Create("m_1", "order-77", 5000, "USD", "order-77"); !errors.Is(err, idem.ErrMismatch) {
t.Fatalf("same key, other amount: want mismatch, got %v", err)
}
}
func TestLostResponseChargesOnce(t *testing.T) {
psp := &FakePSP{ID: "stripe", LoseResponses: 1}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "k1", 2500, "USD", "o1")
got, err := s.Confirm(context.Background(), p.ID, "pm_card_visa", false)
if err != nil || got.Status != intent.Succeeded {
t.Fatalf("got %s %v", got.Status, err)
}
// a client retry of the whole confirm call changes nothing
_, _ = s.Confirm(context.Background(), p.ID, "pm_card_visa", false)
if psp.Charges != 1 {
t.Fatalf("PSP charged %d times", psp.Charges)
}
if s.Ledger.Balance("sales:USD") != 2500 || len(s.Ledger.Journal()) != 1 {
t.Fatalf("ledger: sales=%d rows=%d", s.Ledger.Balance("sales:USD"), len(s.Ledger.Journal()))
}
if n := len(s.Outbox.Pending(10)); n != 1 {
t.Fatalf("want 1 outbox event, got %d", n)
}
}
func TestAmbiguousOutcomeIsParkedNotFailedOver(t *testing.T) {
primary := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}
backup := &FakePSP{ID: "adyen"}
s := newSvc(primary, backup)
p, _, _ := s.Create("m_1", "k2", 4000, "EUR", "o2")
got, err := s.Confirm(context.Background(), p.ID, "pm_x", false)
if !errors.Is(err, ErrAmbiguous) || got.Status != intent.RequiresConfirmation {
t.Fatalf("got %s %v, want requires_confirmation + ErrAmbiguous", got.Status, err)
}
if backup.Charges != 0 {
t.Fatal("failing over after an ambiguous outcome risks a double charge")
}
if u := s.UnknownAttempts(); len(u) != 1 || u[0].Key != p.ID+":attempt:1" {
t.Fatalf("unknown attempts: %+v", u)
}
// PSP recovers: retry resumes the SAME key at the SAME PSP
primary.LoseResponses, primary.LookupDown = 0, false
got, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
if got.Status != intent.Succeeded || primary.Charges != 1 {
t.Fatalf("status %s charges %d", got.Status, primary.Charges)
}
}
func TestFailoverOnlyWhenProvablyNotProcessed(t *testing.T) {
primary := &FakePSP{ID: "stripe", Down: true}
backup := &FakePSP{ID: "adyen"}
s := newSvc(primary, backup)
p, _, _ := s.Create("m_1", "k3", 1500, "GBP", "o3")
got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
if got.Status != intent.Succeeded || backup.Charges != 1 || primary.Charges != 0 {
t.Fatalf("status %s primary %d backup %d", got.Status, primary.Charges, backup.Charges)
}
if s.Ledger.Balance("psp_receivable:adyen:GBP") != 1500 {
t.Fatal("receivable must be booked against the PSP that charged")
}
}
func TestDeclineEmitsFailureAndNoLedger(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe", DeclineCode: "insufficient_funds"})
p, _, _ := s.Create("m_1", "k4", 999, "USD", "o4")
got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
if got.Status != intent.RequiresPaymentMethod || len(s.Ledger.Journal()) != 0 {
t.Fatalf("got %s", got.Status)
}
ev := s.Outbox.Pending(10)
if len(ev) != 1 || ev[0].Topic != "payments.payment_failed" {
t.Fatalf("got %+v", ev)
}
}
func TestAuthorizePartialCaptureRefund(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "k5", 10_000, "USD", "hotel-1")
got, _ := s.Confirm(context.Background(), p.ID, "pm_x", true)
if got.Status != intent.RequiresCapture || len(s.Ledger.Journal()) != 0 {
t.Fatalf("a hold is not revenue; got %s", got.Status)
}
if _, err := s.Capture(context.Background(), p.ID, 8_250); err != nil {
t.Fatal(err)
}
if err := s.Refund(context.Background(), p.ID, "rf-1", 1_000); err != nil {
t.Fatal(err)
}
if err := s.Refund(context.Background(), p.ID, "rf-2", 8_000); err == nil {
t.Fatal("refund above captured amount must fail")
}
if s.Ledger.Balance("sales:USD")-s.Ledger.Balance("refunds:USD") != 7_250 {
t.Fatal("net revenue wrong")
}
for cur, v := range s.Ledger.TrialBalance() {
if v != 0 {
t.Fatalf("trial balance %s=%d", cur, v)
}
}
}
func TestWebhookDuplicatesAndStaleEvents(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe", Require3DS: true})
p, _, _ := s.Create("m_1", "k6", 3000, "EUR", "o6")
got, _ := s.Confirm(context.Background(), p.ID, "pm_x", false)
if got.Status != intent.RequiresAction {
t.Fatalf("got %s", got.Status)
}
if ok, err := webhook(s, "evt_1", p.ID, intent.PSPSucceeded, 3000, refOf(s, p.ID)); !ok || err != nil {
t.Fatalf("first delivery: %v %v", ok, err)
}
if ok, _ := webhook(s, "evt_1", p.ID, intent.PSPSucceeded, 3000, refOf(s, p.ID)); ok {
t.Fatal("duplicate delivery applied twice")
}
if ok, _ := webhook(s, "evt_0", p.ID, intent.PSPActionReq, 0, refOf(s, p.ID)); ok {
t.Fatal("older event applied after success")
}
if s.Ledger.Balance("sales:EUR") != 3000 {
t.Fatal("ledger posted twice or not at all")
}
}
type countingPublisher struct{ n int }
func (c *countingPublisher) Publish(context.Context, outbox.Event) error { c.n++; return nil }
func TestOutboxRelayAndConsumerDedup(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe"})
p, _, _ := s.Create("m_1", "k7", 100, "USD", "o7")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
pub := &countingPublisher{}
n, _ := outbox.RelayOnce(context.Background(), s.Outbox, pub, time.Now)
if n != 1 || len(s.Outbox.Pending(10)) != 0 {
t.Fatalf("relayed %d", n)
}
var in outbox.Inbox
if !in.FirstTime("evt_pi_0001_v2") || in.FirstTime("evt_pi_0001_v2") {
t.Fatal("inbox must accept an event id once")
}
}
func TestRefundIsCheckedBeforeThePSPAndReplaySafe(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "k8", 5_000, "USD", "o8")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
if err := s.Refund(context.Background(), p.ID, "rf-big", 6_000); !errors.Is(err, ErrRefund) {
t.Fatalf("over-refund: %v", err)
}
if len(psp.Refunds) != 0 {
t.Fatal("an over-refund must never reach the PSP")
}
for i := 0; i < 2; i++ { // client retries the same refund
if err := s.Refund(context.Background(), p.ID, "rf-a", 2_000); err != nil {
t.Fatal(err)
}
}
got, _ := s.Get(p.ID)
if got.AmountRefunded != 2_000 || s.Ledger.Balance("refunds:USD") != 2_000 || len(psp.Refunds) != 1 {
t.Fatalf("refunded %d, ledger %d, psp %d", got.AmountRefunded, s.Ledger.Balance("refunds:USD"), len(psp.Refunds))
}
q, _, _ := s.Create("m_1", "k9", 100, "USD", "o9")
if err := s.Refund(context.Background(), q.ID, "rf-none", 100); !errors.Is(err, ErrRefund) {
t.Fatalf("refund of an unpaid intent: %v", err)
}
}
func TestWebhookForUnknownIntentIsRetriedLater(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe", Require3DS: true})
if _, err := webhook(s, "evt_early", "pi_9999", intent.PSPSucceeded, 700, refOf(s, "pi_9999")); !errors.Is(err, ErrNotFound) {
t.Fatalf("want not found, got %v", err)
}
p, _, _ := s.Create("m_1", "k10", 700, "USD", "o10") // becomes pi_0001
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
if _, err := webhook(s, "evt_x", p.ID+"-missing", intent.PSPSucceeded, 700, refOf(s, p.ID+"-missing")); err == nil {
t.Fatal("want error")
}
if ok, err := webhook(s, "evt_x", p.ID, intent.PSPSucceeded, 700, refOf(s, p.ID)); !ok || err != nil {
t.Fatalf("redelivery after a failure must be processed: %v %v", ok, err)
}
}
func TestConcurrentRefundsCannotOverRefund(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "k11", 1_000, "USD", "o11")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
errs := make(chan error, 2)
for _, k := range []string{"rf-x", "rf-y"} {
go func(k string) { errs <- s.Refund(context.Background(), p.ID, k, 700) }(k)
}
var ok, refused int
for i := 0; i < 2; i++ {
if err := <-errs; err == nil {
ok++
} else if errors.Is(err, ErrRefund) || errors.Is(err, ErrInFlight) {
refused++
}
}
got, _ := s.Get(p.ID)
if ok != 1 || refused != 1 || len(psp.Refunds) != 1 || got.AmountRefunded != 700 {
t.Fatalf("ok=%d refused=%d psp=%d refunded=%d", ok, refused, len(psp.Refunds), got.AmountRefunded)
}
}تستهای درهمتنیدگی اجرا و شکست (Interleaving and failure tests): هرکدام در نسخهای قبلی از سرویس شکست میخوردند؛ testHook ترتیب درهمتنیدهٔ اجرا را تحمیل میکند:
package payment
import (
"context"
"errors"
"sync"
"testing"
"academy/payment-processing-architecture/intent"
)
// Finding 3: two concurrent Confirm calls must not create two provider keys. Since round 2
// the second caller is refused with ErrInFlight while the first holds the payment.
func TestConcurrentConfirmChargesOnce(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "r1", 2_500, "USD", "r1")
arrived, gate := make(chan struct{}, 1), make(chan struct{})
s.testHook = func(pt string) {
if pt == "confirm:after-lookup" {
arrived <- struct{}{}
<-gate
}
}
var wg sync.WaitGroup
wg.Add(1)
go func() { defer wg.Done(); _, _ = s.Confirm(context.Background(), p.ID, "pm_x", false) }()
<-arrived // A has chosen its attempt and is about to charge
_, errB := s.Confirm(context.Background(), p.ID, "pm_x", false)
close(gate)
wg.Wait()
if !errors.Is(errB, ErrInFlight) || psp.Charges != 1 || len(s.Ledger.Journal()) != 1 {
t.Fatalf("errB=%v PSP charges=%d journal rows=%d, want ErrInFlight, 1, 1", errB, psp.Charges, len(s.Ledger.Journal()))
}
}
// Finding 4a: the reservation must hold until the refund is booked.
func TestRefundReservationHeldUntilBooked(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "r2", 1_000, "USD", "r2")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
var errB error
s.testHook = func(pt string) {
if pt == "refund:before-booking" {
s.testHook = nil
errB = s.Refund(context.Background(), p.ID, "rf-b", 700) // B runs while A is not booked yet
}
}
errA := s.Refund(context.Background(), p.ID, "rf-a", 700)
if errA != nil || !(errors.Is(errB, ErrRefund) || errors.Is(errB, ErrInFlight)) || len(psp.Refunds) != 1 {
t.Fatalf("errA=%v errB=%v psp refunds=%d, want nil, ErrRefund, 1", errA, errB, len(psp.Refunds))
}
}
// Finding 4b: an ambiguous PSP refund error keeps the amount reserved.
func TestAmbiguousRefundKeepsReservation(t *testing.T) {
psp := &FakePSP{ID: "stripe", LoseRefundResponses: 1}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "r3", 1_000, "USD", "r3")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
if err := s.Refund(context.Background(), p.ID, "rf-a", 700); err == nil {
t.Fatal("want an error for the lost refund response")
}
if err := s.Refund(context.Background(), p.ID, "rf-b", 700); !errors.Is(err, ErrRefund) {
t.Fatalf("second refund after an unknown one: %v, want ErrRefund", err)
}
if len(psp.Refunds) != 1 {
t.Fatalf("PSP refunds = %d, want 1", len(psp.Refunds))
}
if pr := s.PendingRefunds(); len(pr) != 1 || pr[0].Key != "rf-a" || pr[0].Amount != 700 {
t.Fatalf("pending refunds: %+v", pr)
}
// the same key later resolves it: booked once, reservation released
if err := s.Refund(context.Background(), p.ID, "rf-a", 700); err != nil {
t.Fatal(err)
}
got, _ := s.Get(p.ID)
if got.AmountRefunded != 700 || len(s.PendingRefunds()) != 0 || s.Ledger.Balance("refunds:USD") != 700 {
t.Fatalf("refunded=%d pending=%d ledger=%d", got.AmountRefunded, len(s.PendingRefunds()), s.Ledger.Balance("refunds:USD"))
}
}
// Finding 4c: a provable refusal frees the reservation again.
func TestRefusedRefundReleasesReservation(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "r6", 1_000, "USD", "r6")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", false)
psp.Down = true
if err := s.Refund(context.Background(), p.ID, "rf-a", 700); !errors.Is(err, ErrUnavailable) {
t.Fatalf("got %v, want ErrUnavailable", err)
}
psp.Down = false
if err := s.Refund(context.Background(), p.ID, "rf-b", 700); err != nil {
t.Fatalf("amount must be free again: %v", err)
}
}
// Finding 9: a verified success webhook completes a manual-capture intent.
func TestSuccessWebhookCompletesManualCapture(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe"})
p, _, _ := s.Create("m_1", "r4", 5_000, "USD", "r4")
got, _ := s.Confirm(context.Background(), p.ID, "pm_x", true)
if got.Status != intent.RequiresCapture {
t.Fatalf("got %s", got.Status)
}
ok, err := webhook(s, "evt_cap", p.ID, intent.PSPSucceeded, 5_000, refOf(s, p.ID))
got, _ = s.Get(p.ID)
if !ok || err != nil || got.Status != intent.Succeeded || s.Ledger.Balance("sales:USD") != 5_000 {
t.Fatalf("applied=%v err=%v status=%s sales=%d", ok, err, got.Status, s.Ledger.Balance("sales:USD"))
}
}
// Finding 10: Capture must call the PSP before booking, and book nothing if the PSP refuses.
func TestCaptureCallsPSPFirst(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "r5", 10_000, "USD", "r5")
_, _ = s.Confirm(context.Background(), p.ID, "pm_x", true)
psp.Down = true
if _, err := s.Capture(context.Background(), p.ID, 8_250); err == nil {
t.Fatal("PSP down: capture must fail")
}
if got, _ := s.Get(p.ID); got.Status != intent.RequiresCapture || len(s.Ledger.Journal()) != 0 {
t.Fatalf("booked without the PSP: %s, %d rows", got.Status, len(s.Ledger.Journal()))
}
psp.Down = false
if _, err := s.Capture(context.Background(), p.ID, 8_250); err != nil {
t.Fatal(err)
}
if len(psp.Captures) != 1 || s.Ledger.Balance("sales:USD") != 8_250 {
t.Fatalf("PSP captures=%d sales=%d", len(psp.Captures), s.Ledger.Balance("sales:USD"))
}
}package payment
import (
"context"
"errors"
"math"
"testing"
"academy/payment-processing-architecture/intent"
)
var bg = context.Background()
// refused reports an error that means "not done, nothing sent": a business refusal or 409.
func refused(err error) bool { return errors.Is(err, ErrRefund) || errors.Is(err, ErrInFlight) }
// N1: A is refused by the primary and pauses before failing over; B runs the whole flow.
func TestFailoverRaceChargesOnce(t *testing.T) {
primary, backup := &FakePSP{ID: "stripe", Down: true}, &FakePSP{ID: "adyen"}
s := newSvc(primary, backup)
p, _, _ := s.Create("m_1", "n1", 1_500, "GBP", "n1")
s.testHook = func(pt string) {
if pt == "confirm:before-fallback" {
s.testHook = nil
_, _ = s.Confirm(bg, p.ID, "pm_x", false) // B
}
}
_, _ = s.Confirm(bg, p.ID, "pm_x", false) // A
if backup.Charges != 1 {
t.Fatalf("backup charged %d times, want 1", backup.Charges)
}
}
// N2: an unknown attempt is never superseded because a later retry was refused.
func TestRefusalDoesNotProveAnEarlierUnknownAttempt(t *testing.T) {
primary, backup := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}, &FakePSP{ID: "adyen"}
s := newSvc(primary, backup)
p, _, _ := s.Create("m_1", "n2", 4_000, "EUR", "n2")
_, _ = s.Confirm(bg, p.ID, "pm_x", false) // processed at the PSP, answer lost: unknown
primary.LoseResponses, primary.LookupDown, primary.Down = 0, false, true
_, _ = s.Confirm(bg, p.ID, "pm_x", false) // retry refused before processing
primary.Down = false
got, _ := s.Confirm(bg, p.ID, "pm_x", false) // recovery
if primary.Charges != 1 || backup.Charges != 0 || got.Status != intent.Succeeded {
t.Fatalf("primary=%d backup=%d status=%s, want 1, 0, succeeded", primary.Charges, backup.Charges, got.Status)
}
}
func captured(t *testing.T, psp *FakePSP, key string, amount int64) (*Service, string) {
t.Helper()
s := newSvc(psp)
p, _, _ := s.Create("m_1", key, amount, "USD", key)
if got, _ := s.Confirm(bg, p.ID, "pm_x", false); got.Status != intent.Succeeded {
t.Fatalf("setup: %s", got.Status)
}
return s, p.ID
}
// N3a: an unknown refund keeps its reservation even if a retry is refused.
func TestUnknownRefundSurvivesRetryRefusal(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s, id := captured(t, psp, "n3a", 1_000)
psp.LoseRefundResponses = 1
_ = s.Refund(bg, id, "rf-a", 700) // refunded at the PSP, answer lost
psp.Down = true
_ = s.Refund(bg, id, "rf-a", 700) // retry refused
psp.Down = false
if err := s.Refund(bg, id, "rf-b", 700); !refused(err) {
t.Fatalf("second refund: %v, want refused", err)
}
if len(psp.Refunds) != 1 {
t.Fatalf("PSP refunds %d, want 1", len(psp.Refunds))
}
}
// N3b: an unclassified error after sending is an unknown outcome, not "not processed".
func TestUnclassifiedRefundErrorIsUnknown(t *testing.T) {
psp := &FakePSP{ID: "stripe", RefundErr: errors.New("read tcp: connection reset by peer")}
s, id := captured(t, psp, "n3b", 1_000)
_ = s.Refund(bg, id, "rf-a", 700)
psp.RefundErr = nil
if err := s.Refund(bg, id, "rf-b", 700); !refused(err) {
t.Fatalf("second refund: %v, want refused", err)
}
}
// N4: two failing calls with the same key must not release one reservation twice.
func TestDuplicateRefundFailuresDoNotUnderflowReservation(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s, id := captured(t, psp, "n4", 1_000)
psp.LoseRefundResponses = 1
_ = s.Refund(bg, id, "rf-a", 700) // unknown: 700 reserved
psp.Down = true
s.testHook = func(pt string) {
if pt == "refund:before-booking" {
s.testHook = nil
_ = s.Refund(bg, id, "rf-a", 700) // concurrent duplicate, also refused
}
}
_ = s.Refund(bg, id, "rf-a", 700)
psp.Down = false
calls := psp.RefundCalls
if err := s.Refund(bg, id, "rf-c", 1_500); !refused(err) {
t.Fatalf("refund above the captured amount: %v", err)
}
if psp.RefundCalls != calls {
t.Fatal("an over-refund reached the PSP")
}
}
// N5: a partial capture reported by webhook books the captured amount, not the hold.
func TestPartialCaptureReportedByWebhookFirst(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "n5", 10_000, "USD", "n5")
_, _ = s.Confirm(bg, p.ID, "pm_x", true)
s.testHook = func(pt string) {
if pt == "capture:after-psp" {
s.testHook = nil
_, _ = webhook(s, "evt_cap", p.ID, intent.PSPSucceeded, 8_250, refOf(s, p.ID)) // webhook beats the response
}
}
_, _ = s.Capture(bg, p.ID, 8_250)
got, _ := s.Get(p.ID)
if got.AmountReceived != 8_250 || s.Ledger.Balance("sales:USD") != 8_250 {
t.Fatalf("received=%d sales=%d, want 8250 both", got.AmountReceived, s.Ledger.Balance("sales:USD"))
}
}
// N6: a competing capture with another amount for the same key is rejected.
func TestCompetingCaptureAmounts(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "n6", 10_000, "USD", "n6")
_, _ = s.Confirm(bg, p.ID, "pm_x", true)
var errB error
s.testHook = func(pt string) {
if pt == "capture:after-psp" {
s.testHook = nil
_, errB = s.Capture(bg, p.ID, 9_000)
}
}
_, errA := s.Capture(bg, p.ID, 8_250)
if errA != nil || errB == nil || s.Ledger.Balance("sales:USD") != 8_250 || psp.Captures["capture:"+p.ID] != 8_250 {
t.Fatalf("errA=%v errB=%v sales=%d psp=%d", errA, errB, s.Ledger.Balance("sales:USD"), psp.Captures["capture:"+p.ID])
}
}
// N10: a failed posting leaves the intent unchanged, and a later retry repairs it.
func TestFailedPostingDoesNotCompleteTheIntent(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big, _, _ := s.Create("m_1", "n10a", math.MaxInt64, "USD", "n10a")
_, _ = s.Confirm(bg, big.ID, "pm_x", false)
small, _, _ := s.Create("m_1", "n10b", 1, "USD", "n10b")
if _, err := s.Confirm(bg, small.ID, "pm_x", false); err == nil {
t.Fatal("posting overflowed: Confirm must report it")
}
if got, _ := s.Get(small.ID); got.Status == intent.Succeeded {
t.Fatal("intent marked succeeded without its journal entry")
}
if _, err := s.Ledger.Reverse("capture:"+big.ID, "rev:"+big.ID, "make room"); err != nil {
t.Fatal(err)
}
got, err := s.Confirm(bg, small.ID, "pm_x", false)
if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
t.Fatalf("repair: err=%v status=%s charges=%d", err, got.Status, psp.Charges)
}
found := false
for _, tx := range s.Ledger.Journal() {
found = found || tx.ID == "capture:"+small.ID
}
if !found {
t.Fatal("repair did not post the capture")
}
}
// N11: one payment per merchant and order, whatever the client key.
func TestOnePaymentPerOrder(t *testing.T) {
s := newSvc(&FakePSP{ID: "stripe"})
if _, _, err := s.Create("m_1", "key-a", 100, "USD", "order-9"); err != nil {
t.Fatal(err)
}
if _, _, err := s.Create("m_1", "key-b", 100, "USD", "order-9"); err == nil {
t.Fatal("a second client key for the same order must be rejected")
}
}
// N12: a completed refund key replays only for the same payment and amount.
func TestCompletedRefundKeyChecksParameters(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s, a := captured(t, psp, "n12a", 1_000)
b, _, _ := s.Create("m_1", "n12b", 1_000, "USD", "n12b")
_, _ = s.Confirm(bg, b.ID, "pm_x", false)
if err := s.Refund(bg, a, "K", 100); err != nil {
t.Fatal(err)
}
if err := s.Refund(bg, b.ID, "K", 100); err == nil {
t.Fatal("key K on another payment must be rejected")
}
if err := s.Refund(bg, a, "K", 200); err == nil {
t.Fatal("key K with another amount must be rejected")
}
if err := s.Refund(bg, a, "K", 100); err != nil {
t.Fatalf("exact replay: %v", err)
}
}
// The only exits for an unknown refund: the same key succeeds, or reconciliation resolves it.
func TestResolveRefundAfterLookup(t *testing.T) {
psp := &FakePSP{ID: "stripe", TimeoutBeforeRefund: 1} // times out BEFORE processing
s, id := captured(t, psp, "res", 1_000)
_ = s.Refund(bg, id, "rf-a", 700) // unknown (nothing happened at the PSP)
if err := s.ResolveRefund("rf-a", false); err != nil { // lookup: the PSP has no such refund
t.Fatal(err)
}
if err := s.Refund(bg, id, "rf-b", 700); err != nil {
t.Fatalf("amount must be free after a proven non-refund: %v", err)
}
psp.LoseRefundResponses = 1
_ = s.Refund(bg, id, "rf-c", 300) // unknown again
if err := s.ResolveRefund("rf-c", true); err != nil { // lookup: refunded
t.Fatal(err)
}
if got, _ := s.Get(id); got.AmountRefunded != 1_000 || s.Ledger.Balance("refunds:USD") != 1_000 {
t.Fatalf("refunded=%d ledger=%d", got.AmountRefunded, s.Ledger.Balance("refunds:USD"))
}
if ext := psp.RefundedTotal(); ext != 1_000 { // N26: the PSP's own total must agree
t.Fatalf("PSP refunded %d in total, booked 1000", ext)
}
}package payment
import (
"math"
"sync"
"testing"
"time"
"academy/payment-processing-architecture/intent"
)
// fillSales books a MaxInt64 USD payment so the next USD capture posting overflows.
func fillSales(t *testing.T, s *Service) string {
t.Helper()
big, _, _ := s.Create("m_1", "fill", math.MaxInt64, "USD", "fill")
if got, err := s.Confirm(bg, big.ID, "pm_x", false); err != nil || got.Status != intent.Succeeded {
t.Fatalf("fill: %v %s", err, got.Status)
}
return big.ID
}
func makeRoom(t *testing.T, s *Service, txID string) {
t.Helper()
if _, err := s.Ledger.Reverse(txID, "rev:"+txID, "make room"); err != nil {
t.Fatal(err)
}
}
// N16: a delayed decline for attempt 1 must not touch attempt 2's unbooked success.
func TestStaleDeclineWebhookDoesNotTouchLaterAttempt(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n16", 10, "USD", "n16")
psp.DeclineCode = "insufficient_funds"
_, _ = s.Confirm(bg, x.ID, "pm_x", false) // attempt 1 declined
psp.DeclineCode = ""
_, _ = s.Confirm(bg, x.ID, "pm_x", false) // attempt 2 charged, posting overflows: unbooked
ref1 := s.attempts[x.ID][0].PSPRef
_, _ = webhook(s, "evt_late_decline", x.ID, intent.PSPDeclined, 0, ref1)
makeRoom(t, s, "capture:"+big)
got, err := s.Confirm(bg, x.ID, "pm_x", false)
if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
t.Fatalf("err=%v status=%s charges=%d, want succeeded and 2 charges (fill + one)", err, got.Status, psp.Charges)
}
}
// N18: success webhook before the synchronous answer; the reference must survive.
func TestWebhookFirstSuccessKeepsReference(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "n18", 1_000, "USD", "n18")
psp.BeforeAuthorizeReturn = func(r Result) {
psp.BeforeAuthorizeReturn = nil
_, _ = webhook(s, "evt_first", p.ID, intent.PSPSucceeded, r.Amount, r.PSPRef)
}
if got, err := s.Confirm(bg, p.ID, "pm_x", false); err != nil || got.Status != intent.Succeeded {
t.Fatalf("confirm: %v %s", err, got.Status)
}
if err := s.Refund(bg, p.ID, "rf-1", 100); err != nil {
t.Fatalf("refund after a webhook-first success: %v", err)
}
}
// N19: a rejected capture must not read the intent after unlocking (run with -race).
func TestRejectedCaptureCloneIsRaceFree(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
p, _, _ := s.Create("m_1", "n19", 10_000, "USD", "n19")
_, _ = s.Confirm(bg, p.ID, "pm_x", true)
var wg sync.WaitGroup
psp.BeforeCaptureReturn = func() {
psp.BeforeCaptureReturn = nil
wg.Add(1)
go func() { defer wg.Done(); _, _ = s.Capture(bg, p.ID, 8_250) }() // B: refused, busy
time.Sleep(20 * time.Millisecond) // no synchronisation with B on purpose
}
if _, err := s.Capture(bg, p.ID, 8_250); err != nil {
t.Fatal(err)
}
wg.Wait()
}
// N31: UnknownAttempts must not expose the stored result.
func TestUnknownAttemptsReturnsCopies(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n31", 10, "USD", "n31")
_, _ = s.Confirm(bg, x.ID, "pm_x", false) // unbooked
for _, a := range s.UnknownAttempts() {
if a.Result != nil {
a.Result.Outcome = intent.PSPDeclined
}
}
makeRoom(t, s, "capture:"+big)
got, err := s.Confirm(bg, x.ID, "pm_x", false)
if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
t.Fatalf("err=%v status=%s charges=%d", err, got.Status, psp.Charges)
}
}
// N17: after the resend window an unknown attempt or refund is never sent again.
func TestNoResendAfterTheWindow(t *testing.T) {
clock := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
psp := &FakePSP{ID: "stripe", LoseResponses: 5, LookupDown: true}
s := newSvc(psp)
s.now = func() time.Time { return clock }
p, _, _ := s.Create("m_1", "n17", 1_000, "USD", "n17")
_, _ = s.Confirm(bg, p.ID, "pm_x", false) // unknown
clock = clock.Add(25 * time.Hour)
psp.LoseResponses, psp.LookupDown = 0, false
calls := psp.AuthorizeCalls
if _, err := s.Confirm(bg, p.ID, "pm_x", false); err == nil || psp.AuthorizeCalls != calls {
t.Fatalf("resent after the window: err=%v calls %d -> %d", err, calls, psp.AuthorizeCalls)
}
q := &FakePSP{ID: "stripe"}
s2, id := captured(t, q, "n17r", 1_000)
clk := time.Date(2026, 11, 28, 9, 0, 0, 0, time.UTC)
s2.now = func() time.Time { return clk }
q.LoseRefundResponses = 1
_ = s2.Refund(bg, id, "rf-a", 300) // unknown
clk = clk.Add(25 * time.Hour)
rc := q.RefundCalls
if err := s2.Refund(bg, id, "rf-a", 300); err == nil || q.RefundCalls != rc {
t.Fatalf("refund resent after the window: err=%v calls %d -> %d", err, rc, q.RefundCalls)
}
}
// N25: a capture whose PSP call succeeded but whose posting failed is booked on retry
// without calling the PSP again (it may be down by then).
func TestUnbookedCaptureIsBookedWithoutThePSP(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n25c", 10, "USD", "n25c")
_, _ = s.Confirm(bg, x.ID, "pm_x", true) // hold, nothing posted
if _, err := s.Capture(bg, x.ID, 10); err == nil {
t.Fatal("posting overflow must be reported")
}
makeRoom(t, s, "capture:"+big)
psp.Down = true
if got, err := s.Capture(bg, x.ID, 10); err != nil || got.Status != intent.Succeeded {
t.Fatalf("retry must book the known capture: %v %s", err, got.Status)
}
}
// N25: the same for a refund.
func TestUnbookedRefundIsBookedWithoutThePSP(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
if err := s.Refund(bg, big, "rf-big", math.MaxInt64); err != nil { // refunds:USD = MaxInt64
t.Fatal(err)
}
makeRoom(t, s, "capture:"+big)
x, _, _ := s.Create("m_1", "n25r", 10, "USD", "n25r")
_, _ = s.Confirm(bg, x.ID, "pm_x", false)
if err := s.Refund(bg, x.ID, "rf-x", 5); err == nil {
t.Fatal("refund posting overflow must be reported")
}
makeRoom(t, s, "refund:rf-big")
psp.Down = true
if err := s.Refund(bg, x.ID, "rf-x", 5); err != nil {
t.Fatalf("retry must book the known refund: %v", err)
}
if got, _ := s.Get(x.ID); got.AmountRefunded != 5 {
t.Fatalf("refunded %d", got.AmountRefunded)
}
}package payment
import (
"testing"
"academy/payment-processing-architecture/intent"
)
// N32: a delayed synchronous answer must not erase a success the webhook retained.
func TestDelayedResponseKeepsRetainedWebhookSuccess(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n32", 10, "USD", "n32")
psp.BeforeAuthorizeReturn = func(r Result) { // the hold exists; it is captured at the PSP and
psp.BeforeAuthorizeReturn = nil // the success webhook arrives before our authorize answer
if _, err := webhook(s, "evt_cap", x.ID, intent.PSPSucceeded, 10, r.PSPRef); err == nil {
t.Error("webhook posting should overflow")
}
}
_, _ = s.Confirm(bg, x.ID, "pm_x", true) // the late PSPAuthorized answer is applied now
makeRoom(t, s, "capture:"+big)
got, err := s.Confirm(bg, x.ID, "pm_x", true)
if err != nil || got.Status != intent.Succeeded || got.AmountReceived != 10 {
t.Fatalf("retained success lost: err=%v status=%s received=%d", err, got.Status, got.AmountReceived)
}
}
// N33: a webhook validated while its attempt was latest must not apply after supersession.
func TestWebhookCannotApplyAfterItsAttemptWasSuperseded(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n33", 10, "USD", "n33")
arrived, release, done := make(chan struct{}), make(chan struct{}), make(chan struct{})
s.testHook = func(pt string) {
if pt == "webhook:window" {
close(arrived)
<-release
}
}
psp.DeclineCode = "insufficient_funds"
psp.BeforeAuthorizeReturn = func(r Result) {
psp.BeforeAuthorizeReturn = nil
go func() { _, _ = webhook(s, "evt_a_decline", x.ID, intent.PSPDeclined, 0, r.PSPRef); close(done) }()
<-arrived // A's decline webhook is past its checks
}
_, _ = s.Confirm(bg, x.ID, "pm_x", false) // A: declined synchronously
s.testHook = nil
psp.DeclineCode = ""
_, _ = s.Confirm(bg, x.ID, "pm_x", false) // B: charged, posting overflows -> unbooked
close(release)
<-done
makeRoom(t, s, "capture:"+big)
got, err := s.Confirm(bg, x.ID, "pm_x", false)
if err != nil || got.Status != intent.Succeeded || psp.Charges != 2 {
t.Fatalf("err=%v status=%s charges=%d, want succeeded, 2", err, got.Status, psp.Charges)
}
}
// N35: Capture repair books a success the webhook retained, without calling the PSP.
func TestCaptureRepairUsesWebhookRetainedSuccess(t *testing.T) {
psp := &FakePSP{ID: "stripe"}
s := newSvc(psp)
big := fillSales(t, s)
x, _, _ := s.Create("m_1", "n35", 10, "USD", "n35")
_, _ = s.Confirm(bg, x.ID, "pm_x", true)
psp.LoseCaptureResponses = 1
_, _ = s.Capture(bg, x.ID, 10) // captured at the PSP, answer lost
if _, err := webhook(s, "evt_cap", x.ID, intent.PSPSucceeded, 10, refOf(s, x.ID)); err == nil {
t.Fatal("webhook posting should overflow")
}
makeRoom(t, s, "capture:"+big)
psp.Down = true
got, err := s.Capture(bg, x.ID, 10)
if err != nil || got.Status != intent.Succeeded {
t.Fatalf("capture retry must book the retained success: %v %s", err, got.Status)
}
}package payment
import "academy/payment-processing-architecture/intent"
// webhook delivers a verified event carrying its PSP reference.
func webhook(s *Service, evt, id string, ev intent.Event, amount int64, ref string) (bool, error) {
return s.HandleWebhook(evt, id, ev, amount, ref)
}
// refOf returns the reference of the payment's latest attempt (what the PSP's event carries).
func refOf(s *Service, id string) string {
s.mu.Lock()
defer s.mu.Unlock()
if a := s.lastAttempt(id); a != nil {
return a.PSPRef
}
return "ref_unknown"
}بررسی امضای Webhook با روش دستی Stripe؛ raw body، همهٔ v1ها، constant time و tolerance:
// Package webhook verifies Stripe-Signature headers by the manual scheme in
// docs.stripe.com/webhooks ("Verify webhook signatures manually"):
// split on ",", keep t and every v1, HMAC-SHA256(secret, t + "." + raw body),
// constant-time compare, then check the timestamp against a tolerance.
// In production prefer stripe-go's webhook.ConstructEvent (DefaultTolerance 300 s).
package webhook
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"errors"
"strconv"
"strings"
"time"
)
var (
ErrNoTimestamp = errors.New("webhook: header has no t= entry")
ErrNoSignatures = errors.New("webhook: header has no v1= entry")
ErrNoMatch = errors.New("webhook: no v1 signature matches")
ErrTooOld = errors.New("webhook: timestamp outside tolerance")
ErrBadTolerance = errors.New("webhook: tolerance must be > 0 (0 disables the replay check)")
)
// Verifier holds every active secret: during a secret roll Stripe keeps the old one
// valid for up to 7 days and sends one v1 per secret.
type Verifier struct {
Secrets [][]byte
Tolerance time.Duration
Now func() time.Time
}
// Verify authenticates the raw, unmodified body.
func (v Verifier) Verify(body []byte, header string) error {
if v.Tolerance <= 0 {
return ErrBadTolerance
}
now := time.Now
if v.Now != nil {
now = v.Now
}
var ts int64
var haveTS bool
var sigs [][]byte
for _, item := range strings.Split(header, ",") {
k, val, ok := strings.Cut(strings.TrimSpace(item), "=")
if !ok {
continue
}
switch k {
case "t":
n, err := strconv.ParseInt(val, 10, 64)
if err != nil {
return ErrNoTimestamp
}
ts, haveTS = n, true
case "v1":
if b, err := hex.DecodeString(val); err == nil {
sigs = append(sigs, b)
}
default:
// v0 (sandbox only), secret, destination, payload: debug data, never trusted
}
}
if !haveTS {
return ErrNoTimestamp
}
if len(sigs) == 0 {
return ErrNoSignatures
}
matched := false
for _, secret := range v.Secrets {
want := sign(secret, ts, body)
for _, got := range sigs {
if hmac.Equal(want, got) { // constant time
matched = true
}
}
}
if !matched {
return ErrNoMatch
}
age := now().Sub(time.Unix(ts, 0))
if age > v.Tolerance || age < -v.Tolerance {
return ErrTooOld
}
return nil
}
// Header builds a header the way Stripe does (for tests and the Stripe CLI-style lab).
func Header(secret []byte, ts time.Time, body []byte) string {
return "t=" + strconv.FormatInt(ts.Unix(), 10) + ",v1=" + hex.EncodeToString(sign(secret, ts.Unix(), body))
}
func sign(secret []byte, ts int64, body []byte) []byte {
m := hmac.New(sha256.New, secret)
m.Write([]byte(strconv.FormatInt(ts, 10)))
m.Write([]byte("."))
m.Write(body)
return m.Sum(nil)
}package webhook
import (
"errors"
"testing"
"time"
)
var (
secret = []byte("whsec_test_secret")
body = []byte(`{"id":"evt_1","type":"payment_intent.succeeded","data":{"object":{"id":"pi_1"}}}`)
t0 = time.Unix(1798765432, 0)
)
func verifier(now time.Time, secrets ...[]byte) Verifier {
if len(secrets) == 0 {
secrets = [][]byte{secret}
}
return Verifier{Secrets: secrets, Tolerance: 5 * time.Minute, Now: func() time.Time { return now }}
}
func TestValid(t *testing.T) {
if err := verifier(t0.Add(30*time.Second)).Verify(body, Header(secret, t0, body)); err != nil {
t.Fatal(err)
}
}
func TestTamperedBody(t *testing.T) {
h := Header(secret, t0, body)
changed := []byte(`{"id":"evt_1", "type":"payment_intent.succeeded","data":{"object":{"id":"pi_1"}}}`) // one extra space
if err := verifier(t0).Verify(changed, h); !errors.Is(err, ErrNoMatch) {
t.Fatalf("got %v", err)
}
}
func TestReplayOutsideTolerance(t *testing.T) {
if err := verifier(t0.Add(6*time.Minute)).Verify(body, Header(secret, t0, body)); !errors.Is(err, ErrTooOld) {
t.Fatalf("got %v", err)
}
}
func TestOnlyV0IsRejected(t *testing.T) {
h := "t=1798765432,v0=6ffbb59b2300aae63f272406069a9788598b792a944a07aba816edb039989a39"
if err := verifier(t0).Verify(body, h); !errors.Is(err, ErrNoSignatures) {
t.Fatalf("got %v", err)
}
}
func TestUnknownEntriesAndAnyOrder(t *testing.T) {
h := "payload=a25aefc6,destination=we_123," + Header(secret, t0, body) + ",secret=whsec_****"
if err := verifier(t0).Verify(body, h); err != nil {
t.Fatal(err)
}
}
func TestSecretRollTwoV1(t *testing.T) {
old, cur := []byte("whsec_old"), []byte("whsec_new")
h := Header(old, t0, body) + ",v1=" + Header(cur, t0, body)[len("t=1798765432,v1="):]
if err := verifier(t0, cur).Verify(body, h); err != nil {
t.Fatalf("new secret alone must verify: %v", err)
}
if err := verifier(t0, []byte("whsec_other")).Verify(body, h); !errors.Is(err, ErrNoMatch) {
t.Fatalf("got %v", err)
}
}
func TestZeroToleranceIsAConfigError(t *testing.T) {
v := verifier(t0)
v.Tolerance = 0
if err := v.Verify(body, Header(secret, t0, body)); !errors.Is(err, ErrBadTolerance) {
t.Fatalf("got %v", err)
}
}Outbox و Inbox:
// Package outbox gives exactly-once effects from at-least-once delivery: events are
// written in the same transaction as the state change, a relay publishes them (maybe twice),
// and consumers drop duplicates by event ID. Mechanics: /messaging/outbox-pattern.
package outbox
import (
"context"
"sync"
"time"
)
// Event is one row of the outbox table.
type Event struct {
ID string // unique, used by consumers for dedup
Topic string // e.g. payments.payment_succeeded
Key string // partition key: the payment ID keeps per-payment order
Payload string
CreatedAt time.Time
PublishedAt time.Time
}
// Outbox is the table; Append is called inside the business transaction.
type Outbox struct {
mu sync.Mutex
events []Event
}
// Append adds an event (caller holds the business transaction).
func (o *Outbox) Append(e Event) {
o.mu.Lock()
defer o.mu.Unlock()
o.events = append(o.events, e)
}
// Pending returns unpublished events in insertion order.
func (o *Outbox) Pending(limit int) []Event {
o.mu.Lock()
defer o.mu.Unlock()
var out []Event
for _, e := range o.events {
if e.PublishedAt.IsZero() {
out = append(out, e)
if len(out) == limit {
break
}
}
}
return out
}
func (o *Outbox) markPublished(id string, at time.Time) {
o.mu.Lock()
defer o.mu.Unlock()
for i := range o.events {
if o.events[i].ID == id {
o.events[i].PublishedAt = at
}
}
}
// Publisher is the broker client (Kafka, RabbitMQ, SNS...).
type Publisher interface {
Publish(ctx context.Context, e Event) error
}
// RelayOnce publishes pending events; a crash between Publish and markPublished
// re-sends the event on the next run, which is why consumers must dedupe.
func RelayOnce(ctx context.Context, o *Outbox, p Publisher, now func() time.Time) (int, error) {
n := 0
for _, e := range o.Pending(100) {
if err := p.Publish(ctx, e); err != nil {
return n, err // stop to keep per-key order; retry later
}
o.markPublished(e.ID, now())
n++
}
return n, nil
}
// Inbox is the consumer-side dedup table (unique event_id).
type Inbox struct {
mu sync.Mutex
seen map[string]bool
}
// FirstTime records id and reports whether it is new. In SQL this is
// INSERT ... ON CONFLICT DO NOTHING in the same transaction as the side effect.
func (in *Inbox) FirstTime(id string) bool {
in.mu.Lock()
defer in.mu.Unlock()
if in.seen == nil {
in.seen = map[string]bool{}
}
if in.seen[id] {
return false
}
in.seen[id] = true
return true
}
// Forget removes id so a redelivery is processed again (the side effect failed).
func (in *Inbox) Forget(id string) {
in.mu.Lock()
defer in.mu.Unlock()
delete(in.seen, id)
}Saga پرداخت با void بهعنوان compensation و فهرست dead-letter:
// Package checkout runs an order checkout as an orchestrated saga: reserve stock,
// authorize the card (manual capture), book the shipment, capture. Each step has a
// compensation; when a later step fails, the completed steps are undone in reverse order
// (release stock, void the authorization). A compensation that keeps failing is parked
// on a dead-letter list for a human or a later sweep. Mechanics: /messaging/saga-pattern.
package checkout
import (
"context"
"errors"
"fmt"
)
// Step is one local transaction and its compensation. Both must be idempotent: the
// orchestrator may run either again after a crash, with the same key.
type Step struct {
Name string
Do func(ctx context.Context, key string) error
Undo func(ctx context.Context, key string) error // nil: nothing to undo (e.g. capture is last)
}
// Parked is a compensation that did not succeed.
type Parked struct {
Saga, Step string
Err error
}
// Orchestrator runs sagas and keeps a dead-letter list.
type Orchestrator struct {
UndoTries int
DeadLetter []Parked
Log []string
}
var ErrCompensated = errors.New("checkout: saga failed and was compensated")
// Run executes steps in order. key is the saga id; each step receives key+":"+name as its
// idempotency key, so a retried step never double-reserves or double-authorizes.
func (o *Orchestrator) Run(ctx context.Context, key string, steps []Step) error {
tries := o.UndoTries
if tries <= 0 {
tries = 3
}
for i, s := range steps {
if err := s.Do(ctx, key+":"+s.Name); err != nil {
o.Log = append(o.Log, "fail "+s.Name)
for j := i - 1; j >= 0; j-- {
u := steps[j]
if u.Undo == nil {
continue
}
var uerr error
for t := 0; t < tries; t++ {
if uerr = u.Undo(ctx, key+":"+u.Name); uerr == nil {
break
}
}
if uerr != nil {
o.DeadLetter = append(o.DeadLetter, Parked{Saga: key, Step: u.Name, Err: uerr})
o.Log = append(o.Log, "parked undo "+u.Name)
continue
}
o.Log = append(o.Log, "undo "+u.Name)
}
return fmt.Errorf("%w: step %s: %v", ErrCompensated, s.Name, err)
}
o.Log = append(o.Log, "do "+s.Name)
}
return nil
}package checkout
import (
"context"
"errors"
"strings"
"testing"
)
type fakes struct {
reserved, authorized map[string]bool
voids int
voidFails int
shipFails bool
}
func (f *fakes) steps() []Step {
return []Step{
{Name: "reserve_stock",
Do: func(_ context.Context, k string) error { f.reserved[k] = true; return nil },
Undo: func(_ context.Context, k string) error { delete(f.reserved, k); return nil }},
{Name: "authorize",
Do: func(_ context.Context, k string) error { f.authorized[k] = true; return nil },
Undo: func(_ context.Context, k string) error { // void the hold
if f.voidFails > 0 {
f.voidFails--
return errors.New("psp: timeout")
}
f.voids++
delete(f.authorized, k)
return nil
}},
{Name: "book_shipment", Do: func(context.Context, string) error {
if f.shipFails {
return errors.New("carrier: no slot")
}
return nil
}},
{Name: "capture", Do: func(context.Context, string) error { return nil }},
}
}
func newFakes() *fakes { return &fakes{reserved: map[string]bool{}, authorized: map[string]bool{}} }
func TestHappyPath(t *testing.T) {
f, o := newFakes(), &Orchestrator{}
if err := o.Run(context.Background(), "order-1", f.steps()); err != nil {
t.Fatal(err)
}
if strings.Join(o.Log, ",") != "do reserve_stock,do authorize,do book_shipment,do capture" {
t.Fatal(o.Log)
}
}
func TestShipmentFailureVoidsAndReleases(t *testing.T) {
f, o := newFakes(), &Orchestrator{}
f.shipFails = true
err := o.Run(context.Background(), "order-2", f.steps())
if !errors.Is(err, ErrCompensated) {
t.Fatal(err)
}
if f.voids != 1 || len(f.reserved) != 0 || len(f.authorized) != 0 {
t.Fatalf("voids=%d reserved=%v authorized=%v", f.voids, f.reserved, f.authorized)
}
if got := strings.Join(o.Log, ","); got != "do reserve_stock,do authorize,fail book_shipment,undo authorize,undo reserve_stock" {
t.Fatal(got)
}
}
func TestVoidThatKeepsFailingIsDeadLettered(t *testing.T) {
f, o := newFakes(), &Orchestrator{UndoTries: 2}
f.shipFails, f.voidFails = true, 5
_ = o.Run(context.Background(), "order-3", f.steps())
if len(o.DeadLetter) != 1 || o.DeadLetter[0].Step != "authorize" {
t.Fatalf("dead letter: %+v", o.DeadLetter)
}
if len(f.reserved) != 0 {
t.Fatal("the other compensations must still run")
}
}Chargeback در ledger؛ کارمزد در صورت برد باقی میماند:
// Package dispute books a card chargeback in the double-entry ledger. When a cardholder
// disputes a payment, the PSP debits the disputed amount plus a dispute fee from the
// merchant balance at once (Stripe: "Debits the disputed amount, plus a dispute fee");
// winning returns the amount, and Stripe never returns the dispute received fee.
package dispute
import (
"errors"
"fmt"
"academy/payment-processing-architecture/ledger"
)
// Status mirrors Stripe's dispute statuses for a formal chargeback.
type Status string
const (
NeedsResponse Status = "needs_response"
UnderReview Status = "under_review"
Won Status = "won"
Lost Status = "lost"
)
var ErrState = errors.New("dispute: invalid transition")
// Dispute is one chargeback against one captured payment.
type Dispute struct {
ID, PaymentID, PSP, Currency string
Amount, Fee int64
Status Status
}
// accounts opens the accounts it needs (idempotent) and returns their ids.
func accounts(l *ledger.Ledger, psp, cur string) (receivable, losses, fees string) {
receivable = "psp_receivable:" + psp + ":" + cur
losses, fees = "chargeback_losses:"+cur, "dispute_fees:"+cur
_ = l.Open(ledger.Account{ID: receivable, Currency: cur, Kind: ledger.Asset, AllowNegative: true})
_ = l.Open(ledger.Account{ID: losses, Currency: cur, Kind: ledger.Expense})
_ = l.Open(ledger.Account{ID: fees, Currency: cur, Kind: ledger.Expense})
return
}
// Open books the immediate debit. The posting id is derived from the dispute id, so a
// duplicate charge.dispute.created webhook posts nothing.
func Open(l *ledger.Ledger, d *Dispute) error {
recv, losses, fees := accounts(l, d.PSP, d.Currency)
entries := []ledger.Entry{{Account: losses, Direction: ledger.Debit, Amount: d.Amount}}
if d.Fee > 0 { // some networks (e.g. Cartes Bancaires in SEPA on Stripe) charge no received fee
entries = append(entries, ledger.Entry{Account: fees, Direction: ledger.Debit, Amount: d.Fee})
}
entries = append(entries, ledger.Entry{Account: recv, Direction: ledger.Credit, Amount: d.Amount + d.Fee})
_, _, err := l.Post(ledger.Transaction{ID: "dispute_opened:" + d.ID, Description: "chargeback " + d.PaymentID, Entries: entries})
if err == nil {
d.Status = NeedsResponse
}
return err
}
// SubmitEvidence moves the dispute to review (the issuer decides, typically in 60-75 days).
func SubmitEvidence(d *Dispute) error {
if d.Status != NeedsResponse {
return fmt.Errorf("%w: evidence in %s", ErrState, d.Status)
}
d.Status = UnderReview
return nil
}
// Close books the outcome. Won: the disputed amount comes back, the fee does not.
// Lost: nothing moves; the loss booked at Open stays.
func Close(l *ledger.Ledger, d *Dispute, won bool) error {
if d.Status != UnderReview && d.Status != NeedsResponse {
return fmt.Errorf("%w: close in %s", ErrState, d.Status)
}
if !won {
d.Status = Lost
return nil
}
recv, losses, _ := accounts(l, d.PSP, d.Currency)
_, _, err := l.Post(ledger.Transaction{ID: "dispute_won:" + d.ID, Description: "chargeback reversed " + d.PaymentID,
Entries: []ledger.Entry{
{Account: recv, Direction: ledger.Debit, Amount: d.Amount},
{Account: losses, Direction: ledger.Credit, Amount: d.Amount},
}})
if err == nil {
d.Status = Won
}
return err
}package dispute
import (
"testing"
"academy/payment-processing-architecture/ledger"
)
func TestWonDisputeReturnsAmountButNotFee(t *testing.T) {
l := ledger.New(nil)
d := &Dispute{ID: "dp_1", PaymentID: "pi_1", PSP: "stripe", Currency: "USD", Amount: 5_000, Fee: 1_500}
if err := Open(l, d); err != nil {
t.Fatal(err)
}
if err := Open(l, d); err != nil { // duplicate webhook
t.Fatal(err)
}
if got := l.Balance("psp_receivable:stripe:USD"); got != -6_500 {
t.Fatalf("receivable after open: %d", got)
}
if err := SubmitEvidence(d); err != nil {
t.Fatal(err)
}
if err := Close(l, d, true); err != nil {
t.Fatal(err)
}
if l.Balance("chargeback_losses:USD") != 0 || l.Balance("dispute_fees:USD") != 1_500 {
t.Fatalf("losses %d fees %d", l.Balance("chargeback_losses:USD"), l.Balance("dispute_fees:USD"))
}
if len(l.Journal()) != 2 || l.TrialBalance()["USD"] != 0 {
t.Fatal("want exactly two balanced postings")
}
}
func TestLostDisputeKeepsTheLoss(t *testing.T) {
l := ledger.New(nil)
d := &Dispute{ID: "dp_2", PaymentID: "pi_2", PSP: "adyen", Currency: "EUR", Amount: 2_000, Fee: 0}
if err := Open(l, d); err != nil { // no fee line when the fee is zero
t.Fatal(err)
}
if err := Close(l, d, false); err != nil || d.Status != Lost {
t.Fatal(err)
}
if err := SubmitEvidence(d); err == nil {
t.Fatal("no evidence after the outcome")
}
if l.Balance("chargeback_losses:EUR") != 2_000 {
t.Fatal("loss must stay booked")
}
}موتور تقلب و ریسک: velocity، rule، threshold امتیاز و بودجهٔ مدل:
// Package fraud is a small real-time decision engine: velocity counters, ordered rules,
// a risk score with a hard latency budget, and four outcomes (allow, request 3DS, review, block).
// The default thresholds mirror Stripe Radar's documented ones: 65+ elevated, 75+ high.
package fraud
import (
"context"
"sort"
"strings"
"sync"
"time"
)
// Action is the decision.
type Action string
const (
Allow Action = "allow"
Request3D Action = "request_3ds" // step-up: SCA challenge, liability shift to the issuer
Review Action = "review" // human review queue
Block Action = "block"
)
// Payment holds the features known at decision time.
type Payment struct {
AmountUSD int64 // minor units, normalized
CardFingerprint string // PSP's stable card id, never the PAN
BIN string // first 6-8 digits: issuer, country, debit/credit/prepaid
CardCountry string
IPCountry string
IP string
DeviceID string // device fingerprint from the checkout SDK
Email string
CustomerAgeDays int
Is3DSCapable bool
At time.Time
}
// Velocity counts events per key in a sliding window.
type Velocity struct {
mu sync.Mutex
window time.Duration
hits map[string][]time.Time
}
// NewVelocity returns a counter with the given window.
func NewVelocity(w time.Duration) *Velocity {
return &Velocity{window: w, hits: map[string][]time.Time{}}
}
// Add records one event and returns the count in the window, including this one.
func (v *Velocity) Add(key string, at time.Time) int {
v.mu.Lock()
defer v.mu.Unlock()
keep := v.hits[key][:0]
for _, t := range v.hits[key] {
if at.Sub(t) < v.window {
keep = append(keep, t)
}
}
keep = append(keep, at)
v.hits[key] = keep
return len(keep)
}
// Signals are derived features.
type Signals struct {
CardsPerDevice int // distinct attempts per device in the window: card testing
AttemptsPerCard int
AttemptsPerIP int
Score int // 0-99, -1 when the model missed its budget
}
// Rule is one line of the rules engine.
type Rule struct {
Name string
Action Action
When func(p Payment, s Signals) bool
}
// Scorer is the ML model behind a network call.
type Scorer interface {
Score(ctx context.Context, p Payment) (int, error)
}
// Engine evaluates in a fixed order: allow-list, block, review, request-3DS, then score.
type Engine struct {
Allowlist map[string]bool // trusted card fingerprints
Rules []Rule
Model Scorer
ModelBudget time.Duration // e.g. 50 ms of a ~300 ms checkout budget
ReviewAt int // default 65
BlockAt int // default 75
byDevice *Velocity
byCard *Velocity
byIP *Velocity
}
// NewEngine uses 10-minute velocity windows and Radar-like thresholds.
func NewEngine(model Scorer, rules ...Rule) *Engine {
return &Engine{Allowlist: map[string]bool{}, Rules: rules, Model: model, ModelBudget: 50 * time.Millisecond,
ReviewAt: 65, BlockAt: 75,
byDevice: NewVelocity(10 * time.Minute), byCard: NewVelocity(10 * time.Minute), byIP: NewVelocity(10 * time.Minute)}
}
// Decision is the answer with its reasons (store it: you need it for disputes and tuning).
type Decision struct {
Action Action
Score int
Reasons []string
}
// Decide never blocks longer than the model budget; if the model is late it decides on rules.
func (e *Engine) Decide(ctx context.Context, p Payment) Decision {
e.byDevice.Add("dev:"+p.DeviceID+"|"+p.CardFingerprint, p.At)
s := Signals{
CardsPerDevice: e.distinctCards(p.DeviceID, p.At),
AttemptsPerCard: e.byCard.Add("card:"+p.CardFingerprint, p.At),
AttemptsPerIP: e.byIP.Add("ip:"+p.IP, p.At),
Score: -1,
}
if e.Allowlist[p.CardFingerprint] {
return Decision{Action: Allow, Score: -1, Reasons: []string{"allowlist"}}
}
if e.Model != nil {
mctx, cancel := context.WithTimeout(ctx, e.ModelBudget)
if sc, err := e.Model.Score(mctx, p); err == nil {
s.Score = sc
}
cancel()
}
var reasons []string
best := Allow
for _, r := range e.ordered() {
if r.When(p, s) {
reasons = append(reasons, r.Name)
if rank(r.Action) > rank(best) {
best = r.Action
}
}
}
switch {
case s.Score >= e.BlockAt:
reasons = append(reasons, "score>=block")
best = Block
case s.Score >= e.ReviewAt && rank(best) < rank(Review):
reasons = append(reasons, "score>=review")
if p.Is3DSCapable {
best = Request3D // cheaper than a human: let the issuer authenticate
} else {
best = Review
}
case s.Score < 0:
reasons = append(reasons, "model_timeout:rules_only")
}
return Decision{Action: best, Score: s.Score, Reasons: reasons}
}
// distinctCards counts card fingerprints seen on one device inside the window.
func (e *Engine) distinctCards(device string, at time.Time) int {
e.byDevice.mu.Lock()
defer e.byDevice.mu.Unlock()
n := 0
prefix := "dev:" + device + "|"
for k, v := range e.byDevice.hits {
if !strings.HasPrefix(k, prefix) {
continue
}
for _, t := range v {
if at.Sub(t) < e.byDevice.window {
n++
break
}
}
}
return n
}
func (e *Engine) ordered() []Rule {
rs := append([]Rule(nil), e.Rules...)
sort.SliceStable(rs, func(i, j int) bool { return rank(rs[i].Action) > rank(rs[j].Action) })
return rs
}
func rank(a Action) int {
switch a {
case Block:
return 3
case Review:
return 2
case Request3D:
return 1
}
return 0
}
// DefaultRules is a starting set; tune each with backtests before turning it on.
func DefaultRules() []Rule {
return []Rule{
{"card_testing: >5 cards on one device in 10m", Block, func(p Payment, s Signals) bool { return s.CardsPerDevice > 5 }},
{"velocity: >3 attempts per card in 10m", Review, func(p Payment, s Signals) bool { return s.AttemptsPerCard > 3 }},
{"geo: card country != IP country and amount > 250 USD", Request3D, func(p Payment, s Signals) bool {
return p.CardCountry != p.IPCountry && p.AmountUSD > 25_000
}},
{"new customer, large first order", Request3D, func(p Payment, s Signals) bool {
return p.CustomerAgeDays < 1 && p.AmountUSD > 50_000
}},
}
}package fraud
import (
"context"
"fmt"
"testing"
"time"
)
type fixedScore int
func (f fixedScore) Score(context.Context, Payment) (int, error) { return int(f), nil }
type slowModel struct{}
func (slowModel) Score(ctx context.Context, _ Payment) (int, error) {
select {
case <-ctx.Done():
return 0, ctx.Err()
case <-time.After(time.Second):
return 10, nil
}
}
var t0 = time.Date(2026, 11, 26, 12, 0, 0, 0, time.UTC)
func base() Payment {
return Payment{AmountUSD: 4_999, CardFingerprint: "fp_1", BIN: "424242", CardCountry: "US", IPCountry: "US",
IP: "203.0.113.7", DeviceID: "dev_1", CustomerAgeDays: 400, Is3DSCapable: true, At: t0}
}
func TestLowRiskAllowed(t *testing.T) {
d := NewEngine(fixedScore(12), DefaultRules()...).Decide(context.Background(), base())
if d.Action != Allow {
t.Fatalf("got %+v", d)
}
}
func TestScoreThresholds(t *testing.T) {
if d := NewEngine(fixedScore(70), DefaultRules()...).Decide(context.Background(), base()); d.Action != Request3D {
t.Fatalf("elevated + 3DS-capable card should step up, got %+v", d)
}
p := base()
p.Is3DSCapable = false
if d := NewEngine(fixedScore(70), DefaultRules()...).Decide(context.Background(), p); d.Action != Review {
t.Fatalf("elevated without 3DS should go to review, got %+v", d)
}
if d := NewEngine(fixedScore(80), DefaultRules()...).Decide(context.Background(), base()); d.Action != Block {
t.Fatalf("got %+v", d)
}
}
func TestCardTestingIsBlocked(t *testing.T) {
e := NewEngine(fixedScore(5), DefaultRules()...)
var d Decision
for i := 0; i < 7; i++ {
p := base()
p.CardFingerprint = fmt.Sprintf("fp_%d", i)
p.AmountUSD = 100
p.At = t0.Add(time.Duration(i) * time.Second)
d = e.Decide(context.Background(), p)
}
if d.Action != Block {
t.Fatalf("7 cards on one device in seconds: got %+v", d)
}
}
func TestGeoMismatchStepsUp(t *testing.T) {
p := base()
p.IPCountry, p.AmountUSD = "NL", 30_000
if d := NewEngine(fixedScore(20), DefaultRules()...).Decide(context.Background(), p); d.Action != Request3D {
t.Fatalf("got %+v", d)
}
}
func TestModelTimeoutFallsBackToRules(t *testing.T) {
e := NewEngine(slowModel{}, DefaultRules()...)
start := time.Now()
d := e.Decide(context.Background(), base())
if time.Since(start) > 200*time.Millisecond {
t.Fatal("decision exceeded the latency budget")
}
if d.Action != Allow || d.Score != -1 {
t.Fatalf("got %+v", d)
}
}
func TestAllowlistWins(t *testing.T) {
e := NewEngine(fixedScore(99), DefaultRules()...)
e.Allowlist["fp_1"] = true
if d := e.Decide(context.Background(), base()); d.Action != Allow {
t.Fatalf("got %+v", d)
}
}Dunning: رد soft و hard و برنامهٔ محدود:
// Package dunning decides whether and when to retry a failed recurring charge.
// Hard declines need a new payment method; soft declines are retried on a schedule
// that stops after a maximum number of attempts or a maximum duration (Stripe's default
// Smart Retries policy for new accounts: up to 8 retries within 2 weeks).
package dunning
import "time"
// hard is the list Stripe documents as "can't automatically retry" for subscriptions.
var hard = map[string]bool{
"incorrect_number": true, "lost_card": true, "pickup_card": true, "stolen_card": true,
"revocation_of_authorization": true, "revocation_of_all_authorizations": true,
"authentication_required": true, "highest_risk_level": true, "transaction_not_allowed": true,
}
// Kind of a decline.
type Kind int
const (
Soft Kind = iota // retry later: insufficient_funds, try_again_later, processing_error...
Hard // stop: ask the customer for a new card (or for authentication)
)
// Classify maps a decline code to Soft or Hard. Unknown codes are Soft but count toward the cap.
func Classify(code string) Kind {
if hard[code] {
return Hard
}
return Soft
}
// Policy is a fixed retry schedule (a "smart" schedule replaces Delays with a model's choice).
type Policy struct {
Delays []time.Duration // delay after attempt 1, 2, 3...
MaxAttempts int // including the first attempt
MaxDuration time.Duration // from the first failure
}
// Default retries 1, 2, 4 and 6 days after each failure (days 1, 3, 7 and 13):
// at most 5 attempts, all inside 14 days.
func Default() Policy {
d := 24 * time.Hour
return Policy{Delays: []time.Duration{d, 2 * d, 4 * d, 6 * d}, MaxAttempts: 5, MaxDuration: 14 * d}
}
// Decision tells the billing job what to do next.
type Decision struct {
Retry bool
At time.Time
Notify bool // e-mail the customer (update card / authenticate)
Outcome string // retry, needs_new_payment_method, exhausted
}
// Next is called after attempt number `attempt` (1-based) failed with `code`.
func (p Policy) Next(attempt int, code string, firstFailure, now time.Time) Decision {
if Classify(code) == Hard {
return Decision{Notify: true, Outcome: "needs_new_payment_method"}
}
if attempt >= p.MaxAttempts || attempt > len(p.Delays) {
return Decision{Notify: true, Outcome: "exhausted"}
}
at := now.Add(p.Delays[attempt-1])
if at.Sub(firstFailure) > p.MaxDuration {
return Decision{Notify: true, Outcome: "exhausted"}
}
return Decision{Retry: true, At: at, Notify: attempt == 1, Outcome: "retry"}
}package dunning
import (
"testing"
"time"
)
func TestHardDeclineStopsImmediately(t *testing.T) {
now := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
d := Default().Next(1, "stolen_card", now, now)
if d.Retry || d.Outcome != "needs_new_payment_method" || !d.Notify {
t.Fatalf("got %+v", d)
}
}
func TestSoftDeclineFollowsScheduleThenStops(t *testing.T) {
p := Default()
first := time.Date(2026, 11, 1, 9, 0, 0, 0, time.UTC)
now := first
var outcomes []string
for attempt := 1; attempt <= 6; attempt++ {
d := p.Next(attempt, "insufficient_funds", first, now)
outcomes = append(outcomes, d.Outcome)
if !d.Retry {
break
}
now = d.At
}
want := []string{"retry", "retry", "retry", "retry", "exhausted"}
if len(outcomes) != len(want) {
t.Fatalf("got %v", outcomes)
}
for i := range want {
if outcomes[i] != want[i] {
t.Fatalf("got %v, want %v", outcomes, want)
}
}
// retries on days 1, 3, 7 and 13; attempt 5 fails on day 13: exhausted by the attempt cap.
if now.Sub(first) != 13*24*time.Hour {
t.Fatalf("last retry at %v", now.Sub(first))
}
}Reconciliation با settlement file:
// Package recon matches our payment records against a PSP settlement file
// (for example a Stripe payout reconciliation report or an Adyen settlement detail report,
// reduced here to five columns). It finds what each side has that the other does not.
package recon
import (
"encoding/csv"
"errors"
"fmt"
"io"
"sort"
"strconv"
"time"
)
// Row is one settled line: psp_ref,type,gross,fee,currency.
type Row struct {
PSPRef string
Type string // charge, refund, chargeback, fee
Gross int64
Fee int64
Currency string
}
// Record is what our database says.
type Record struct {
PSPRef string // empty when the attempt is "unknown" (no answer from the PSP)
IntentKey string // our provider idempotency key
Amount int64
Currency string
CreatedAt time.Time
}
// Report is the outcome; every non-empty list is a ticket or an automatic fix.
type Report struct {
Matched int
MissingAtPSP []Record // we booked it, PSP did not settle it (yet): investigate after the cutoff
MissingLocally []Row // PSP settled money we never booked: ambiguous outcome or a bug
AmountMismatch []string
Fees int64
}
// ParseCSV reads the file with a header line.
func ParseCSV(r io.Reader) ([]Row, error) {
cr := csv.NewReader(r)
all, err := cr.ReadAll()
if err != nil {
return nil, err
}
if len(all) == 0 {
return nil, errors.New("recon: empty file")
}
var out []Row
for i, rec := range all[1:] {
if len(rec) != 5 {
return nil, fmt.Errorf("recon: line %d: want 5 columns", i+2)
}
gross, err1 := strconv.ParseInt(rec[2], 10, 64)
fee, err2 := strconv.ParseInt(rec[3], 10, 64)
if err1 != nil || err2 != nil {
return nil, fmt.Errorf("recon: line %d: amounts must be integer minor units", i+2)
}
out = append(out, Row{PSPRef: rec[0], Type: rec[1], Gross: gross, Fee: fee, Currency: rec[4]})
}
return out, nil
}
// Reconcile compares charges. Records newer than cutoff are not yet expected in the file.
func Reconcile(ours []Record, file []Row, cutoff time.Time) Report {
var rep Report
byRef := map[string]Row{}
for _, r := range file {
rep.Fees += r.Fee
if r.Type == "charge" {
byRef[r.PSPRef] = r
}
}
seen := map[string]bool{}
for _, o := range ours {
r, ok := byRef[o.PSPRef]
switch {
case !ok && o.CreatedAt.Before(cutoff):
rep.MissingAtPSP = append(rep.MissingAtPSP, o)
case !ok:
case r.Gross != o.Amount || r.Currency != o.Currency:
rep.AmountMismatch = append(rep.AmountMismatch,
fmt.Sprintf("%s: ours %d %s, psp %d %s", o.PSPRef, o.Amount, o.Currency, r.Gross, r.Currency))
seen[o.PSPRef] = true
default:
rep.Matched++
seen[o.PSPRef] = true
}
}
for ref, r := range byRef {
if !seen[ref] {
rep.MissingLocally = append(rep.MissingLocally, r)
}
}
sort.Slice(rep.MissingLocally, func(i, j int) bool { return rep.MissingLocally[i].PSPRef < rep.MissingLocally[j].PSPRef })
return rep
}package recon
import (
"strings"
"testing"
"time"
)
const file = `psp_ref,type,gross,fee,currency
ch_1,charge,1099,62,USD
ch_2,charge,2500,103,USD
ch_9,charge,4000,146,USD
re_1,refund,-500,0,USD
`
func TestReconcile(t *testing.T) {
rows, err := ParseCSV(strings.NewReader(file))
if err != nil {
t.Fatal(err)
}
day := time.Date(2026, 11, 25, 0, 0, 0, 0, time.UTC)
ours := []Record{
{PSPRef: "ch_1", Amount: 1099, Currency: "USD", CreatedAt: day},
{PSPRef: "ch_2", Amount: 2000, Currency: "USD", CreatedAt: day}, // we booked less
{PSPRef: "ch_3", Amount: 700, Currency: "USD", CreatedAt: day}, // PSP never settled it
{PSPRef: "ch_4", Amount: 800, Currency: "USD", CreatedAt: day.Add(48 * time.Hour)}, // too new to judge
}
rep := Reconcile(ours, rows, day.Add(24*time.Hour))
if rep.Matched != 1 || len(rep.AmountMismatch) != 1 || len(rep.MissingAtPSP) != 1 || rep.MissingAtPSP[0].PSPRef != "ch_3" {
t.Fatalf("got %+v", rep)
}
// ch_9: money moved that we never booked, the classic "unknown attempt" that succeeded
if len(rep.MissingLocally) != 1 || rep.MissingLocally[0].PSPRef != "ch_9" {
t.Fatalf("got %+v", rep.MissingLocally)
}
if rep.Fees != 311 {
t.Fatalf("fees %d", rep.Fees)
}
}
func TestRejectsDecimalAmounts(t *testing.T) {
_, err := ParseCSV(strings.NewReader("psp_ref,type,gross,fee,currency\nch_1,charge,10.99,0.62,USD\n"))
if err == nil {
t.Fatal("a settlement file in major units must be converted explicitly, not parsed as float")
}
}برنامهٔ آزمایشگاه که همهٔ سناریوها را در یک process اجرا میکند:
// Command demo runs the chapter's lab in one process: no PSP, no database, no broker.
package main
import (
"context"
"fmt"
"strings"
"time"
"academy/payment-processing-architecture/checkout"
"academy/payment-processing-architecture/dispute"
"academy/payment-processing-architecture/dunning"
"academy/payment-processing-architecture/fraud"
"academy/payment-processing-architecture/money"
"academy/payment-processing-architecture/payment"
"academy/payment-processing-architecture/recon"
"academy/payment-processing-architecture/webhook"
)
func main() {
ctx := context.Background()
fmt.Println("== 1. lost response, same key, one charge")
stripe := &payment.FakePSP{ID: "stripe", LoseResponses: 1}
adyen := &payment.FakePSP{ID: "adyen"}
svc := payment.NewService(200*time.Millisecond, stripe, adyen)
p, _, _ := svc.Create("m_1", "order-1001", 2500, "USD", "order-1001")
got, _ := svc.Confirm(ctx, p.ID, "pm_card_visa", false)
again, replayed, _ := svc.Create("m_1", "order-1001", 2500, "USD", "order-1001")
fmt.Printf("intent=%s status=%s psp_charges=%d replayed_create=%v same_id=%v\n",
got.ID, got.Status, stripe.Charges, replayed, again.ID == got.ID)
fmt.Println("== 2. ambiguous outcome: park, do not fail over")
stripe.LoseResponses, stripe.LookupDown = 9, true
q, _, _ := svc.Create("m_1", "order-1002", 4000, "USD", "order-1002")
got, _ = svc.Confirm(ctx, q.ID, "pm_card_visa", false)
fmt.Printf("status=%s unknown_attempts=%d adyen_charges=%d\n", got.Status, len(svc.UnknownAttempts()), adyen.Charges)
stripe.LoseResponses, stripe.LookupDown = 0, false
got, _ = svc.Confirm(ctx, q.ID, "pm_card_visa", false)
fmt.Printf("after recovery: status=%s stripe_charges=%d\n", got.Status, stripe.Charges)
fmt.Println("== 3. hold, partial capture, refund, trial balance")
h, _, _ := svc.Create("m_1", "hotel-7", 10000, "USD", "hotel-7")
_, _ = svc.Confirm(ctx, h.ID, "pm_card_visa", true)
_, _ = svc.Capture(ctx, h.ID, 8250)
_ = svc.Refund(ctx, h.ID, "rf-hotel-7-1", 1000)
fmt.Printf("sales=%d refunds=%d receivable=%d trial=%v journal_rows=%d outbox=%d\n",
svc.Ledger.Balance("sales:USD"), svc.Ledger.Balance("refunds:USD"),
svc.Ledger.Balance("psp_receivable:stripe:USD"), svc.Ledger.TrialBalance(),
len(svc.Ledger.Journal()), len(svc.Outbox.Pending(100)))
fmt.Println("== 4. money")
parts, _ := money.Money{Amount: 100, Currency: "USD"}.Allocate(1, 1, 1)
eur, _ := money.Convert(money.Money{Amount: 1000, Currency: "USD"}, "EUR", "0.9235")
fmt.Printf("split 1.00 USD three ways: %v %v %v | 10.00 USD @0.9235 = %v\n", parts[0], parts[1], parts[2], eur)
fmt.Println("== 5. webhook signature")
secret := []byte("whsec_lab")
body := []byte(`{"id":"evt_1","type":"payment_intent.succeeded"}`)
now := time.Unix(1798765432, 0)
v := webhook.Verifier{Secrets: [][]byte{secret}, Tolerance: 5 * time.Minute, Now: func() time.Time { return now }}
fmt.Println("valid:", v.Verify(body, webhook.Header(secret, now, body)))
fmt.Println("tampered:", v.Verify([]byte(strings.Replace(string(body), "evt_1", "evt_2", 1)), webhook.Header(secret, now, body)))
fmt.Println("replayed 10m later:", v.Verify(body, webhook.Header(secret, now.Add(-10*time.Minute), body)))
fmt.Println("== 6. fraud decisions")
eng := fraud.NewEngine(nil, fraud.DefaultRules()...)
base := fraud.Payment{AmountUSD: 4999, CardFingerprint: "fp_a", CardCountry: "US", IPCountry: "US",
IP: "203.0.113.7", DeviceID: "dev_9", CustomerAgeDays: 300, Is3DSCapable: true, At: now}
fmt.Println("normal:", eng.Decide(ctx, base).Action)
geo := base
geo.IPCountry, geo.AmountUSD = "NL", 30000
fmt.Println("geo mismatch, 300 USD:", eng.Decide(ctx, geo).Action)
var last fraud.Decision
for i := 0; i < 7; i++ {
c := base
c.CardFingerprint, c.AmountUSD, c.DeviceID = fmt.Sprintf("fp_t%d", i), 100, "dev_bot"
last = eng.Decide(ctx, c)
}
fmt.Println("7 cards, one device:", last.Action, last.Reasons)
fmt.Println("== 7. reconciliation")
rows, _ := recon.ParseCSV(strings.NewReader("psp_ref,type,gross,fee,currency\nstripe_ch_1,charge,2500,103,USD\nstripe_ch_2,charge,4000,146,USD\nstripe_ch_9,charge,1200,65,USD\n"))
rep := recon.Reconcile([]recon.Record{
{PSPRef: "stripe_ch_1", Amount: 2500, Currency: "USD"},
{PSPRef: "stripe_ch_2", Amount: 4000, Currency: "USD"},
}, rows, now)
fmt.Printf("matched=%d missing_locally=%d (%s) fees=%d\n", rep.Matched, len(rep.MissingLocally), rep.MissingLocally[0].PSPRef, rep.Fees)
fmt.Println("== 8. chargeback: open, win")
d := &dispute.Dispute{ID: "dp_1", PaymentID: "pi_0001", PSP: "stripe", Currency: "USD", Amount: 2500, Fee: 1500}
_ = dispute.Open(svc.Ledger, d)
opened := svc.Ledger.Balance("psp_receivable:stripe:USD")
_ = dispute.SubmitEvidence(d)
_ = dispute.Close(svc.Ledger, d, true)
fmt.Printf("receivable after open=%d after win=%d fee_kept=%d status=%s trial=%v\n",
opened, svc.Ledger.Balance("psp_receivable:stripe:USD"), svc.Ledger.Balance("dispute_fees:USD"), d.Status, svc.Ledger.TrialBalance())
fmt.Println("== 9. dunning")
pol := dunning.Default()
fmt.Println("stolen_card:", pol.Next(1, "stolen_card", now, now).Outcome)
nd := pol.Next(1, "insufficient_funds", now, now)
fmt.Println("insufficient_funds:", nd.Outcome, "in", nd.At.Sub(now))
fmt.Println("== 10. checkout saga: shipment fails, hold is voided")
var log []string
o := &checkout.Orchestrator{}
err := o.Run(ctx, "order-77", []checkout.Step{
{Name: "reserve_stock", Do: func(context.Context, string) error { return nil },
Undo: func(context.Context, string) error { log = append(log, "released"); return nil }},
{Name: "authorize", Do: func(context.Context, string) error { return nil },
Undo: func(context.Context, string) error { log = append(log, "voided"); return nil }},
{Name: "book_shipment", Do: func(context.Context, string) error { return fmt.Errorf("carrier: no slot") }},
})
fmt.Println(err, log)
}زاویهٔ Go
| قابلیت Go | کاربرد در پرداخت | نکته |
|---|---|---|
int64 برای minor units در struct | نوع پول (Money type) | Add با کنترل overflow؛ هرگز float64 |
math/big.Rat، math/big.Int | تبدیل دقیق FX و half-even | big.Rat.SetString("0.9235") دقیق است |
github.com/shopspring/decimal | حساب Decimal؛ stripe-go v87 به آن وابسته است | اینجا استفاده نشده؛ math/big کافی است |
context.WithTimeout | بودجهٔ هر تماس PSP و مدل تقلب | context.DeadlineExceeded پس از ارسال unknown outcome است |
errors.Is همراه sentinel error | ErrTimeout، ErrUnavailable، ErrAmbiguous تصمیم failover را هدایت میکنند | Wrap با %w |
crypto/hmac + crypto/sha256، hmac.Equal | امضای webhook | مقایسهٔ constant-time |
encoding/csv | Settlement file | مبلغ را integer parse کنید |
database/sql / pgx با BEGIN ... COMMIT | یک transaction برای state + ledger + outbox | sync.Mutex در این ماژول جای آن را گرفته |
github.com/stripe/stripe-go/v87 | stripe.NewClient، sc.V1PaymentIntents، webhook.ConstructEvent | go 1.24؛ retry خودکار با کلید idempotency، پیشفرض 2 |
go test -race | ثبت همزمان ledger و تحویل webhook | TestInvariantsUnderConcurrentTransfers |
Laravel
سمت Laravel از Laravel Cashier (Stripe) برای integration، query builder مستقیم برای ledger و inbox، و queued job برای webhook و reconciliation استفاده میکند. همهٔ فایلهای منبع از php -l گذشتهاند؛ برای این فصل application واقعی Laravel boot نشده است.
قبل
شمارهٔ کارت به سرور POST و با CVV لاگ میشود؛ پول float است؛ Http::retry(3, 200) بعد از timeout دوباره charge میفرستد؛ balance قابلتغییر و ایمیل همگام است:
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Http;
use Illuminate\Support\Facades\Mail;
// The naive checkout: every comment is a production incident.
class BeforeCheckoutController extends Controller
{
public function pay(Request $request, Order $order)
{
// Raw card number posted to our server: the whole app is now in PCI DSS scope (SAQ D).
$card = $request->input('card_number');
// Float money, no idempotency key, a retry policy that re-sends a charge after a timeout.
$response = Http::retry(3, 200)->post('https://psp.example.test/charge', [
'amount' => $order->total * 1.0,
'card' => $card,
]);
logger()->info('charge', ['card' => $card, 'cvv' => $request->input('cvv')]); // PAN and CVV in logs
$order->update(['status' => 'paid', 'balance' => $order->balance - $order->total]); // mutable balance
Mail::to($request->user())->send(new \App\Mail\Receipt($order)); // lost if the process dies here
return response()->json($response->json());
}
}بعد
Checkout از راه Stripe client در Cashier با ترتیبی که هر نقطهٔ crash قابلبازیابی باشد: (1) ردیف payments با شناسهٔ pay_<order>، یکی برای هر سفارش، پیش از هر تماس PSP وجود دارد. (2) PaymentIntent با کلید pay_<order>:intent و metadata.payment_id و همیشه با پارامترهای یکسان ساخته میشود. Retry پس از crash در پنجرهٔ 24 ساعتهٔ Stripe همان intent را میگیرد و حتی اگر مرحلهٔ 3 اجرا نشده باشد، webhook worker با metadata ردیف را پیدا میکند. (3) شناسه فقط با whereNull('stripe_payment_intent_id') متصل میشود و هرگز بازنویسی نمیشود؛ checkout دوم همان سفارش، intent متصلشده را دوباره استفاده میکند. کارت ذخیرهشده در فراخوانی جدا با کلید خودش confirm میشود. مسیر refund ابتدا Gate::authorize('refund', $order) را بررسی میکند و هدر Idempotency-Key کلاینت را لازم میداند. کلید روی ردیف refunds ذخیره میشود؛ retry همان ردیف را بازپخش میکند و مبلغ متفاوت 422 میگیرد. پیش از تماس Stripe، مبلغ در ردیف با وضعیت pending و first_sent_at رزرو میشود؛ شناسهٔ ردیف کلید Stripe است و خود controller چیزی در ledger ثبت نمیکند. Replay فقط وقتی دوباره به Stripe میفرستد که ردیف هنوز Stripe refund id نداشته و عمرش کمتر از 23 ساعت باشد؛ کمتر از نگهداری 24 ساعتهٔ کلید Stripe. پس از آن وضعیت needs_reconciliation میشود، مسیر 409 میدهد و چیزی ارسال نمیشود تا کلید منقضیشده refund دوم نسازد. هر ردیف دقیقاً به یک Stripe refund نگاشت میشود؛ اگر worker برای همان ردیف refund دوم provider را ببیند، exception میاندازد تا retry و سپس dead-letter شود، نه اینکه ack کند. Controller هرگز status را تعیین نمیکند؛ worker از webhook تأییدشده تعیین میکند. محدودیت: پس از پایان پنجرهٔ کلید Stripe، crash میان مراحل 2 و 3 فقط با fallback Webhook یا reconciliation کشف میشود:
<?php
namespace App\Http\Controllers;
use App\Models\Order;
use Illuminate\Http\Request;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use RuntimeException;
// Checkout on Stripe through Cashier's Stripe client. The card never touches our server
// (Payment Element in an iframe), so the server sees pm_... ids only.
// Order of steps, so every crash point is recoverable:
// 1. the payments row exists before any PSP call (pay_<order>, one per order);
// 2. the PSP call carries a key derived from that row and metadata.payment_id, so a retry
// after a crash gets the SAME PaymentIntent back (Stripe keeps keys at least 24 h) and a
// webhook can find the row even if step 3 never ran;
// 3. the intent id is attached only if the row has none: it is never overwritten.
class CheckoutController extends Controller
{
private const MERCHANT = 'shop'; // single-merchant monolith
private const RESEND_WINDOW_HOURS = 23; // below Stripe's 24 h key retention
// Payment Element flow: the browser confirms with the client secret.
public function start(Request $request, Order $order)
{
$intent = $this->intentFor($request, $order);
return view('checkout', ['clientSecret' => $intent->client_secret, 'order' => $order]);
}
// Saved card, confirmed on the server; 3-D Secure sends the customer to Cashier's page.
public function charge(Request $request, Order $order)
{
$intent = $this->intentFor($request, $order);
if (in_array($intent->status, ['requires_payment_method', 'requires_confirmation'], true)) {
$pm = (string) $request->input('payment_method');
$intent = Cashier::stripe()->paymentIntents->confirm($intent->id, ['payment_method' => $pm],
['idempotency_key' => "{$this->paymentId($order)}:confirm:{$pm}"]); // a double click confirms once
}
if ($intent->status === 'requires_action') {
return redirect()->route('cashier.payment', [$intent->id, 'redirect' => route('orders.show', $order)]);
}
return response()->json(['status' => $intent->status]); // the webhook books the result
}
// Refunds need an Idempotency-Key header from the client (400 without it). The key is
// stored on the refund row: a retry with the same key and amount replays that row (and
// resends to Stripe with the row id as Stripe's key if the first call never stored a
// refund id); the same key with another amount is 422. The amount is reserved (row
// `pending`) BEFORE calling Stripe; the worker books it from refund.* events. A Stripe
// error leaves the row pending: reserved until the webhook or reconciliation resolves it.
public function refund(Request $request, Order $order)
{
Gate::authorize('refund', $order); // OrderPolicy: 403 otherwise
$clientKey = (string) $request->header('Idempotency-Key', '');
if ($clientKey === '' || strlen($clientKey) > 255) {
abort(400, 'Idempotency-Key header required');
}
$amount = (int) $request->input('amount');
$refund = DB::transaction(function () use ($order, $amount, $clientKey) {
$payment = DB::table('payments')->where('id', $this->paymentId($order))->lockForUpdate()->first();
if ($payment === null) {
abort(422, 'no payment');
}
$existing = DB::table('refunds')->where(['payment_id' => $payment->id, 'client_key' => $clientKey])->first();
if ($existing !== null) {
abort_if((int) $existing->amount !== $amount, 422, 'Idempotency-Key reused with another amount');
return $existing; // replay: no new row, no new key
}
$open = (int) DB::table('refunds')->where('payment_id', $payment->id)
->whereIn('state', ['pending', 'needs_reconciliation'])->sum('amount'); // reserved
if ($payment->status !== 'succeeded' || $amount <= 0
|| $payment->amount_refunded + $open + $amount > $payment->amount_received) {
abort(422, 'refund not allowed');
}
$row = ['id' => 'rf_'.Str::ulid(), 'payment_id' => $payment->id, 'client_key' => $clientKey, 'amount' => $amount,
'currency' => $payment->currency, 'state' => 'pending', 'stripe_refund_id' => null,
'first_sent_at' => now(), 'created_at' => now(), 'updated_at' => now()];
DB::table('refunds')->insert($row);
return (object) $row;
});
if ($refund->stripe_refund_id === null && $refund->state === 'pending'
&& Carbon::parse($refund->first_sent_at)->lt(now()->subHours(self::RESEND_WINDOW_HOURS))) {
// Past Stripe's key retention a resend could create a SECOND refund: stop, keep the
// amount reserved, and let reconciliation (or the webhook) settle what happened.
DB::table('refunds')->where('id', $refund->id)->where('state', 'pending')
->update(['state' => 'needs_reconciliation', 'updated_at' => now()]);
return response()->json(['refund' => $refund->id, 'state' => 'needs_reconciliation'], 409);
}
if ($refund->stripe_refund_id === null && $refund->state === 'pending') {
$intentId = DB::table('payments')->where('id', $this->paymentId($order))->value('stripe_payment_intent_id');
$created = Cashier::stripe()->refunds->create(
['payment_intent' => $intentId, 'amount' => $amount, 'metadata' => ['refund_id' => $refund->id]],
['idempotency_key' => $refund->id], // the same Stripe refund on every replay
);
DB::table('refunds')->where('id', $refund->id)->whereNull('stripe_refund_id')->update(['stripe_refund_id' => $created->id]);
}
$state = DB::table('refunds')->where('id', $refund->id)->value('state');
return response()->json(['refund' => $refund->id, 'state' => $state], 202);
}
private function paymentId(Order $order): string
{
return 'pay_'.$order->id;
}
// Returns the order's one PaymentIntent: the attached one, or one created with a key
// derived from the payment row. Never a second intent for the same order.
private function intentFor(Request $request, Order $order): object
{
$id = $this->paymentId($order);
DB::table('payments')->insertOrIgnore([ // step 1 (rerun-safe)
'id' => $id, 'merchant_id' => self::MERCHANT, 'order_id' => (string) $order->id,
'amount' => $order->total_minor, 'currency' => 'USD', 'status' => 'requires_payment_method',
'created_at' => now(), 'updated_at' => now(),
]);
$payment = DB::table('payments')->where('id', $id)->first();
if ((int) $payment->amount !== (int) $order->total_minor) {
throw new RuntimeException("order {$order->id} changed amount after its payment was created");
}
if ($payment->stripe_payment_intent_id !== null) { // reuse, never replace
return Cashier::stripe()->paymentIntents->retrieve($payment->stripe_payment_intent_id);
}
$intent = Cashier::stripe()->paymentIntents->create([ // step 2
'amount' => $payment->amount,
'currency' => 'usd',
'customer' => $request->user()->stripe_id,
'metadata' => ['payment_id' => $id, 'order_id' => (string) $order->id],
], ['idempotency_key' => "{$id}:intent"]); // same parameters on every retry
$attached = DB::table('payments')->where('id', $id)->whereNull('stripe_payment_intent_id')
->update(['stripe_payment_intent_id' => $intent->id, 'updated_at' => now()]); // step 3
if ($attached === 0 && DB::table('payments')->where('id', $id)->value('stripe_payment_intent_id') !== $intent->id) {
throw new RuntimeException("payment {$id} already mapped to another intent");
}
return $intent;
}
}مجوز بازپرداخت (Refund authorization): مسیر Gate::authorize('refund', $order) را صدا میزند؛ OrderPolicy شناساییشده به کارمند پشتیبانی یا مالک سفارش اجازه میدهد؛ رد مجوز 403 است:
<?php
namespace App\Policies;
use App\Models\Order;
use App\Models\User;
// Discovered automatically (app/Policies next to app/Models). CheckoutController::refund
// calls Gate::authorize('refund', $order): a denial is an AuthorizationException, i.e. 403.
class OrderPolicy
{
public function refund(User $user, Order $order): bool
{
// Support staff, or the order's owner if your business allows self-service refunds.
return (bool) $user->is_support || $user->id === $order->user_id;
}
}ماشین حالت (State machine) به شکل backed enum با نگاشت eventهای Stripe. canBecome() هم پیکان جدول و هم پیشرفت بر اساس رتبه را میپذیرد؛ چون ترتیب webhookها معلوم نیست و شاید ردیف محلی هرگز requires_confirmation را ندیده باشد. پرداختی که هنوز requires_payment_method است، payment_intent.succeeded را میپذیرد. هیچ انتقالی از succeeded یا canceled به بیرون وجود ندارد:
<?php
namespace App\Payments;
use DomainException;
// Stripe PaymentIntent statuses as a backed enum with the legal transitions.
enum PaymentStatus: string
{
case RequiresPaymentMethod = 'requires_payment_method';
case RequiresConfirmation = 'requires_confirmation';
case RequiresAction = 'requires_action';
case Processing = 'processing';
case RequiresCapture = 'requires_capture';
case Succeeded = 'succeeded';
case Canceled = 'canceled';
/** @return list<self> */
public function next(): array
{
return match ($this) {
self::RequiresPaymentMethod => [self::RequiresConfirmation, self::Canceled],
self::RequiresConfirmation => [self::RequiresAction, self::Processing, self::RequiresCapture,
self::Succeeded, self::RequiresPaymentMethod, self::Canceled],
self::RequiresAction => [self::Processing, self::RequiresCapture, self::Succeeded,
self::RequiresPaymentMethod, self::Canceled],
self::Processing => [self::Succeeded, self::RequiresPaymentMethod],
self::RequiresCapture => [self::Succeeded, self::Canceled],
self::Succeeded, self::Canceled => [],
};
}
public function isTerminal(): bool
{
return $this === self::Succeeded || $this === self::Canceled;
}
// How far along the lifecycle a status is; skipped intermediate states are normal
// because webhooks arrive out of order and we may never see requires_confirmation.
public function rank(): int
{
return match ($this) {
self::RequiresPaymentMethod => 0,
self::RequiresConfirmation => 1,
self::RequiresAction => 2,
self::Processing, self::RequiresCapture => 3,
self::Succeeded, self::Canceled => 4,
};
}
// A verified PSP event may move the payment along a table edge OR forward past states
// we never recorded (requires_payment_method -> succeeded). Nothing leaves a terminal state.
public function canBecome(self $to): bool
{
if ($this->isTerminal()) {
return false;
}
return in_array($to, $this->next(), true) || $to->rank() > $this->rank();
}
public function to(self $to): self
{
if (! $this->canBecome($to)) {
throw new DomainException("invalid transition {$this->value} -> {$to->value}");
}
return $to;
}
// Map a Stripe event type to the status it implies.
public static function fromStripeEvent(string $type): ?self
{
return match ($type) {
'payment_intent.succeeded' => self::Succeeded,
'payment_intent.processing' => self::Processing,
'payment_intent.requires_action' => self::RequiresAction,
'payment_intent.amount_capturable_updated' => self::RequiresCapture,
'payment_intent.payment_failed' => self::RequiresPaymentMethod,
'payment_intent.canceled' => self::Canceled,
default => null,
};
}
}سرویس دفترکل (Ledger service): ثبت متوازن و idempotent در DB::transaction(..., attempts: 3)، قفل حسابها با ترتیب ثابت:
<?php
namespace App\Payments;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;
use RuntimeException;
// Double-entry postings inside DB::transaction. Callers that also change a payment row
// or write an outbox event call post() from inside their own transaction (nested = savepoint).
class LedgerService
{
private const DEBIT_NORMAL = ['asset', 'expense'];
/**
* @param list<array{account: string, direction: 'D'|'C', amount: int}> $entries
* @return bool true when posted now, false when the id was already posted (idempotent)
*/
public function post(string $transactionId, string $description, array $entries): bool
{
if (count($entries) < 2) {
throw new InvalidArgumentException('a transaction needs at least two entries');
}
return DB::transaction(function () use ($transactionId, $description, $entries) {
if (DB::table('journal_transactions')->where('id', $transactionId)->exists()) {
return false;
}
// Lock accounts in a fixed order so two postings never deadlock each other.
$ids = array_values(array_unique(array_column($entries, 'account')));
sort($ids);
$accounts = DB::table('ledger_accounts')->whereIn('id', $ids)
->orderBy('id')->lockForUpdate()->get()->keyBy('id');
$perCurrency = [];
$delta = [];
foreach ($entries as $e) {
$acct = $accounts[$e['account']] ?? throw new RuntimeException("unknown account {$e['account']}");
if (! is_int($e['amount']) || $e['amount'] <= 0) {
throw new InvalidArgumentException('amounts are positive integers in minor units');
}
$signed = $e['direction'] === 'D' ? $e['amount'] : -$e['amount'];
$perCurrency[$acct->currency] = ($perCurrency[$acct->currency] ?? 0) + $signed;
$normal = in_array($acct->kind, self::DEBIT_NORMAL, true) ? $signed : -$signed;
$delta[$acct->id] = ($delta[$acct->id] ?? 0) + $normal;
}
foreach ($perCurrency as $currency => $sum) {
if ($sum !== 0) {
throw new RuntimeException("unbalanced: {$currency} off by {$sum}");
}
}
foreach ($delta as $id => $d) {
if (! $accounts[$id]->allow_negative && $accounts[$id]->balance + $d < 0) {
throw new RuntimeException("insufficient balance on {$id}");
}
}
DB::table('journal_transactions')->insert(['id' => $transactionId, 'description' => $description]);
foreach ($entries as $e) {
DB::table('ledger_entries')->insert([
'transaction_id' => $transactionId,
'account_id' => $e['account'],
'direction' => $e['direction'],
'amount' => $e['amount'],
'currency' => $accounts[$e['account']]->currency,
]);
}
foreach ($delta as $id => $d) {
DB::table('ledger_accounts')->where('id', $id)->increment('balance', $d);
}
return true;
}, attempts: 3);
}
}Webhook endpoint: بدنهٔ خام (Raw body)، هر امضای v1 در برابر هر secret فعال و tolerance بررسی میشود؛ سپس insertOrIgnore در inbox. هر بار که ردیف هنوز پردازشنشده است job ارسال میشود، نه فقط هنگام اولین insert. بنابراین اگر بین insert و dispatch، crash رخ دهد، تحویل مجدد هنوز پردازش را راه میاندازد. هر exception پاسخ 500 میدهد و Stripe دوباره تلاش میکند:
<?php
namespace App\Http\Controllers;
use App\Jobs\ProcessStripeEvent;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
// Custom endpoint (Cashier users get the same checks from its webhook middleware).
// Verify -> store in the inbox (dedup by event id) -> dispatch if unprocessed -> 200 fast.
// DispatchPendingWebhooks sweeps rows that were stored but never got a job.
class StripeWebhookController extends Controller
{
private const TOLERANCE_SECONDS = 300;
public function __invoke(Request $request): JsonResponse
{
$payload = $request->getContent(); // the raw body: never re-encoded JSON
$header = (string) $request->header('Stripe-Signature', '');
if (! $this->verify($payload, $header, config('services.stripe.webhook_secrets', []))) {
return response()->json(['error' => 'invalid signature'], 400);
}
$event = json_decode($payload, true, flags: JSON_THROW_ON_ERROR);
DB::table('webhooks_inbox')->insertOrIgnore([
'psp' => 'stripe',
'event_id' => $event['id'],
'event_type' => $event['type'],
'object_id' => $event['data']['object']['id'] ?? null,
'payload' => $payload,
]);
// Dispatch whenever the row is still unprocessed, not only on the first insert: if the
// process died (or the queue was down) after the insert last time, this redelivery is
// what gets the event processed. A duplicate job is harmless: the job locks the row
// and returns when processed_at is set. Exceptions here mean 500, so Stripe retries.
$processed = DB::table('webhooks_inbox')
->where(['psp' => 'stripe', 'event_id' => $event['id']])->value('processed_at');
if ($processed === null) {
ProcessStripeEvent::dispatch($event['id']);
}
return response()->json(['received' => true]); // processed duplicates also get 200
}
/** @param list<string> $secrets current and, during a roll, previous secret */
private function verify(string $payload, string $header, array $secrets): bool
{
$timestamp = null;
$signatures = [];
foreach (explode(',', $header) as $item) {
[$key, $value] = array_pad(explode('=', trim($item), 2), 2, '');
if ($key === 't' && ctype_digit($value)) {
$timestamp = (int) $value;
} elseif ($key === 'v1') {
$signatures[] = $value; // ignore v0 and debug entries
}
}
if ($timestamp === null || $signatures === []) {
return false;
}
$matched = false;
foreach ($secrets as $secret) {
$expected = hash_hmac('sha256', $timestamp.'.'.$payload, $secret);
foreach ($signatures as $sig) {
$matched = hash_equals($expected, $sig) || $matched; // constant time, no short circuit
}
}
return $matched && abs(time() - $timestamp) <= self::TOLERANCE_SECONDS;
}
}Webhook job: یک transaction برای inbox، payment، refund، ledger و outbox. پرداخت با intent id پیدا میشود؛ اگر checkout پیش از اتصال شناسه crash کرده باشد، با metadata.payment_id، و ردیفی که به intent دیگری متصل است رد میشود. رویداد refund.created یا refund.updated با وضعیت succeeded بازپرداخت را یک بار ثبت میکند: journal id برابر Stripe refund id، بهروزرسانی amount_refunded و outbox. رویداد refund.failed یا وضعیت failed / canceled اگر refund هنوز pending باشد رزرو را آزاد میکند؛ اگر قبلاً ثبت شده باشد، ثبت را معکوس میکند: journal با refund_failed:<id>، کاهش amount_refunded و رویداد payments.refund_failed. Refund ساختهشده در Dashboard که نمیشناسیم، ردیف خودش را میگیرد. charge.refunded فقط جمع جاری را کنترل میکند و تا وقتی refundی ثبت نشده باشد exception میاندازد؛ retry و سپس dead-letter. پیشرفت اعمال و event کهنه ack میشود. تضاد وضعیتهای پایانی، مثلاً succeeded محلی در برابر canceled در PSP، بهجای ack باعث exception است. Event پرداختی که هنوز نداریم با backoff تکرار میشود. هنگام requires_capture زمان capture_before مربوط به hold از charge ذخیره میشود؛ یک تماس Stripe API داخل transaction که در این مقیاس پذیرفتنی است. پس از آخرین تلاش، ردیف last_error را بهعنوان رکورد dead-letter نگه میدارد:
<?php
namespace App\Jobs;
use App\Payments\LedgerService;
use App\Payments\PaymentStatus;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Backoff;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Carbon;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Laravel\Cashier\Cashier;
use RuntimeException;
use Throwable;
// Applies one stored webhook exactly once: inbox row, payment row, refund row, ledger and
// outbox change in ONE transaction, so a crash anywhere leaves either all or nothing.
// Anything it cannot explain throws: the queue retries, and after the last try failed()
// leaves the row as a dead letter. It never acks an event it did not apply or prove stale.
#[Tries(8)]
#[Backoff([10, 30, 60, 300])]
class ProcessStripeEvent implements ShouldQueue
{
use Queueable;
public function __construct(public string $eventId) {}
public function handle(LedgerService $ledger): void
{
DB::transaction(function () use ($ledger) {
$row = DB::table('webhooks_inbox')
->where(['psp' => 'stripe', 'event_id' => $this->eventId])
->lockForUpdate()->first();
if ($row === null || $row->processed_at !== null) {
return; // duplicate job or already done
}
$event = json_decode($row->payload, true);
$object = $event['data']['object'];
match (true) {
str_starts_with($event['type'], 'payment_intent.') => $this->paymentIntentEvent($ledger, $event['type'], $object),
in_array($event['type'], ['refund.created', 'refund.updated', 'refund.failed'], true) => $this->refundEvent($ledger, $object),
$event['type'] === 'charge.refunded' => $this->checkRefundTotal($object),
default => null, // not a money event for this service
};
DB::table('webhooks_inbox')->where(['psp' => 'stripe', 'event_id' => $this->eventId])
->update(['processed_at' => now(), 'attempts' => $row->attempts + 1]);
});
}
private function paymentIntentEvent(LedgerService $ledger, string $type, array $intent): void
{
$target = PaymentStatus::fromStripeEvent($type);
if ($target === null) {
return;
}
$payment = $this->paymentFor($intent['id'], $intent['metadata']['payment_id'] ?? null);
$current = PaymentStatus::from($payment->status);
if ($current->canBecome($target)) {
$this->apply($ledger, $payment, $target, $intent); // edge or forward progress
} elseif ($current->isTerminal() && $target->isTerminal() && $current !== $target) {
throw new RuntimeException("conflict: local {$current->value}, PSP {$target->value} for {$intent['id']}");
}
// else: a stale event the current state already covers (e.g. processing after succeeded)
}
// Find the payment by intent id; if checkout crashed before storing the id, recover the
// mapping from metadata.payment_id (set BEFORE the PSP call). Never overwrite another id.
private function paymentFor(string $intentId, ?string $paymentId): object
{
$payment = DB::table('payments')->where('stripe_payment_intent_id', $intentId)->lockForUpdate()->first();
if ($payment === null && $paymentId !== null) {
$payment = DB::table('payments')->where('id', $paymentId)->lockForUpdate()->first();
if ($payment !== null && $payment->stripe_payment_intent_id === null) {
DB::table('payments')->where('id', $paymentId)->whereNull('stripe_payment_intent_id')
->update(['stripe_payment_intent_id' => $intentId, 'updated_at' => now()]);
$payment->stripe_payment_intent_id = $intentId;
} elseif ($payment !== null) {
throw new RuntimeException("payment {$paymentId} is mapped to {$payment->stripe_payment_intent_id}, not {$intentId}");
}
}
// No row yet (the webhook beat our commit) or not ours: retry, never ack.
return $payment ?? throw new RuntimeException("no payment for {$intentId} yet");
}
private function apply(LedgerService $ledger, object $payment, PaymentStatus $to, array $intent): void
{
$received = (int) ($intent['amount_received'] ?? 0);
$changes = [
'status' => $to->value,
'amount_received' => $received,
'version' => $payment->version + 1,
'updated_at' => now(),
];
if ($to === PaymentStatus::RequiresCapture && isset($intent['latest_charge'])) {
// The hold's real expiry lives on the Charge (Visa MIT about 5 days, not 7):
// the capture scheduler works from this column, never from a fixed window.
$charge = Cashier::stripe()->charges->retrieve($intent['latest_charge']);
$before = $charge->payment_method_details->card->capture_before ?? null;
$changes['capture_before'] = $before ? Carbon::createFromTimestamp($before) : null;
}
DB::table('payments')->where('id', $payment->id)->where('version', $payment->version)->update($changes);
if ($to === PaymentStatus::Succeeded) {
$cur = strtoupper($payment->currency);
$ledger->post("capture:{$payment->id}", "capture {$payment->id}", [
['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'D', 'amount' => $received],
['account' => "sales:{$cur}", 'direction' => 'C', 'amount' => $received],
]);
}
$this->outbox('payments.payment_'.$to->value, $payment->id, ['status' => $to->value, 'amount_received' => $received]);
}
// refund.created / refund.updated / refund.failed. A succeeded refund is booked exactly once
// (journal id = Stripe refund id). A failed or canceled one releases the reservation if it
// was still pending; if it had already been booked (the bank returned the money later),
// the booking is reversed: a reversing journal entry, amount_refunded reduced, an outbox
// event so support can refund the customer another way.
private function refundEvent(LedgerService $ledger, array $refund): void
{
$payment = $this->paymentFor($refund['payment_intent'], null);
$local = DB::table('refunds')->where('stripe_refund_id', $refund['id'])->lockForUpdate()->first()
?? (isset($refund['metadata']['refund_id'])
? DB::table('refunds')->where('id', $refund['metadata']['refund_id'])->lockForUpdate()->first()
: null);
if ($local === null) { // created outside the app (Dashboard)
$local = (object) ['id' => 'rf_'.$refund['id'], 'state' => 'pending', 'amount' => (int) $refund['amount'],
'stripe_refund_id' => $refund['id']];
DB::table('refunds')->insert(['id' => $local->id, 'payment_id' => $payment->id, 'client_key' => 'psp:'.$refund['id'],
'amount' => $local->amount, 'currency' => strtoupper($refund['currency']), 'state' => 'pending',
'stripe_refund_id' => $refund['id'], 'created_at' => now(), 'updated_at' => now()]);
}
if ($local->stripe_refund_id !== null && $local->stripe_refund_id !== $refund['id']) {
// One row, one provider refund. A second provider refund for the same row means a
// resend created another refund: never ack it as "already final" (that under-counts).
throw new RuntimeException("refund row {$local->id} is {$local->stripe_refund_id}; second provider refund {$refund['id']}");
}
if ((int) $local->amount !== (int) $refund['amount']) {
throw new RuntimeException("refund {$refund['id']}: local {$local->amount}, PSP {$refund['amount']}");
}
$cur = strtoupper($payment->currency);
$failed = in_array($refund['status'], ['failed', 'canceled'], true);
$open = in_array($local->state, ['pending', 'needs_reconciliation'], true);
if ($failed && $open) { // never booked: free the reservation
DB::table('refunds')->where('id', $local->id)->update(['state' => 'failed', 'stripe_refund_id' => $refund['id'], 'updated_at' => now()]);
return;
}
if ($failed && $local->state === 'succeeded') { // booked, then returned by the bank
$ledger->post("refund_failed:{$refund['id']}", "refund failed {$payment->id}", [
['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'D', 'amount' => $local->amount],
['account' => "refunds:{$cur}", 'direction' => 'C', 'amount' => $local->amount],
]);
DB::table('payments')->where('id', $payment->id)->decrement('amount_refunded', $local->amount);
DB::table('refunds')->where('id', $local->id)->update(['state' => 'failed', 'updated_at' => now()]);
$this->outbox('payments.refund_failed', $payment->id, ['refund' => $refund['id'], 'amount' => $local->amount,
'reason' => $refund['failure_reason'] ?? null]);
return;
}
if (! $open || $refund['status'] !== 'succeeded') {
return; // already final here, or still pending at Stripe
}
if ($payment->amount_refunded + $local->amount > $payment->amount_received) {
throw new RuntimeException("refund {$refund['id']} exceeds what {$payment->id} received");
}
$ledger->post("refund:{$refund['id']}", "refund {$payment->id}", [
['account' => "refunds:{$cur}", 'direction' => 'D', 'amount' => $local->amount],
['account' => "psp_receivable:stripe:{$cur}", 'direction' => 'C', 'amount' => $local->amount],
]);
DB::table('payments')->where('id', $payment->id)->increment('amount_refunded', $local->amount);
DB::table('refunds')->where('id', $local->id)->update(['state' => 'succeeded', 'stripe_refund_id' => $refund['id'], 'updated_at' => now()]);
$this->outbox('payments.payment_refunded', $payment->id, ['refund' => $refund['id'], 'amount' => $local->amount]);
}
// charge.refunded carries the charge's running total. If it is ahead of what we booked,
// a refund.* event is still on its way (or was lost): throw so the job retries, and after
// the last try the row becomes a dead letter for a human. Equal totals: nothing to do.
private function checkRefundTotal(array $charge): void
{
$payment = $this->paymentFor($charge['payment_intent'], null);
if ((int) $charge['amount_refunded'] > (int) $payment->amount_refunded) {
throw new RuntimeException("charge {$charge['id']} refunded {$charge['amount_refunded']}, booked {$payment->amount_refunded}");
}
}
private function outbox(string $topic, string $paymentId, array $data): void
{
DB::table('outbox')->insert([
'event_id' => (string) Str::uuid(),
'topic' => $topic,
'aggregate_id' => $paymentId,
'payload' => json_encode(['id' => $paymentId] + $data),
]);
}
// After the last try the inbox row stays unprocessed with the error: the dead letter a human reads.
public function failed(?Throwable $exception): void
{
DB::table('webhooks_inbox')->where(['psp' => 'stripe', 'event_id' => $this->eventId])
->update(['last_error' => Str::limit((string) $exception?->getMessage(), 500)]);
}
}پویش Webhookهای معطل (Pending-webhook sweeper): فرمان Artisan هر پنج دقیقه اجرا میشود؛ برای ردیفهای inbox قدیمیتر از ده دقیقه که نه پردازش شدهاند و نه dead-letter، job ارسال میکند؛ ممکن است PSP دیگر آنها را تحویل ندهد:
<?php
namespace App\Console\Commands;
use App\Jobs\ProcessStripeEvent;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
// Safety net for inbox rows that were stored but never got a job (crash after the insert,
// queue outage, a PSP that gave up redelivering). Rows with last_error are dead letters
// for a human and are not re-dispatched. Schedule it in routes/console.php:
// Schedule::command('payments:dispatch-pending-webhooks')->everyFiveMinutes();
class DispatchPendingWebhooks extends Command
{
protected $signature = 'payments:dispatch-pending-webhooks {--older-than=10 : minutes}';
protected $description = 'Dispatch ProcessStripeEvent for unprocessed webhook inbox rows';
public function handle(): void
{
$count = 0;
DB::table('webhooks_inbox')
->where('psp', 'stripe')
->whereNull('processed_at')
->whereNull('last_error')
->where('received_at', '<', now()->subMinutes((int) $this->option('older-than')))
->orderBy('received_at')
->limit(500)
->pluck('event_id')
->each(function (string $eventId) use (&$count) {
ProcessStripeEvent::dispatch($eventId); // idempotent job: duplicates are no-ops
$count++;
});
$this->info("dispatched {$count}");
}
}تطبیق روزانه (Daily reconciliation) فایل تسویه با ردیفهایی که برنامه مینویسد: chargeها با هویت provider، یعنی psp + intent id، به payments متصل و از نظر مبلغ، ارز و status مقایسه میشوند. سطر refund با Stripe refund id به refunds و از راه پرداخت آن به همان provider تطبیق مییابد. پرداختهای succeeded که پس از سه روز در هیچ batch نیستند هم فهرست میشوند. قرارداد فایل، قالب سادهشدهٔ پنجستونی این فصل است؛ ستونهای گزارش PSP خودتان را به آن نگاشت کنید:
<?php
namespace App\Jobs;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Queue\Queueable;
use Illuminate\Queue\Attributes\Tries;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Storage;
// Daily queued job: load the PSP settlement file, then diff it against the rows checkout
// and the webhook worker actually write: payments (charges) and refunds.
// File contract (this chapter's reduced format): psp_ref,type,gross,fee,currency where
// psp_ref is the PaymentIntent id for charges and the refund id (re_...) for refunds;
// map your PSP's report columns to that before loading.
// Schedule it with Schedule::job(new ReconcileSettlementFile(...))->dailyAt('06:00').
#[Tries(3)]
class ReconcileSettlementFile implements ShouldQueue
{
use Queueable;
public function __construct(public string $psp, public string $batchId, public string $path) {}
public function handle(): void
{
$stream = Storage::disk('local')->readStream($this->path);
$header = fgetcsv($stream); // psp_ref,type,gross,fee,currency
DB::transaction(function () use ($stream, $header) {
while (($line = fgetcsv($stream)) !== false) {
$row = array_combine($header, $line);
DB::table('settlement_lines')->insertOrIgnore([ // re-running the job is safe
'psp' => $this->psp,
'batch_id' => $this->batchId,
'psp_reference' => $row['psp_ref'],
'line_type' => $row['type'],
'gross' => (int) $row['gross'], // file is in minor units
'fee' => (int) $row['fee'],
'currency' => strtoupper($row['currency']),
]);
}
});
fclose($stream);
$lines = fn (string $type) => DB::table('settlement_lines as s')
->where(['s.psp' => $this->psp, 's.batch_id' => $this->batchId, 's.line_type' => $type]);
// Charges: matched on provider identity (psp + intent id), then amount AND currency.
$charges = $lines('charge')
->leftJoin('payments as p', fn ($j) => $j->on('p.stripe_payment_intent_id', '=', 's.psp_reference')
->on('p.psp', '=', 's.psp'))
->select('s.psp_reference', 's.gross', 's.currency', 'p.id', 'p.amount_received', 'p.currency as our_currency', 'p.status')
->get();
$missingLocally = $charges->whereNull('id')->pluck('psp_reference');
$mismatch = $charges->whereNotNull('id')->filter(fn ($c) => (int) $c->gross !== (int) $c->amount_received
|| $c->currency !== strtoupper($c->our_currency) || $c->status !== 'succeeded')->pluck('psp_reference');
// Refunds: the PSP refunded money we did not book (or booked differently).
// Refunds: matched on provider identity through the refund's payment (psp + refund id).
$refunds = $lines('refund')
->leftJoin('refunds as r', 'r.stripe_refund_id', '=', 's.psp_reference')
->leftJoin('payments as rp', fn ($j) => $j->on('rp.id', '=', 'r.payment_id')->on('rp.psp', '=', 's.psp'))
->select('s.psp_reference', 's.gross', 's.currency', 'r.id', 'rp.id as payment', 'r.amount',
'r.currency as our_currency', 'r.state')
->get();
$refundIssues = $refunds->filter(fn ($r) => $r->id === null || $r->payment === null || $r->state !== 'succeeded'
|| abs((int) $r->gross) !== (int) $r->amount || $r->currency !== strtoupper($r->our_currency))
->pluck('psp_reference');
// Booked here, absent from every loaded batch of this PSP: investigate after the cutoff.
$missingAtPsp = DB::table('payments as p')->where('p.psp', $this->psp)->where('p.status', 'succeeded')
->where('p.updated_at', '<', now()->subDays(3))
->whereNotExists(fn ($q) => $q->from('settlement_lines as s')->whereColumn('s.psp_reference', 'p.stripe_payment_intent_id')
->whereColumn('s.psp', 'p.psp')->where('s.line_type', 'charge'))
->pluck('p.id');
Log::channel('payments')->warning('settlement reconciliation', [
'psp' => $this->psp,
'batch' => $this->batchId,
'missing_locally' => $missingLocally->all(),
'amount_or_currency_mismatch' => $mismatch->all(),
'refund_issues' => $refundIssues->all(),
'missing_at_psp' => $missingAtPsp->all(),
]);
}
}Routeها: مسیر webhook با preventRequestForgery(except: [...]) از CSRF مستثنا میشود:
<?php
// routes/web.php: payment routes. Webhooks bypass CSRF; in bootstrap/app.php:
// ->withMiddleware(function (Middleware $middleware): void {
// $middleware->preventRequestForgery(except: ['stripe/*', 'webhooks/*']);
// })
use App\Http\Controllers\CheckoutController;
use App\Http\Controllers\StripeWebhookController;
use Illuminate\Support\Facades\Route;
Route::middleware('auth')->group(function () {
Route::post('/orders/{order}/pay', [CheckoutController::class, 'start']);
Route::post('/orders/{order}/charge', [CheckoutController::class, 'charge']);
Route::post('/orders/{order}/refund', [CheckoutController::class, 'refund']);
});
// Our own endpoint (Cashier registers its own /stripe/webhook route with signature middleware).
Route::post('/webhooks/stripe', StripeWebhookController::class)->middleware('throttle:600,1');Migration برای همان جدولهای SQL schema، بدون triggerها:
<?php
use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
// Laravel 13 migration kept in sync with sql/schema.sql: same tables, columns and recovery
// states (psp_result, first_sent_at, refused/unbooked, needs_reconciliation), so the recovery
// and reconciliation queries on the page run against either. The PostgreSQL triggers (append-only,
// balanced, entry currency) belong in a raw DB::unprepared() migration of their own.
return new class extends Migration
{
public function up(): void
{
Schema::create('idempotency_keys', function (Blueprint $table) {
$table->string('merchant_id');
$table->string('key');
$table->string('fingerprint'); // sha256 of the canonical request
$table->string('status'); // in_progress, completed
$table->unsignedSmallInteger('response_code')->nullable();
$table->json('response_body')->nullable();
$table->timestamp('created_at')->useCurrent();
$table->timestamp('expires_at')->index();
$table->primary(['merchant_id', 'key']);
});
Schema::create('payments', function (Blueprint $table) {
$table->string('id')->primary();
$table->string('merchant_id');
$table->string('order_id');
$table->unsignedBigInteger('amount'); // minor units
$table->char('currency', 3);
$table->string('status')->default('requires_payment_method');
$table->string('capture_method')->default('automatic');
$table->unsignedBigInteger('amount_capturable')->default(0);
$table->unsignedBigInteger('amount_received')->default(0);
$table->unsignedBigInteger('amount_refunded')->default(0);
$table->string('psp')->default('stripe'); // provider identity for reconciliation
$table->string('stripe_payment_intent_id')->nullable()->unique();
$table->timestamp('capture_before')->nullable()->index(); // hold expiry from the PSP
$table->unsignedInteger('version')->default(0);
$table->timestamps();
$table->unique(['merchant_id', 'order_id']);
});
Schema::create('payment_attempts', function (Blueprint $table) {
$table->id();
$table->string('payment_id');
$table->string('psp'); // stripe, adyen
$table->string('psp_idem_key')->unique(); // pi_...:attempt:N, reused on every retry
$table->string('psp_reference')->nullable()->index();
$table->string('state'); // sent, unknown, refused, done, unbooked
$table->json('psp_result')->nullable(); // kept while 'unbooked': booked later, never re-sent
$table->string('decline_code')->nullable();
$table->timestamp('first_sent_at')->useCurrent()->index(); // resend window starts here (< 24 h)
$table->timestamp('created_at')->useCurrent();
$table->foreign('payment_id')->references('id')->on('payments');
});
Schema::create('ledger_accounts', function (Blueprint $table) {
$table->string('id')->primary(); // psp_receivable:stripe:USD
$table->char('currency', 3);
$table->string('kind'); // asset, expense, liability, revenue, equity
$table->boolean('allow_negative')->default(false);
$table->bigInteger('balance')->default(0); // cached, derived from entries
});
// The accounts every posting in this chapter uses (LedgerService throws on an unknown
// account, so they must exist before the first capture). One set per currency.
foreach (['USD'] as $cur) {
DB::table('ledger_accounts')->insert([
['id' => "psp_receivable:stripe:{$cur}", 'currency' => $cur, 'kind' => 'asset', 'allow_negative' => true, 'balance' => 0],
['id' => "sales:{$cur}", 'currency' => $cur, 'kind' => 'revenue', 'allow_negative' => false, 'balance' => 0],
['id' => "refunds:{$cur}", 'currency' => $cur, 'kind' => 'expense', 'allow_negative' => false, 'balance' => 0],
['id' => "psp_fees:{$cur}", 'currency' => $cur, 'kind' => 'expense', 'allow_negative' => false, 'balance' => 0],
['id' => "cash:bank:{$cur}", 'currency' => $cur, 'kind' => 'asset', 'allow_negative' => false, 'balance' => 0],
]);
}
Schema::create('journal_transactions', function (Blueprint $table) {
$table->string('id')->primary(); // capture:pi_..., idempotent posting id
$table->string('description');
$table->timestamp('posted_at')->useCurrent();
});
Schema::create('ledger_entries', function (Blueprint $table) {
$table->id();
$table->string('transaction_id');
$table->string('account_id');
$table->char('direction', 1); // D or C
$table->unsignedBigInteger('amount');
$table->char('currency', 3);
$table->foreign('transaction_id')->references('id')->on('journal_transactions');
$table->foreign('account_id')->references('id')->on('ledger_accounts');
$table->index(['account_id', 'id']);
});
Schema::create('outbox', function (Blueprint $table) {
$table->id();
$table->string('event_id')->unique();
$table->string('topic');
$table->string('aggregate_id');
$table->json('payload');
$table->timestamp('created_at')->useCurrent();
$table->timestamp('published_at')->nullable()->index();
});
Schema::create('webhooks_inbox', function (Blueprint $table) {
$table->string('psp');
$table->string('event_id');
$table->string('event_type');
$table->string('object_id')->nullable();
$table->json('payload');
$table->timestamp('received_at')->useCurrent();
$table->timestamp('processed_at')->nullable()->index();
$table->unsignedInteger('attempts')->default(0);
$table->text('last_error')->nullable();
$table->primary(['psp', 'event_id']);
});
Schema::create('refunds', function (Blueprint $table) {
$table->string('id')->primary(); // rf_<ulid>: also the Stripe idempotency key
$table->string('payment_id');
$table->string('client_key'); // the client's Idempotency-Key
$table->unsignedBigInteger('amount');
$table->char('currency', 3);
$table->string('state'); // pending, needs_reconciliation (both reserved), succeeded, failed
$table->string('stripe_refund_id')->nullable()->unique(); // exactly one provider refund per row
$table->timestamp('first_sent_at')->nullable(); // provider key retention counts from here
$table->timestamps();
$table->foreign('payment_id')->references('id')->on('payments');
$table->unique(['payment_id', 'client_key']); // one refund per client key and payment
});
Schema::create('settlement_lines', function (Blueprint $table) {
$table->string('psp');
$table->string('batch_id'); // payout / settlement batch
$table->string('psp_reference');
$table->string('line_type'); // charge, refund, chargeback, fee
$table->bigInteger('gross');
$table->bigInteger('fee');
$table->char('currency', 3);
$table->primary(['psp', 'batch_id', 'psp_reference', 'line_type']);
});
}
public function down(): void
{
foreach (['settlement_lines', 'refunds', 'webhooks_inbox', 'outbox', 'ledger_entries', 'journal_transactions',
'ledger_accounts', 'payment_attempts', 'payments', 'idempotency_keys'] as $t) {
Schema::dropIfExists($t);
}
}
};Schema در PostgreSQL با triggerهای append-only و بررسی تراز معوق:
-- PostgreSQL 16+ schema for a payment service. Money is BIGINT minor units + ISO 4217 code.
CREATE TABLE idempotency_keys (
merchant_id TEXT NOT NULL,
key TEXT NOT NULL CHECK (length(key) BETWEEN 1 AND 255),
fingerprint TEXT NOT NULL, -- sha256 of the canonical request
status TEXT NOT NULL CHECK (status IN ('in_progress', 'completed')),
response_code INT,
response_body JSONB,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
expires_at TIMESTAMPTZ NOT NULL DEFAULT now() + interval '24 hours',
PRIMARY KEY (merchant_id, key)
);
CREATE TABLE payments ( -- one row per payment intent
id TEXT PRIMARY KEY, -- pi_...
merchant_id TEXT NOT NULL,
order_id TEXT NOT NULL,
amount BIGINT NOT NULL CHECK (amount > 0),
currency CHAR(3) NOT NULL,
status TEXT NOT NULL CHECK (status IN ('requires_payment_method', 'requires_confirmation',
'requires_action', 'processing', 'requires_capture', 'succeeded', 'canceled')),
capture_method TEXT NOT NULL DEFAULT 'automatic' CHECK (capture_method IN ('automatic', 'manual')),
amount_capturable BIGINT NOT NULL DEFAULT 0,
amount_received BIGINT NOT NULL DEFAULT 0,
amount_refunded BIGINT NOT NULL DEFAULT 0 CHECK (amount_refunded <= amount_received),
psp TEXT NOT NULL DEFAULT 'stripe', -- provider identity (reconciliation)
stripe_payment_intent_id TEXT UNIQUE, -- Laravel flow: attached once, never overwritten
capture_before TIMESTAMPTZ, -- hold expiry from the PSP (Stripe charge:
-- payment_method_details.card.capture_before)
version INT NOT NULL DEFAULT 0, -- optimistic lock
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (merchant_id, order_id) -- one live intent per order
);
CREATE INDEX payments_capture_due ON payments (capture_before) WHERE status = 'requires_capture';
CREATE TABLE payment_attempts ( -- one row per call to a PSP
id BIGSERIAL PRIMARY KEY,
payment_id TEXT NOT NULL REFERENCES payments (id),
psp TEXT NOT NULL, -- stripe, adyen
psp_idem_key TEXT NOT NULL UNIQUE, -- pi_...:attempt:N, reused on every retry
psp_reference TEXT, -- ch_... / pspReference
state TEXT NOT NULL CHECK (state IN ('sent', 'unknown', 'refused', 'done', 'unbooked')),
psp_result JSONB, -- kept while 'unbooked': booked later, never re-sent
decline_code TEXT, -- insufficient_funds, do_not_honor...
first_sent_at TIMESTAMPTZ NOT NULL DEFAULT now(), -- resend window starts here (< 24 h)
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
CHECK (state <> 'unbooked' OR psp_result IS NOT NULL)
);
CREATE INDEX payment_attempts_open ON payment_attempts (first_sent_at)
WHERE state IN ('sent', 'unknown', 'unbooked');
CREATE TABLE ledger_accounts (
id TEXT PRIMARY KEY, -- psp_receivable:stripe:USD
currency CHAR(3) NOT NULL,
kind TEXT NOT NULL CHECK (kind IN ('asset', 'expense', 'liability', 'revenue', 'equity')),
allow_negative BOOLEAN NOT NULL DEFAULT false,
balance BIGINT NOT NULL DEFAULT 0, -- cached normal-side balance, derived from entries
version BIGINT NOT NULL DEFAULT 0,
CHECK (allow_negative OR balance >= 0)
);
CREATE TABLE journal_transactions ( -- immutable header
id TEXT PRIMARY KEY, -- capture:pi_..., refund:<key>: idempotent posting
description TEXT NOT NULL,
posted_at TIMESTAMPTZ NOT NULL DEFAULT now(),
reverses TEXT REFERENCES journal_transactions (id)
);
CREATE TABLE ledger_entries ( -- immutable lines
id BIGSERIAL PRIMARY KEY,
transaction_id TEXT NOT NULL REFERENCES journal_transactions (id),
account_id TEXT NOT NULL REFERENCES ledger_accounts (id),
direction CHAR(1) NOT NULL CHECK (direction IN ('D', 'C')),
amount BIGINT NOT NULL CHECK (amount > 0),
currency CHAR(3) NOT NULL
);
CREATE INDEX ledger_entries_account ON ledger_entries (account_id, id);
-- Append-only: nobody may UPDATE or DELETE journal rows; corrections are reversing transactions.
CREATE FUNCTION forbid_change() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN RAISE EXCEPTION 'ledger is append-only (%)', TG_TABLE_NAME; END $$;
CREATE TRIGGER entries_immutable BEFORE UPDATE OR DELETE ON ledger_entries
FOR EACH ROW EXECUTE FUNCTION forbid_change();
CREATE TRIGGER journal_immutable BEFORE UPDATE OR DELETE ON journal_transactions
FOR EACH ROW EXECUTE FUNCTION forbid_change();
-- An entry's currency must be its account's currency: no silent cross-currency transfer
-- (an FX conversion is two balanced transactions through an FX account per currency).
CREATE FUNCTION check_entry_currency() RETURNS trigger LANGUAGE plpgsql AS $$
BEGIN
IF NOT EXISTS (SELECT 1 FROM ledger_accounts WHERE id = NEW.account_id AND currency = NEW.currency) THEN
RAISE EXCEPTION 'entry currency % does not match account %', NEW.currency, NEW.account_id;
END IF;
RETURN NEW;
END $$;
CREATE TRIGGER entries_currency BEFORE INSERT ON ledger_entries
FOR EACH ROW EXECUTE FUNCTION check_entry_currency();
-- Debits = credits per currency, checked at COMMIT (deferred): the trigger fires once per
-- inserted entry, but only after all entries of the transaction exist.
CREATE FUNCTION check_balanced() RETURNS trigger LANGUAGE plpgsql AS $$
DECLARE bad RECORD;
BEGIN
SELECT currency, sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) AS diff
INTO bad
FROM ledger_entries WHERE transaction_id = NEW.transaction_id
GROUP BY currency HAVING sum(CASE direction WHEN 'D' THEN amount ELSE -amount END) <> 0
LIMIT 1;
IF FOUND THEN
RAISE EXCEPTION 'unbalanced journal transaction % (% off by %)', NEW.transaction_id, bad.currency, bad.diff;
END IF;
RETURN NULL;
END $$;
CREATE CONSTRAINT TRIGGER entries_balanced AFTER INSERT ON ledger_entries
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION check_balanced();
CREATE TABLE outbox ( -- written in the same transaction as payments/ledger
id BIGSERIAL PRIMARY KEY,
event_id TEXT NOT NULL UNIQUE,
topic TEXT NOT NULL, -- payments.payment_succeeded
aggregate_id TEXT NOT NULL, -- payment id: partition key
payload JSONB NOT NULL,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
published_at TIMESTAMPTZ
);
CREATE INDEX outbox_unpublished ON outbox (id) WHERE published_at IS NULL;
CREATE TABLE webhooks_inbox ( -- raw PSP events, stored before processing
psp TEXT NOT NULL,
event_id TEXT NOT NULL, -- evt_... / Adyen pspReference+eventCode
event_type TEXT NOT NULL,
object_id TEXT, -- data.object.id: second dedup key
payload JSONB NOT NULL,
received_at TIMESTAMPTZ NOT NULL DEFAULT now(),
processed_at TIMESTAMPTZ,
attempts INT NOT NULL DEFAULT 0,
last_error TEXT, -- after N attempts: dead letter for a human
PRIMARY KEY (psp, event_id)
);
CREATE INDEX webhooks_inbox_pending ON webhooks_inbox (received_at) WHERE processed_at IS NULL;
CREATE TABLE refunds ( -- Laravel flow: one row per refund request
id TEXT PRIMARY KEY, -- rf_<ulid>, also the PSP idempotency key
payment_id TEXT NOT NULL REFERENCES payments (id),
client_key TEXT NOT NULL, -- the client's Idempotency-Key
amount BIGINT NOT NULL CHECK (amount > 0),
currency CHAR(3) NOT NULL,
state TEXT NOT NULL CHECK (state IN ('pending', 'needs_reconciliation', 'succeeded', 'failed')),
stripe_refund_id TEXT UNIQUE, -- re_...: exactly one provider refund per row
first_sent_at TIMESTAMPTZ, -- provider key retention counts from here
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
UNIQUE (payment_id, client_key)
);
CREATE TABLE settlement_lines ( -- loaded from the PSP settlement file
psp TEXT NOT NULL,
batch_id TEXT NOT NULL, -- payout / settlement batch
psp_reference TEXT NOT NULL,
line_type TEXT NOT NULL, -- charge, refund, chargeback, fee
gross BIGINT NOT NULL,
fee BIGINT NOT NULL,
currency CHAR(3) NOT NULL,
PRIMARY KEY (psp, batch_id, psp_reference, line_type)
);زاویهٔ Laravel
| قابلیت Laravel 13 | رفتار طبق مستندات | کاربرد اینجا |
|---|---|---|
Cashier $user->pay($amount) | ساخت payment intent در پوشش Laravel\Cashier\Payment؛ مبلغ "in the lowest denominator" | Checkout یکباره با Payment Element |
Cashier $user->charge($amount, $paymentMethod, $options) | "will throw an exception if the charge fails"؛ خروجی Laravel\Cashier\Payment | کارت ذخیرهشده |
Laravel\Cashier\Exceptions\IncompletePayment | هنگام نیاز به اقدام اضافه مثل 3DS | Redirect به cashier.payment همراه redirect |
Cashier $user->refund($paymentIntentId) | "the Stripe Payment Intent ID as its first argument" را میگیرد | Refund کامل |
Cashier::stripe() | Client زیرین Stripe PHP SDK | کلیدهای idempotency و Checkout session |
| Cashier webhooks | Controller در /stripe/webhook؛ STRIPE_WEBHOOK_SECRET؛ php artisan cashier:webhook | جدولهای مدیریتشدهٔ Cashier همگام میمانند |
$middleware->preventRequestForgery(except: ['stripe/*']) | مستثنا کردن URI از CSRF با middleware به نام PreventRequestForgery | مسیر webhook |
DB::transaction(fn, attempts: 3) | اجرای مجدد closure هنگام deadlock | ثبت ledger |
lockForUpdate() | SELECT ... FOR UPDATE | حسابها، ردیف inbox و payment |
insertOrIgnore() | "will ignore errors while inserting records"؛ "duplicate record errors will be ignored and other types of errors may also be ignored depending on the database engine" | Inbox، settlement line و ردیف payments در checkout |
dispatch(...)->afterCommit() | ارسال بعد از commit تراکنشهای باز | Job پیش از وجود ردیف inbox اجرا نمیشود |
#[Tries(8)]، #[Backoff([10, 30, 60, 300])] | شکل attribute برای tries و backoff؛ بعد از آرایه "the last value is used" | Webhook job |
Job failed(?Throwable $e) | فراخوانی پس از آخرین attempt | نوشتن last_error؛ رکورد dead-letter |
Schedule::job(...)->dailyAt('06:00')، Schedule::command(...)->everyFiveMinutes() | زمانبند (Scheduler)؛ در مستندات Schedule::job(new Heartbeat)->everyFiveMinutes() و ->dailyAt('13:00') | Reconciliation و sweeper Webhookهای معطل |
حل مسئلههای کلاسیک
برداشت دوباره پس از Timeout
| راهحل | روش | مزیت | هزینه / محدودیت |
|---|---|---|---|
| کلید مشتقشدهٔ provider (Derived provider key) | pi_...:attempt:N، یکسان در هر retry | PSP نتیجهٔ اول را میدهد | فقط داخل پنجرهٔ نگهداری PSP؛ 24 h در Stripe v1 |
| پرسوجو سپس تکرار (Query-then-retry) | Lookup تلاش، سپس ارسال با همان کلید | بیشتر unknownها در چند ثانیه حل میشوند | مسیر lookup یا replay پاسخ ذخیرهشده لازم است |
| نگهداشتن نامعلوم، بدون failover (Park unknown) | state = 'unknown' و sweep بعدی | PSP دوم برداشت نمیکند | مشتری چند دقیقه pending میبیند |
یکتایی (merchant_id, order_id) | قید DB | دو کلید کلاینت دو intent نمیسازند | یک intent زنده برای هر سفارش |
Webhook پیش از Commit خودمان میرسد
ردیف payments را مثل CheckoutController پیش از تماس PSP بسازید تا معمولاً پیش از هر webhook وجود داشته باشد. اگر webhook باز هم زودتر رسید، آن را ذخیره کنید و 200 بدهید. Job ردیف payment را پیدا نمیکند و exception میاندازد؛ صف با backoff در #[Backoff] تا وجود ردیف دوباره تلاش میکند. Event را processed نکنید. اگر crash پس از insert مانع dispatch شده باشد، تحویل مجدد بهخاطر پردازشنشده بودن ردیف job را ارسال میکند و payments:dispatch-pending-webhooks باقی موارد را پیدا میکند.
Webhook بیترتیب وضعیت نهایی را بازنویسی میکند
ماشین حالت (State machine) پیکانی از succeeded به بیرون ندارد؛ job رویداد کهنه را ack و نادیده میگیرد. حالت معکوس هم مهم است: اگر payment_intent.succeeded وقتی برسد که ردیف محلی هنوز requires_payment_method است، چون eventهای میانی دیر رسیدهاند یا subscription آنها را نداشتهایم، این پیشرفت است. باید اعمال و در ledger ثبت شود، نه اینکه کهنه فرض و ack شود. Stripe میگوید مقصد "isn’t dependent on receiving events in a specific order". با created مرتب نکنید؛ "Snapshot events record created in seconds, so distinct events can share a timestamp". اگر شک دارید، شیء را از API بخوانید.
Webhook جعلی یا بازپخششده
امضا را روی بدنهٔ خام (Raw body) با hash_equals / hmac.Equal بررسی کنید. Timestamp باید داخل tolerance باشد. هنگام secret roll هر secret فعال قابلقبول است؛ بعد با event id حذف تکرار (Dedup) کنید.
Refund بیشتر از پرداخت یا دو بار بازپرداخت
هر بازپرداخت (Refund) ثبتنشده را از قبل مصرفشده حساب کنید: پیش از تماس PSP باید amount_refunded + open refunds + amount <= amount_received برقرار باشد. هر refund کلید خودش را داشته باشد که به یک پرداخت و یک مبلغ مقید است؛ پارامتر متفاوت خطاست و تکرار دقیق نتیجهٔ اول را میدهد. در Go این قرارداد Refund(id, key, amount) است؛ در Laravel هدر Idempotency-Key کلاینت روی ردیف refunds ذخیره میشود تا retry درخواست HTTP، Stripe refund دوم نسازد. رد شدن یک retry یا شکست دستهبندینشده، مجوز آزاد کردن مبلغ رزروشده نیست؛ lookup باید ثابت کند refund انجام نشده است. Refundی که بانک بعداً برمیگرداند، با refund.failed یا refund.updated دارای وضعیت failed، هم در journal و هم در amount_refunded معکوس میشود. قید SQL یعنی CHECK (amount_refunded <= amount_received) آخرین سد دفاع است. در Laravel مسیر فقط ردیف pending در refunds را رزرو میکند؛ worker از رویدادهای refund.* ثبت میکند.
حسابهای ما از PSP فاصله گرفتهاند
تطبیق روزانه (Reconciliation) روی settlement file انجام دهید. کارمزد و payout باید journal entry داشته باشند، حساب واسط یا clearing account باید صفر شود و هر سطر unmatched باید ticket داشته باشد.
موجودی با UPDATE «اصلاح» شده است
Triggerها UPDATE و DELETE جدولهای journal را رد میکنند. اصلاح با ثبت معکوس (Reversing entry) در Ledger.Reverse است تا audit trail خطا، اصلاح و ثبتکننده را نگه دارد.
شمارهٔ کارت در لاگهاست
کارت را در iframe متعلق به PSP بگیرید؛ مسیر SAQ A. فقط token بفرستید، request body را از لاگ مسیرهای پرداخت حذف کنید، لاگ را برای الگوی PAN اسکن کنید و هر PAN پیداشده را incident بدانید.
حملهٔ Card testing
Endpoint پرداخت را برای هر IP و session محدود کنید. قواعد سرعت (Velocity rules) روی تعداد کارت متمایز در هر دستگاه اعمال کنید، دستگاه را block کنید، CAPTCHA اضافه کنید و نرخ authorization را زیر نظر بگیرید.
Capture فراموش و Hold منقضی شده است
انقضای اعلامشدهٔ PSP را با پرداخت ذخیره کنید: payments.capture_before از payment_method_details.card.capture_before روی charge، هنگامی که intent به requires_capture میرسد. Job مربوط به capture/void با همین زمان کار کند: هر موردی که capture_before آن در 24 ساعت آینده است capture یا void شود؛ برای کمتر از 12 ساعت یا نبودن capture_before هشدار بدهید. قاعدهٔ ثابت «7 روز، هشدار در روز 5» غلط است: hold آغازشده توسط پذیرندهٔ Visa در Stripe پس از 4 روز و 18 ساعت منقضی میشود؛ Mastercard از نوع card-present پس از 2 روز. برای زمان بیشتر، در صورت پشتیبانی از extended authorization استفاده کنید یا دوباره authorize کنید.
جبران با Void شکست میخورد
عمل جبرانی (Compensation) را تعداد محدودی retry و سپس در dead-letter نگه دارید. Hold خودش منقضی میشود، اما مشتری تا آن زمان آن را میبیند؛ انسان یا sweep باید دوباره پیگیری کند.
انتخاب
کدام روش Capture
| موقعیت | پیشنهاد | تکنیک اضافه | دلیل |
|---|---|---|---|
| کالای دیجیتال با تحویل فوری | برداشت خودکار (Automatic capture) | بررسی تقلب پیش از confirm | چیزی برای لغو بعدی نیست |
| کالای فیزیکی با ارسال چند روز بعد | برداشت دستی (Manual capture) هنگام ارسال | Job برای capture/void بر اساس capture_before هر پرداخت | Refund برای ناموجودی لازم نیست |
| مبلغ نهایی نامعلوم؛ هتل، اجاره، غذا | Authorization بیشتر و partial capture | روی بیشتر کارتها فقط یک capture | باقی خودکار آزاد میشود |
| Checkout چندمرحلهای بین سرویسها | اول authorize، آخر capture | Saga با void بهعنوان compensation | جبران پیش از capture رایگان است |
| اشتراک | روش ذخیرهشده با SetupIntent و off-session MIT | Dunning و smart retries | مشتری حاضر نیست |
کدام روش اتصال
| موقعیت | اتصال (Integration) | PCI | بدهبستان |
|---|---|---|---|
| تیم کوچک، checkout استاندارد | صفحهٔ PSP مثل Stripe Checkout | SAQ A | کمترین کنترل UX |
| UX سفارشی | فیلد iframe؛ Payment Element، Adyen Drop-in | SAQ A + معیار اسکریپت | اسکریپتهای صفحه باید کنترل شوند |
| برنامهٔ Laravel روی Stripe | Laravel Cashier + Stripe PHP SDK برای کمبودها | SAQ A | Cashier دفترکل نمیسازد |
| سرویس Go روی Stripe | stripe-go پشت interface خودتان به نام PSP | SAQ A | State، ledger و outbox را شما مینویسید |
| نیاز به دو PSP | Router + network token یا vault شخص ثالث | وابسته به vault | Reconciliation دوبرابر |
| فرم کارت اختصاصی | پرهیز کنید | SAQ D | صدها کنترل |
کدام سیاست Retry
| شکست | سیاست | دلیل |
|---|---|---|
| Timeout / 5xx هنگام checkout | همان key، همان PSP، چند ثانیه؛ سپس park | نتیجهٔ نامعلوم (Unknown outcome) |
| Connect refused | Failover با attempt و کلید تازه | اثبات شده پردازش نشده |
| Soft decline در checkout | روش دیگر از مشتری بخواهید | مشتری حاضر است |
| Soft decline در تمدید | برنامهٔ dunning یا smart retries | شاید موجودی اضافه شود |
| Hard decline | توقف و درخواست روش تازه | Retry موفق نمیشود |
| خطای پردازش webhook | Retry صف با backoff و سپس dead-letter | PSP قبلاً 200 گرفته |
کدام اقدام تقلب
| سیگنال | اقدام | دلیل |
|---|---|---|
| کارتهای زیاد روی یک دستگاه در چند دقیقه | Block | Card testing |
| امتیاز 75+؛ پیشفرض high در Radar | Block | ریسک بالا |
| امتیاز 65–74، کارت دارای 3DS | درخواست 3DS | انتقال مسئولیت (Liability shift)، ارزانتر از انسان |
| امتیاز 65–74، بدون 3DS | صف بررسی دستی (Manual review queue) | تصمیم انسانی پیش از capture |
| مشتری مطمئن در allowlist | Allow | پرهیز از false positive |
| Timeout مدل | فقط rule | Checkout منتظر مدل نماند |
در معماری: از یک پردازه تا سیستم توزیعشده
یکپارچه: یک پردازه، یک پایگاهداده
در فروشگاه یکپارچه (Monolith) با Laravel و Cashier، checkout controller، webhook controller، queue worker و جدولهای ledger همگی در یک پایگاهدادهاند؛ payment، journal entry و outbox در یک DB::transaction commit میشوند. این سادهترین طراحی درست و همان شکل فایلهای PHP این فصل است. مثال: CheckoutController ردیف payments با شناسهٔ pay_<order> را مینویسد، PaymentIntent را با کلید pay_<order>:intent و metadata.payment_id میسازد و اگر هنوز شناسهای متصل نیست، شناسهاش را وصل میکند. StripeWebhookController رویداد را ذخیره و job را ارسال میکند. ProcessStripeEvent با stripe_payment_intent_id ردیف را مییابد؛ در یک transaction وضعیت را جلو میبرد، capture:pay_... ثبت میکند و outbox برای ایمیل رسید مینویسد. Job ایمیل از outbox میخواند؛ sweeper و reconciliation روزانه موارد جامانده را پیدا میکنند.
یکپارچهٔ ماژولار: مرزبندی بدون شبکه
در یکپارچهٔ ماژولار (Modular monolith)، ماژولها را جدا کنید: payments مالک intent، attempt و PSP adapter؛ ledger مالک حساب و journal و تنها نویسندهٔ entry؛ risk مالک تصمیم؛ و orders. ماژول دیگر از interface به payments درخواست میدهد و event میگیرد؛ کسی مستقیم جدول payments و ledger را نمینویسد. مثال: orders تابع payments.createIntent(order, key) را صدا میزند و منتظر payment_succeeded میماند. گزارش مالی ledger را میخواند، نه جدول payments.
میکروسرویسها: هر پیکان یک تصمیم است
در میکروسرویسها (Microservices)، سرویس پرداخت مالک intent، attempt، adapter و webhook endpoint است؛ سرویس ledger مالک journal entry است و سفارش و fulfilment مصرفکنندهٔ event هستند. Transaction مشترکی ندارید. Payment state و outbox را با هم مینویسد؛ relay رویداد payments.payment_succeeded را با payment id بهعنوان partition key منتشر میکند؛ ledger با آن، capture:pi_... را idempotent ثبت میکند؛ سفارش پس از payment_succeeded ارسال میشود. خود checkout یک saga است: reserve موجودی → authorize → ship → capture؛ compensation آن void است. کلید idempotency هر hop از saga id مشتق میشود.
دادهٔ توزیعشده: replica، cache و region
در دادهٔ توزیعشده (Distributed data)، برای تصمیمی مثل «refund مجاز است؟» یا «کیف پول چقدر دارد؟» موجودی و status را از replica نخوانید. تأخیر replica (Replica lag) به refund دوبرابر تبدیل میشود. انبارهٔ idempotency روی primary یا store با سازگاری قوی باشد؛ کلیدی که replica هنوز نمیبیند زمینهٔ برداشت تکراری است. در multi-region هر پرداخت را با merchant یا intent id به region اصلیاش مقید کنید تا state machine، کلید و ثبت ledger یک محل نوشتن داشته باشند. Webhook ممکن است به هر region برسد؛ با object id به home region مسیریابی کنید یا در inbox سراسری ذخیره کنید. Ledger بر اساس account shard میشود؛ journal entry میان دو shard، ثبت دومرحلهای pending → posted یا یک shard برای هر merchant لازم دارد.
مسیر رشد: 1x، 10x، 100x
| بار | طراحی | چه چیزی عوض میشود |
|---|---|---|
| 1x؛ چند پرداخت در دقیقه | Monolith با Cashier، یک PostgreSQL و job تطبیق روزانه | چیزی برای بهینهسازی نیست؛ اول صحت |
| 10x؛ دهها پرداخت در ثانیه و قلهٔ حراج | سرویس پرداخت و queue worker؛ تخلیهٔ inbox با چند worker؛ موتور تقلب با velocity در Redis | حساب داغ مثل sales ثبتها را ترتیبی میکند (Serialise)؛ حساب فرعی به تفکیک merchant یا shard و سپس تجمیع |
| 100x؛ هزاران پرداخت در ثانیه و چند region | سرویس مستقل ledger با حساب shardشده، outbox با CDC، routing دو PSP، home region و streaming reconciliation | رقابت حساب داغ، میلیونها سطر تطبیق روزانه و rate limit خود PSP گلوگاهاند |
آزمایشگاه
آزمایشهای 1 تا 4 برای این فصل با Go 1.27.4 در یک process اجرا شدهاند؛ نسخهٔ محیط go version go1.27.4 darwin/arm64 است و go1.27.4 در تاریخچهٔ انتشار Go آمده است. خروجی ثبتشده در ادامه آمده. آزمایشهای 5 و 6 موردانتظار و اجرانشده هستند؛ حساب تست Stripe و برنامهٔ Laravel لازم دارند.
1. Handler سادهلوح.
$ cd docs/snippets/system-design/payment-processing-architecture/go
$ go run ./before
charges sent to PSP: 3 (customer paid twice for the first order)
balance: 0.30000000000000004 (expected 0.3)دو سفارش و سه charge؛ retry سفارش اول پس از گم شدن پاسخ، پرداخت واقعی دوم ساخته است. Balance هم دام float را نشان میدهد.
2. همهٔ سناریوها در یک پردازه.
$ go run ./cmd/demo
== 1. lost response, same key, one charge
intent=pi_0001 status=succeeded psp_charges=1 replayed_create=true same_id=true
== 2. ambiguous outcome: park, do not fail over
status=requires_confirmation unknown_attempts=1 adyen_charges=0
after recovery: status=succeeded stripe_charges=2
== 3. hold, partial capture, refund, trial balance
sales=14750 refunds=1000 receivable=13750 trial=map[USD:0] journal_rows=4 outbox=5
== 4. money
split 1.00 USD three ways: 0.34 USD 0.33 USD 0.33 USD | 10.00 USD @0.9235 = 9.24 EUR
== 5. webhook signature
valid: <nil>
tampered: webhook: no v1 signature matches
replayed 10m later: webhook: timestamp outside tolerance
== 6. fraud decisions
normal: allow
geo mismatch, 300 USD: request_3ds
7 cards, one device: block [card_testing: >5 cards on one device in 10m model_timeout:rules_only]
== 7. reconciliation
matched=2 missing_locally=1 (stripe_ch_9) fees=314
== 8. chargeback: open, win
receivable after open=9750 after win=12250 fee_kept=1500 status=won trial=map[USD:0]
== 9. dunning
stolen_card: needs_new_payment_method
insufficient_funds: retry in 24h0m0s
== 10. checkout saga: shipment fails, hold is voided
checkout: saga failed and was compensated: step book_shipment: carrier: no slot [voided released]خروجی را بخشبهبخش بخوانید. در (1)، پاسخ گمشده فقط یک charge دارد و create تکراری همان intent را میدهد. در (2)، Stripe بعد از برداشت پاسخ نمیدهد؛ attempt نگه داشته میشود و Adyen اصلاً صدا نمیخورد. همان کلید بعداً مسئله را حل میکند؛ شمارندهٔ 2 مجموع هر دو سفارش است. در (3) جریان هتل trial balance صفر دارد. در (4)، 1.00 USD به 34/33/33 تقسیم و FX با half-even گرد میشود. در (5)، بدنهٔ دستکاریشده و امضای 10 دقیقه قبل رد میشوند. در (6)، تصمیم معمولی، step-up و block داریم؛ مدل حاضر نیست و ruleها تصمیم میگیرند. در (7)، stripe_ch_9 نزد PSP تسویه شده ولی ما نمیشناختیمش. در (8)، برد chargeback مبلغ 2500 را برمیگرداند ولی کارمزد 1500 میماند. در (9)، hard و soft decline را میبینید. در (10)، شکست ارسال، hold را void و سپس کالا را با ترتیب معکوس آزاد میکند.
3. تستها.
$ gofmt -l . && go vet ./... && go test -race -count=1 ./...
? academy/payment-processing-architecture/before [no test files]
ok academy/payment-processing-architecture/checkout 1.198s
? academy/payment-processing-architecture/cmd/demo [no test files]
ok academy/payment-processing-architecture/dispute 1.167s
ok academy/payment-processing-architecture/dunning 1.172s
ok academy/payment-processing-architecture/fraud 1.222s
? academy/payment-processing-architecture/idem [no test files]
ok academy/payment-processing-architecture/intent 1.204s
ok academy/payment-processing-architecture/ledger 1.265s
ok academy/payment-processing-architecture/money 1.263s
? academy/payment-processing-architecture/outbox [no test files]
ok academy/payment-processing-architecture/payment 1.313s
ok academy/payment-processing-architecture/recon 1.235s
ok academy/payment-processing-architecture/webhook 1.234s
$ go test -v ./payment/
--- PASS: TestConcurrentConfirmChargesOnce (0.00s)
--- PASS: TestRefundReservationHeldUntilBooked (0.00s)
--- PASS: TestAmbiguousRefundKeepsReservation (0.00s)
--- PASS: TestRefusedRefundReleasesReservation (0.00s)
--- PASS: TestSuccessWebhookCompletesManualCapture (0.00s)
--- PASS: TestCaptureCallsPSPFirst (0.00s)
--- PASS: TestFailoverRaceChargesOnce (0.00s)
--- PASS: TestRefusalDoesNotProveAnEarlierUnknownAttempt (0.00s)
--- PASS: TestUnknownRefundSurvivesRetryRefusal (0.00s)
--- PASS: TestUnclassifiedRefundErrorIsUnknown (0.00s)
--- PASS: TestDuplicateRefundFailuresDoNotUnderflowReservation (0.00s)
--- PASS: TestPartialCaptureReportedByWebhookFirst (0.00s)
--- PASS: TestCompetingCaptureAmounts (0.00s)
--- PASS: TestFailedPostingDoesNotCompleteTheIntent (0.00s)
--- PASS: TestOnePaymentPerOrder (0.00s)
--- PASS: TestCompletedRefundKeyChecksParameters (0.00s)
--- PASS: TestResolveRefundAfterLookup (0.00s)
--- PASS: TestStaleDeclineWebhookDoesNotTouchLaterAttempt (0.00s)
--- PASS: TestWebhookFirstSuccessKeepsReference (0.00s)
--- PASS: TestRejectedCaptureCloneIsRaceFree (0.02s)
--- PASS: TestUnknownAttemptsReturnsCopies (0.00s)
--- PASS: TestNoResendAfterTheWindow (0.00s)
--- PASS: TestUnbookedCaptureIsBookedWithoutThePSP (0.00s)
--- PASS: TestUnbookedRefundIsBookedWithoutThePSP (0.00s)
--- PASS: TestDelayedResponseKeepsRetainedWebhookSuccess (0.00s)
--- PASS: TestWebhookCannotApplyAfterItsAttemptWasSuperseded (0.00s)
--- PASS: TestCaptureRepairUsesWebhookRetainedSuccess (0.00s)
--- PASS: TestCreateIsIdempotent (0.00s)
--- PASS: TestLostResponseChargesOnce (0.00s)
--- PASS: TestAmbiguousOutcomeIsParkedNotFailedOver (0.00s)
--- PASS: TestFailoverOnlyWhenProvablyNotProcessed (0.00s)
--- PASS: TestDeclineEmitsFailureAndNoLedger (0.00s)
--- PASS: TestAuthorizePartialCaptureRefund (0.00s)
--- PASS: TestWebhookDuplicatesAndStaleEvents (0.00s)
--- PASS: TestOutboxRelayAndConsumerDedup (0.00s)
--- PASS: TestRefundIsCheckedBeforeThePSPAndReplaySafe (0.00s)
--- PASS: TestWebhookForUnknownIntentIsRetriedLater (0.00s)
--- PASS: TestConcurrentRefundsCannotOverRefund (0.00s)4. دفترکل را عمداً خراب کنید. تست TestUnbalancedIsRejected مقدار debit برابر 1099 و credit برابر 1000 میفرستد. Post خطای ledger: debits != credits میدهد و چیزی اضافه نمیشود (اجراشده):
$ go test -v -run Unbalanced ./ledger/
=== RUN TestUnbalancedIsRejected
--- PASS: TestUnbalancedIsRejected (0.00s)اگر تست را به یک سطر تغییر دهید، ledger: a transaction needs at least two entries میگیرید؛ این نتیجه از کد انتظار میرود و اجرا نشده است.
5. حالت تست Stripe، سرتاسری از راه برنامه؛ موردانتظار، اجرا نشده. فرمان stripe events resend، endpoint ثبتشده با --webhook-endpoint=<endpoint_id> میخواهد؛ پس این آزمایش روی staging انجام میشود. در Dashboard، مسیر Workbench → Webhooks → Create an event destination → Webhook endpoint را بروید و URL را https://staging.example.com/webhooks/stripe بگذارید. شناسهٔ we_... و secret از نوع whsec_... را نشان میدهد؛ secret برای services.stripe.webhook_secrets است. پرداخت از checkout خود برنامه ساخته میشود تا ردیف موردنیاز worker وجود داشته باشد.
0 $ php artisan migrate --force # creates the tables AND seeds the ledger accounts
... create_payment_tables ........................ DONE
$ psql -c "SELECT id FROM ledger_accounts ORDER BY id" # cash:bank:USD, psp_fees:USD,
# psp_receivable:stripe:USD, refunds:USD, sales:USD
$ curl -s -c jar -b jar -o /dev/null https://staging.example.com/orders/42 # jar holds a logged-in session
$ XSRF=$(awk '$6=="XSRF-TOKEN"{print $7}' jar | python3 -c 'import sys,urllib.parse as u; print(u.unquote(sys.stdin.read().strip()))')
1 $ curl -s -b jar -c jar -H "X-XSRF-TOKEN: $XSRF" -X POST https://staging.example.com/orders/42/charge -d payment_method=pm_card_visa
{"status":"succeeded"} # payments row pay_42 first, then pi_A with
# metadata.payment_id=pay_42, key pay_42:intent
2 (Stripe -> staging) POST /webhooks/stripe evt_A payment_intent.succeeded 200
worker: pay_42 requires_payment_method -> succeeded (forward progress), journal capture:pay_42,
outbox payments.payment_succeeded, inbox processed_at set
3 $ stripe events resend evt_A --webhook-endpoint=we_staging
(Stripe -> staging) POST /webhooks/stripe 200 # row exists, processed_at set -> no job
4 $ curl -s -b jar -c jar -H "X-XSRF-TOKEN: $XSRF" -X POST https://staging.example.com/orders/42/charge -d payment_method=pm_card_visa
{"status":"succeeded"} # same order: the attached pi_A is reused, no new charge
5 $ stripe trigger payment_intent.succeeded # an intent the app never created
worker: "no payment for pi_B yet" -> retried with backoff -> after 8 tries last_error set (dead letter)
6 $ curl -s -X POST https://staging.example.com/webhooks/stripe -H 'Stripe-Signature: t=1,v1=00' -d '{}'
{"error":"invalid signature"} # 400Routeها در گروه web هستند، پس PreventRequestForgery اعمال میشود. اسکریپت هدر Sec-Fetch-Site ندارد و middleware به بررسی token برمیگردد. Laravel میگوید "stores the current CSRF token in an encrypted XSRF-TOKEN cookie"؛ مقدار این cookie در هدر X-XSRF-TOKEN مرحلهٔ 0 قرار میگیرد. مرحلهٔ 5 نمونهٔ توقف امن است: رویدادی که به هیچ پرداختی نگاشت نمیشود، هرگز processed علامت نمیخورد. برای توسعهٔ محلی، stripe login و stripe listen --all-snapshot --forward-to localhost:8000/webhooks/stripe رویداد را بدون URL ثبتشده forward میکنند؛ listener، signing secret خودش را چاپ میکند. Resend به endpoint ثبتشده نیاز دارد. طبق Stripe، stripe events resend <event_id> --webhook-endpoint=<endpoint_id> تا "for up to 30 days after the event creation" و Resend در Dashboard تا "for up to 15 days" کار میکند. pm_card_visa روش پرداخت تست Stripe است که در README کتابخانهٔ stripe-php آمده است.
6. Idempotency در برابر Stripe؛ موردانتظار، اجرا نشده.
$ curl https://api.stripe.com/v1/payment_intents -u sk_test_...: \
-H "Idempotency-Key: lab-order-1001-attempt-1" -d amount=2500 -d currency=usd \
-d "payment_method_types[]=card"
{ "id": "pi_A...", "status": "requires_payment_method", ... }
$ (same command again)
{ "id": "pi_A...", ... } # same object: the saved response
$ (same key, -d amount=9999)
{ "error": { ... } } # parameters differ from the original requestStripe حالت آخر را اینطور مستند میکند: لایهٔ idempotency "compares incoming parameters to those of the original request and errors if they’re not the same". بدنهٔ دقیق خطا برای این فصل ضبط نشده است.
بدفهمیهای رایج
| باور | واقعیت |
|---|---|
| «پول float با دو رقم اعشار است» | Minor units صحیح + کد ISO 4217؛ JPY برابر 0، BHD برابر 3 و CLF برابر 4 رقم؛ float سنت گم میکند |
| «Timeout یعنی پرداخت شکست خورده» | Unknown outcome است؛ اول با همان کلید روشنش کنید |
| «با هر خطا به PSP پشتیبان برو» | فقط اگر ثابت شود PSP اول کاری نکرده؛ وگرنه دوبار برداشت میکنید |
| «کلید idempotency تازه در هر retry امنتر است» | کلید تازه پرداخت تازه است؛ از intent و attempt مشتق کنید |
| «Authorization یعنی پول را گرفتهایم» | Hold در capture_before اعلامشدهٔ PSP منقضی میشود؛ Visa MIT حدود 5 روز و بیشتر کارتهای آنلاین 7 روز؛ باید capture کنید |
| «جبران authorization، refund است» | Void کنید؛ refund فقط برای پول captureشده است |
| «آخرین webhook برنده است» | At-least-once و بیترتیباند؛ state machine تصمیم میگیرد |
| «اول JSON را parse کن، بعد امضا» | Raw body را بررسی کنید؛ JSON بازسازیشده همان بایتها نیست |
| «Tolerance صفر سختگیرانهترین تنظیم است» | بررسی replay را کلاً غیرفعال میکند |
| «ستون balance و audit log همان ledger است» | Ledger موجودی را از ثبتهای تغییرناپذیر و متوازن مشتق میکند |
| «ثبت اشتباه را UPDATE کن» | Reversing entry بزنید؛ audit trail هر دو را نگه میدارد |
| «Webhook ما را از reconciliation بینیاز میکند» | Fee، payout، refund در dashboard و event گمشده در settlement file آشکار میشوند |
| «PSP یعنی حذف PCI DSS» | ممکن است دامنه را به SAQ A کم کند؛ اسکریپت checkout هنوز مسئولیت شماست |
| «3-D Secure جلوی هر dispute را میگیرد» | مسئولیت تقلب را منتقل میکند؛ اعتراض نرسیدن کالا باقی است |
| «برد dispute همهچیز را برمیگرداند» | Stripe، dispute received fee را برنمیگرداند؛ بهجز مکزیک |
| «هر تمدید ردشده را ساعتی retry کن» | Hard decline موفق نمیشود؛ soft decline برنامهٔ محدود دارد |
| «مدل تقلب تصمیم میگیرد» | وقتی مدل دیر است، rule، velocity و fallback تصمیم میگیرند |
چکیده
| موضوع | چه چیزی یادتان بماند |
|---|---|
| پول (Money) | BIGINT برای minor units و CHAR(3)؛ decimal برای نرخ؛ یک بار گرد کردن با half-even یا قاعدهٔ کسبوکار |
| وضعیت (State) | 7 وضعیت PaymentIntent در Stripe؛ یک جدول انتقال؛ ستون version |
| جابهجاییها (Movements) | Authorize → capture یکباره، ≤ hold و پیش از capture_before یا void؛ refundها ≤ capture و هرکدام کلید جدا |
| کلید کلاینت (Client key) | Idempotency-Key header؛ 409 در حال اجرا، 422 عدمتطبیق، 400 نبود کلید |
| کلید provider (Provider key) | pi_...:attempt:N؛ Stripe v1 برابر 24 h و Adyen برابر 7 تا 14 روز نگه میدارد |
| نتیجهٔ نامعلوم (Unknown outcome) | Query یا ارسال با همان کلید؛ رد بعدی چیزی ثابت نمیکند؛ park؛ هرگز failover نکنید؛ reconciliation |
| دفترکل (Ledger) | Debit = credit برای هر ارز؛ append-only؛ reversal؛ موجودی مشتقشده |
| اعلانها (Webhooks) | Raw body، HMAC، constant time، tolerance برابر 300 s، چند secret، inbox و 200 سریع |
| ترتیب و تکرار (Order and duplicates) | At-least-once و بیترتیب؛ dedup با event id؛ state machine رویداد کهنه را رد میکند |
| جدول خروجی (Outbox) | Event در همان transaction؛ relay حداقل یکباره؛ dedup مصرفکننده |
| زنجیرهٔ جبرانی (Saga) | اول authorize، آخر capture؛ void جبران رایگان؛ undo ناموفق به dead-letter |
| تطبیق (Reconciliation) | روزانه با psp_reference و payout id؛ ثبت fee و payout؛ صفر کردن clearing |
| اعتراضها (Disputes) | کسر فوری مبلغ + fee؛ فرصت پاسخ 7–21 روز؛ fee هنگام برد باقی میماند |
| احراز هویت قوی (SCA) | PSD2 / RTS 2018/389؛ 3DS2 با frictionless یا challenge؛ MIT نیازمند mandate |
| امنیت کارت (PCI) | iframe خود PSP → SAQ A؛ معیار اسکریپت از 31 Mar 2025؛ PAN/CVV هرگز لاگ نشود |
| تقلب (Fraud) | Velocity + rule + score با 65/75 در Radar + 3DS step-up + review queue؛ بودجهٔ مدل 50 ms |
| وصول مجدد (Dunning) | توقف hard decline؛ برنامهٔ محدود soft decline؛ Stripe Smart Retries تا 8 بار در 2 هفته |
| کتابخانهها (Libraries) | Cashier برای Stripe در Laravel؛ Stripe PHP SDK برای key و constructEvent؛ stripe-go v87 با go 1.24 |
محدودیتهای شناختهشدهٔ نمونه
کد این صفحه نمونهٔ آموزشی با توقف امن (Fail closed) است. هرجا سازوکار کامل production خارج از دامنه است، نمونه وضعیت را تشخیص میدهد و با خطا، حالت unknown یا dead-letter متوقف میشود تا برداشت یا ثبت اشتباه نکند. رفتار جایگزین در هر مورد:
| حوزه | سیستم production چه میکند | نمونه بهجایش چه میکند |
|---|---|---|
| انحصار عملیات هر پرداخت در Go (Per-payment exclusion) | در طول تماس PSP، row lock یا وضعیت processing را در پایگاهداده نگه میدارد | توکن single-flight در حافظه؛ فراخوان دوم ErrInFlight یا 409 میگیرد |
| نتیجهٔ نامعلوم پس از پنجرهٔ کلید در Go (Unknown outcomes) | جریان خودکار lookup و تعیین تکلیف اجرا میکند | پس از ResendWindow برابر 23 h هرگز ارسال نمیکند؛ ErrNeedsReconciliation میدهد؛ UnknownAttempts، PendingRefunds و ResolveRefund مسیرهای دستیاند |
| دستهبندی خطا در Go (Error classification) | هر کد PSP را به processed / not processed / unknown نگاشت میکند | فقط ErrUnavailable برای کلید تازه یعنی پردازش نشده؛ بقیه unknown هستند |
| نسبت دادن webhook در Go (Webhook attribution) | برای هر نوع event از object idهای PSP استفاده میکند | برای هر attempt یک payment reference را تطبیق میدهد؛ event نامنطبق یا متناقض ErrNotFound / ErrMismatch میگیرد و retry میشود، هرگز ack نمیشود |
| برداشت جزئی با webhook در Go (Partial capture) | مبلغ capture را از شیء PSP میخواند | مبلغ روی event اجباری است؛ بدون آن موفقیت رد میشود |
| چند برداشت و رزرو تمدیدشده (Multi-capture, extended authorization) | چند capture برای هر hold را دنبال میکند | یک capture برای هر hold؛ مبلغ دوم ErrMismatch است |
| ثبت چندارزی و تبدیل ارز (FX) | حسابهای FX و نرخ هر transaction را دارد | رد میشود؛ trigger در SQL سطری را که ارز آن با حساب فرق دارد رد میکند |
| تست یکپارچگی Laravel (Integration tests) | Feature test در برابر حالت تست Stripe | فقط php -l؛ مسیرها در متن و آزمایشگاه بررسی شدهاند، موردانتظار و اجرانشده |
| تکرار refund پس از پنجرهٔ کلید در Laravel (Refund replay) | Lookup خودکار refund در PSP | ردیف needs_reconciliation میشود و مبلغ رزرو میماند؛ مسیر 409 میدهد و ارسال نمیکند؛ provider refund دوم برای یک ردیف به مسیر dead-letter میرود |
| حسابهای دفترکل (Ledger accounts) | هنگام ورود merchant، برای هر ارز حساب باز میکند | Migration حسابهای USD موردنیاز نمونه را seed میکند؛ ارز دیگر ردیف خودش را لازم دارد؛ حساب ناشناخته در LedgerService::post باعث exception، retry و سپس dead-letter میشود |
| فاصلهٔ crash در checkout مربوط به Laravel (Crash window) | برای خود تماس PSP هم transactional outbox دارد | کلید پایدار pay_<order>:intent و metadata.payment_id؛ پس از نگهداری 24 h کلید Stripe، فاصله با fallback Webhook یا reconciliation کشف میشود |
| refund برگشتی بانک در Laravel (Returned refunds) | خودکار از کانال دیگر دوباره بازپرداخت میکند | Journal و amount_refunded را معکوس و payments.refund_failed را برای پشتیبانی منتشر میکند |
| مجوز refund در Laravel (Refund permissions) | نقشهای دقیق و audit ثبتکنندهٔ refund | OrderPolicy::refund: کارمند پشتیبانی یا مالک سفارش؛ در غیر این صورت 403 |
| فایل تطبیق (Reconciliation file) | قالب کامل گزارشهای PSP | قرارداد سادهشدهٔ پنجستونی؛ ستونهای PSP خودتان را به آن نگاشت کنید |
| SQL | Migration و تست اجراشده روی PostgreSQL | مطابق فایل schema نوشته و با خواندن بررسی شده؛ روی میزبان ساخت PostgreSQL نبود |
خودآزمایی: پرسش و پاسخ
- حیاتی تقریباً در هر مصاحبه پرسیده میشود
- مهم پرتکرار؛ در سطح senior انتظار میرود
- تکمیلی عمق بیشتر؛ تمایز ایجاد میکند
۱ — چرا پول را نباید float ذخیره کرد و جایگزین چیست؟ حیاتی
پاسخ
پاسخ: ممیز شناور دودویی (Binary floating point) بیشتر کسرهای دهدهی را دقیق نگه نمیدارد؛ 0.1 + 0.2 = 0.30000000000000004، پس جمع و مقایسه منحرف میشوند. مقدار صحیح در کوچکترین واحد ارز (Minor units) همراه کد ISO 4217 ذخیره کنید و توان را از فهرست ISO بگیرید؛ JPY صفر، USD دو و BHD سه. برای نرخ از decimal استفاده کنید و فقط یک بار با قاعدهٔ صریح به minor units گرد کنید.
۲ — تماس با PSP به Timeout میخورد؛ چه میکنید و چه کاری هرگز نباید کرد؟ حیاتی
پاسخ
پاسخ: آن را نتیجهٔ نامعلوم (Unknown outcome) بدانید؛ از PSP بپرسید یا همان درخواست را با همان provider idempotency key بفرستید. اگر هنوز نامعلوم است، attempt را unknown کنید، «در انتظار» نشان دهید و حل را به sweep یا reconciliation بسپارید. هرگز کلید تازه یا PSP دیگر را امتحان نکنید؛ شاید اولی پول را گرفته باشد.
۳ — کلید Idempotency ارسالی به PSP را چطور میسازید و چرا هر بار UUID تازه نمیسازید؟ حیاتی
پاسخ
پاسخ: از هویت پایدار کسبوکار، یعنی intent id و شمارهٔ attempt، مثل pi_42:attempt:1 مشتق و در ستون unique ذخیره کنید. در نتیجه هر retry و worker دوبارهراهافتاده همان کلید را میفرستد. UUID تازه هر retry را به پرداخت تازه تبدیل میکند؛ عمر کلید هم باید از retryها بیشتر باشد، چون کلید Stripe API v1 پس از 24 ساعت قابلپاکسازی است.
۴ — Void و Refund چه فرقی دارند و در Saga پرداخت کدام جبران است؟ حیاتی
پاسخ
پاسخ: لغو رزرو (Void) یک authorization برداشتنشده را لغو میکند؛ hold آزاد میشود و پولی جابهجا نشده است. بازپرداخت (Refund) پول captureشده را پس میدهد و رسیدنش به کارت چند روز طول میکشد. اول authorize و آخر capture کنید تا شکست پیش از capture با void کمهزینه جبران شود. Refund فقط پس از capture، compensation است.
۵ — Handler Webhook بهترتیب چه کارهایی باید انجام دهد؟ حیاتی
پاسخ
پاسخ: Raw body را بخواند و امضا را با HMAC روی t.body، همهٔ v1ها، همهٔ secretهای فعال و مقایسهٔ constant-time بررسی کند. Timestamp را با replay window بررسی کند؛ tolerance برابر 0 هر تحویل واقعی را رد میکند. سپس در inbox با کلید event id درج کند؛ تکراریِ پردازششده همینجا تمام میشود، اما تکراریِ پردازشنشده job را دوباره dispatch میکند. سریع 2xx بدهد و در queued job، داخل یک transaction مطابق state machine پردازش کند. بعد از آخرین retry، ردیف و خطایش را بهعنوان dead-letter نگه دارد.
۶ — چرا پرداخت به Double-entry ledger نیاز دارد، نه فقط ستون Balance؟ مهم
پاسخ
پاسخ: هر حرکت یک journal entry متوازن با debit = credit است؛ باگ نمیتواند پول را بیرد بسازد یا حذف کند. Entryها append-only هستند، پس موجودی در هر تاریخ قابلبازمحاسبه و حسابرسی است و reversal تاریخ اصلاح را نگه میدارد. Clearing account مثل دریافتنی PSP جریان نیمهتمام را نشان میدهد. موجودی قابلویرایش ممکن است از log جدا شود و معلوم نباشد کدام درست است.
۷ — Stripe پس از payment_intent.succeeded رویداد payment_intent.processing میفرستد؛ سیستم چه میکند؟ مهم
پاسخ
پاسخ: state عوض نمیشود؛ state machine پیکانی از succeeded به processing ندارد. Job رویداد را ack و processed میکند، بدون تغییر وضعیت. Stripe ترتیب را تضمین نمیکند و میگوید با created مرتب نکنید؛ اگر تازهترین حقیقت لازم است، شیء را از API بگیرید.
۸ — Outbox با تحویل حداقل یکباره چطور اثر دقیقاً یکباره میدهد؟ مهم
پاسخ
پاسخ: ردیف event با تغییر payment و ledger در یک transaction نوشته میشود؛ فقط و فقط وقتی تغییر commit شده باشد وجود دارد. Relay پس از crash ممکن است دوبار publish کند. مصرفکننده هر event id را در inbox و در همان transaction اثر کسبوکار ثبت میکند و تکراری را کنار میگذارد. At-least-once delivery با مصرفکنندهٔ idempotent یک اثر میسازد.
۹ — Reconciliation چه چیزهایی را پیدا میکند که Webhook پیدا نمیکند؟ مهم
پاسخ
پاسخ: Charge تسویهشدهای که ثبت نکردهاید، اغلب unknown outcome موفق؛ refund در dashboard؛ fee و FX؛ chargeback ازدسترفته؛ اختلاف مبلغ؛ و تطبیق payout رسیده به بانک با batch. با PSP reference و payout id تطبیق دهید؛ در Stripe، automatic_payout_id. تاریخ کلید تطبیق نیست.
۱۰ — دریافت کارت در iframe خود PSP چه اثری روی دامنهٔ PCI DSS دارد و چه الزاماتی میماند؟ مهم
پاسخ
پاسخ: اگر کارهای دادهٔ حساب کاملاً برونسپاری شده و سیستم شما هیچ دادهٔ کارت را ذخیره، پردازش یا منتقل نکند، میتوانید بهجای ارزیابی کامل با SAQ A اعتبارسنجی کنید. از SAQ A لازمالاجرا در ۳۱ مارس ۲۰۲۵، باید تأیید کنید سایت در برابر حملهٔ اسکریپتی مؤثر بر سیستم تجارت الکترونیکی آسیبپذیر نیست. Acquirer یا برند کارت تعیین میکند کدام اعتبارسنجی لازم است.
۱۱ — پرداخت با Score برابر 70 و کارت دارای 3DS رسیده؛ موتور ریسک چه میکند و چرا Block نمیکند؟ تکمیلی
پاسخ
پاسخ: 3-D Secure درخواست میکند تا issuer دارنده را احراز هویت کند و معمولاً مسئولیت تقلب به issuer منتقل شود. Block فروش احتمالاً واقعی را میگیرد و manual review وقت انسان میخواهد؛ step-up کمهزینهترین اقدام امن است. بدون پشتیبانی 3DS همین score به review میرود؛ threshold پیشفرض Radar برابر 65 برای elevated و 75 برای high است.
۱۲ — یک تمدید با stolen_card و دیگری با insufficient_funds شکست میخورد؛ Dunning با هرکدام چه میکند؟ تکمیلی
پاسخ
پاسخ: stolen_card در فهرست hard declineهای Stripe است؛ retry خودکار ندارد و از مشتری روش پرداخت تازه میخواهید. insufficient_funds از نوع soft است؛ با سقف تعداد attempt و مدت کل retry میکنید و ایمیل میفرستید. وقتی برنامه تمام شد، اشتراک را cancel یا unpaid میکنید.
واژهنامه
| اصطلاح | معنی |
|---|---|
| ارائهدهندهٔ پرداخت (PSP) | Payment service provider مثل Stripe و Adyen؛ API واحد برای کارت و روشهای دیگر |
| صادرکننده (Issuer) | بانک صاحب کارت؛ پرداخت را تأیید یا رد میکند |
| پذیرنده (Acquirer) | بانک پذیرندهٔ کارت برای فروشنده در شبکه |
| شبکهٔ کارت (Card network) | Visa، Mastercard و مانند آن؛ مسیریابی authorization و dispute |
| قصد پرداخت (Payment intent) | تلاش برای گرفتن یک مبلغ بابت یک سفارش؛ شیء Stripe آن PaymentIntent است |
| PaymentIntent | شیء API در Stripe با وضعیت requires_payment_method تا succeeded / canceled |
| ماشین حالت (State machine) | وضعیتها و انتقالهای ثابت؛ رویداد غیرمجاز رد میشود |
| رزرو مبلغ (Authorization) | Hold صادرکننده؛ اگر capture نشود منقضی میشود |
| برداشت (Capture) | تبدیل authorization به charge کامل یا جزئی |
| لغو رزرو (Void) | لغو authorization برداشتنشده و آزادسازی hold |
| بازپرداخت (Refund) | بازگرداندن پول captureشده به روش پرداخت |
| بازپرداخت جزئی (Partial refund) | بازگرداندن بخشی از capture؛ چند بار مجاز است |
| برداشت دستی (Manual capture) | اکنون authorize و بعداً capture؛ capture_method=manual |
| کلید تکرار امن (Idempotency key) | کلید یکتای کلاینت؛ سرور برای هر کلید یک بار اجرا میکند |
| هدر کلید (Idempotency-Key header) | هدر HTTP حامل کلید در پیشنویس IETF و Stripe |
| کلید ارائهدهنده (Provider idempotency key) | کلید PSP مشتقشده از intent و attempt |
| اثرانگشت درخواست (Fingerprint) | Hash درخواست canonical برای تشخیص کلید تکراری با پارامتر متفاوت؛ 422 |
| نتیجهٔ نامعلوم (Unknown outcome) | Timeout یا 5xx پس از ارسال؛ اثر شاید اتفاق افتاده باشد |
| مهلت تماس (Timeouts) | Deadline هر تماس؛ کوتاه و داخل بودجهٔ checkout |
| تلاش مجدد (Retries) | ارسال با همان کلید؛ محدود، با backoff و jitter |
| تلاش (Attempt) | یک تماس با یک PSP و یک کلید؛ sent، done، unknown |
| تعویض مسیر (Failover) | امتحان PSP دیگر، فقط بعد از پردازشنشدن اثباتشده |
| کوچکترین واحد (Minor units) | سنت، ین یا فلس که بهصورت integer ذخیره میشود |
| ISO 4217 | استاندارد کد ارز و توان minor units |
| نوع پول (Money type) | Value object مبلغ صحیح و کد ارز با عملیات امن |
| دهدهی (Decimal) | نوع دقیق برای نرخ و کسر؛ NUMERIC، big.Rat، bcmath |
| دامهای ممیزشناور (Float pitfalls) | ممیز شناور دودویی (Binary floating point) مقدار 0.1 را دقیق نمایش نمیدهد؛ جمع و مقایسه منحرف میشوند |
| گرد کردن ارز (Currency rounding) | قاعدهٔ صریح half-up یا half-even برای تبدیل مقدار دقیق به minor units |
| تقسیم مبلغ (Allocation) | سهمبندی با حفظ برابری جمع سهمها و کل |
| دفترکل دوطرفه (Double-entry ledger) | هر journal entry دارای مجموع debit و credit یکسان است |
| ثبت روزنامه (Journal entry) | مجموعهٔ اتمی و متوازن سطرهای ledger؛ journal transaction |
| بدهکار (Debit) | ثبت افزایندهٔ حسابهای debit-normal؛ دارایی و هزینه |
| بستانکار (Credit) | ثبت افزایندهٔ حسابهای credit-normal؛ بدهی، درآمد و سرمایه |
| ماهیت بدهکار / بستانکار (Debit normal / credit normal) | مشخص میکند کدام سمت موجودی حساب را افزایش میدهد |
| حساب واسط (Clearing account) | پول در مسیر، مثل دریافتنی PSP؛ باید صفر شود |
| تراز آزمایشی (Trial balance) | مجموع debit منهای credit؛ در ledger سالم صفر |
| تغییرناپذیری دفترکل (Ledger immutability) | ثبتها هیچوقت ویرایش یا حذف نمیشوند |
| فقطافزودنی (Append-only) | فقط insert مجاز است؛ اینجا با trigger اعمال میشود |
| ثبت معکوس (Reversal) | Journal entry تازه که قرینهٔ ثبت اشتباه است |
| رد حسابرسی (Audit trail) | تاریخچهٔ کامل و تغییرناپذیر اینکه چه کسی، چه چیزی و چه وقت ثبت کرده |
| اعلان HTTP (Webhook) | Callback از PSP برای اعلام event |
| بررسی امضا (Signature verification) | کنترل HMAC روی raw body با signing secret |
| Stripe-Signature | هدر Stripe؛ timestamp با t= و یک v1= از HMAC-SHA256 برای هر secret فعال |
| HMAC | کد اصالت پیام مبتنی بر hash؛ HMAC-SHA256 در Stripe و Adyen |
| پنجرهٔ بازپخش (Replay window) | Tolerance روی timestamp امضاشده؛ 5 دقیقه در کتابخانههای Stripe |
| چرخش راز (Secret roll) | تعویض signing secret با همپوشانی؛ تا 7 روز در Stripe |
| تحویل حداقل یکباره (At-least-once delivery) | هر event یک بار یا بیشتر میرسد |
| Webhook بیترتیب (Out-of-order webhooks) | ترتیب رسیدن با ترتیب ساخته شدن فرق دارد |
| جدول Idempotency Webhook (Webhook idempotency table) | Inbox با کلید PSP و event id؛ insert تکراری بیاثر است |
| صندوق ورودی (Inbox) | جدول dedup مصرفکننده برای شناسهٔ event پردازششده |
| پیام کنارگذاشتهشده (Dead-letter) | محل پیام پس از آخرین retry ناموفق، برای انسان یا sweep |
| صندوق خروجی (Outbox) | جدول event در transaction کسبوکار؛ انتشار با relay |
| اثر دقیقاً یکباره (Exactly-once effect) | یک اثر کسبوکار با وجود تحویل تکراری |
| Saga | دنبالهٔ transactionهای محلی با compensation بهجای transaction سراسری |
| جبران (Compensation) | خنثیسازی معنایی مرحلهٔ تمامشده؛ void یا release |
| تطبیق (Reconciliation) | مقایسهٔ ثبت خودتان با settlement file و بانک |
| فایل تسویه (Settlement file) | گزارش PSP از سطرهای تسویه با gross، fee و net در هر batch |
| واریز به بانک (Payout) | انتقال موجودی PSP به حساب بانکی شما |
| برگشت بانکی (Chargeback) | برگشت پرداخت کارت به ابتکار issuer |
| اعتراض (Dispute) | پروندهٔ chargeback یا inquiry با مدرک و نتیجه |
| درخواست اطلاعات (Inquiry) | درخواست پیش از dispute یا retrieval |
| انتقال مسئولیت (Liability shift) | مسئولیت تقلب پس از 3DS موفق به issuer منتقل میشود |
| 3-D Secure | پروتکل احراز هویت کارت EMV 3DS2 با frictionless و challenge |
| احراز هویت قوی (SCA) | Strong Customer Authentication؛ احراز هویت دوعاملی لازم در EEA |
| PSD2 | دستورالعمل دوم خدمات پرداخت اتحادیهٔ اروپا؛ RTS آن، Regulation 2018/389، تعریف SCA را میدهد |
| تراکنش آغازشده توسط پذیرنده (Merchant-Initiated Transaction, MIT) | Merchant-initiated transaction؛ برداشت off-session با mandate |
| PCI DSS | استاندارد امنیت دادهٔ صنعت کارت؛ نسخهٔ جاری v4.0.1 |
| SAQ A | کوتاهترین خودارزیابی PCI برای برونسپاری کامل کارهای دادهٔ کارت |
| شمارهٔ کارت (PAN) | Primary account number |
| جایگزینی با توکن (Tokenization) | جایگزینی PAN با token قابلاستفاده فقط از راه PSP |
| توکن شبکه (Network tokens) | صادرشده توسط شبکه مثل Visa Token Service؛ ماندگار پس از صدور مجدد کارت |
| نگهداری کارت (Card vaulting) | ذخیره برای استفادهٔ مجدد؛ PAN در vault خود PSP میماند |
| موتور ریسک (Risk engine) | ترکیب rule، velocity و model برای تصمیم |
| امتیاز تقلب (Fraud score) | خروجی مدل؛ Radar برابر 0–99 |
| قواعد سرعت (Velocity rules) | محدودیت attempt برای کارت، دستگاه، IP یا ایمیل در پنجرهٔ زمانی |
| اثرانگشت دستگاه (Device fingerprint) | شناسهٔ پایدار دستگاه مشتری از SDK مربوط به checkout |
| آزمایش کارت (Card testing) | Bot کارتهای دزدیدهشده را با charge کوچک امتحان میکند |
| صف بررسی دستی (Manual review queue) | پرداخت نگهداشتهشده برای تصمیم انسان |
| رد موقت (Soft decline) | شاید بعداً موفق شود؛ insufficient_funds |
| رد قطعی (Hard decline) | روش پرداخت تازه لازم دارد؛ stolen_card |
| وصول مجدد (Dunning) | Retry برداشت دورهای ناموفق و تماس با مشتری |
| تلاش هوشمند (Smart retries) | زمان retry با مدل؛ Stripe پیشفرض تا 8 بار در 2 هفته |
| Laravel Cashier | بستهٔ billing مربوط به Stripe در Laravel، روی Stripe PHP SDK |
| Stripe PHP SDK | stripe/stripe-php؛ Webhook::constructEvent و گزینهٔ idempotency_key |
| stripe-go | github.com/stripe/stripe-go/v87؛ stripe.NewClient و webhook.ConstructEvent |
منابع
- Brandur Leach. Designing robust and predictable APIs with idempotency, Stripe blog, February 22, 2017. https://stripe.com/blog/idempotency
- Ilya Ganelin. Ledger: Stripe’s system for tracking and validating money movement, Stripe blog, February 16, 2024. https://stripe.com/blog/ledger-stripe-system-for-tracking-and-validating-money-movement
- Stripe Docs. How PaymentIntents and SetupIntents work (lifecycle). https://docs.stripe.com/payments/paymentintents/lifecycle
- Stripe Docs. Payment Intents API. https://docs.stripe.com/payments/payment-intents
- Stripe Docs. Idempotent requests. https://docs.stripe.com/api/idempotent_requests
- Stripe Docs. Low-level error handling. https://docs.stripe.com/error-low-level
- Stripe Docs. Webhooks and Verify webhook signatures. https://docs.stripe.com/webhooks, https://docs.stripe.com/webhooks/signature
- Stripe Docs. Process undelivered webhook events. https://docs.stripe.com/webhooks/process-undelivered-events
- Stripe API reference. Events. https://docs.stripe.com/api/events
- Stripe API reference. The PaymentIntent object (
latest_charge). https://docs.stripe.com/api/payment_intents/object - Stripe Docs. Place a hold on a payment method. https://docs.stripe.com/payments/place-a-hold-on-a-payment-method
- Stripe Docs. Refunds. https://docs.stripe.com/refunds
- Stripe Docs. Supported currencies. https://docs.stripe.com/currencies
- Stripe Docs. Disputes, How disputes work, Responding to disputes. https://docs.stripe.com/disputes, https://docs.stripe.com/disputes/how-disputes-work, https://docs.stripe.com/disputes/responding
- Stripe Docs. Radar and Risk evaluation. https://docs.stripe.com/radar, https://docs.stripe.com/radar/risk-evaluation
- Stripe Docs. Strong Customer Authentication and 3D Secure. https://docs.stripe.com/strong-customer-authentication, https://docs.stripe.com/payments/3d-secure
- Stripe Docs. Integration security guide. https://docs.stripe.com/security/guide
- Stripe Docs. Save and reuse payment methods, Payment Element. https://docs.stripe.com/payments/save-and-reuse, https://docs.stripe.com/payments/payment-element
- Stripe Docs. Declines and Decline codes. https://docs.stripe.com/declines, https://docs.stripe.com/declines/codes
- Stripe Docs. Smart Retries and Revenue recovery. https://docs.stripe.com/billing/revenue-recovery/smart-retries, https://docs.stripe.com/billing/revenue-recovery
- Stripe Docs. Payout reconciliation report, Balance report, Payouts. https://docs.stripe.com/reports/payout-reconciliation, https://docs.stripe.com/reports/balance, https://docs.stripe.com/payouts
- Stripe Docs. SEPA Direct Debit. https://docs.stripe.com/payments/sepa-debit
- stripe-go README,
webhook/client.goandgo.mod. https://raw.githubusercontent.com/stripe/stripe-go/master/README.md, https://raw.githubusercontent.com/stripe/stripe-go/master/webhook/client.go, https://raw.githubusercontent.com/stripe/stripe-go/master/go.mod - stripe-php README,
Webhook.php,WebhookSignature.php,Util/RequestOptions.php. https://raw.githubusercontent.com/stripe/stripe-php/master/README.md, https://raw.githubusercontent.com/stripe/stripe-php/master/lib/Webhook.php, https://raw.githubusercontent.com/stripe/stripe-php/master/lib/WebhookSignature.php, https://raw.githubusercontent.com/stripe/stripe-php/master/lib/Util/RequestOptions.php - Adyen Docs. API idempotency. https://docs.adyen.com/development-resources/api-idempotency
- Adyen Docs. Webhooks and Verify HMAC signatures. https://docs.adyen.com/development-resources/webhooks, https://docs.adyen.com/development-resources/webhooks/secure-webhooks/verify-hmac-signatures
- Adyen Docs. Handle webhook events, Troubleshoot webhooks, Configure and manage webhooks. https://docs.adyen.com/development-resources/webhooks/handle-webhook-events, https://docs.adyen.com/development-resources/webhooks/troubleshoot, https://docs.adyen.com/development-resources/webhooks/configure-and-manage
- Adyen Docs. 3D Secure. https://docs.adyen.com/online-payments/3d-secure
- Adyen Docs. Capture, Cancel, Refund. https://docs.adyen.com/online-payments/capture, https://docs.adyen.com/online-payments/cancel, https://docs.adyen.com/online-payments/refund
- Adyen Docs. Risk management. https://docs.adyen.com/risk-management
- Adyen Docs. Settlement reconciliation. https://docs.adyen.com/reporting/settlement-reconciliation
- PCI Security Standards Council. PCI DSS. https://www.pcisecuritystandards.org/standards/pci-dss/
- PCI SSC blog. Just Published: PCI DSS v4.0.1. https://blog.pcisecuritystandards.org/just-published-pci-dss-v4-0-1
- PCI SSC blog. Important Updates Announced for Merchants Validating to Self-Assessment Questionnaire A. https://blog.pcisecuritystandards.org/important-updates-announced-for-merchants-validating-to-self-assessment-questionnaire-a
- PCI SSC blog. Now is the Time for Organizations to Adopt the Future-Dated Requirements of PCI DSS v4.x. https://blog.pcisecuritystandards.org/now-is-the-time-for-organizations-to-adopt-the-future-dated-requirements-of-pci-dss-v4-x
- EMVCo. EMV 3-D Secure. https://www.emvco.com/emv-technologies/3-d-secure/
- European Banking Authority. Regulatory Technical Standards on strong customer authentication and secure communication under PSD2. https://www.eba.europa.eu/regulation-and-policy/payment-services-and-electronic-money/regulatory-technical-standards-on-strong-customer-authentication-and-secure-communication-under-psd2
- Visa. Visa Token Service. https://usa.visa.com/products/visa-token-service.html
- SIX (ISO 4217 maintenance agency). ISO 4217 list one (XML, published 2026-09-17). https://www.six-group.com/dam/download/financial-information/data-center/iso-currrency/lists/list-one.xml
- Wikipedia (secondary). ISO 4217 and Chargeback. https://en.wikipedia.org/wiki/ISO_4217, https://en.wikipedia.org/wiki/Chargeback
- Fielding, Nottingham, Reschke. RFC 9110: HTTP Semantics, section 9.2.2. https://www.rfc-editor.org/rfc/rfc9110.txt
- IETF HTTPAPI. The Idempotency-Key HTTP Header Field (draft-ietf-httpapi-idempotency-key-header). https://datatracker.ietf.org/doc/html/draft-ietf-httpapi-idempotency-key-header
- Martin Fowler. Patterns for Accounting and Money. https://martinfowler.com/eaaDev/AccountingNarrative.html, https://martinfowler.com/eaaCatalog/money.html
- Modern Treasury. Accounting for Developers, Part I and Ledger database. https://www.moderntreasury.com/journal/accounting-for-developers-part-i, https://www.moderntreasury.com/learn/ledger-database
- Square Developer. Idempotency. https://developer.squareup.com/docs/build-basics/common-api-patterns/idempotency
- Brandur Leach. Implementing Stripe-like Idempotency Keys in Postgres. https://brandur.org/idempotency-keys
- Shopify Engineering. 10 Tips for Building Resilient Payment Systems. https://shopify.engineering/building-resilient-payment-systems
- Laravel 13. Cashier (Stripe), Queues, Database, CSRF Protection, HTTP Client. https://laravel.com/docs/13.x/billing, https://laravel.com/docs/13.x/queues, https://laravel.com/docs/13.x/database, https://laravel.com/docs/13.x/csrf, https://laravel.com/docs/13.x/http-client
- laravel/cashier-stripe 16.x README,
composer.json,config/cashier.php,src/Payment.php,src/Http/Middleware/VerifyWebhookSignature.php. https://raw.githubusercontent.com/laravel/cashier-stripe/16.x/README.md, https://raw.githubusercontent.com/laravel/cashier-stripe/16.x/composer.json, https://raw.githubusercontent.com/laravel/cashier-stripe/16.x/config/cashier.php, https://raw.githubusercontent.com/laravel/cashier-stripe/16.x/src/Payment.php, https://raw.githubusercontent.com/laravel/cashier-stripe/16.x/src/Http/Middleware/VerifyWebhookSignature.php - Laravel 13. Task Scheduling, Query Builder, Eloquent: Mutators & Casting, Artisan Console, Authorization. https://laravel.com/docs/13.x/scheduling, https://laravel.com/docs/13.x/queries, https://laravel.com/docs/13.x/eloquent-mutators, https://laravel.com/docs/13.x/artisan, https://laravel.com/docs/13.x/authorization
- Go. Release History (go1.27.4). https://go.dev/doc/devel/release