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/webhooks.md ADDED
@@ -0,0 +1,231 @@
1
+ # Webhooks
2
+
3
+ ## Endpoint
4
+
5
+ Point your Mollie dashboard webhook URL to:
6
+
7
+ ```
8
+ POST https://yourapp.com/mollie_pay/webhooks
9
+ ```
10
+
11
+ ## How it works
12
+
13
+ ```
14
+ POST /mollie_pay/webhooks (from Mollie)
15
+ → validate mollie_id format (reject junk IDs with 422)
16
+ → ProcessWebhookJob.perform_later (enqueue for async processing)
17
+ → head :ok (respond immediately)
18
+
19
+ ProcessWebhookJob:
20
+ → route by ID prefix (tr_ → Payment, sub_ → Subscription, re_ → Refund, stl_ → Settlement)
21
+ → fetch full object from Mollie API
22
+ → upsert local record via record_from_mollie
23
+ → enqueue NotifyBillableJob for the on_mollie_* hook (only on actual state changes)
24
+ → detect chargebacks via amount_charged_back comparison (see below)
25
+ ```
26
+
27
+ No event model, no mutable state. The controller validates and enqueues. The job
28
+ fetches from Mollie and delegates to domain models. MolliePay responds immediately
29
+ with `200 OK`, then processes asynchronously via Active Job. On failure, the job
30
+ retries with polynomial backoff (up to 5 attempts). Resources not found on Mollie
31
+ (404) or locally (unknown subscription/refund IDs) are discarded, not retried.
32
+
33
+ ## Authorized payments (pay later)
34
+
35
+ Manual-capture methods such as Billink move a payment to `authorized` before
36
+ `paid`. The webhook path above handles this without extra setup: the first
37
+ `authorized` webhook sets `authorized_at` and fires `on_mollie_payment_authorized`.
38
+ After `mollie_capture`, the next webhook moves the payment to `paid`; after
39
+ `mollie_release_authorization`, to `canceled` (or to `paid` when a capture had
40
+ already succeeded); and after 28 days without a capture, to `expired`. Each transition enqueues its hook (see Idempotency: hooks run at least once). Capture-level events
41
+ (`capture.succeeded`, `capture.failed`) exist only as next-gen webhook events and
42
+ are logged, not processed.
43
+
44
+ ## Verification
45
+
46
+ No signature verification is needed. Mollie's webhook pattern sends only an
47
+ `id` parameter, which MolliePay validates against the format
48
+ `(tr|sub|re|stl)_[a-zA-Z0-9]+` and then fetches directly from the Mollie API.
49
+ The API key is the verification — only your key can fetch your objects.
50
+
51
+ ## Chargeback detection
52
+
53
+ Mollie does **not** send separate chargeback webhooks. Chargebacks arrive via
54
+ the normal payment webhook (`tr_` prefix) — the payment status stays `"paid"`,
55
+ only `amountChargedBack` changes.
56
+
57
+ Detection works by comparing `amount_charged_back` before and after the payment
58
+ update in `Payment.record_from_mollie`. When the amount changes,
59
+ `MolliePay::SyncChargebacksJob` is enqueued to run `Chargeback.sync_for_payment`,
60
+ which fetches individual chargebacks from the Mollie API and upserts them
61
+ locally with independent retries.
62
+
63
+ ```
64
+ Payment webhook or subscription sync (tr_xxx)
65
+ → Payment.record_from_mollie
66
+ → captures previous amount_charged_back
67
+ → updates payment record
68
+ → if amount_charged_back changed:
69
+ → SyncChargebacksJob.perform_later(payment)
70
+ → Chargeback.sync_for_payment(payment)
71
+ → fetches chargebacks from Mollie API
72
+ → upserts each chargeback (find_or_initialize_by mollie_id)
73
+ → enqueues on_mollie_chargeback_received for new chargebacks
74
+ → enqueues on_mollie_chargeback_reversed when reversed_at is set
75
+ ```
76
+
77
+ Hooks are dispatched **after** all chargeback records are persisted, preventing
78
+ lost notifications on partial failure.
79
+
80
+ ## Idempotency
81
+
82
+ Hooks fire **only on actual state changes**. For most models this means status
83
+ transitions. For chargebacks, it means new records (`new_record?` before save)
84
+ or newly reversed chargebacks (`reversed_at` changing from nil to a value).
85
+
86
+ If Mollie sends the same webhook multiple times (which it does routinely), or
87
+ two webhook workers finish out of order, local statuses never move backwards and
88
+ hooks do not re-trigger. Each synced model enforces allowed status transitions
89
+ and write-once timestamps in a single conditional SQL `UPDATE` with no database
90
+ lock held across Mollie API calls. For models with reversible transitions or
91
+ mutable fields (`Payment`, `Subscription`, and `SalesInvoice`), webhook jobs
92
+ check `sync_version` before fetching from Mollie and re-fetch if another writer
93
+ updated the row while the request was in flight.
94
+
95
+ Each hook runs in its own `MolliePay::NotifyBillableJob`, enqueued after the
96
+ record is saved. When your hook raises, for example because `mollie_subscribe`
97
+ hits a Mollie error, that job retries the hook with polynomial backoff, up to
98
+ 5 attempts. Hooks are therefore at least once: implement your `on_mollie_*`
99
+ callbacks **idempotently**. They are safe for side effects (send emails,
100
+ provision access, update billing state) but must handle being called more than
101
+ once for the same transition.
102
+
103
+ Transition timestamps (`paid_at`, `canceled_at`, `failed_at`, `expired_at`,
104
+ `refunded_at`, `mandated_at`) and `Payment#created_at_mollie` are set once when
105
+ first observed and never overwritten.
106
+
107
+ ## Active Job
108
+
109
+ MolliePay requires Active Job for webhook processing. Configure your queue
110
+ adapter in `config/application.rb`:
111
+
112
+ ```ruby
113
+ config.active_job.queue_adapter = :solid_queue # or :sidekiq, :good_job, etc.
114
+ ```
115
+
116
+ Webhook jobs are enqueued on the `:default` queue. Processing includes:
117
+
118
+ - **Retry policy:** polynomial backoff, up to 5 attempts on Mollie API and database errors
119
+ - **Discard policy:** Mollie 404s and locally unknown subscription/refund IDs are discarded immediately, as are next-gen sales invoice events for an invoice with no local record
120
+ - **Idempotency:** `record_from_mollie` uses `find_or_initialize_by` — safe to process the same webhook multiple times
121
+ - **Hooks:** each `on_mollie_*` hook runs in `NotifyBillableJob` on the `:default` queue, with its own retries (polynomial backoff, up to 5 attempts)
122
+ - **Chargebacks:** when `amount_charged_back` changes on a synced payment, `SyncChargebacksJob` reconciles the payment's chargebacks on the `:default` queue with independent retries (polynomial backoff, up to 5 attempts) and discards Mollie 404s or deleted payments
123
+ - **Pending mandates:** when a first payment is paid while its mandate is still `pending`, `RefreshPendingMandateJob` re-fetches the mandate with polynomial backoff, for up to 10 attempts over roughly four hours, until Mollie reports it `valid` or `invalid`
124
+ - **Customer cleanup:** when two calls create an owner's customer at the same time, the call that saves second enqueues `DeleteMollieCustomerJob` to delete the extra customer it created at Mollie, retrying with polynomial backoff (up to 5 attempts) and discarding Mollie 404s
125
+ - **Scheduled subscription sync:** Mollie sends no webhooks for subscription status changes (`canceled`, `suspended`, `completed`). Schedule `SyncSubscriptionsJob` to walk `pending` and `active` subscriptions and fan out one `SyncSubscriptionJob` per subscription on the sweep job's queue. Each `SyncSubscriptionJob` retries transient errors with polynomial backoff (up to 5 attempts), retries `StaleSyncError` (up to 2 job attempts after 3 uncached inline attempts), discards `ActiveJob::DeserializationError`, reconciles missed subscription payments before updating subscription status, and marks the subscription `canceled` locally (firing `on_mollie_subscription_canceled`) when Mollie answers `404` for the subscription itself
126
+
127
+ ## Next-Gen Webhooks (beta)
128
+
129
+ MolliePay also supports Mollie's **Next-Gen Webhooks** — event-based webhook
130
+ subscriptions with HMAC-SHA256 signature verification. These are separate from
131
+ classic webhooks and provide event types not available via the classic approach
132
+ (e.g., `sales-invoice.paid`).
133
+
134
+ ### Endpoint
135
+
136
+ ```
137
+ POST https://yourapp.com/mollie_pay/webhook_events
138
+ ```
139
+
140
+ Register this URL in the Mollie Dashboard under Webhooks. Select the event
141
+ types you want to receive.
142
+
143
+ ### Configuration
144
+
145
+ ```ruby
146
+ MolliePay.configure do |config|
147
+ config.webhook_signing_secret = ENV["MOLLIE_WEBHOOK_SIGNING_SECRET"]
148
+ end
149
+ ```
150
+
151
+ The signing secret is displayed once when you create the webhook subscription
152
+ in the Mollie Dashboard. Store it immediately — it cannot be retrieved later.
153
+
154
+ Without `webhook_signing_secret` the endpoint answers `404 Not Found` and
155
+ accepts no events, signed or not. An event the engine cannot verify is never
156
+ queued.
157
+
158
+ For secret rotation, pass an array:
159
+
160
+ ```ruby
161
+ config.webhook_signing_secret = [
162
+ ENV["MOLLIE_WEBHOOK_SECRET_NEW"],
163
+ ENV["MOLLIE_WEBHOOK_SECRET_OLD"]
164
+ ]
165
+ ```
166
+
167
+ ### How it works
168
+
169
+ ```
170
+ POST /mollie_pay/webhook_events (from Mollie, with X-Mollie-Signature header)
171
+ → 404 if no signing secret is configured
172
+ → verify HMAC-SHA256 signature
173
+ → parse JSON event payload
174
+ → 422 unless the body is an object with resource "event" and string
175
+ id, type and entityId (any type is accepted, known or not)
176
+ → ProcessWebhookEventJob.perform_later(event)
177
+ → head :ok
178
+
179
+ ProcessWebhookEventJob#perform(event)
180
+ → sales-invoice.* → find the local SalesInvoice by entityId
181
+ → none: log and discard (the invoice was not created through the engine)
182
+ → fetch the invoice from Mollie, SalesInvoice.record_from_mollie
183
+ → on_mollie_sales_invoice_issued / _paid hooks fire only on a status change
184
+ → any other type: log and ignore
185
+ → on failure: retries with polynomial backoff (5 attempts), discards Mollie 404s
186
+ ```
187
+
188
+ Subscribe the webhook to the `sales-invoice.*` events to keep local invoices in
189
+ sync. Payment and refund events are ignored: the engine syncs those through
190
+ classic webhooks, which Mollie still recommends for payment updates.
191
+
192
+ ### Event payload
193
+
194
+ ```json
195
+ {
196
+ "resource": "event",
197
+ "id": "whe_xxx",
198
+ "type": "sales-invoice.paid",
199
+ "entityId": "invoice_xxx",
200
+ "createdAt": "2026-03-22T10:00:00+00:00",
201
+ "_embedded": {
202
+ "entity": { ... }
203
+ }
204
+ }
205
+ ```
206
+
207
+ ### Classic vs Next-Gen coexistence
208
+
209
+ Both endpoints are active simultaneously:
210
+
211
+ | Endpoint | Payload | Verification | Events |
212
+ |----------|---------|-------------|--------|
213
+ | `POST /mollie_pay/webhooks` | Resource ID only | API key (implicit) | Payment and refund status changes (plus any `sub_` ID if sent) |
214
+ | `POST /mollie_pay/webhook_events` | Full event JSON | HMAC signature | Sales invoices (other event types are logged and ignored) |
215
+
216
+ Classic webhooks are **not** deprecated. The engine syncs payments and refunds
217
+ from classic webhooks; subscription status changes (which Mollie does not send
218
+ webhooks for) and any missed recurring payments are synced by scheduling
219
+ `MolliePay::SyncSubscriptionsJob`.
220
+
221
+ ## Rate limiting
222
+
223
+ Both webhook endpoints are publicly accessible by design. Consider rate
224
+ limiting them at the infrastructure level:
225
+
226
+ ```ruby
227
+ # config/initializers/rack_attack.rb
228
+ Rack::Attack.throttle("mollie_webhooks", limit: 100, period: 60) do |req|
229
+ (req.path == "/mollie_pay/webhooks" || req.path == "/mollie_pay/webhook_events") && req.post? && req.ip
230
+ end
231
+ ```
@@ -0,0 +1,44 @@
1
+ module MolliePay
2
+ module Generators
3
+ class InstallGenerator < Rails::Generators::Base
4
+ source_root File.expand_path("templates", __dir__)
5
+
6
+ desc "Install MolliePay: create initializer and copy migrations"
7
+
8
+ class_option :skip_migrations, type: :boolean, default: false,
9
+ desc: "Skip copying and running migrations"
10
+
11
+ def copy_initializer
12
+ template "initializer.rb.tt", "config/initializers/mollie_pay.rb"
13
+ end
14
+
15
+ def install_migrations
16
+ return if options[:skip_migrations]
17
+
18
+ rails_command "mollie_pay:install:migrations", inline: true
19
+ end
20
+
21
+ def run_migrations
22
+ return if options[:skip_migrations]
23
+
24
+ rails_command "db:migrate", inline: true
25
+ end
26
+
27
+ def print_post_install_instructions
28
+ say ""
29
+ say "MolliePay installed successfully!", :green
30
+ say ""
31
+ say "Add the following to your config/routes.rb:", :yellow
32
+ say ""
33
+ say ' mount MolliePay::Engine => "/mollie_pay"'
34
+ say ""
35
+ say "Then include MolliePay::Billable in your billable model:", :yellow
36
+ say ""
37
+ say " class User < ApplicationRecord"
38
+ say " include MolliePay::Billable"
39
+ say " end"
40
+ say ""
41
+ end
42
+ end
43
+ end
44
+ end
@@ -0,0 +1,12 @@
1
+ MolliePay.configure do |config|
2
+ config.api_key = ENV["MOLLIE_API_KEY"]
3
+ config.host = ENV["MOLLIE_HOST"] # e.g. "https://yourapp.com"
4
+ config.default_redirect_path = "/payments/:id"
5
+ config.currency = "EUR"
6
+
7
+ # Sign every request to Mollie, once a public key is registered on the API
8
+ # key. bin/rails mollie_pay:request_signing:generate makes the key pair; where
9
+ # to keep the private key is in
10
+ # https://github.com/peterberkenbosch/mollie_pay/blob/master/docs/request-signing.md
11
+ # config.request_signing_key = ENV["MOLLIE_REQUEST_SIGNING_KEY"]
12
+ end
@@ -0,0 +1,124 @@
1
+ module Mollie
2
+ class SalesInvoice < Base
3
+ STATUS_DRAFT = "draft".freeze
4
+ STATUS_ISSUED = "issued".freeze
5
+ STATUS_PAID = "paid".freeze
6
+ STATUS_CANCELED = "cancelled".freeze # Mollie's spelling
7
+
8
+ attr_accessor :id,
9
+ :profile_id,
10
+ :status,
11
+ :invoice_number,
12
+ :recipient_identifier,
13
+ :recipient,
14
+ :lines,
15
+ :payment_term,
16
+ :vat_scheme,
17
+ :vat_mode,
18
+ :memo,
19
+ :metadata,
20
+ :is_e_invoice,
21
+ :email_details,
22
+ :payment_details,
23
+ :subtotal_amount,
24
+ :discounted_subtotal_amount,
25
+ :total_vat_amount,
26
+ :total_amount,
27
+ :amount_due,
28
+ :created_at,
29
+ :issued_at,
30
+ :paid_at,
31
+ :due_at,
32
+ :_links
33
+
34
+ alias links _links
35
+
36
+ def self.resource_name(_parent_id = nil)
37
+ "sales-invoices"
38
+ end
39
+
40
+ def draft?
41
+ status == STATUS_DRAFT
42
+ end
43
+
44
+ def issued?
45
+ status == STATUS_ISSUED
46
+ end
47
+
48
+ def paid?
49
+ status == STATUS_PAID
50
+ end
51
+
52
+ def canceled?
53
+ status == STATUS_CANCELED
54
+ end
55
+
56
+ def pdf_url
57
+ Util.extract_url(links, "pdf_link")
58
+ end
59
+
60
+ def payment_url
61
+ Util.extract_url(links, "invoice_payment")
62
+ end
63
+
64
+ def subtotal_amount=(amount)
65
+ @subtotal_amount = Amount.new(amount) if amount
66
+ end
67
+
68
+ def discounted_subtotal_amount=(amount)
69
+ @discounted_subtotal_amount = Amount.new(amount) if amount
70
+ end
71
+
72
+ def total_vat_amount=(amount)
73
+ @total_vat_amount = Amount.new(amount) if amount
74
+ end
75
+
76
+ def total_amount=(amount)
77
+ @total_amount = Amount.new(amount) if amount
78
+ end
79
+
80
+ def amount_due=(amount)
81
+ @amount_due = Amount.new(amount) if amount
82
+ end
83
+
84
+ def created_at=(value)
85
+ @created_at = begin
86
+ Time.parse(value.to_s)
87
+ rescue ArgumentError
88
+ nil
89
+ end
90
+ end
91
+
92
+ def issued_at=(value)
93
+ @issued_at = begin
94
+ Time.parse(value.to_s)
95
+ rescue ArgumentError
96
+ nil
97
+ end
98
+ end
99
+
100
+ def paid_at=(value)
101
+ @paid_at = begin
102
+ Time.parse(value.to_s)
103
+ rescue ArgumentError
104
+ nil
105
+ end
106
+ end
107
+
108
+ def due_at=(value)
109
+ @due_at = begin
110
+ Time.parse(value.to_s)
111
+ rescue ArgumentError
112
+ nil
113
+ end
114
+ end
115
+
116
+ def recipient=(recipient)
117
+ @recipient = OpenStruct.new(recipient) if recipient.is_a?(Hash)
118
+ end
119
+
120
+ def metadata=(metadata)
121
+ @metadata = OpenStruct.new(metadata) if metadata.is_a?(Hash)
122
+ end
123
+ end
124
+ end
@@ -0,0 +1,101 @@
1
+ module MolliePay
2
+ class ConfigurationError < Error; end
3
+
4
+ class Configuration
5
+ UUID_PATTERN = "[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}".freeze
6
+
7
+ attr_accessor :api_key
8
+ attr_accessor :host
9
+ attr_accessor :default_redirect_path
10
+ attr_accessor :currency
11
+ attr_accessor :webhook_signing_secret
12
+ attr_accessor :request_signing_key
13
+
14
+ def initialize
15
+ @currency = "EUR"
16
+ end
17
+
18
+ def validate!
19
+ raise ConfigurationError, "MolliePay.configuration.api_key is required" if api_key.blank?
20
+ raise ConfigurationError, "MolliePay.configuration.host is required" if host.blank?
21
+ end
22
+
23
+ def webhook_url
24
+ "#{host_without_trailing_slash}#{MolliePay::Engine.routes.url_helpers.webhooks_path}"
25
+ end
26
+
27
+ def redirect_url_for(payment)
28
+ return nil if default_redirect_path.blank?
29
+
30
+ path = default_redirect_path.gsub(":id", payment.id.to_s)
31
+ "#{host_without_trailing_slash}#{path}"
32
+ end
33
+
34
+ def payment_id_from_redirect_url(redirect_url)
35
+ return nil if redirect_url.blank? || default_redirect_path.blank? || host.blank?
36
+ return nil unless default_redirect_path.include?(":id")
37
+
38
+ prefix = Regexp.escape(host_without_trailing_slash)
39
+ escaped_placeholder = Regexp.escape(":id")
40
+ path_pattern = Regexp.escape(default_redirect_path)
41
+ .sub(escaped_placeholder) { "(?<id>#{UUID_PATTERN})" }
42
+ .gsub(escaped_placeholder) { "\\k<id>" }
43
+
44
+ match = /\A#{prefix}#{path_pattern}\z/.match(redirect_url.to_s)
45
+ match&.named_captures&.fetch("id")
46
+ end
47
+
48
+ # Returns nil (not configured) or a non-empty array of secrets.
49
+ # Treats nil, "", and [] as "not configured" to prevent silent rejection
50
+ # when an empty array is passed.
51
+ def webhook_signing_secrets
52
+ secrets = Array(webhook_signing_secret).reject(&:blank?)
53
+ secrets.empty? ? nil : secrets
54
+ end
55
+
56
+ # Returns nil (not configured) or the Ed25519 private key that signs every
57
+ # request to Mollie. request_signing_key holds it as PEM, as PEM with its
58
+ # line breaks written as "\n", or as the one line of base64 between the
59
+ # PEM's first and last line, which is the form a secret store and an
60
+ # environment variable hold without trouble.
61
+ def request_signing_private_key
62
+ return nil if request_signing_key.blank?
63
+ return @request_signing_private_key if @request_signing_private_key_source == request_signing_key
64
+
65
+ key = RequestSignature.read_key(request_signing_key)
66
+ raise ConfigurationError, "MolliePay.configuration.request_signing_key must be an Ed25519 private key" unless key.oid == "ED25519"
67
+ raise ConfigurationError, "MolliePay.configuration.request_signing_key holds the public key; it needs the private one" unless RequestSignature.private?(key)
68
+
69
+ @request_signing_private_key_source = request_signing_key
70
+ @request_signing_private_key = key
71
+ rescue OpenSSL::PKey::PKeyError
72
+ raise ConfigurationError, "MolliePay.configuration.request_signing_key is not a readable private key"
73
+ end
74
+
75
+ # The public half of the configured key as PEM: what is registered at
76
+ # Mollie. Nil when no key is configured.
77
+ def request_signing_public_key
78
+ request_signing_private_key&.public_to_pem
79
+ end
80
+
81
+ def inspect
82
+ "#<MolliePay::Configuration host=#{host.inspect} default_redirect_path=#{default_redirect_path.inspect} currency=#{currency.inspect} api_key=[FILTERED]>"
83
+ end
84
+
85
+ private
86
+
87
+ def host_without_trailing_slash
88
+ host&.chomp("/")
89
+ end
90
+ end
91
+
92
+ class << self
93
+ def configuration
94
+ @configuration ||= Configuration.new
95
+ end
96
+
97
+ def configure
98
+ yield configuration
99
+ end
100
+ end
101
+ end
@@ -0,0 +1,31 @@
1
+ module MolliePay
2
+ class Engine < ::Rails::Engine
3
+ isolate_namespace MolliePay
4
+
5
+ initializer "mollie_pay.configure_mollie_client" do
6
+ ActiveSupport.on_load(:active_record) do
7
+ ::Mollie::Client.configure do |client|
8
+ client.api_key = MolliePay.configuration.api_key
9
+ end
10
+ end
11
+ end
12
+
13
+ initializer "mollie_pay.sign_mollie_requests" do
14
+ ::Mollie::Client.prepend(MolliePay::RequestSignature::Client)
15
+
16
+ # Reads the key at boot, so a bad key fails here and not on the first payment.
17
+ config.after_initialize { MolliePay.configuration.request_signing_private_key }
18
+ end
19
+
20
+ initializer "mollie_pay.warn_missing_webhook_secret", after: :finisher_hook do
21
+ config.after_initialize do
22
+ if MolliePay.configuration.webhook_signing_secrets.nil?
23
+ Rails.logger.warn(
24
+ "[MolliePay] webhook_signing_secret is not configured. " \
25
+ "Next-gen webhook events at /webhook_events are refused with 404 until it is set."
26
+ )
27
+ end
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,12 @@
1
+ module MolliePay
2
+ class Error < StandardError; end
3
+ class MandateRequired < Error; end
4
+ class MandatePending < Error; end
5
+ class SubscriptionNotFound < Error; end
6
+ class PaymentNotCancelable < Error; end
7
+ class PaymentNotAuthorized < Error; end
8
+ class InvalidSignature < Error; end
9
+ class InvoiceNotUpdatable < Error; end
10
+ class InvalidAmount < Error; end
11
+ class StaleSyncError < Error; end
12
+ end