mollie_pay 0.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. checksums.yaml +7 -0
  2. data/MIT-LICENSE +20 -0
  3. data/README.md +426 -0
  4. data/Rakefile +6 -0
  5. data/app/controllers/mollie_pay/application_controller.rb +4 -0
  6. data/app/controllers/mollie_pay/webhook_events_controller.rb +53 -0
  7. data/app/controllers/mollie_pay/webhooks_controller.rb +20 -0
  8. data/app/jobs/mollie_pay/application_job.rb +24 -0
  9. data/app/jobs/mollie_pay/delete_mollie_customer_job.rb +16 -0
  10. data/app/jobs/mollie_pay/notify_billable_job.rb +17 -0
  11. data/app/jobs/mollie_pay/process_webhook_event_job.rb +39 -0
  12. data/app/jobs/mollie_pay/process_webhook_job.rb +56 -0
  13. data/app/jobs/mollie_pay/refresh_pending_mandate_job.rb +22 -0
  14. data/app/jobs/mollie_pay/sync_chargebacks_job.rb +19 -0
  15. data/app/jobs/mollie_pay/sync_subscription_job.rb +18 -0
  16. data/app/jobs/mollie_pay/sync_subscriptions_job.rb +16 -0
  17. data/app/models/concerns/mollie_pay/has_uuid.rb +19 -0
  18. data/app/models/concerns/mollie_pay/syncable.rb +208 -0
  19. data/app/models/mollie_pay/application_record.rb +45 -0
  20. data/app/models/mollie_pay/billable.rb +445 -0
  21. data/app/models/mollie_pay/chargeback.rb +103 -0
  22. data/app/models/mollie_pay/customer.rb +32 -0
  23. data/app/models/mollie_pay/mandate.rb +113 -0
  24. data/app/models/mollie_pay/payment.rb +241 -0
  25. data/app/models/mollie_pay/refund.rb +61 -0
  26. data/app/models/mollie_pay/sales_invoice.rb +131 -0
  27. data/app/models/mollie_pay/subscription.rb +215 -0
  28. data/config/routes.rb +4 -0
  29. data/db/migrate/20260315142959_create_mollie_pay_customers.rb +9 -0
  30. data/db/migrate/20260315143008_create_mollie_pay_mandates.rb +13 -0
  31. data/db/migrate/20260315143014_create_mollie_pay_subscriptions.rb +15 -0
  32. data/db/migrate/20260315143020_create_mollie_pay_payments.rb +20 -0
  33. data/db/migrate/20260315143026_create_mollie_pay_refunds.rb +14 -0
  34. data/db/migrate/20260315143032_create_mollie_pay_webhook_events.rb +12 -0
  35. data/db/migrate/20260315143040_add_status_indexes_to_mollie_pay.rb +8 -0
  36. data/db/migrate/20260315143050_add_checkout_url_to_mollie_pay_payments.rb +5 -0
  37. data/db/migrate/20260316120000_make_mollie_id_nullable_on_mollie_pay_payments.rb +5 -0
  38. data/db/migrate/20260317100000_make_webhook_event_mollie_id_unique.rb +6 -0
  39. data/db/migrate/20260317194500_add_authorized_at_to_mollie_pay_payments.rb +5 -0
  40. data/db/migrate/20260317194501_add_amount_tracking_to_mollie_pay_payments.rb +9 -0
  41. data/db/migrate/20260318100000_add_name_to_mollie_pay_subscriptions.rb +12 -0
  42. data/db/migrate/20260318110000_drop_mollie_pay_webhook_events.rb +19 -0
  43. data/db/migrate/20260321000001_create_mollie_pay_chargebacks.rb +15 -0
  44. data/db/migrate/20260326000002_create_mollie_pay_sales_invoices.rb +19 -0
  45. data/db/migrate/20261115000001_change_mollie_pay_money_to_decimal.rb +38 -0
  46. data/db/migrate/20261202000001_add_sync_version_to_mollie_pay_tables.rb +13 -0
  47. data/db/migrate/20261202000002_add_created_at_mollie_to_mollie_pay_payments.rb +5 -0
  48. data/db/migrate/20261203000001_add_mandate_to_mollie_pay_payments.rb +6 -0
  49. data/docs/api.md +359 -0
  50. data/docs/mandates.md +340 -0
  51. data/docs/request-signing.md +178 -0
  52. data/docs/testing.md +177 -0
  53. data/docs/tutorial.md +1340 -0
  54. data/docs/webhooks.md +231 -0
  55. data/lib/generators/mollie_pay/install/install_generator.rb +44 -0
  56. data/lib/generators/mollie_pay/install/templates/initializer.rb.tt +12 -0
  57. data/lib/mollie/sales_invoice.rb +124 -0
  58. data/lib/mollie_pay/configuration.rb +101 -0
  59. data/lib/mollie_pay/engine.rb +31 -0
  60. data/lib/mollie_pay/errors.rb +12 -0
  61. data/lib/mollie_pay/request_signature.rb +160 -0
  62. data/lib/mollie_pay/test_fixtures/customer.json +36 -0
  63. data/lib/mollie_pay/test_fixtures/payment.json +40 -0
  64. data/lib/mollie_pay/test_fixtures/payment_billink.json +79 -0
  65. data/lib/mollie_pay/test_fixtures/payment_with_chargebacks.json +72 -0
  66. data/lib/mollie_pay/test_fixtures/refund.json +32 -0
  67. data/lib/mollie_pay/test_fixtures/sales_invoice.json +72 -0
  68. data/lib/mollie_pay/test_fixtures/subscription.json +48 -0
  69. data/lib/mollie_pay/test_helper.rb +576 -0
  70. data/lib/mollie_pay/version.rb +3 -0
  71. data/lib/mollie_pay/webhook_signature.rb +21 -0
  72. data/lib/mollie_pay.rb +182 -0
  73. data/lib/tasks/mollie_pay_tasks.rake +43 -0
  74. metadata +148 -0
data/docs/mandates.md ADDED
@@ -0,0 +1,340 @@
1
+ # SEPA Direct Debit Mandates
2
+
3
+ A SEPA Direct Debit mandate is a legal authorization from a customer allowing you
4
+ to debit their bank account. MolliePay supports two ways to create mandates, each
5
+ with different compliance obligations.
6
+
7
+ ## Two Paths to Mandates
8
+
9
+ ### Path 1: First Payment (Recommended)
10
+
11
+ Use `mollie_pay_first` to create a payment with `sequenceType: "first"`. The
12
+ customer is redirected to Mollie's checkout, where their bank authenticates them
13
+ with Strong Customer Authentication (SCA). On success, Mollie automatically
14
+ creates a `directdebit` mandate.
15
+
16
+ ```ruby
17
+ payment = current_organization.mollie_pay_first(
18
+ amount: 100, description: "Activation fee"
19
+ )
20
+ redirect_to payment.checkout_url
21
+ ```
22
+
23
+ **This is the recommended approach for most applications.** Mollie's checkout
24
+ handles consent display, bank authentication, and mandate creation. Your
25
+ compliance obligations are minimal.
26
+
27
+ #### Pay by Bank as the first payment
28
+
29
+ Pay by Bank (`paybybank`) can be used as the first payment method. Mollie
30
+ relaunched it on GoCardless technology in October 2026; it captures the
31
+ customer's IBAN during checkout, which Mollie uses for the mandate. It is live
32
+ in the Netherlands, with wider European rollout planned through 2027. Pay by
33
+ Bank cannot be used for the recurring payments themselves: those are collected
34
+ via SEPA Direct Debit on the mandate.
35
+
36
+ ```ruby
37
+ payment = current_organization.mollie_pay_first(
38
+ amount: 100, description: "Activation fee", method: "paybybank"
39
+ )
40
+ redirect_to payment.checkout_url
41
+ ```
42
+
43
+ A Pay by Bank payment stays `pending` until the funds reach Mollie: seconds for
44
+ an instant SEPA transfer, 2-3 business days for a standard one.
45
+ `on_mollie_first_payment_paid` and `on_mollie_mandate_created` fire only once it
46
+ is `paid`, so don't call `mollie_subscribe` before then.
47
+
48
+ A Pay by Bank first payment creates a `directdebit` mandate, the same as iDEAL
49
+ and Bancontact. **SEPA Direct Debit must be enabled on your Mollie profile**,
50
+ otherwise Mollie cannot create the mandate.
51
+
52
+ Mollie can report the mandate as `pending` while it has not yet received the
53
+ IBAN from the first payment. This happens with iDEAL too: the payment can arrive
54
+ `paid` a few seconds before its mandate is `valid`. Mollie sends no webhook for
55
+ the mandate itself, and none for the payment once it is paid. MolliePay stores
56
+ the mandate as `pending` and `MolliePay::RefreshPendingMandateJob` re-fetches it
57
+ with growing waits until Mollie reports it `valid` or `invalid`.
58
+ `on_mollie_mandate_created` fires once when it turns `valid`, so subscribe from
59
+ that hook rather than from `on_mollie_first_payment_paid`.
60
+
61
+ The job tries 10 times over roughly four hours. If the mandate is still
62
+ `pending` after that, the job fails with `MolliePay::MandatePending` in your
63
+ queue backend and the mandate stays `pending`. Retry that job, or enqueue a new
64
+ one with `MolliePay::RefreshPendingMandateJob.perform_later(mandate)`.
65
+
66
+ #### Subscribing on a specific mandate (re-authorization)
67
+
68
+ Each synced payment stores its local mandate in `payment.mandate` (and the
69
+ reverse association `mandate.payments` lists the originating first payment and
70
+ subsequent recurring payments). Both associations are persisted before
71
+ `on_mollie_mandate_created` and `on_mollie_first_payment_paid` run. If a hook
72
+ also needs unpersisted Mollie fields such as `metadata`, fetch the live payment
73
+ with `payment.mollie_record`.
74
+
75
+ Pass `mandate:` to `mollie_subscribe` to send `mandateId` to Mollie instead of
76
+ letting Mollie pick any valid mandate on the customer. The mandate must belong
77
+ to the billable customer (otherwise `MolliePay::Error` is raised) and have
78
+ status `"valid"` in the database (otherwise `MolliePay::MandateRequired` is
79
+ raised).
80
+
81
+ Always subscribe from `on_mollie_mandate_created(mandate)` — where `mandate` is
82
+ guaranteed to be persisted and `"valid"`, even for iDEAL or Pay by Bank
83
+ mandates that start as `"pending"`. When a customer re-authorizes after an
84
+ earlier account bounced, an existing local subscription for that `name` may
85
+ still be `active` or `pending`, and `mollie_subscribe` returns it unchanged.
86
+
87
+ Because `NotifyBillableJob` delivers hooks at least once and pending mandates
88
+ can activate out of order, comparing only against the active subscription's
89
+ current `mandate_id` is not safe: a delayed or retried hook for an older
90
+ still-valid mandate would cancel the subscription on the newer mandate and
91
+ recreate it on the old one. Two concurrent hook executions for the same
92
+ subscription can also race between canceling and re-subscribing.
93
+
94
+ To re-authorize safely:
95
+
96
+ 1. Persist which first payment (or mandate) the host currently intends to use
97
+ before redirecting the customer to Mollie's checkout, and ignore hooks for
98
+ superseded mandates before canceling any subscription.
99
+ 2. Serialize concurrent hook executions for the same billable and subscription
100
+ name (for example with Solid Queue's `limits_concurrency` or your job
101
+ backend's equivalent per-subscription lock — never hold a database
102
+ transaction or row lock open across Mollie HTTP calls).
103
+
104
+ ```ruby
105
+ # 1. Record the intended first payment before redirecting to Mollie checkout:
106
+ payment = current_organization.mollie_pay_first(
107
+ amount: BigDecimal("0.01"),
108
+ description: "Update payment method"
109
+ )
110
+ current_organization.update!(intended_mandate_payment_id: payment.id)
111
+ redirect_to payment.checkout_url, allow_other_host: true
112
+ ```
113
+
114
+ ```ruby
115
+ # 2. Enqueue a serialized job from your billable model's hook:
116
+ def on_mollie_mandate_created(mandate)
117
+ ReauthorizeSubscriptionJob.perform_later(self, mandate)
118
+ end
119
+ ```
120
+
121
+ ```ruby
122
+ # 3. Ignore superseded mandates and serialize cancel + subscribe per subscription:
123
+ class ReauthorizeSubscriptionJob < ApplicationJob
124
+ limits_concurrency to: 1, key: ->(organization, _mandate) { [ organization.id, "default" ] }
125
+ retry_on StandardError, wait: :polynomially_longer, attempts: 5
126
+
127
+ def perform(organization, mandate)
128
+ organization.reload
129
+
130
+ intended_payment_id = organization.intended_mandate_payment_id
131
+ return unless intended_payment_id.present?
132
+ return unless mandate.payments.where(id: intended_payment_id).exists?
133
+
134
+ existing = organization.mollie_subscriptions.where(
135
+ status: MolliePay::Subscription::ACTIVE_STATUSES,
136
+ name: "default"
137
+ ).first
138
+
139
+ if existing
140
+ existing_mandate_id = begin
141
+ existing.mollie_record.mandate_id
142
+ rescue Mollie::ResourceNotFoundError
143
+ nil
144
+ end
145
+ return if existing_mandate_id == mandate.mollie_id
146
+
147
+ organization.mollie_cancel_subscription(name: "default")
148
+ end
149
+
150
+ organization.mollie_subscribe(
151
+ amount: BigDecimal("25.00"),
152
+ interval: "1 month",
153
+ description: "Monthly plan",
154
+ mandate: mandate
155
+ )
156
+ end
157
+ end
158
+ ```
159
+
160
+ If you need the first payment that established the mandate inside
161
+ `on_mollie_mandate_created(mandate)`, read
162
+ `mandate.payments.first_payments.first`.
163
+
164
+ ### Path 2: Direct Mandate Creation
165
+
166
+ Use `mollie_create_mandate` to create a SEPA DD mandate directly from an IBAN.
167
+ This is useful for migrating mandates from another provider or when you already
168
+ have a bank relationship with the customer.
169
+
170
+ ```ruby
171
+ mandate = current_organization.mollie_create_mandate(
172
+ method: "directdebit",
173
+ consumer_name: "Jane Doe",
174
+ consumer_account: "NL55INGB0000000000",
175
+ signature_date: Date.today
176
+ )
177
+ ```
178
+
179
+ > **You are legally responsible for collecting customer authorization before
180
+ > calling this method.** Mollie's checkout is not involved — there is no bank
181
+ > authentication or consent display. See the requirements below.
182
+
183
+ ### Comparison
184
+
185
+ | Aspect | First Payment | Direct Creation |
186
+ |--------|--------------|-----------------|
187
+ | Bank authentication (SCA) | Yes — handled by bank | No |
188
+ | Consent text display | Handled by Mollie checkout | Your responsibility |
189
+ | Proof of consent | Bank authentication | You must collect and store |
190
+ | Dispute risk | Lower (authorized mandate) | Higher (you must prove consent) |
191
+ | Best for | Most SaaS applications | Mandate migrations, pre-existing relationships |
192
+ | Method | `mollie_pay_first` | `mollie_create_mandate` |
193
+
194
+ ## Legal Requirements for Direct Mandate Creation
195
+
196
+ When using `mollie_create_mandate`, the European Payments Council (EPC) SEPA
197
+ Direct Debit Core Rulebook requires you to:
198
+
199
+ ### 1. Display the Mandate Authorization Text
200
+
201
+ You must show the customer the following standard text (or equivalent in their
202
+ language) before they authorize the mandate:
203
+
204
+ > By signing this mandate form, you authorise (A) **{YOUR COMPANY NAME}** to
205
+ > send instructions to your bank to debit your account and (B) your bank to
206
+ > debit your account in accordance with the instructions from **{YOUR COMPANY
207
+ > NAME}**.
208
+ >
209
+ > As part of your rights, you are entitled to a refund from your bank under the
210
+ > terms and conditions of your agreement with your bank. A refund must be
211
+ > claimed within 8 weeks starting from the date on which your account was
212
+ > debited. Your rights are explained in a statement that you can obtain from
213
+ > your bank.
214
+
215
+ Replace `{YOUR COMPANY NAME}` with your business name. Note that Mollie acts as
216
+ the creditor of record (Creditor Identifier: `NL08ZZZ502057730000`), so Mollie's
217
+ name appears on the customer's bank statement.
218
+
219
+ ### 2. Collect Required Information
220
+
221
+ | Field | Description | Required |
222
+ |-------|-------------|----------|
223
+ | Full name | Account holder name | Yes |
224
+ | IBAN | International Bank Account Number | Yes |
225
+ | Explicit consent | Customer actively accepts the mandate | Yes |
226
+ | BIC | Bank Identifier Code | Optional (derived from IBAN) |
227
+
228
+ ### 3. Record Proof of Consent
229
+
230
+ When the customer accepts the mandate on your website, record:
231
+
232
+ - **Timestamp** — exact date and time of acceptance
233
+ - **IP address** — the customer's IP at time of acceptance
234
+ - **User agent** — browser identification string
235
+ - **Mandate text version** — the exact text the customer agreed to
236
+ - **Customer identifiers** — name, email, account used
237
+
238
+ Pass the consent date to Mollie via the `signature_date` parameter:
239
+
240
+ ```ruby
241
+ mandate = current_organization.mollie_create_mandate(
242
+ method: "directdebit",
243
+ consumer_name: "Jane Doe",
244
+ consumer_account: "NL55INGB0000000000",
245
+ signature_date: Date.today
246
+ )
247
+ ```
248
+
249
+ ### 4. Store Records
250
+
251
+ Mandate consent records must be stored for:
252
+
253
+ - **Active mandates**: entire duration the mandate is active
254
+ - **After last collection**: at least **36 months** after the final debit
255
+ - **Best practice**: retain for **10 years** (varies by national law)
256
+
257
+ Records must be stored in a way that prevents modification (integrity
258
+ protection). If a customer disputes a debit, you must be able to produce
259
+ the mandate as evidence.
260
+
261
+ ### 5. Communicate to the Customer
262
+
263
+ After the customer accepts:
264
+
265
+ 1. **Confirmation**: Show the mandate details on a confirmation page or send
266
+ via email immediately
267
+ 2. **Pre-notification**: Notify the customer at least **14 calendar days** before
268
+ each debit (can be shortened to a minimum of 2 days by written agreement
269
+ with the customer)
270
+
271
+ ## Collecting Consent on the Web
272
+
273
+ ### Recommended Approach
274
+
275
+ Display the full mandate text on a dedicated form page. The customer fills in
276
+ their name and IBAN, reads the authorization text, and submits the form. The
277
+ form submission constitutes their consent.
278
+
279
+ A well-designed consent form includes:
280
+
281
+ 1. IBAN and name input fields
282
+ 2. The full EPC mandate authorization text (visible, not behind a link)
283
+ 3. A clear submit button with text like "Authorize Direct Debit"
284
+ 4. Recording of timestamp, IP, and user agent on submission
285
+
286
+ ### Is a Checkbox Sufficient?
287
+
288
+ A simple checkbox is a "Simple Electronic Signature" (SES) under the EU's eIDAS
289
+ Regulation. For SEPA Core Direct Debit (consumer-facing), this is accepted in
290
+ practice when combined with visible mandate text and proper record-keeping.
291
+
292
+ For SEPA B2B Direct Debit (business-to-business), an Advanced Electronic
293
+ Signature (AES) or Qualified Electronic Signature (QES) is required. This is
294
+ beyond what a checkbox provides — consider a dedicated e-signature service.
295
+
296
+ ### Legal Standing
297
+
298
+ Under eIDAS Regulation (EU No 910/2014), electronic signatures cannot be denied
299
+ legal effect solely because they are electronic. E-mandates collected via web
300
+ forms are valid across all 36 SEPA countries when they comply with the
301
+ requirements above.
302
+
303
+ The key factor in disputes is **evidence quality**, not signature type. A form
304
+ submission with timestamp, IP address, displayed mandate text, and stored consent
305
+ record is defensible. A mandate created with no consent evidence is not.
306
+
307
+ ## Revoking Mandates
308
+
309
+ Customers can request mandate revocation at any time. Use `mollie_revoke_mandate`
310
+ to revoke on Mollie's side and update the local record:
311
+
312
+ ```ruby
313
+ mandate = current_organization.mollie_mandate
314
+ current_organization.mollie_revoke_mandate(mandate)
315
+ ```
316
+
317
+ This sets the mandate status to `invalid` locally and on Mollie. Any active
318
+ subscriptions using this mandate should be canceled separately.
319
+
320
+ ## Quick Reference
321
+
322
+ | Obligation | First Payment | Direct Creation |
323
+ |------------|:------------:|:---------------:|
324
+ | Display mandate text | Mollie handles | You |
325
+ | Collect IBAN + name | Mollie handles | You |
326
+ | Record consent proof | Bank auth | You |
327
+ | Store records 36+ months | Recommended | Required |
328
+ | Pre-notify before debits | Recommended | Required |
329
+ | Send mandate copy | Mollie handles | You |
330
+
331
+ ## References
332
+
333
+ - [EPC SEPA DD Mandate Requirements](https://www.europeanpaymentscouncil.eu/what-we-do/epc-payment-schemes/sepa-direct-debit/sdd-mandate)
334
+ - [Mollie Recurring Payments](https://docs.mollie.com/docs/recurring-payments)
335
+ - [Mollie Create Mandate API](https://docs.mollie.com/reference/create-mandate)
336
+ - [Mollie Pay by Bank](https://docs.mollie.com/docs/pay-by-bank)
337
+ - [Mollie OpenAPI specification](https://github.com/mollie/openapi)
338
+ - [Mollie relaunches Pay by Bank (2026-10-02)](https://www.mollie.com/news/mollie-relaunches-pay-by-bank)
339
+ - [Mollie and GoCardless combine](https://www.mollie.com/news/mollie-and-gocardless)
340
+ - [eIDAS Regulation (EU No 910/2014)](https://eur-lex.europa.eu/legal-content/EN/TXT/?uri=uriserv:OJ.L_.2014.257.01.0073.01.ENG)
@@ -0,0 +1,178 @@
1
+ # Request signing
2
+
3
+ Mollie can require that every API request is signed with an Ed25519 key
4
+ ([request signing](https://docs.mollie.com/reference/request-signing)). You
5
+ register a public key on an API key in the Mollie dashboard; from then on
6
+ Mollie answers `401` to any request made with that API key that does not
7
+ carry a valid signature. MolliePay signs every request it sends once it has
8
+ the private key.
9
+
10
+ What this buys you: an API key that leaks on its own can no longer be used.
11
+ What it does not: if the API key and the private key leak together, signing
12
+ protects nothing.
13
+
14
+ ## Set it up
15
+
16
+ 1. **Generate a key pair** in your app:
17
+
18
+ ```sh
19
+ bin/rails mollie_pay:request_signing:generate
20
+ ```
21
+
22
+ It prints the public key as PEM and the private key as one line. Nothing is
23
+ written to disk, so the private key is shown once.
24
+
25
+ 2. **Store the private key** as a secret (see [Where to keep the private
26
+ key](#where-to-keep-the-private-key)) and point the engine at it:
27
+
28
+ ```ruby
29
+ # config/initializers/mollie_pay.rb
30
+ config.request_signing_key = ENV["MOLLIE_REQUEST_SIGNING_KEY"]
31
+ ```
32
+
33
+ 3. **Register the public key** in the Mollie dashboard: Developers > API
34
+ keys, the "Public key" field of a new API key. Paste the whole PEM,
35
+ including the `BEGIN` and `END` lines. The dashboard offers the field when
36
+ a key is created, so this gives you a new API key: deploy it together with
37
+ the private key.
38
+
39
+ 4. **Check it** from the deployed app:
40
+
41
+ ```sh
42
+ bin/rails mollie_pay:request_signing:verify
43
+ ```
44
+
45
+ | Answer | Meaning |
46
+ |---|---|
47
+ | `OK` | Mollie refuses unsigned requests for this API key and accepts the app's signature. |
48
+ | `Not enforced` | Mollie accepts unsigned requests, so no public key is registered on this API key. |
49
+ | `Refused` | Mollie enforces signing and rejects the app's signature: the registered public key is not this private key's, the API key is wrong, or the clock is off. |
50
+
51
+ The check makes two requests that read the payment methods and change
52
+ nothing.
53
+
54
+ Signing is harmless while Mollie does not enforce it: an API key without a
55
+ public key answers signed requests as usual. So the private key can go out
56
+ before the API key that needs it.
57
+
58
+ ## Where to keep the private key
59
+
60
+ The private key is a secret of the same weight as the API key. It belongs
61
+ where your other production secrets live, and nowhere else.
62
+
63
+ **An environment variable from a secret manager.** The single line the
64
+ generator prints has no line breaks and no quotes to escape, so it fits any
65
+ secret store, `.env` file or deploy tool:
66
+
67
+ ```sh
68
+ MOLLIE_REQUEST_SIGNING_KEY=MC4CAQAwBQYDK2VwBCIEI...
69
+ ```
70
+
71
+ **Rails encrypted credentials.** `bin/rails credentials:edit --environment production`:
72
+
73
+ ```yaml
74
+ mollie:
75
+ request_signing_key: MC4CAQAwBQYDK2VwBCIEI...
76
+ ```
77
+
78
+ ```ruby
79
+ config.request_signing_key = Rails.application.credentials.dig(:mollie, :request_signing_key)
80
+ ```
81
+
82
+ `request_signing_key` takes three forms, so whatever your secret store makes
83
+ of the key is read:
84
+
85
+ | Form | Example |
86
+ |---|---|
87
+ | The single line | `MC4CAQAwBQYDK2VwBCIEI...` |
88
+ | PEM | `-----BEGIN PRIVATE KEY-----`, the line, `-----END PRIVATE KEY-----` |
89
+ | PEM with `\n` written out | `-----BEGIN PRIVATE KEY-----\nMC4C...\n-----END PRIVATE KEY-----\n` |
90
+
91
+ A value that is not an Ed25519 private key, the public key included, raises
92
+ `MolliePay::ConfigurationError` when the app boots, not on the first payment.
93
+
94
+ ## Rules for the private key
95
+
96
+ - **Never in the repository.** Not in the initializer, not in a `.env` file
97
+ that is committed, not in a fixture. Not in a chat, a ticket, a CI log or a
98
+ screenshot either.
99
+ - **One key pair per API key.** A pair for production, another for staging,
100
+ another for a developer's test key. A test pair that leaks then says
101
+ nothing about production.
102
+ - **Only where Mollie is called.** The web and job processes need it. CI does
103
+ not: the test suite stubs Mollie and needs no key at all.
104
+ - **Generate it where you trust the screen.** The generator prints the key to
105
+ the terminal. Copy it into the secret store, then clear the scrollback. If
106
+ you would sooner have files, see [With openssl](#with-openssl).
107
+ - **Keep the clock right.** Mollie rejects a signature whose timestamp is more
108
+ than 5 minutes from its own time. A server without time synchronisation
109
+ will start failing with `401`.
110
+
111
+ MolliePay never logs the key, and `MolliePay.configuration.inspect` leaves it
112
+ out, as it does the API key.
113
+
114
+ ## When something goes wrong
115
+
116
+ - **The private key is lost.** It cannot be recovered and the public key is
117
+ no help. Generate a new pair and create a new API key with the new public
118
+ key.
119
+ - **The private key, or both keys, leaked.** Delete the API key in the Mollie
120
+ dashboard first: that ends what the leak can do. Then set up a new API key
121
+ with a new pair.
122
+ - **Which public key belongs to the key this app has?**
123
+
124
+ ```sh
125
+ bin/rails mollie_pay:request_signing:public_key
126
+ ```
127
+
128
+ It derives the public key from the configured private key, to compare with
129
+ what the dashboard shows or to register it again.
130
+ - **Every call fails with `401` after a deploy.** Run
131
+ `mollie_pay:request_signing:verify`. `Refused` with a key you trust usually
132
+ means the API key and the private key are from different pairs, for example
133
+ production's API key with staging's private key.
134
+
135
+ ## Rotating
136
+
137
+ 1. Generate a new pair.
138
+ 2. Create a new API key in the Mollie dashboard with the new public key.
139
+ 3. Deploy the new API key and the new private key together.
140
+ 4. Run `mollie_pay:request_signing:verify`.
141
+ 5. Delete the old API key at Mollie.
142
+
143
+ Webhooks keep working through a rotation, as long as the new API key is for
144
+ the same website profile: Mollie sends an id, and the engine fetches the
145
+ object with whatever API key it has at that moment.
146
+
147
+ ## With openssl
148
+
149
+ The generator needs nothing but the app. The same pair with `openssl`, as
150
+ files:
151
+
152
+ ```sh
153
+ umask 077
154
+ openssl genpkey -algorithm Ed25519 -out ed25519_private.pem
155
+ openssl pkey -in ed25519_private.pem -pubout -out ed25519_public.pem
156
+ ```
157
+
158
+ Paste `ed25519_public.pem` into Mollie, store the contents of
159
+ `ed25519_private.pem` as the secret, and delete both files. The PEM file's
160
+ contents are accepted as they are.
161
+
162
+ ## In tests
163
+
164
+ A host app's tests need no key. With a key set and WebMock in use, the
165
+ stubbed requests carry `X-Client-Signature` and `X-Client-Signed-At`, so a
166
+ test can assert on them:
167
+
168
+ ```ruby
169
+ MolliePay.configuration.request_signing_key = OpenSSL::PKey.generate_key("ED25519").private_to_pem
170
+ ```
171
+
172
+ ## For engine development
173
+
174
+ `bin/e2e-request-signing` in this repository runs against Mollie's real API
175
+ with a test API key that has a public key registered. It proves that Mollie
176
+ refuses an unsigned request, sends every kind of request the engine makes,
177
+ signed, and ends with wrongly signed requests that must be refused. The test
178
+ suite never runs it; its header says how to run it.
data/docs/testing.md ADDED
@@ -0,0 +1,177 @@
1
+ # Testing
2
+
3
+ MolliePay ships test helpers for Minitest that stub all Mollie API calls. Add
4
+ to your `test/test_helper.rb`:
5
+
6
+ ```ruby
7
+ require "mollie_pay/test_helper"
8
+
9
+ class ActiveSupport::TestCase
10
+ include MolliePay::TestHelper
11
+ end
12
+ ```
13
+
14
+ This gives you stub helpers and fake response builders in all your tests.
15
+
16
+ ## Stub helpers
17
+
18
+ Each helper stubs a Mollie API call and runs your block:
19
+
20
+ ```ruby
21
+ class OrganizationTest < ActiveSupport::TestCase
22
+ test "one-off payment" do
23
+ stub_mollie_payment_create do
24
+ payment = @org.mollie_pay_once(amount: 5000, description: "Test")
25
+ assert_equal "open", payment.status
26
+ assert payment.checkout_url.present?
27
+ end
28
+ end
29
+
30
+ test "first payment with new customer" do
31
+ stub_mollie_customer_and_payment_create do
32
+ payment = new_org.mollie_pay_first(amount: 1000, description: "Setup")
33
+ assert new_org.reload.mollie_customer.present?
34
+ end
35
+ end
36
+
37
+ test "subscribe" do
38
+ stub_mollie_subscription_create do
39
+ subscription = @org.mollie_subscribe(
40
+ amount: 2500, interval: "1 month", description: "Monthly"
41
+ )
42
+ assert_equal "active", subscription.status
43
+ end
44
+ end
45
+
46
+ test "cancel subscription" do
47
+ stub_mollie_subscription_cancel do
48
+ @org.mollie_cancel_subscription
49
+ end
50
+ end
51
+
52
+ test "refund" do
53
+ stub_mollie_refund_create do
54
+ refund = @org.mollie_refund(payment)
55
+ assert_equal "queued", refund.status
56
+ end
57
+ end
58
+ end
59
+ ```
60
+
61
+ All stubs accept keyword overrides to control the Mollie response:
62
+
63
+ ```ruby
64
+ stub_mollie_payment_create(id: "tr_custom123", status: "paid") do
65
+ # ...
66
+ end
67
+
68
+ stub_mollie_customer_and_payment_create(
69
+ customer_overrides: { id: "cst_specific" },
70
+ payment_overrides: { id: "tr_specific", status: "open" }
71
+ ) do
72
+ # ...
73
+ end
74
+ ```
75
+
76
+ ## Fake response builders
77
+
78
+ Build individual Mollie response objects when you need more control:
79
+
80
+ ```ruby
81
+ response = fake_mollie_payment(id: "tr_test123", status: "paid")
82
+ response = fake_mollie_customer(id: "cst_test123")
83
+ response = fake_mollie_subscription(id: "sub_test123", status: "active")
84
+ response = fake_mollie_refund(id: "re_test123", status: "queued")
85
+ response = fake_mollie_capture(id: "cpt_test123", payment_id: "tr_test123")
86
+ ```
87
+
88
+ All IDs default to random values (`tr_test<hex>`, etc.) when not specified.
89
+
90
+ ## Available helpers
91
+
92
+ | Helper | Stubs | Default response |
93
+ |---|---|---|
94
+ | `stub_mollie_payment_create` | `Mollie::Payment.create` | `status: "open"`, random ID and checkout URL |
95
+ | `stub_mollie_customer_and_payment_create` | `Mollie::Customer.create` + `Mollie::Payment.create` | Both with random IDs |
96
+ | `stub_mollie_subscription_create` | `Mollie::Customer::Subscription.create` | `status: "active"`, random ID |
97
+ | `stub_mollie_subscription_cancel` | `Mollie::Customer::Subscription.cancel` | Returns nil |
98
+ | `stub_mollie_subscription_update` | `Mollie::Customer::Subscription.update` | `status: "active"`, random ID |
99
+ | `stub_mollie_refund_create` | `Mollie::Payment::Refund.create` | `status: "queued"`, random ID |
100
+ | `stub_mollie_capture_create` | `Mollie::Payment.get` (authorized payment) + `Mollie::Payment::Capture.create` | Random `cpt_` ID; `status: "open"` makes `mollie_capture` raise |
101
+ | `stub_mollie_payment_release_authorization` | `Mollie::Payment.get` (authorized payment whose `release_authorization` returns true) | `status: "paid"` makes `mollie_release_authorization` raise |
102
+
103
+ `stub_mollie_capture_create` and `stub_mollie_payment_release_authorization`
104
+ override `Mollie::Payment.get` for the whole block.
105
+
106
+ ## WebMock-based API stubs
107
+
108
+ For integration tests that exercise the full Mollie SDK pipeline (JSON parsing,
109
+ object construction, HTTP handling), use the `webmock_mollie_*` helpers. These
110
+ stub the actual HTTP endpoints with realistic Mollie API v2 HAL+JSON responses.
111
+
112
+ ```ruby
113
+ class OrganizationIntegrationTest < ActiveSupport::TestCase
114
+ test "payment creation through full SDK pipeline" do
115
+ webmock_mollie_payment_create do
116
+ payment = @org.mollie_pay_once(amount: 5000, description: "Test")
117
+ assert_equal "tr_test1234AB", payment.mollie_id
118
+ end
119
+ end
120
+
121
+ test "subscription" do
122
+ webmock_mollie_subscription_create do
123
+ subscription = @org.mollie_subscribe(amount: 2500, interval: "1 month", description: "Monthly")
124
+ assert_equal "sub_test1234AB", subscription.mollie_id
125
+ end
126
+ end
127
+
128
+ test "webhook payment fetch" do
129
+ webmock_mollie_payment_get("tr_abc123", status: "paid", customer_id: "cst_xyz") do
130
+ mollie_payment = Mollie::Payment.get("tr_abc123")
131
+ assert_equal "paid", mollie_payment.status
132
+ end
133
+ end
134
+
135
+ test "billink authorization webhook" do
136
+ webmock_mollie_payment_get("tr_abc123", fixture: "payment_billink", status: "authorized", customer_id: "cst_xyz") do
137
+ MolliePay::ProcessWebhookJob.perform_now("tr_abc123")
138
+ end
139
+ end
140
+ end
141
+ ```
142
+
143
+ Hooks run in `MolliePay::NotifyBillableJob`, not inside `ProcessWebhookJob`
144
+ or the `Billable` call that saved the change (only `mollie_swap_subscription`
145
+ and `mollie_mark_invoice_paid` call their hook inline). To run your hook in a webhook test, wrap the call in
146
+ `perform_enqueued_jobs { ... }` from `ActiveJob::TestHelper`, or assert the
147
+ job was enqueued:
148
+
149
+ ```ruby
150
+ assert_enqueued_with job: MolliePay::NotifyBillableJob, args: [ org, :on_mollie_payment_paid, payment ]
151
+ ```
152
+
153
+ `webmock_mollie_payment_get` loads `payment.json` by default. Pass
154
+ `fixture: "payment_billink"` for a Billink (manual capture) payment with
155
+ `captureMode`, `captureBefore`, `billingAddress` and `lines`.
156
+
157
+ All WebMock helpers accept keyword overrides that merge into the JSON fixture:
158
+
159
+ ```ruby
160
+ webmock_mollie_payment_create(id: "tr_custom", status: "paid", amount_value: "50.00") do
161
+ # ...
162
+ end
163
+ ```
164
+
165
+ | Helper | Stubs | Endpoint |
166
+ |---|---|---|
167
+ | `webmock_mollie_payment_create` | `POST /v2/payments` | Full payment JSON with checkout link |
168
+ | `webmock_mollie_customer_and_payment_create` | `POST /v2/customers` + `POST /v2/payments` | Both resources |
169
+ | `webmock_mollie_subscription_create` | `POST /v2/customers/:id/subscriptions` | Active subscription JSON |
170
+ | `webmock_mollie_subscription_cancel` | `DELETE /v2/customers/:id/subscriptions/:id` | 204 No Content |
171
+ | `webmock_mollie_refund_create` | `POST /v2/payments/:id/refunds` | Queued refund JSON |
172
+ | `webmock_mollie_payment_get` | `GET /v2/payments/:id` | Payment JSON (for webhook tests) |
173
+ | `webmock_mollie_payment_get_with_chargebacks` | `GET /v2/payments/:id` | Payment JSON with embedded chargebacks |
174
+
175
+ **When to use which:** Method-level stubs (`stub_mollie_*`) are faster and
176
+ simpler — use them for unit tests. WebMock stubs (`webmock_mollie_*`) exercise
177
+ the full SDK including JSON parsing — use them for integration tests.