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/tutorial.md ADDED
@@ -0,0 +1,1340 @@
1
+ # Building a SaaS billing app with MolliePay
2
+
3
+ This tutorial walks you through building a complete billing system for a SaaS
4
+ application using MolliePay and vanilla Rails. You'll implement one-off payments,
5
+ monthly subscriptions, and yearly subscriptions — all with real Mollie checkout
6
+ pages and webhook processing.
7
+
8
+ **What you'll build:**
9
+
10
+ - Account signup and login
11
+ - One-off payments with Mollie checkout
12
+ - Monthly subscription (€25/month)
13
+ - Yearly subscription (€250/year)
14
+ - Billing dashboard with payment history
15
+ - Cancel and resubscribe flows
16
+
17
+ **Prerequisites:**
18
+
19
+ - Ruby 3.2+ and Rails 8.1+
20
+ - A [Mollie account](https://my.mollie.com/dashboard/signup/7878281?lang=nl) (free to create)
21
+ - A Mollie **test** API key (starts with `test_`)
22
+ - [cloudflared](https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/) or [ngrok](https://ngrok.com) for webhook tunneling
23
+
24
+ **Time:** About 45 minutes.
25
+
26
+ ---
27
+
28
+ ## Part 1: Project setup
29
+
30
+ ### Create the Rails app
31
+
32
+ ```sh
33
+ rails new acme_saas --css=tailwind
34
+ cd acme_saas
35
+ ```
36
+
37
+ The `--css=tailwind` flag sets up Tailwind CSS via the `tailwindcss-rails` gem.
38
+
39
+ ### Add MolliePay
40
+
41
+ Add to your `Gemfile`:
42
+
43
+ ```ruby
44
+ gem "mollie_pay", github: "peterberkenbosch/mollie_pay"
45
+ ```
46
+
47
+ Install MolliePay:
48
+
49
+ ```sh
50
+ bundle install
51
+ bin/rails generate mollie_pay:install
52
+ ```
53
+
54
+ This creates the initializer at `config/initializers/mollie_pay.rb`, copies the
55
+ migrations, and runs them. Open the generated initializer and review the
56
+ defaults — we'll set the environment variables later when we start the server.
57
+
58
+ ### Mount the engine
59
+
60
+ Add the engine route to `config/routes.rb`:
61
+
62
+ ```ruby
63
+ Rails.application.routes.draw do
64
+ mount MolliePay::Engine => "/mollie_pay"
65
+ end
66
+ ```
67
+
68
+ The generated initializer looks like this:
69
+
70
+ ```ruby
71
+ MolliePay.configure do |config|
72
+ config.api_key = ENV["MOLLIE_API_KEY"]
73
+ config.host = ENV["MOLLIE_HOST"] # e.g. "https://yourapp.com"
74
+ config.default_redirect_path = "/payments/:id"
75
+ config.currency = "EUR"
76
+ end
77
+ ```
78
+
79
+ The `host` is used to build the webhook URL automatically from the engine's
80
+ mount path. The `default_redirect_path` is combined with `host` to form the
81
+ full redirect URL — `:id` is replaced with the local payment record's ID, so
82
+ Mollie redirects the customer to the right payment page after checkout.
83
+
84
+ ### Add authentication
85
+
86
+ Rails 8 includes a built-in authentication generator. First, uncomment the
87
+ bcrypt gem in your `Gemfile` — the auth generator requires it for
88
+ `has_secure_password`:
89
+
90
+ ```ruby
91
+ # Gemfile — uncomment this line:
92
+ gem "bcrypt", "~> 3.1.7"
93
+ ```
94
+
95
+ ```sh
96
+ bundle install
97
+ bin/rails generate authentication
98
+ ```
99
+
100
+ This creates `User`, `Session`, and `Current` models, plus a `SessionsController`
101
+ for login. It does **not** create a signup flow — we'll add that next.
102
+
103
+ Run the generated migration:
104
+
105
+ ```sh
106
+ bin/rails db:migrate
107
+ ```
108
+
109
+ ### Add signup
110
+
111
+ Create a registrations controller:
112
+
113
+ ```ruby
114
+ # app/controllers/registrations_controller.rb
115
+ class RegistrationsController < ApplicationController
116
+ allow_unauthenticated_access only: [ :new, :create ]
117
+
118
+ def new
119
+ @user = User.new
120
+ end
121
+
122
+ def create
123
+ @user = User.new(user_params)
124
+
125
+ if @user.save
126
+ start_new_session_for @user
127
+ redirect_to root_path, notice: "Account created successfully."
128
+ else
129
+ render :new, status: :unprocessable_entity
130
+ end
131
+ end
132
+
133
+ private
134
+
135
+ def user_params
136
+ params.expect(user: [ :email_address, :password, :password_confirmation ])
137
+ end
138
+ end
139
+ ```
140
+
141
+ Create the signup view at `app/views/registrations/new.html.erb`:
142
+
143
+ ```erb
144
+ <div class="max-w-md mx-auto mt-16">
145
+ <h1 class="text-2xl font-bold mb-6">Sign up</h1>
146
+
147
+ <% if @user.errors.any? %>
148
+ <div class="bg-red-50 border border-red-200 text-red-700 rounded-lg p-4 mb-6">
149
+ <h2 class="font-semibold mb-2"><%= pluralize(@user.errors.count, "error") %> prevented signup:</h2>
150
+ <ul class="list-disc list-inside text-sm">
151
+ <% @user.errors.full_messages.each do |message| %>
152
+ <li><%= message %></li>
153
+ <% end %>
154
+ </ul>
155
+ </div>
156
+ <% end %>
157
+
158
+ <%= form_with model: @user, url: registration_path, class: "space-y-4" do |form| %>
159
+ <div>
160
+ <%= form.label :email_address, class: "block text-sm font-medium text-gray-700 mb-1" %>
161
+ <%= form.email_field :email_address, required: true,
162
+ class: "w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" %>
163
+ </div>
164
+
165
+ <div>
166
+ <%= form.label :password, class: "block text-sm font-medium text-gray-700 mb-1" %>
167
+ <%= form.password_field :password, required: true,
168
+ class: "w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" %>
169
+ </div>
170
+
171
+ <div>
172
+ <%= form.label :password_confirmation, class: "block text-sm font-medium text-gray-700 mb-1" %>
173
+ <%= form.password_field :password_confirmation, required: true,
174
+ class: "w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" %>
175
+ </div>
176
+
177
+ <div>
178
+ <%= form.submit "Sign up",
179
+ class: "w-full bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700 cursor-pointer" %>
180
+ </div>
181
+ <% end %>
182
+
183
+ <p class="mt-4 text-sm text-gray-600">
184
+ Already have an account? <%= link_to "Log in", new_session_path, class: "text-indigo-600 hover:underline" %>
185
+ </p>
186
+ </div>
187
+ ```
188
+
189
+ Add the routes in `config/routes.rb`. The authentication generator already added
190
+ a `resource :session` line — keep that and add the registration and root routes:
191
+
192
+ ```ruby
193
+ Rails.application.routes.draw do
194
+ mount MolliePay::Engine => "/mollie_pay"
195
+
196
+ resource :registration, only: [ :new, :create ]
197
+ resource :session, only: [ :new, :create, :destroy ]
198
+
199
+ root "dashboard#show"
200
+ end
201
+ ```
202
+
203
+ ### Make User billable
204
+
205
+ Add `MolliePay::Billable` to your `User` model:
206
+
207
+ ```ruby
208
+ # app/models/user.rb
209
+ class User < ApplicationRecord
210
+ include MolliePay::Billable
211
+
212
+ has_secure_password
213
+ has_many :sessions, dependent: :destroy
214
+
215
+ normalizes :email_address, with: -> (e) { e.strip.downcase }
216
+
217
+ validates :email_address, presence: true, uniqueness: true
218
+
219
+ # Rails 8 auth uses email_address; Mollie expects email
220
+ alias_attribute :email, :email_address
221
+ end
222
+ ```
223
+
224
+ > **Note:** MolliePay uses a polymorphic association, so it works with any model
225
+ > name — `User`, `Account`, `Organization`, `Team`, etc.
226
+ >
227
+ > **Why `alias_attribute`?** The Rails 8 auth generator creates an
228
+ > `email_address` column, but `Billable#create_mollie_customer_on_mollie` checks
229
+ > for `email`. Without the alias, Mollie customers are created without an email
230
+ > address, which degrades identification in the Mollie dashboard.
231
+
232
+ ### Create the dashboard
233
+
234
+ ```ruby
235
+ # app/controllers/dashboard_controller.rb
236
+ class DashboardController < ApplicationController
237
+ def show
238
+ end
239
+ end
240
+ ```
241
+
242
+ Create `app/views/dashboard/show.html.erb`:
243
+
244
+ ```erb
245
+ <div class="max-w-2xl mx-auto mt-16">
246
+ <h1 class="text-2xl font-bold mb-2">Dashboard</h1>
247
+ <p class="text-gray-600 mb-8">Welcome, <%= Current.user.email_address %>!</p>
248
+
249
+ <div class="grid grid-cols-1 sm:grid-cols-3 gap-4">
250
+ <%= link_to new_payment_path,
251
+ class: "block p-6 bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition" do %>
252
+ <h2 class="font-semibold text-gray-900">Make a payment</h2>
253
+ <p class="text-sm text-gray-500 mt-1">One-off payment via Mollie</p>
254
+ <% end %>
255
+
256
+ <%= link_to pricing_path,
257
+ class: "block p-6 bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition" do %>
258
+ <h2 class="font-semibold text-gray-900">Subscriptions</h2>
259
+ <p class="text-sm text-gray-500 mt-1">Monthly or yearly plans</p>
260
+ <% end %>
261
+
262
+ <%= link_to billing_path,
263
+ class: "block p-6 bg-white rounded-lg border border-gray-200 shadow-sm hover:shadow-md transition" do %>
264
+ <h2 class="font-semibold text-gray-900">Billing</h2>
265
+ <p class="text-sm text-gray-500 mt-1">Payment history & subscription</p>
266
+ <% end %>
267
+ </div>
268
+ </div>
269
+ ```
270
+
271
+ Don't worry about the missing routes — we'll add them in the next parts.
272
+
273
+ ### Add flash messages and navigation
274
+
275
+ The controllers use flash messages (`notice:`, `alert:`) on redirects, but the
276
+ default application layout doesn't render them. Let's add a flash partial and a
277
+ navigation bar.
278
+
279
+ Create `app/views/layouts/_flash.html.erb`:
280
+
281
+ ```erb
282
+ <% if notice %>
283
+ <div class="max-w-2xl mx-auto mt-4 px-4">
284
+ <div class="bg-green-50 border border-green-200 rounded-lg p-4 text-sm text-green-800">
285
+ <%= notice %>
286
+ </div>
287
+ </div>
288
+ <% end %>
289
+
290
+ <% if alert %>
291
+ <div class="max-w-2xl mx-auto mt-4 px-4">
292
+ <div class="bg-red-50 border border-red-200 rounded-lg p-4 text-sm text-red-800">
293
+ <%= alert %>
294
+ </div>
295
+ </div>
296
+ <% end %>
297
+ ```
298
+
299
+ Create `app/views/shared/_navbar.html.erb`:
300
+
301
+ ```erb
302
+ <nav class="bg-white border-b border-gray-200">
303
+ <div class="max-w-4xl mx-auto px-4 py-3 flex items-center justify-between">
304
+ <div class="flex items-center gap-6">
305
+ <%= link_to "Acme SaaS", root_path, class: "font-bold text-gray-900" %>
306
+ <% if authenticated? %>
307
+ <%= link_to "Dashboard", root_path, class: "text-sm text-gray-600 hover:text-gray-900" %>
308
+ <%= link_to "Pricing", pricing_path, class: "text-sm text-gray-600 hover:text-gray-900" %>
309
+ <%= link_to "Billing", billing_path, class: "text-sm text-gray-600 hover:text-gray-900" %>
310
+ <% else %>
311
+ <%= link_to "Pricing", pricing_path, class: "text-sm text-gray-600 hover:text-gray-900" %>
312
+ <% end %>
313
+ </div>
314
+
315
+ <div>
316
+ <% if authenticated? %>
317
+ <span class="text-sm text-gray-500 mr-3"><%= Current.user.email_address %></span>
318
+ <%= button_to "Log out", session_path, method: :delete,
319
+ class: "text-sm text-gray-600 hover:text-gray-900 cursor-pointer" %>
320
+ <% else %>
321
+ <%= link_to "Log in", new_session_path, class: "text-sm text-gray-600 hover:text-gray-900 mr-3" %>
322
+ <%= link_to "Sign up", new_registration_path,
323
+ class: "text-sm bg-indigo-600 text-white px-3 py-1.5 rounded-lg hover:bg-indigo-700" %>
324
+ <% end %>
325
+ </div>
326
+ </div>
327
+ </nav>
328
+ ```
329
+
330
+ Now include both in your application layout. Open
331
+ `app/views/layouts/application.html.erb` and update the `<body>`:
332
+
333
+ ```erb
334
+ <body>
335
+ <%= render "shared/navbar" %>
336
+ <%= render "layouts/flash" %>
337
+ <%= yield %>
338
+ </body>
339
+ ```
340
+
341
+ > **Login page styling:** The auth generator creates a basic
342
+ > `sessions/new.html.erb` view. It works as-is, but if you want it to match the
343
+ > Tailwind styling of the signup page, copy the structure from
344
+ > `registrations/new.html.erb` and adjust the form fields.
345
+
346
+ ---
347
+
348
+ ## Part 2: One-off payments
349
+
350
+ This is the simplest Mollie flow: create a payment, redirect the customer to
351
+ Mollie's checkout page, and handle the return.
352
+
353
+ > **Turbo Drive and external redirects:** Rails 8 includes Turbo Drive by
354
+ > default, which intercepts form submissions via `fetch()`. Cross-origin
355
+ > redirects (like Mollie's checkout URL) are silently blocked by the browser.
356
+ > Add `data: { turbo: false }` to every form that redirects to Mollie. You'll
357
+ > see this in the payment form and pricing page buttons below.
358
+
359
+ ### Create the payments controller
360
+
361
+ ```ruby
362
+ # app/controllers/payments_controller.rb
363
+ class PaymentsController < ApplicationController
364
+ def new
365
+ end
366
+
367
+ def create
368
+ amount = params.expect(:amount).to_d
369
+ description = params.expect(:description)
370
+
371
+ payment = Current.user.mollie_pay_once(
372
+ amount: amount,
373
+ description: description
374
+ )
375
+
376
+ redirect_to payment.checkout_url, allow_other_host: true
377
+ rescue Mollie::RequestError, MolliePay::ConfigurationError => e
378
+ Rails.logger.error("Mollie API error: #{e.message}")
379
+ redirect_to new_payment_path, alert: "Payment service unavailable. Please try again."
380
+ end
381
+
382
+ def show
383
+ @payment = Current.user.mollie_payments.find(params[:id])
384
+ end
385
+ end
386
+ ```
387
+
388
+ > **What's happening:** `mollie_pay_once` creates a payment on Mollie's API,
389
+ > stores the local record, and returns it with the `checkout_url` populated.
390
+ > We redirect the user to Mollie's hosted payment page. After they complete (or
391
+ > abandon) payment, Mollie redirects them back to the `default_redirect_path`.
392
+
393
+ ### Add the views
394
+
395
+ `app/views/payments/new.html.erb`:
396
+
397
+ ```erb
398
+ <div class="max-w-md mx-auto mt-16">
399
+ <h1 class="text-2xl font-bold mb-6">Make a payment</h1>
400
+
401
+ <%= form_with url: payments_path, method: :post, data: { turbo: false }, class: "space-y-4" do |form| %>
402
+ <div>
403
+ <%= form.label :amount, "Amount (EUR)",
404
+ class: "block text-sm font-medium text-gray-700 mb-1" %>
405
+ <%= form.number_field :amount, value: 10.00, min: 1, step: 0.01,
406
+ class: "w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" %>
407
+ <p class="text-xs text-gray-500 mt-1">e.g. 1000 = €10.00</p>
408
+ </div>
409
+
410
+ <div>
411
+ <%= form.label :description,
412
+ class: "block text-sm font-medium text-gray-700 mb-1" %>
413
+ <%= form.text_field :description, value: "Test payment",
414
+ class: "w-full rounded-lg border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500" %>
415
+ </div>
416
+
417
+ <div>
418
+ <%= form.submit "Pay with Mollie",
419
+ class: "w-full bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700 cursor-pointer" %>
420
+ </div>
421
+ <% end %>
422
+ </div>
423
+ ```
424
+
425
+ `app/views/payments/show.html.erb`:
426
+
427
+ ```erb
428
+ <div class="max-w-lg mx-auto mt-16">
429
+ <h1 class="text-2xl font-bold mb-6">Payment <%= @payment.mollie_id %></h1>
430
+
431
+ <div class="bg-white rounded-lg border border-gray-200 shadow-sm p-6 space-y-3">
432
+ <div class="flex justify-between">
433
+ <span class="text-sm text-gray-500">Status</span>
434
+ <span class="font-medium"><%= @payment.status %></span>
435
+ </div>
436
+ <div class="flex justify-between">
437
+ <span class="text-sm text-gray-500">Amount</span>
438
+ <span class="font-medium">€<%= format("%.2f", @payment.amount) %></span>
439
+ </div>
440
+ <div class="flex justify-between">
441
+ <span class="text-sm text-gray-500">Created</span>
442
+ <span class="font-medium"><%= @payment.created_at.strftime("%d %b %Y %H:%M") %></span>
443
+ </div>
444
+ <% if @payment.paid_at %>
445
+ <div class="flex justify-between">
446
+ <span class="text-sm text-gray-500">Paid at</span>
447
+ <span class="font-medium"><%= @payment.paid_at.strftime("%d %b %Y %H:%M") %></span>
448
+ </div>
449
+ <% end %>
450
+ </div>
451
+
452
+ <div class="mt-6">
453
+ <% if @payment.status == "open" %>
454
+ <div class="bg-yellow-50 border border-yellow-200 rounded-lg p-4 text-sm text-yellow-800">
455
+ Waiting for payment confirmation from Mollie...
456
+ <%= link_to "Refresh", payment_path(@payment), class: "underline font-medium" %>
457
+ </div>
458
+ <% elsif @payment.paid? %>
459
+ <div class="bg-green-50 border border-green-200 rounded-lg p-4 text-sm text-green-800 font-medium">
460
+ Payment successful!
461
+ </div>
462
+ <% else %>
463
+ <div class="bg-gray-50 border border-gray-200 rounded-lg p-4 text-sm text-gray-700">
464
+ Payment status: <%= @payment.status %>
465
+ </div>
466
+ <% end %>
467
+ </div>
468
+
469
+ <p class="mt-6">
470
+ <%= link_to "← Back to dashboard", root_path, class: "text-sm text-indigo-600 hover:underline" %>
471
+ </p>
472
+ </div>
473
+ ```
474
+
475
+ ### Add routes
476
+
477
+ Update `config/routes.rb`:
478
+
479
+ ```ruby
480
+ Rails.application.routes.draw do
481
+ mount MolliePay::Engine => "/mollie_pay"
482
+
483
+ resource :registration, only: [ :new, :create ]
484
+ resource :session, only: [ :new, :create, :destroy ]
485
+
486
+ resources :payments, only: [ :new, :create, :show ]
487
+
488
+ root "dashboard#show"
489
+ end
490
+ ```
491
+
492
+ > **How the redirect works:** When the customer completes (or abandons) payment,
493
+ > Mollie redirects them back to the `default_redirect_path` you configured —
494
+ > `/payments/:id`. MolliePay replaces `:id` with the local payment record's ID,
495
+ > so the customer lands directly on the payment show page.
496
+ >
497
+ > **Why the status might still be "open":** Mollie redirects the customer back
498
+ > *before* the webhook fires. The customer returns to your app, but the payment
499
+ > status update arrives asynchronously via the webhook. This is by design — the
500
+ > webhook is the source of truth, not the redirect.
501
+
502
+ ---
503
+
504
+ ## Part 3: Subscriptions
505
+
506
+ > **Payment method prerequisites for mandates**
507
+ >
508
+ > Recurring billing requires a **mandate** — permission to charge the customer's
509
+ > payment method in the future. Not all payment methods support mandate creation.
510
+ > Activate at least one of these in your Mollie dashboard (Settings → Website
511
+ > profiles → Payment methods):
512
+ >
513
+ > | Method | Mandate type |
514
+ > |---|---|
515
+ > | **Credit card** | Card mandate (supports zero-amount first payments) |
516
+ > | **iDEAL** | SEPA Direct Debit mandate |
517
+ > | **Bancontact** | SEPA Direct Debit mandate |
518
+ > | **PayPal** | PayPal billing agreement (supports zero-amount first payments) |
519
+ >
520
+ > One-off payments (`mollie_pay_once`) work with any enabled method. First
521
+ > payments (`mollie_pay_first`) require a mandate-capable method — if none are
522
+ > active, the Mollie API returns `422 No suitable payment methods found`.
523
+
524
+ Mollie recurring billing works in two steps:
525
+
526
+ 1. **First payment** — establishes a *mandate* (permission to charge the
527
+ customer's payment method in the future)
528
+ 2. **Subscription** — uses the mandate to charge automatically on a schedule
529
+
530
+ You cannot create a subscription without a valid mandate. The mandate is created
531
+ automatically when the first payment is completed.
532
+
533
+ ### Add plan columns to User
534
+
535
+ We need to track what plan the user selected so we know what to subscribe them
536
+ to after the mandate is established:
537
+
538
+ ```sh
539
+ bin/rails generate migration AddPlanToUsers plan:string
540
+ bin/rails db:migrate
541
+ ```
542
+
543
+ ### Create the pricing page
544
+
545
+ ```ruby
546
+ # app/controllers/pricing_controller.rb
547
+ class PricingController < ApplicationController
548
+ allow_unauthenticated_access only: :show
549
+
550
+ PLANS = {
551
+ "monthly" => { amount: BigDecimal("25.00"), interval: "1 month", label: "Monthly", price: "€25/month" },
552
+ "yearly" => { amount: BigDecimal("250.00"), interval: "12 months", label: "Yearly", price: "€250/year (save €50)" }
553
+ }.freeze
554
+
555
+ def show
556
+ @plans = PLANS
557
+ end
558
+ end
559
+ ```
560
+
561
+ `app/views/pricing/show.html.erb`:
562
+
563
+ ```erb
564
+ <div class="max-w-2xl mx-auto mt-16">
565
+ <h1 class="text-2xl font-bold mb-6">Choose your plan</h1>
566
+
567
+ <% if Current.user&.mollie_subscribed? %>
568
+ <div class="bg-green-50 border border-green-200 rounded-lg p-6">
569
+ <p class="text-green-800">
570
+ You're currently subscribed to the <strong><%= Current.user.plan %></strong> plan.
571
+ </p>
572
+ <p class="mt-2">
573
+ <%= link_to "Manage subscription", billing_path,
574
+ class: "text-green-700 font-medium hover:underline" %>
575
+ </p>
576
+ </div>
577
+ <% else %>
578
+ <div class="grid grid-cols-1 sm:grid-cols-2 gap-6">
579
+ <% @plans.each do |key, plan| %>
580
+ <div class="bg-white rounded-lg border border-gray-200 shadow-sm p-6 flex flex-col">
581
+ <h2 class="text-lg font-semibold text-gray-900"><%= plan[:label] %></h2>
582
+ <p class="text-2xl font-bold text-gray-900 mt-2"><%= plan[:price] %></p>
583
+
584
+ <div class="mt-auto pt-6">
585
+ <% if Current.user&.mollie_mandated? %>
586
+ <%= button_to "Subscribe",
587
+ subscriptions_path,
588
+ params: { plan: key },
589
+ method: :post,
590
+ class: "w-full bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700 cursor-pointer" %>
591
+ <% elsif authenticated? %>
592
+ <%= button_to "Get started",
593
+ subscription_setup_path,
594
+ params: { plan: key },
595
+ method: :post,
596
+ form: { data: { turbo: false } },
597
+ class: "w-full bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700 cursor-pointer" %>
598
+ <% else %>
599
+ <%= link_to "Sign up to get started",
600
+ new_registration_path,
601
+ class: "block w-full text-center bg-indigo-600 text-white font-medium py-2 px-4 rounded-lg hover:bg-indigo-700" %>
602
+ <% end %>
603
+ </div>
604
+ </div>
605
+ <% end %>
606
+ </div>
607
+
608
+ <% if authenticated? && !Current.user.mollie_mandated? %>
609
+ <p class="mt-6 text-sm text-gray-500">
610
+ A small first payment (€0.01) establishes your payment method.
611
+ Your subscription starts after this payment is confirmed.
612
+ </p>
613
+ <% end %>
614
+ <% end %>
615
+ </div>
616
+ ```
617
+
618
+ > **Two buttons:** If the user already has a mandate (from a previous payment),
619
+ > they can subscribe directly. If not, they go through the first payment flow.
620
+
621
+ ### Subscription setup (first payment for mandate)
622
+
623
+ ```ruby
624
+ # app/controllers/subscription_setups_controller.rb
625
+ class SubscriptionSetupsController < ApplicationController
626
+ def create
627
+ plan = params[:plan]
628
+ unless PricingController::PLANS.key?(plan)
629
+ redirect_to pricing_path, alert: "Invalid plan."
630
+ return
631
+ end
632
+
633
+ # Store the chosen plan so we can subscribe after the mandate is established
634
+ Current.user.update!(plan: plan)
635
+
636
+ # Create a first payment to establish the mandate
637
+ # Using €0.01 — the minimum amount Mollie accepts
638
+ payment = Current.user.mollie_pay_first(
639
+ amount: BigDecimal("0.01"),
640
+ description: "Payment method setup for #{PricingController::PLANS[plan][:label]} plan"
641
+ )
642
+
643
+ redirect_to payment.checkout_url, allow_other_host: true
644
+ rescue Mollie::RequestError, MolliePay::ConfigurationError => e
645
+ Rails.logger.error("Mollie API error: #{e.message}")
646
+ redirect_to pricing_path, alert: "Payment service unavailable. Please try again."
647
+ end
648
+ end
649
+ ```
650
+
651
+ > **Why €0.01?** The first payment's purpose is to create a mandate — permission
652
+ > to charge the customer's payment method in the future. The amount can be
653
+ > anything. We use the minimum so the customer isn't surprised by a charge.
654
+
655
+ ### Subscriptions controller
656
+
657
+ ```ruby
658
+ # app/controllers/subscriptions_controller.rb
659
+ class SubscriptionsController < ApplicationController
660
+ def create
661
+ plan_key = params[:plan] || Current.user.plan
662
+ plan = PricingController::PLANS[plan_key]
663
+
664
+ unless plan
665
+ redirect_to pricing_path, alert: "Invalid plan."
666
+ return
667
+ end
668
+
669
+ unless Current.user.mollie_mandated?
670
+ redirect_to pricing_path, alert: "Please complete a first payment to set up your payment method."
671
+ return
672
+ end
673
+
674
+ Current.user.update!(plan: plan_key)
675
+
676
+ Current.user.mollie_subscribe(
677
+ amount: plan[:amount],
678
+ interval: plan[:interval],
679
+ description: "Acme SaaS #{plan[:label]} subscription"
680
+ )
681
+
682
+ redirect_to billing_path, notice: "Subscription activated!"
683
+ rescue Mollie::RequestError, MolliePay::ConfigurationError => e
684
+ Rails.logger.error("Mollie API error: #{e.message}")
685
+ redirect_to pricing_path, alert: "Subscription could not be created. Please try again."
686
+ end
687
+
688
+ def destroy
689
+ Current.user.mollie_cancel_subscription
690
+ redirect_to billing_path, notice: "Subscription canceled."
691
+ rescue MolliePay::SubscriptionNotFound
692
+ redirect_to billing_path, alert: "No active subscription to cancel."
693
+ end
694
+ end
695
+ ```
696
+
697
+ ### Add routes
698
+
699
+ Update `config/routes.rb` with all the new routes:
700
+
701
+ ```ruby
702
+ Rails.application.routes.draw do
703
+ mount MolliePay::Engine => "/mollie_pay"
704
+
705
+ resource :registration, only: [ :new, :create ]
706
+ resource :session, only: [ :new, :create, :destroy ]
707
+
708
+ resources :payments, only: [ :new, :create, :show ]
709
+
710
+ resource :pricing, only: :show, controller: "pricing"
711
+ resource :subscription_setup, only: :create
712
+ resource :subscription, only: [ :create, :destroy ]
713
+ resource :billing, only: :show
714
+
715
+ root "dashboard#show"
716
+ end
717
+ ```
718
+
719
+ ### Auto-subscribe after first payment
720
+
721
+ When the first payment completes, Mollie fires a webhook. MolliePay processes it,
722
+ stores the mandate the payment created, and calls `on_mollie_mandate_created` on
723
+ your model once that mandate is valid. Without this hook, users would pay €0.01,
724
+ get a mandate, and then need to manually navigate back to the pricing page and
725
+ click "Subscribe" — a confusing experience.
726
+
727
+ Subscribe from `on_mollie_mandate_created`, not from
728
+ `on_mollie_first_payment_paid`. With iDEAL, Mollie can report the payment paid
729
+ a few seconds before the mandate is valid. `on_mollie_first_payment_paid` then
730
+ runs while `mollie_mandated?` is still false, and `mollie_subscribe` would raise
731
+ `MolliePay::MandateRequired`. MolliePay keeps re-fetching a pending mandate in
732
+ the background and calls `on_mollie_mandate_created` when it turns valid.
733
+
734
+ Add the auto-subscribe hook to your `User` model:
735
+
736
+ ```ruby
737
+ # app/models/user.rb — add this method to the User class
738
+ def on_mollie_mandate_created(mandate)
739
+ return if mollie_subscribed? # idempotency guard — prevents duplicate subscriptions on webhook retry
740
+ return unless plan.present?
741
+
742
+ plan_details = PricingController::PLANS[plan]
743
+ return unless plan_details
744
+
745
+ mollie_subscribe(
746
+ amount: plan_details[:amount],
747
+ interval: plan_details[:interval],
748
+ description: "Acme SaaS #{plan_details[:label]} subscription",
749
+ mandate: mandate
750
+ )
751
+ end
752
+ ```
753
+
754
+ > **Important:** This hook runs in a background job (via Active Job), not in the
755
+ > user's HTTP request. That's why we stored the plan on the User model earlier —
756
+ > the hook needs to know which plan was chosen.
757
+
758
+ ---
759
+
760
+ ## Part 4: Billing dashboard
761
+
762
+ Create a billing page where users can see their subscription status, payment
763
+ history, and manage their subscription.
764
+
765
+ ```ruby
766
+ # app/controllers/billings_controller.rb
767
+ class BillingsController < ApplicationController
768
+ def show
769
+ @subscription = Current.user.mollie_subscription
770
+ @mandate = Current.user.mollie_mandate
771
+ @payments = Current.user.mollie_payments.order(created_at: :desc).limit(10) # real has_many :through association
772
+ end
773
+ end
774
+ ```
775
+
776
+ `app/views/billings/show.html.erb`:
777
+
778
+ ```erb
779
+ <div class="max-w-3xl mx-auto mt-16">
780
+ <h1 class="text-2xl font-bold mb-8">Billing</h1>
781
+
782
+ <%# ── Subscription ── %>
783
+ <section class="mb-8">
784
+ <h2 class="text-lg font-semibold text-gray-900 mb-3">Subscription</h2>
785
+
786
+ <% if @subscription&.active? %>
787
+ <div class="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
788
+ <div class="space-y-3">
789
+ <div class="flex justify-between">
790
+ <span class="text-sm text-gray-500">Plan</span>
791
+ <span class="font-medium"><%= Current.user.plan&.capitalize || "Active" %></span>
792
+ </div>
793
+ <div class="flex justify-between">
794
+ <span class="text-sm text-gray-500">Status</span>
795
+ <span class="inline-flex items-center px-2 py-0.5 rounded-full text-xs font-medium bg-green-100 text-green-800">
796
+ <%= @subscription.status %>
797
+ </span>
798
+ </div>
799
+ <div class="flex justify-between">
800
+ <span class="text-sm text-gray-500">Amount</span>
801
+ <span class="font-medium">€<%= format("%.2f", @subscription.amount) %> / <%= @subscription.interval %></span>
802
+ </div>
803
+ </div>
804
+
805
+ <div class="mt-6 pt-4 border-t border-gray-100">
806
+ <%= button_to "Cancel subscription", subscription_path, method: :delete,
807
+ data: { turbo_confirm: "Are you sure you want to cancel?" },
808
+ class: "text-sm text-red-600 hover:text-red-800 font-medium cursor-pointer" %>
809
+ </div>
810
+ </div>
811
+ <% else %>
812
+ <div class="bg-gray-50 rounded-lg border border-gray-200 p-6 text-gray-500">
813
+ No active subscription.
814
+ <%= link_to "View plans", pricing_path, class: "text-indigo-600 hover:underline font-medium" %>
815
+ </div>
816
+ <% end %>
817
+ </section>
818
+
819
+ <%# ── Payment method ── %>
820
+ <section class="mb-8">
821
+ <h2 class="text-lg font-semibold text-gray-900 mb-3">Payment method</h2>
822
+
823
+ <% if @mandate %>
824
+ <div class="bg-white rounded-lg border border-gray-200 shadow-sm p-6">
825
+ <div class="space-y-3">
826
+ <div class="flex justify-between">
827
+ <span class="text-sm text-gray-500">Method</span>
828
+ <span class="font-medium"><%= @mandate.method %></span>
829
+ </div>
830
+ <div class="flex justify-between">
831
+ <span class="text-sm text-gray-500">Status</span>
832
+ <span class="font-medium"><%= @mandate.status %></span>
833
+ </div>
834
+ </div>
835
+ </div>
836
+ <% else %>
837
+ <div class="bg-gray-50 rounded-lg border border-gray-200 p-6 text-gray-500">
838
+ No payment method on file.
839
+ </div>
840
+ <% end %>
841
+ </section>
842
+
843
+ <%# ── Payment history ── %>
844
+ <section>
845
+ <h2 class="text-lg font-semibold text-gray-900 mb-3">Payment history</h2>
846
+
847
+ <% if @payments.any? %>
848
+ <div class="bg-white rounded-lg border border-gray-200 shadow-sm overflow-hidden">
849
+ <table class="min-w-full divide-y divide-gray-200">
850
+ <thead class="bg-gray-50">
851
+ <tr>
852
+ <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Date</th>
853
+ <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Payment ID</th>
854
+ <th class="px-6 py-3 text-right text-xs font-medium text-gray-500 uppercase tracking-wider">Amount</th>
855
+ <th class="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase tracking-wider">Status</th>
856
+ <th class="px-6 py-3"></th>
857
+ </tr>
858
+ </thead>
859
+ <tbody class="divide-y divide-gray-200">
860
+ <% @payments.each do |payment| %>
861
+ <tr>
862
+ <td class="px-6 py-4 text-sm text-gray-700"><%= payment.created_at.strftime("%d %b %Y") %></td>
863
+ <td class="px-6 py-4 text-sm font-mono text-gray-500"><%= payment.mollie_id %></td>
864
+ <td class="px-6 py-4 text-sm text-gray-700 text-right">€<%= format("%.2f", payment.amount) %></td>
865
+ <td class="px-6 py-4 text-sm"><%= payment.status %></td>
866
+ <td class="px-6 py-4 text-sm text-right">
867
+ <%= link_to "View", payment_path(payment), class: "text-indigo-600 hover:underline" %>
868
+ </td>
869
+ </tr>
870
+ <% end %>
871
+ </tbody>
872
+ </table>
873
+ </div>
874
+ <% else %>
875
+ <div class="bg-gray-50 rounded-lg border border-gray-200 p-6 text-gray-500">
876
+ No payments yet.
877
+ </div>
878
+ <% end %>
879
+ </section>
880
+
881
+ <p class="mt-8">
882
+ <%= link_to "← Back to dashboard", root_path, class: "text-sm text-indigo-600 hover:underline" %>
883
+ </p>
884
+ </div>
885
+ ```
886
+
887
+ ---
888
+
889
+ ## Part 5: Running it locally
890
+
891
+ ### Start a tunnel
892
+
893
+ Mollie needs to reach your local server to send webhooks. Open a new terminal
894
+ and start a tunnel:
895
+
896
+ **Using cloudflared (no account needed):**
897
+
898
+ ```sh
899
+ cloudflared tunnel --url localhost:3000
900
+ ```
901
+
902
+ This gives you a URL like `https://random-words.trycloudflare.com`.
903
+
904
+ **Using ngrok:**
905
+
906
+ ```sh
907
+ ngrok http 3000
908
+ ```
909
+
910
+ This gives you a URL like `https://xxxx.ngrok-free.app`.
911
+
912
+ ### Allow the tunnel host
913
+
914
+ Add the tunnel hostname to `config/environments/development.rb`:
915
+
916
+ ```ruby
917
+ # For cloudflared:
918
+ config.hosts << /.*\.trycloudflare\.com/
919
+
920
+ # Or for ngrok:
921
+ # config.hosts << /.*\.ngrok-free\.app/
922
+ ```
923
+
924
+ ### Set environment variables
925
+
926
+ Get your test API key from the [Mollie Dashboard](https://my.mollie.com/dashboard/signup/7878281?lang=nl)
927
+ under Developers → API keys.
928
+
929
+ ```sh
930
+ export MOLLIE_API_KEY="test_xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
931
+ export MOLLIE_HOST="https://your-tunnel-url.trycloudflare.com"
932
+ ```
933
+
934
+ > **Replace** `your-tunnel-url.trycloudflare.com` with your actual tunnel URL.
935
+ > The webhook URL and redirect URL are derived automatically from the host.
936
+
937
+ ### Start the server
938
+
939
+ ```sh
940
+ bin/dev
941
+ ```
942
+
943
+ > **Note:** Use `bin/dev` instead of `bin/rails server` — this starts both the
944
+ > Rails server and the Tailwind CSS watcher via Foreman.
945
+
946
+ ### Test the flow
947
+
948
+ 1. **Sign up** at `http://localhost:3000/registration/new`
949
+
950
+ 2. **Make a one-off payment:**
951
+ - Click "Make a payment" on the dashboard
952
+ - Enter an amount (e.g., 1000 for €10.00) and a description
953
+ - Click "Pay with Mollie"
954
+ - You'll be redirected to Mollie's **test checkout** page
955
+ - Select a payment method and status (click "Paid")
956
+ - You'll be redirected back to your app
957
+
958
+ 3. **Subscribe to a plan:**
959
+ - Click "Subscriptions" on the dashboard
960
+ - Choose Monthly (€25/month) or Yearly (€250/year)
961
+ - Click "Get started" — this creates a €0.01 first payment
962
+ - Complete the payment on Mollie's test checkout (click "Paid")
963
+ - Return to your app and go to the pricing page
964
+ - Your mandate is now established — click "Subscribe"
965
+
966
+ 4. **Check the billing dashboard:**
967
+ - Click "Billing" to see your subscription and payment history
968
+
969
+ 5. **Cancel subscription:**
970
+ - On the billing page, click "Cancel subscription"
971
+
972
+ ### Understanding test mode
973
+
974
+ In Mollie test mode:
975
+ - Payments don't actually charge anything
976
+ - The checkout page shows status buttons (Paid, Failed, Canceled, Expired)
977
+ instead of real payment forms
978
+ - You manually choose the outcome to test different scenarios
979
+ - Webhooks fire just like in production
980
+
981
+ ### Checking webhook processing
982
+
983
+ Watch your Rails server logs. When Mollie sends a webhook, you'll see:
984
+
985
+ ```
986
+ Started POST "/mollie_pay/webhooks" for 127.0.0.1
987
+ Processing by MolliePay::WebhooksController#create as */*
988
+ Parameters: {"id"=>"tr_xxxxxxxx"}
989
+ [ActiveJob] Enqueued MolliePay::ProcessWebhookJob
990
+ ```
991
+
992
+ And when the job processes:
993
+
994
+ ```
995
+ [ActiveJob] Performing MolliePay::ProcessWebhookJob
996
+ [ActiveJob] Performed MolliePay::ProcessWebhookJob
997
+ ```
998
+
999
+ ---
1000
+
1001
+ ## Complete routes file
1002
+
1003
+ Here's the final `config/routes.rb` for reference:
1004
+
1005
+ ```ruby
1006
+ Rails.application.routes.draw do
1007
+ mount MolliePay::Engine => "/mollie_pay"
1008
+
1009
+ resource :registration, only: [ :new, :create ]
1010
+ resource :session, only: [ :new, :create, :destroy ]
1011
+
1012
+ resources :payments, only: [ :new, :create, :show ]
1013
+
1014
+ resource :pricing, only: :show, controller: "pricing"
1015
+ resource :subscription_setup, only: :create
1016
+ resource :subscription, only: [ :create, :destroy ]
1017
+ resource :billing, only: :show
1018
+
1019
+ root "dashboard#show"
1020
+ end
1021
+ ```
1022
+
1023
+ ---
1024
+
1025
+ ## Part 6: Payment method selection
1026
+
1027
+ Different payment methods create different mandate types and have different
1028
+ first-payment flows. Understanding this is important for a good user experience.
1029
+
1030
+ ### Payment method comparison
1031
+
1032
+ | Payment Method | Mollie `method` | First Payment | Mandate Type | Recurring Via | Subscription Start |
1033
+ |---|---|---|---|---|---|
1034
+ | iDEAL | `"ideal"` | €0.01 | SEPA Direct Debit | SEPA DD | Immediate |
1035
+ | Credit Card | `"creditcard"` | Full plan amount | Credit Card | Credit Card | Next period |
1036
+ | SEPA Direct Debit | `"ideal"` (via iDEAL) | €0.01 | SEPA Direct Debit | SEPA DD | Immediate |
1037
+
1038
+ ### Why credit card charges the full amount
1039
+
1040
+ Credit card mandates support charging the full plan amount as the first payment.
1041
+ This IS the first subscription charge. The subscription then starts at the next
1042
+ period using `start_date:` to avoid double-charging.
1043
+
1044
+ ### Why SEPA DD uses iDEAL
1045
+
1046
+ SEPA Direct Debit mandates are created through iDEAL — this is standard Mollie
1047
+ practice. The €0.01 payment establishes the mandate, then SEPA DD handles
1048
+ recurring charges.
1049
+
1050
+ ### Adding payment method selection
1051
+
1052
+ Update your pricing view to include method radio buttons:
1053
+
1054
+ ```erb
1055
+ <%# app/views/pricing/show.html.erb — inside each plan card %>
1056
+ <%= form_with url: subscription_setup_path, data: { turbo: false } do |f| %>
1057
+ <%= f.hidden_field :plan, value: plan_key %>
1058
+
1059
+ <div class="space-y-2 mt-4">
1060
+ <label class="flex items-center gap-2">
1061
+ <%= f.radio_button :method, "ideal", checked: true, class: "accent-blue-600" %>
1062
+ iDEAL (€0.01 setup)
1063
+ </label>
1064
+ <label class="flex items-center gap-2">
1065
+ <%= f.radio_button :method, "creditcard", class: "accent-blue-600" %>
1066
+ Credit Card (first charge is full amount)
1067
+ </label>
1068
+ </div>
1069
+
1070
+ <%= f.submit "Subscribe", class: "mt-4 w-full bg-blue-600 text-white py-2 rounded" %>
1071
+ <% end %>
1072
+ ```
1073
+
1074
+ > **Important:** The `data: { turbo: false }` attribute is essential. Rails 8
1075
+ > includes Turbo Drive by default, which intercepts form submissions via
1076
+ > `fetch()`. Cross-origin redirects (to Mollie's checkout) are silently blocked
1077
+ > by the browser. This attribute disables Turbo for this form.
1078
+
1079
+ ### Updating the controller
1080
+
1081
+ ```ruby
1082
+ # app/controllers/subscription_setups_controller.rb
1083
+ class SubscriptionSetupsController < ApplicationController
1084
+ ALLOWED_METHODS = %w[ideal creditcard].freeze
1085
+
1086
+ def create
1087
+ method = params[:method]
1088
+ method = nil unless ALLOWED_METHODS.include?(method)
1089
+
1090
+ plan = PricingController::PLANS[params[:plan]]
1091
+ return redirect_to pricing_path, alert: "Invalid plan" unless plan
1092
+
1093
+ # Credit card: charge full amount as first payment
1094
+ # Other methods: charge €0.01 to establish mandate
1095
+ amount = method == "creditcard" ? plan[:amount] : 1
1096
+
1097
+ Current.user.update!(plan: params[:plan])
1098
+ payment = Current.user.mollie_pay_first(
1099
+ amount: amount,
1100
+ description: "Acme SaaS — #{plan[:label]} setup",
1101
+ redirect_url: billing_url,
1102
+ method: method
1103
+ )
1104
+ redirect_to payment.checkout_url, allow_other_host: true
1105
+ end
1106
+ end
1107
+ ```
1108
+
1109
+ ### Handling the webhook callback
1110
+
1111
+ Update `on_mollie_mandate_created` to detect full-amount first payments and
1112
+ pass `start_date:` to avoid double-charging:
1113
+
1114
+ ```ruby
1115
+ # app/models/user.rb
1116
+ def on_mollie_mandate_created(mandate)
1117
+ return if mollie_subscribed?
1118
+ return unless plan.present?
1119
+
1120
+ plan_details = PricingController::PLANS[plan]
1121
+ return unless plan_details
1122
+
1123
+ # If first payment covered the full amount (credit card flow),
1124
+ # start subscription at next period to avoid double-charging
1125
+ first_payment = mandate.payments.first_payments.paid.order(:paid_at).last
1126
+ start_date = if first_payment && first_payment.amount >= plan_details[:amount]
1127
+ Date.today + plan_details[:interval_duration]
1128
+ end
1129
+
1130
+ mollie_subscribe(
1131
+ amount: plan_details[:amount],
1132
+ interval: plan_details[:interval],
1133
+ description: "Acme SaaS #{plan_details[:label]} subscription",
1134
+ start_date: start_date,
1135
+ mandate: mandate
1136
+ )
1137
+ end
1138
+ ```
1139
+
1140
+ You will need a helper method to compute the next period start date. Add to your
1141
+ `PricingController::PLANS` hash:
1142
+
1143
+ ```ruby
1144
+ PLANS = {
1145
+ "monthly" => { label: "Monthly", amount: BigDecimal("25.00"), interval: "1 month", interval_duration: 1.month },
1146
+ "yearly" => { label: "Yearly", amount: BigDecimal("250.00"), interval: "12 months", interval_duration: 1.year }
1147
+ }.freeze
1148
+ ```
1149
+
1150
+ ---
1151
+
1152
+ ## Part 7: Using through associations
1153
+
1154
+ MolliePay provides `has_many :through` associations that give your billable model
1155
+ direct access to payments, subscriptions, and mandates without navigating through
1156
+ the customer.
1157
+
1158
+ ### Before and after
1159
+
1160
+ ```ruby
1161
+ # Before (v0.1) — safe navigation required
1162
+ user.mollie_customer&.subscriptions&.active&.exists?
1163
+ user.mollie_customer&.payments || MolliePay::Payment.none
1164
+
1165
+ # After (v0.2) — through associations, nil-safe
1166
+ user.mollie_subscriptions.active.exists?
1167
+ user.mollie_payments # real association, works even without a customer
1168
+ ```
1169
+
1170
+ ### Billing dashboard with real associations
1171
+
1172
+ Since `mollie_payments` is a real ActiveRecord association, it supports full
1173
+ chaining:
1174
+
1175
+ ```ruby
1176
+ # app/controllers/billings_controller.rb
1177
+ @payments = Current.user.mollie_payments.order(created_at: :desc).limit(10)
1178
+ ```
1179
+
1180
+ ### Eager loading for admin views
1181
+
1182
+ When displaying multiple users with their subscription status, use `includes`
1183
+ to avoid N+1 queries:
1184
+
1185
+ ```ruby
1186
+ # app/controllers/admin/users_controller.rb
1187
+ @users = User.includes(mollie_customer: :subscriptions).page(params[:page])
1188
+
1189
+ # In the view — no extra query per user
1190
+ @users.each do |user|
1191
+ user.mollie_subscriptions.active.exists? # uses preloaded data
1192
+ end
1193
+ ```
1194
+
1195
+ ### Available scopes
1196
+
1197
+ All scopes can be chained on the through associations:
1198
+
1199
+ | Association | Scopes |
1200
+ |---|---|
1201
+ | `mollie_subscriptions` | `.active`, `.pending`, `.canceled`, `.suspended`, `.completed` |
1202
+ | `mollie_payments` | `.paid`, `.failed`, `.open`, `.recurring`, `.first_payments` |
1203
+ | `mollie_mandates` | `.valid_status`, `.pending` |
1204
+
1205
+ ---
1206
+
1207
+ ## Part 8: Production hardening
1208
+
1209
+ Before going live, implement these patterns to handle real-world edge cases.
1210
+
1211
+ ### Idempotency guard on the mandate callback
1212
+
1213
+ MolliePay runs each hook in its own job (`NotifyBillableJob`), which retries the
1214
+ hook up to 5 times with polynomial backoff when it raises. Without a guard, a
1215
+ retry after partial success creates a duplicate Mollie subscription — meaning
1216
+ the customer gets charged twice on a recurring basis.
1217
+
1218
+ ```ruby
1219
+ def on_mollie_mandate_created(mandate)
1220
+ return if mollie_subscribed? # essential — prevents duplicate subscriptions
1221
+ # ... rest of subscription creation
1222
+ end
1223
+ ```
1224
+
1225
+ Additionally, `mollie_subscribe` itself has a built-in idempotency guard — it
1226
+ returns the existing subscription if one is pending or active. This provides
1227
+ defense-in-depth.
1228
+
1229
+ ### Webhook processing
1230
+
1231
+ MolliePay has no event model. The controller validates the Mollie ID format and
1232
+ enqueues a job directly. The job fetches from the Mollie API and delegates to
1233
+ domain models. Idempotency lives at the model layer:
1234
+
1235
+ ```ruby
1236
+ # Controller — validate and enqueue, nothing else
1237
+ ProcessWebhookJob.perform_later(mollie_id)
1238
+ head :ok
1239
+
1240
+ # Job — fetch and delegate by ID prefix
1241
+ Payment.record_from_mollie(Mollie::Payment.get(mollie_id))
1242
+
1243
+ # Model — idempotent upsert, hooks enqueued only on status transitions
1244
+ payment = find_or_initialize_by(mollie_id: mp.id)
1245
+ previous_status = payment.status
1246
+ payment.update!(...)
1247
+ payment.notify_billable if payment.status != previous_status
1248
+
1249
+ # NotifyBillableJob — calls the hook, retries it when it raises
1250
+ billable.public_send(hook, record)
1251
+ ```
1252
+
1253
+ This follows the 37signals principle: domain models own their state, ActiveJob
1254
+ owns retry/failure tracking. No mutable event records, no intermediate state.
1255
+
1256
+ ### Syncing subscriptions on a schedule
1257
+
1258
+ Mollie does not send webhooks when a subscription's own status changes — when
1259
+ Mollie cancels a subscription after failed payment retries, suspends it on an
1260
+ invalid mandate, or completes it after `times` charges, no `sub_` webhook
1261
+ arrives. Without a scheduled sync, `mollie_subscribed?` stays `true` and
1262
+ `on_mollie_subscription_canceled`, `on_mollie_subscription_suspended`, and
1263
+ `on_mollie_subscription_completed` never fire.
1264
+
1265
+ Schedule `MolliePay::SyncSubscriptionsJob` in your recurring job configuration
1266
+ (for example, Solid Queue's `config/recurring.yml`, or cron / Sidekiq-Cron /
1267
+ GoodJob):
1268
+
1269
+ ```yaml
1270
+ # config/recurring.yml
1271
+ production:
1272
+ mollie_pay_sync_subscriptions:
1273
+ class: MolliePay::SyncSubscriptionsJob
1274
+ schedule: every day at 3am
1275
+ ```
1276
+
1277
+ `SyncSubscriptionsJob` walks every local subscription in
1278
+ `MolliePay::Subscription::ACTIVE_STATUSES` (`pending` and `active`) and enqueues
1279
+ an isolated `MolliePay::SyncSubscriptionJob` per subscription on the sweep job's
1280
+ queue. High-volume apps can schedule the sweep on a dedicated queue (such as
1281
+ `queue: low`) so nightly sync traffic never delays live `:default` webhooks.
1282
+ Each job reconciles missed subscription payments first, updates the subscription
1283
+ status so hooks fire, and cancels the subscription locally (firing
1284
+ `on_mollie_subscription_canceled`) if Mollie answers `404 Not Found` for the
1285
+ subscription.
1286
+
1287
+ - **Never run the sync with a mismatched `test_`/`live_` API key.** Mollie
1288
+ returns `404` when a `test_` key queries `live_` subscriptions (for example in
1289
+ a staging environment loaded from a production backup), which cancels those
1290
+ subscriptions locally and enqueues `on_mollie_subscription_canceled`.
1291
+ - **Suspended subscriptions are not re-polled automatically.** Re-check one on
1292
+ demand with `MolliePay::SyncSubscriptionJob.perform_later(subscription)` or
1293
+ `subscription.sync_with_mollie`.
1294
+ - **First run on imported subscriptions:** If existing subscriptions were loaded
1295
+ without their historical `MolliePay::Payment` rows, the first sync records
1296
+ them and enqueues their payment hooks — ensure your hooks are idempotent.
1297
+
1298
+ ### Error handling in controllers
1299
+
1300
+ Add a rescue pattern for all controllers that call the Mollie API:
1301
+
1302
+ ```ruby
1303
+ rescue Mollie::RequestError, MolliePay::ConfigurationError => e
1304
+ Rails.logger.error("Mollie API error: #{e.message}")
1305
+ redirect_to pricing_path, alert: "Payment service unavailable. Please try again."
1306
+ end
1307
+ ```
1308
+
1309
+ ### Turbo Drive and external redirects
1310
+
1311
+ Rails 8 includes Turbo Drive by default. Turbo intercepts form submissions via
1312
+ `fetch()`. Cross-origin redirects (to Mollie's checkout page) are silently
1313
+ blocked by the browser.
1314
+
1315
+ **Fix:** Add `data: { turbo: false }` on every form that redirects to Mollie:
1316
+
1317
+ ```erb
1318
+ <%= form_with url: subscription_setup_path, data: { turbo: false } do |f| %>
1319
+ <%# ... %>
1320
+ <% end %>
1321
+ ```
1322
+
1323
+ This applies to subscription setup forms, one-off payment forms, and any form
1324
+ that ultimately redirects to `payment.checkout_url`.
1325
+
1326
+ Also use `allow_other_host: true` in your controller redirects:
1327
+
1328
+ ```ruby
1329
+ redirect_to payment.checkout_url, allow_other_host: true
1330
+ ```
1331
+
1332
+ ### Production deployment checklist
1333
+
1334
+ 1. Switch to a `live_` API key
1335
+ 2. Set `host` to your real domain with HTTPS (e.g. `https://yourapp.com`)
1336
+ 3. Configure a proper queue backend (Solid Queue, Sidekiq, etc.)
1337
+ 4. Schedule `MolliePay::SyncSubscriptionsJob` (e.g. nightly in `config/recurring.yml`)
1338
+ 5. Add rate limiting to the webhook endpoint (see README)
1339
+ 6. Set up monitoring for failed webhook and sync jobs
1340
+ 7. Test each payment method in Mollie's test mode before going live