fluentcart-developer 1.1.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 (66) hide show
  1. package/.gitattributes +2 -0
  2. package/CLAUDE.md +22 -0
  3. package/CONTRIBUTING.md +73 -0
  4. package/LICENSE +21 -0
  5. package/README.md +127 -0
  6. package/SKILL.md +127 -0
  7. package/bin/index.js +281 -0
  8. package/copy-skills.js +43 -0
  9. package/package.json +38 -0
  10. package/skills/fluentcart-developer/SKILL.md +172 -0
  11. package/skills/fluentcart-developer/examples/README.md +25 -0
  12. package/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/fluent-cart/checkout.php +32 -0
  13. package/skills/fluentcart-developer/examples/fluentcart-starter-child-theme/functions.php +40 -0
  14. package/skills/fluentcart-developer/examples/sample-custom-addon/fluentcart-custom-addon.php +114 -0
  15. package/skills/fluentcart-developer/examples/sample-custom-payment-gateway/fluentcart-custom-gateway-example.php +149 -0
  16. package/skills/fluentcart-developer/examples/sample-fee-surcharge-plugin/fluentcart-fee-surcharge.php +38 -0
  17. package/skills/fluentcart-developer/examples/sample-shipping-carrier/fluentcart-custom-shipping-carrier.php +62 -0
  18. package/skills/fluentcart-developer/references/action-hooks-admin-templates.md +787 -0
  19. package/skills/fluentcart-developer/references/action-hooks-cart-checkout.md +1355 -0
  20. package/skills/fluentcart-developer/references/action-hooks-customers-users.md +266 -0
  21. package/skills/fluentcart-developer/references/action-hooks-licenses.md +855 -0
  22. package/skills/fluentcart-developer/references/action-hooks-orders.md +631 -0
  23. package/skills/fluentcart-developer/references/action-hooks-payments-integrations.md +963 -0
  24. package/skills/fluentcart-developer/references/action-hooks-products-coupons.md +585 -0
  25. package/skills/fluentcart-developer/references/action-hooks-subscriptions.md +661 -0
  26. package/skills/fluentcart-developer/references/database-models-query-builder.md +194 -0
  27. package/skills/fluentcart-developer/references/database-models-reference.md +604 -0
  28. package/skills/fluentcart-developer/references/database-schema-reference.md +940 -0
  29. package/skills/fluentcart-developer/references/engineering-notes.md +154 -0
  30. package/skills/fluentcart-developer/references/fee-system-guide.md +449 -0
  31. package/skills/fluentcart-developer/references/filter-hooks-cart-checkout.md +1202 -0
  32. package/skills/fluentcart-developer/references/filter-hooks-customers-subscriptions.md +902 -0
  33. package/skills/fluentcart-developer/references/filter-hooks-integrations-advanced.md +1598 -0
  34. package/skills/fluentcart-developer/references/filter-hooks-orders-payments.md +1319 -0
  35. package/skills/fluentcart-developer/references/filter-hooks-products-pricing.md +628 -0
  36. package/skills/fluentcart-developer/references/filter-hooks-settings-configuration.md +1177 -0
  37. package/skills/fluentcart-developer/references/fluentcart-developer-guide.md +154 -0
  38. package/skills/fluentcart-developer/references/ghost-product-selling.md +458 -0
  39. package/skills/fluentcart-developer/references/modules-and-extensions-reference.md +224 -0
  40. package/skills/fluentcart-developer/references/paddle-gateway-case-study.md +1925 -0
  41. package/skills/fluentcart-developer/references/payment-gateway-integration.md +761 -0
  42. package/skills/fluentcart-developer/references/rest-api-checkout.md +286 -0
  43. package/skills/fluentcart-developer/references/rest-api-coupons.md +794 -0
  44. package/skills/fluentcart-developer/references/rest-api-customer-profile.md +190 -0
  45. package/skills/fluentcart-developer/references/rest-api-customers.md +1121 -0
  46. package/skills/fluentcart-developer/references/rest-api-dashboard-utilities.md +219 -0
  47. package/skills/fluentcart-developer/references/rest-api-email-notifications.md +619 -0
  48. package/skills/fluentcart-developer/references/rest-api-files.md +290 -0
  49. package/skills/fluentcart-developer/references/rest-api-integrations.md +324 -0
  50. package/skills/fluentcart-developer/references/rest-api-labels-attributes.md +321 -0
  51. package/skills/fluentcart-developer/references/rest-api-licensing.md +171 -0
  52. package/skills/fluentcart-developer/references/rest-api-order-bumps.md +200 -0
  53. package/skills/fluentcart-developer/references/rest-api-orders.md +1241 -0
  54. package/skills/fluentcart-developer/references/rest-api-overview.md +131 -0
  55. package/skills/fluentcart-developer/references/rest-api-products.md +2563 -0
  56. package/skills/fluentcart-developer/references/rest-api-public-shop.md +172 -0
  57. package/skills/fluentcart-developer/references/rest-api-reference.md +552 -0
  58. package/skills/fluentcart-developer/references/rest-api-reports.md +377 -0
  59. package/skills/fluentcart-developer/references/rest-api-roles-permissions.md +147 -0
  60. package/skills/fluentcart-developer/references/rest-api-settings.md +528 -0
  61. package/skills/fluentcart-developer/references/rest-api-shipping.md +800 -0
  62. package/skills/fluentcart-developer/references/rest-api-subscriptions.md +606 -0
  63. package/skills/fluentcart-developer/references/rest-api-tax.md +356 -0
  64. package/skills/fluentcart-developer/references/subscription-customization.md +197 -0
  65. package/skills/fluentcart-developer/scripts/cli.js +1 -0
  66. package/skills.sh.json +13 -0
@@ -0,0 +1,1925 @@
1
+ # Paddle Payment Gateway Case Study
2
+
3
+ ## Settings Field Schema Reference
4
+
5
+ # Payment Gateway Settings Fields [](#payment-gateway-settings-fields)
6
+
7
+ This guide explains how to build settings fields for your custom payment gateway in FluentCart. The `fields()` method in your main gateway class (ex: YourGateway.php) returns a schema that FluentCart uses to render settings fields in the admin interface.
8
+ ## Basic Structure [](#basic-structure)
9
+
10
+ The `fields()` method returns an associative array where each key is a field ID and each value is an array defining the field properties:php
11
+ ```
12
+ public function fields(): array
13
+ {
14
+ return [
15
+ 'field_id' => [
16
+ 'type' => 'text', // Field type (required)
17
+ 'label' => 'Field Label', // Display label
18
+ 'value' => 'default_value', // Default value
19
+ // ... other properties
20
+ ],
21
+ // ... more fields
22
+ ];
23
+ }```
24
+
25
+ ## Common Field Properties [](#common-field-properties)
26
+
27
+ All field types support these common properties:
28
+
29
+ | Property | Description |
30
+ | --- | --- |
31
+ | `type` | Required. Defines the field type (see available types below) |
32
+ | `label` | The field label displayed to the user |
33
+ | `value` | Default value for the field |
34
+ | `placeholder` | Placeholder text for input fields |
35
+ | `tooltip` | Brief tooltip displayed on hover |
36
+ | `description` | Brief description displayed below the field |
37
+ | `max_length` | Maximum length of the text/input/password field |
38
+ | `disabled` | Whether the field is disabled (boolean) |
39
+ ## Available Field Types [](#available-field-types)
40
+
41
+ ### Text Fields [](#text-fields)
42
+
43
+ #### `text`, `input`, `password`, `email`, `number` [](#text-input-password-email-number)
44
+
45
+ Basic input fields for text, passwords, number(with min, max), and emails.php
46
+ ```
47
+ 'api_key' => [
48
+ 'type' => 'text',
49
+ 'label' => __('API Key', 'your-plugin'),
50
+ 'placeholder' => __('Enter your API key', 'your-plugin'),
51
+ 'help_text' => __('Find this in your gateway dashboard', 'your-plugin'),
52
+ ],
53
+ 'secret_key' => [
54
+ 'type' => 'password',
55
+ 'label' => __('Secret Key', 'your-plugin'),
56
+ 'placeholder' => __('Enter your secret key', 'your-plugin'),
57
+ ],```
58
+
59
+ ### Toggle Fields [](#toggle-fields)
60
+
61
+ #### `enable` (Toggle Switch) [](#enable-toggle-switch)
62
+
63
+ Creates a toggle switch for enabling/disabling features.php
64
+ ```
65
+ 'is_active' => [
66
+ 'type' => 'enable',
67
+ 'label' => __('Enable Gateway', 'your-plugin'),
68
+ 'value' => 'yes', // or 'no'
69
+ ],```
70
+
71
+ #### `checkbox` [](#checkbox)
72
+
73
+ Creates a single checkbox.php
74
+ ```
75
+ 'save_card' => [
76
+ 'type' => 'checkbox',
77
+ 'label' => __('Save Customer Cards', 'your-plugin'),
78
+ 'value' => 'no',
79
+ 'tooltip' => __('Allow customers to save payment methods', 'your-plugin'),
80
+ ],```
81
+
82
+ ### Selection Fields [](#selection-fields)
83
+
84
+ #### `select` [](#select)
85
+
86
+ Creates a dropdown select menu.php
87
+ ```
88
+ 'checkout_mode' => [
89
+ 'type' => 'select',
90
+ 'label' => __('Checkout Mode', 'your-plugin'),
91
+ 'options' => [
92
+ ['value' => 'hosted', 'label' => __('Hosted Checkout', 'your-plugin')],
93
+ ['value' => 'embedded', 'label' => __('Embedded Checkout', 'your-plugin')],
94
+ ],
95
+ ],```
96
+
97
+ #### `radio` [](#radio)
98
+
99
+ Creates a group of radio buttons.php
100
+ ```
101
+ 'transaction_type' => [
102
+ 'type' => 'radio',
103
+ 'label' => __('Transaction Type', 'your-plugin'),
104
+ 'options' => [
105
+ 'sale' => __('Direct Sale', 'your-plugin'),
106
+ 'authorize' => __('Authorize Only', 'your-plugin'),
107
+ ],
108
+ 'value' => 'sale',
109
+ ],```
110
+
111
+ #### `checkbox_group` [](#checkbox-group)
112
+
113
+ Creates a group of checkboxes.php
114
+ ```
115
+ 'accepted_cards' => [
116
+ 'type' => 'checkbox_group',
117
+ 'title' => __('Accepted Cards', 'your-plugin'),
118
+ 'desc' => __('Select the card types to accept', 'your-plugin'),
119
+ 'options' => [
120
+ 'visa' => __('Visa', 'your-plugin'),
121
+ 'mastercard' => __('Mastercard', 'your-plugin'),
122
+ 'amex' => __('American Express', 'your-plugin'),
123
+ ],
124
+ ],```
125
+
126
+ ### Display Fields [](#display-fields)
127
+
128
+ #### `notice` [](#notice)
129
+
130
+ Displays an informational notice without input.php
131
+ ```
132
+ 'setup_notice' => [
133
+ 'type' => 'notice',
134
+ 'value' => '<p>Configure your gateway settings below.</p>',
135
+ ],```
136
+
137
+ #### `html_attr` [](#html-attr)
138
+
139
+ Displays custom HTML content.php
140
+ ```
141
+ 'webhook_info' => [
142
+ 'type' => 'html_attr',
143
+ 'value' => '<div class="fc-gateway-webhook-info">Webhook URL: ' . $this->getWebhookUrl() . '</div>',
144
+ ],```
145
+
146
+ ### Color Selector [](#color-selector)
147
+
148
+ #### `color` [](#color)
149
+
150
+ Creates a color picker.php
151
+ ```
152
+ 'button_color' => [
153
+ 'type' => 'color',
154
+ 'label' => __('Button Color', 'your-plugin'),
155
+ 'value' => '#3498db',
156
+ ],```
157
+
158
+ ### Advanced Field Groups [](#advanced-field-groups)
159
+
160
+ #### `tabs` [](#tabs)
161
+
162
+ Creates a tabbed interface, useful for separating test and live credentials.php
163
+ ```
164
+ 'payment_mode' => [
165
+ 'type' => 'tabs',
166
+ 'schema' => [
167
+ [
168
+ 'type' => 'tab',
169
+ 'label' => __('Live credentials', 'your-plugin'),
170
+ 'value' => 'live',
171
+ 'schema' => [
172
+ 'live_api_key' => [
173
+ 'type' => 'text',
174
+ 'label' => __('Live API Key', 'your-plugin'),
175
+ ],
176
+ 'live_secret_key' => [
177
+ 'type' => 'password',
178
+ 'label' => __('Live Secret Key', 'your-plugin'),
179
+ ],
180
+ ]
181
+ ],
182
+ [
183
+ 'type' => 'tab',
184
+ 'label' => __('Test credentials', 'your-plugin'),
185
+ 'value' => 'test',
186
+ 'schema' => [
187
+ 'test_api_key' => [
188
+ 'type' => 'text',
189
+ 'label' => __('Test API Key', 'your-plugin'),
190
+ ],
191
+ 'test_secret_key' => [
192
+ 'type' => 'password',
193
+ 'label' => __('Test Secret Key', 'your-plugin'),
194
+ ],
195
+ ]
196
+ ]
197
+ ]
198
+ ],```
199
+
200
+ ## Complete Example [](#complete-example)
201
+
202
+ Here's a complete example of a `fields()` method in a gateway class:php
203
+ ```
204
+ public function fields(): array
205
+ {
206
+ // Get webhook URL
207
+ $webhookUrl = $this->getWebhookUrl();
208
+
209
+ // Test mode credentials
210
+ $testSchema = [
211
+ 'test_api_key' => [
212
+ 'type' => 'text',
213
+ 'label' => __('Test API Key', 'your-plugin'),
214
+ 'placeholder' => __('Enter your test API key', 'your-plugin'),
215
+ ],
216
+ 'test_secret_key' => [
217
+ 'type' => 'password',
218
+ 'label' => __('Test Secret Key', 'your-plugin'),
219
+ 'placeholder' => __('Enter your test secret key', 'your-plugin'),
220
+ ],
221
+ ];
222
+
223
+ // Live mode credentials
224
+ $liveSchema = [
225
+ 'live_api_key' => [
226
+ 'type' => 'text',
227
+ 'label' => __('Live API Key', 'your-plugin'),
228
+ 'placeholder' => __('Enter your live API key', 'your-plugin'),
229
+ ],
230
+ 'live_secret_key' => [
231
+ 'type' => 'password',
232
+ 'label' => __('Live Secret Key', 'your-plugin'),
233
+ 'placeholder' => __('Enter your live secret key', 'your-plugin'),
234
+ ],
235
+ ];
236
+
237
+ return [
238
+ 'setup_notice' => [
239
+ 'type' => 'notice',
240
+ 'value' => '<p>' . __('Configure your gateway settings below.', 'your-plugin') . '</p>',
241
+ ],
242
+ 'payment_mode' => [
243
+ 'type' => 'tabs',
244
+ 'schema' => [
245
+ [
246
+ 'type' => 'tab',
247
+ 'label' => __('Live credentials', 'your-plugin'),
248
+ 'value' => 'live',
249
+ 'schema' => $liveSchema
250
+ ],
251
+ [
252
+ 'type' => 'tab',
253
+ 'label' => __('Test credentials', 'your-plugin'),
254
+ 'value' => 'test',
255
+ 'schema' => $testSchema
256
+ ]
257
+ ]
258
+ ],
259
+ 'checkout_title' => [
260
+ 'type' => 'text',
261
+ 'label' => __('Checkout Title', 'your-plugin'),
262
+ 'value' => __('Credit Card Payment', 'your-plugin'),
263
+ 'placeholder' => __('Appears on the checkout page', 'your-plugin'),
264
+ ],
265
+ 'checkout_description' => [
266
+ 'type' => 'textarea',
267
+ 'label' => __('Checkout Description', 'your-plugin'),
268
+ 'value' => __('Pay securely using your credit card.', 'your-plugin'),
269
+ 'placeholder' => __('Appears on the checkout page', 'your-plugin'),
270
+ ],
271
+ 'webhook_info' => [
272
+ 'type' => 'html_attr',
273
+ 'value' => '<div class="fc-webhook-info">' .
274
+ '<strong>' . __('Webhook URL:', 'your-plugin') . '</strong><br>' .
275
+ '<code>' . $webhookUrl . '</code><br>' .
276
+ __('Configure this URL in your gateway dashboard to receive payment notifications.', 'your-plugin') .
277
+ '</div>',
278
+ ],
279
+ 'debug_mode' => [
280
+ 'type' => 'checkbox',
281
+ 'label' => __('Debug Mode', 'your-plugin'),
282
+ 'value' => 'no',
283
+ 'tooltip' => __('Enable logging for debugging purposes', 'your-plugin'),
284
+ ],
285
+ ];
286
+ }```
287
+
288
+ ## Accessing Settings Values [](#accessing-settings-values)
289
+
290
+ Once settings are saved, you can access them in your gateway class using the `$this->settings->get()` method:php
291
+ ```
292
+ // Get a setting value
293
+ $apiKey = $this->settings->get('api_key');
294
+
295
+ // Get a nested setting value based on payment mode
296
+ $mode = $this->settings->get('payment_mode');
297
+ $apiKey = $this->settings->get($mode . '_api_key');```
298
+
299
+ ## Best Practices [](#best-practices)
300
+
301
+ - **Group Related Settings**: Use tabs to separate test and live credentials
302
+ - **Provide Clear Labels**: Use descriptive labels and help text
303
+ - **Include Validation**: Use appropriate field types for data validation
304
+ - **Secure Sensitive Data**: Use password fields for API secrets
305
+ - **Add Webhook Instructions**: Show webhook URLs and instructions when applicable
306
+
307
+ ## Available Field Types Reference [](#available-field-types-reference)
308
+
309
+ | Field Type | Description |
310
+ | --- | --- |
311
+ | `text`, `input` | Standard text input |
312
+ | `password` | Password input (masked text) |
313
+ | `email` | Email input with validation |
314
+ | `textarea` | Multi-line text input |
315
+ | `select` | Dropdown selection |
316
+ | `radio` | Radio button group |
317
+ | `checkbox` | Single checkbox toggle |
318
+ | `checkbox_group` | Multiple checkbox group |
319
+ | `enable` | Toggle switch |
320
+ | `color` | Color picker |
321
+ | `notice` | Information display |
322
+ | `html_attr` | Raw HTML content |
323
+ | `tabs` | Tabbed interface |
324
+ For more complete payment method integration examples, refer to the [Complete Payment Gateway Integration Guide](https://dev.fluentcart.com/payment-methods-integration/quick-implementation.html).
325
+
326
+ ---
327
+
328
+ ## Paddle Core Implementation Detail
329
+
330
+ # Paddle Gateway Case Study [](#paddle-gateway-case-study)
331
+
332
+ Learn from a real-world implementation by examining how the Paddle payment gateway was integrated into FluentCart Pro. This case study provides practical insights and patterns you can apply to your own gateway development.
333
+ ## Overview [](#overview)
334
+
335
+ The Paddle Gateway demonstrates a **complete production-ready implementation** featuring:
336
+
337
+ - **One-time payments** with full transaction lifecycle
338
+ - **Subscription payments** with recurring billing management
339
+ - **Comprehensive webhook/IPN handling** for real-time updates
340
+ - **Custom checkout experience** with UI customization
341
+ - **Multi-environment support** (test/live modes)
342
+ - **Advanced settings management** with dynamic configuration
343
+ - **Frontend integration** with JavaScript SDK
344
+ - **Error handling and logging** for production reliability
345
+ - **Security best practices** with signature verification
346
+
347
+ This case study shows how to implement **all major payment gateway features** that third-party developers typically need.
348
+ ## Architecture Analysis [](#architecture-analysis)
349
+
350
+ ### File Structure [](#file-structure)
351
+
352
+ ```
353
+ fluent-cart-pro/app/Modules/PaymentMethods/PaddleGateway/
354
+ ├── Paddle.php # Main gateway class
355
+ ├── PaddleSettings.php # Settings management
356
+ ├── PaddleSubscriptions.php # Subscription handling
357
+ ├── PaddleHelper.php # Utility functions
358
+ ├── Processor.php # Payment processing
359
+ ├── Confirmations.php # Payment confirmations
360
+ ├── Price.php # Price management
361
+ ├── Product.php # Product handling
362
+ ├── SubscriptionsManager.php # Subscription lifecycle
363
+ ├── API/
364
+ │ └── API.php # API communication
365
+ └── Webhook/
366
+ └── IPN.php # Web hook processing```
367
+
368
+ ## Main Gateway Implementation [](#main-gateway-implementation)
369
+
370
+ ### Core Gateway Class [](#core-gateway-class)
371
+ php
372
+ ```
373
+ class Paddle extends AbstractPaymentGateway
374
+ {
375
+ private $methodSlug = 'paddle';
376
+
377
+ public array $supportedFeatures = [
378
+ 'payment',
379
+ 'refund',
380
+ 'webhook',
381
+ 'subscriptions',
382
+ 'custom_payment'
383
+ ];
384
+
385
+ public function __construct()
386
+ {
387
+ parent::__construct(
388
+ new PaddleSettings(),
389
+ new PaddleSubscriptions()
390
+ );
391
+
392
+ // Register custom checkout filter
393
+ add_filter('fluent_cart/payment_methods_with_custom_checkout_buttons', function ($methods) {
394
+ $methods[] = 'paddle';
395
+ return $methods;
396
+ });
397
+ }
398
+ }```
399
+
400
+ **Key Insights:**
401
+
402
+ - Uses composition pattern with separate settings and subscription classes
403
+ - Declares all supported features upfront
404
+ - Registers custom checkout behavior during construction
405
+
406
+ ### Gateway Metadata [](#gateway-metadata)
407
+ php
408
+ ```
409
+ public function meta(): array
410
+ {
411
+ return [
412
+ 'title' => __('Paddle', 'fluent-cart-pro'),
413
+ 'route' => 'paddle',
414
+ 'slug' => 'paddle',
415
+ 'description' => __('Pay securely with Paddle - Complete payment solution', 'fluent-cart-pro'),
416
+ 'logo' => Vite::getAssetUrl("images/payment-methods/paddle-logo.svg"),
417
+ 'icon' => Vite::getAssetUrl("images/payment-methods/paddle-logo.svg"),
418
+ 'brand_color' => '#7c3aed',
419
+ 'status' => $this->settings->get('is_active') === 'yes',
420
+ 'upcoming' => false,
421
+ 'supported_features' => $this->supportedFeatures,
422
+ 'tag' => 'beta'
423
+ ];
424
+ }```
425
+
426
+ **Key Insights:**
427
+
428
+ - Uses asset management system (Vite) for icons and logos
429
+ - Includes visual branding with brand colors
430
+ - Shows development status with tags
431
+ - Status reflects actual settings configuration
432
+
433
+ ## Settings Architecture [](#settings-architecture)
434
+
435
+ ### Hierarchical Settings Structure [](#hierarchical-settings-structure)
436
+ php
437
+ ```
438
+ class PaddleSettings extends BaseGatewaySettings
439
+ {
440
+ public $methodHandler = 'fluent_cart_payment_settings_paddle';
441
+
442
+ public static function getDefaults()
443
+ {
444
+ return [
445
+ 'is_active' => 'no',
446
+ 'provider' => 'api_keys',
447
+ 'live_api_key' => '',
448
+ 'live_client_token' => '',
449
+ 'live_webhook_secret' => '',
450
+ 'test_api_key' => '',
451
+ 'test_client_token' => '',
452
+ 'test_webhook_secret' => '',
453
+ 'payment_mode' => 'test',
454
+ 'tax_mode' => 'internal',
455
+ // UI customization options
456
+ 'paddle_checkout_theme' => 'light',
457
+ 'paddle_checkout_button_text' => 'Pay with Paddle',
458
+ 'paddle_checkout_button_color' => '',
459
+ // ... more settings
460
+ ];
461
+ }
462
+ }```
463
+
464
+ **Key Insights:**
465
+
466
+ - Separates live and test credentials
467
+ - Includes UI customization options
468
+ - Uses descriptive setting keys
469
+ - Provides sensible defaults
470
+
471
+ ### Environment-Aware API Keys [](#environment-aware-api-keys)
472
+ php
473
+ ```
474
+ public function getApiKey($mode = '')
475
+ {
476
+ if (!$mode) {
477
+ $mode = $this->getMode();
478
+ }
479
+ return $this->get($mode . '_api_key');
480
+ }
481
+
482
+ public function getMode()
483
+ {
484
+ return $this->get('payment_mode');
485
+ }```
486
+
487
+ **Key Insights:**
488
+
489
+ - Dynamic key resolution based on mode
490
+ - Centralized mode management
491
+ - Consistent naming patterns
492
+
493
+ ### Important: Payment Mode vs Order Mode [](#important-payment-mode-vs-order-mode)
494
+
495
+ FluentCart distinguishes between two different "modes":
496
+
497
+ -
498
+ **Payment Mode** (`payment_mode` in settings): The current test/live configuration in payment gateway settingsphp
499
+ ```
500
+ $this->settings->getMode(); // Returns current payment mode from settings```
501
+
502
+ -
503
+ **Order Mode** (`$order->mode`): The mode captured at checkout time and stored with the orderphp
504
+ ```
505
+ $order->mode; // Returns the mode when this specific order was placed```
506
+
507
+ **Usage Guidelines:**
508
+
509
+ - **For API calls**: Use order mode from `$order->mode` to ensure consistency with the original transaction
510
+ - **For settings/configuration**: Use payment mode from `$this->settings->getMode()`
511
+ - **For transaction storage**: Always store `payment_mode` as `$order->mode` to preserve checkout-time context
512
+ - **For transaction URLs**: Use the stored `payment_mode` from transaction data
513
+
514
+ ## Complete Payment Processing Implementation [](#complete-payment-processing-implementation)
515
+
516
+ ### One-Time Payment Flow [](#one-time-payment-flow)
517
+ php
518
+ ```
519
+ class Processor
520
+ {
521
+ public function handleSinglePayment(PaymentInstance $paymentInstance)
522
+ {
523
+ $order = $paymentInstance->order;
524
+ $transaction = $paymentInstance->transaction;
525
+
526
+ // Prepare payment data for external API
527
+ $paymentData = [
528
+ 'items' => $this->prepareOrderItems($order),
529
+ 'customer' => [
530
+ 'email' => $order->email,
531
+ 'name' => $order->billing_name,
532
+ 'address' => $this->prepareAddress($order)
533
+ ],
534
+ 'custom_data' => [
535
+ 'fct_transaction_hash' => $transaction->uuid,
536
+ 'fct_order_id' => $order->id
537
+ ],
538
+ 'checkout' => [
539
+ 'url' => $this->getCheckoutUrl($order),
540
+ 'success_url' => $this->getSuccessUrl($transaction),
541
+ 'cancel_url' => $this->getCancelUrl($order)
542
+ ]
543
+ ];
544
+
545
+ // Create payment at external gateway
546
+ // Always explicitly pass the order mode for consistency
547
+ $response = API::createPaddleObject('transactions', $paymentData, $order->mode);
548
+
549
+ if (is_wp_error($response)) {
550
+ return [
551
+ 'success' => false,
552
+ 'message' => $response->get_error_message()
553
+ ];
554
+ }
555
+
556
+ // Store external payment ID for webhook processing
557
+ $transaction->update([
558
+ 'vendor_charge_id' => $response['data']['id'],
559
+ 'payment_mode' => $order->mode, // Store order mode from checkout time
560
+ 'meta' => array_merge($transaction->meta ?? [], [
561
+ 'gateway_response' => $response['data']
562
+ ])
563
+ ]);
564
+
565
+ return [
566
+ 'success' => true,
567
+ 'redirect_url' => $response['data']['checkout']['url'],
568
+ 'transaction_id' => $response['data']['id']
569
+ ];
570
+ }
571
+
572
+ private function prepareOrderItems($order)
573
+ {
574
+ $items = [];
575
+ foreach ($order->items as $item) {
576
+ $items[] = [
577
+ 'price_id' => $item->meta['external_price_id'] ?? null,
578
+ 'quantity' => $item->quantity,
579
+ 'name' => $item->title,
580
+ 'description' => $item->description,
581
+ 'unit_price' => $item->unit_price * 100, // Convert to cents
582
+ 'total_price' => $item->total * 100
583
+ ];
584
+ }
585
+ return $items;
586
+ }
587
+ }```
588
+
589
+ **Key Insights:**
590
+
591
+ - Comprehensive order data mapping to external gateway format
592
+ - Custom data inclusion for webhook correlation
593
+ - Proper URL handling for checkout flow
594
+ - Error handling with WP_Error integration
595
+ - Transaction metadata storage for later processing
596
+
597
+ ### Subscription Payment Flow [](#subscription-payment-flow)
598
+ php
599
+ ```
600
+ public function handleSubscriptionPayment(PaymentInstance $paymentInstance)
601
+ {
602
+ $order = $paymentInstance->order;
603
+ $subscription = $paymentInstance->subscription;
604
+ $transaction = $paymentInstance->transaction;
605
+
606
+ // Prepare subscription-specific data
607
+ $subscriptionData = [
608
+ 'items' => $this->prepareSubscriptionItems($order, $subscription),
609
+ 'customer' => $this->prepareCustomerData($order),
610
+ 'billing_cycle' => $this->mapBillingCycle($subscription),
611
+ 'collection_mode' => 'automatic',
612
+ 'proration_billing_mode' => 'prorated_immediately',
613
+ 'custom_data' => [
614
+ 'fct_subscription_hash' => $subscription->uuid,
615
+ 'fct_order_id' => $order->id,
616
+ 'fct_transaction_hash' => $transaction->uuid
617
+ ],
618
+ 'checkout' => [
619
+ 'url' => $this->getCheckoutUrl($order),
620
+ 'success_url' => $this->getSuccessUrl($transaction),
621
+ 'cancel_url' => $this->getCancelUrl($order)
622
+ ]
623
+ ];
624
+
625
+ // Add trial period if applicable
626
+ if ($subscription->trial_days > 0) {
627
+ $subscriptionData['scheduled_change'] = [
628
+ 'action' => 'resume',
629
+ 'effective_at' => gmdate('Y-m-d\TH:i:s\Z', strtotime('+' . $subscription->trial_days . ' days'))
630
+ ];
631
+ }
632
+
633
+ // Create subscription at external gateway
634
+ // Always explicitly pass the order mode for consistency
635
+ $response = API::createPaddleObject('subscriptions', $subscriptionData, $order->mode);
636
+
637
+ if (is_wp_error($response)) {
638
+ return [
639
+ 'success' => false,
640
+ 'message' => $response->get_error_message()
641
+ ];
642
+ }
643
+
644
+ // Store subscription and transaction data
645
+ $subscription->update([
646
+ 'vendor_subscription_id' => $response['data']['id'],
647
+ 'status' => 'pending',
648
+ 'meta' => array_merge($subscription->meta ?? [], [
649
+ 'gateway_response' => $response['data'],
650
+ 'billing_cycle_data' => $response['data']['billing_cycle'] ?? []
651
+ ])
652
+ ]);
653
+
654
+ $transaction->update([
655
+ 'vendor_charge_id' => $response['data']['id'],
656
+ 'subscription_id' => $subscription->id,
657
+ 'payment_mode' => $order->mode, // Store order mode from checkout time
658
+ 'meta' => array_merge($transaction->meta ?? [], [
659
+ 'subscription_data' => $response['data']
660
+ ])
661
+ ]);
662
+
663
+ return [
664
+ 'success' => true,
665
+ 'redirect_url' => $response['data']['checkout']['url'],
666
+ 'subscription_id' => $response['data']['id']
667
+ ];
668
+ }
669
+
670
+ private function prepareSubscriptionItems($order, $subscription)
671
+ {
672
+ $items = [];
673
+ foreach ($order->items as $item) {
674
+ // Map to subscription pricing structure
675
+ $items[] = [
676
+ 'price_id' => $item->meta['recurring_price_id'] ?? $item->meta['external_price_id'],
677
+ 'quantity' => $item->quantity,
678
+ 'name' => $item->title,
679
+ 'description' => $item->description,
680
+ 'billing_cycle' => [
681
+ 'interval' => $this->mapInterval($subscription->billing_interval),
682
+ 'frequency' => $subscription->billing_interval_count ?? 1
683
+ ],
684
+ 'unit_price' => $item->unit_price * 100,
685
+ 'trial_period' => $subscription->trial_days > 0 ? [
686
+ 'interval' => 'day',
687
+ 'frequency' => $subscription->trial_days
688
+ ] : null
689
+ ];
690
+ }
691
+ return $items;
692
+ }
693
+
694
+ private function mapBillingCycle($subscription)
695
+ {
696
+ $intervalMap = [
697
+ 'day' => 'day',
698
+ 'week' => 'week',
699
+ 'month' => 'month',
700
+ 'year' => 'year'
701
+ ];
702
+
703
+ return [
704
+ 'interval' => $intervalMap[$subscription->billing_interval] ?? 'month',
705
+ 'frequency' => $subscription->billing_interval_count ?? 1
706
+ ];
707
+ }```
708
+
709
+ **Key Insights:**
710
+
711
+ - Subscription-specific data structure with billing cycles
712
+ - Trial period handling with scheduled changes
713
+ - Separate subscription and transaction storage
714
+ - Complex item mapping for recurring pricing
715
+ - Comprehensive metadata storage for webhook processing
716
+
717
+ ## Payment Processing [](#payment-processing)
718
+
719
+ ### Payment Delegation Pattern [](#payment-delegation-pattern)
720
+ php
721
+ ```
722
+ public function makePaymentFromPaymentInstance(PaymentInstance $paymentInstance)
723
+ {
724
+ $order = $paymentInstance->order;
725
+
726
+ if ($paymentInstance->subscription) {
727
+ return (new Processor())->handleSubscriptionPayment($paymentInstance);
728
+ }
729
+
730
+ return (new Processor())->handleSinglePayment($paymentInstance);
731
+ }```
732
+
733
+ **Key Insights:**
734
+
735
+ - Delegates to specialized processor class
736
+ - Clean separation between single and subscription payments
737
+ - Maintains single responsibility principle
738
+
739
+ ### API Communication Layer [](#api-communication-layer)
740
+ php
741
+ ```
742
+ class API
743
+ {
744
+ public static function makeRequest($endpoint, $data = [], $method = 'POST', $mode = '')
745
+ {
746
+ $settings = self::getSettings();
747
+
748
+ if (!$mode) {
749
+ $mode = $settings->getMode(); // Get current payment mode from settings
750
+ }
751
+
752
+ $apiKey = $settings->getApiKey($mode);
753
+ if (empty($apiKey)) {
754
+ return new \WP_Error('paddle_api_key_missing', 'API key is missing');
755
+ }
756
+
757
+ $baseUrl = $mode === 'test'
758
+ ? 'https://sandbox-api.paddle.com'
759
+ : 'https://api.paddle.com';
760
+
761
+ $response = wp_remote_request($baseUrl . $endpoint, [
762
+ 'method' => $method,
763
+ 'headers' => [
764
+ 'Authorization' => 'Bearer ' . $apiKey,
765
+ 'Content-Type' => 'application/json',
766
+ ],
767
+ 'body' => $method !== 'GET' ? json_encode($data) : null,
768
+ 'timeout' => 30
769
+ ]);
770
+
771
+ // Error handling...
772
+ return $decodedBody;
773
+ }
774
+ }```
775
+
776
+ **Key Insights:**
777
+
778
+ - Environment-aware endpoint selection
779
+ - Consistent error handling with WP_Error
780
+ - Proper timeout configuration
781
+ - Bearer token authentication
782
+ - **Fallback to settings mode** when no mode parameter provided
783
+ - **Best Practice**: Always explicitly pass the mode parameter for consistency
784
+
785
+ ## Comprehensive Webhook/IPN Implementation [](#comprehensive-webhook-ipn-implementation)
786
+
787
+ ### Complete Webhook Processing Architecture [](#complete-webhook-processing-architecture)
788
+
789
+ The Paddle gateway implements a sophisticated three-layer webhook processing system that handles all payment and subscription events:php
790
+ ```
791
+ class IPN
792
+ {
793
+ private PaddleSettings $settings;
794
+
795
+ public function __construct()
796
+ {
797
+ $this->settings = new PaddleSettings();
798
+ }
799
+
800
+ /**
801
+ * Initialize all webhook event handlers
802
+ */
803
+ public function init(): void
804
+ {
805
+ // Payment lifecycle events
806
+ add_action('fluent_cart/payments/paddle/webhook_transaction_paid', [$this, 'handleTransactionPaid'], 10, 1);
807
+ add_action('fluent_cart/payments/paddle/webhook_transaction_completed', [$this, 'handleTransactionCompleted'], 10, 1);
808
+ add_action('fluent_cart/payments/paddle/webhook_transaction_payment_failed', [$this, 'handleTransactionPaymentFailed'], 10, 1);
809
+
810
+ // Subscription lifecycle events
811
+ add_action('fluent_cart/payments/paddle/webhook_subscription_created', [$this, 'handleSubscriptionActivated'], 10, 1);
812
+ add_action('fluent_cart/payments/paddle/webhook_subscription_activated', [$this, 'handleSubscriptionActivated'], 10, 1);
813
+ add_action('fluent_cart/payments/paddle/webhook_subscription_updated', [$this, 'handleSubscriptionUpdated'], 10, 1);
814
+ add_action('fluent_cart/payments/paddle/webhook_subscription_canceled', [$this, 'handleSubscriptionCanceled'], 10, 1);
815
+ add_action('fluent_cart/payments/paddle/webhook_subscription_paused', [$this, 'handleSubscriptionUpdated'], 10, 1);
816
+ add_action('fluent_cart/payments/paddle/webhook_subscription_resumed', [$this, 'handleSubscriptionUpdated'], 10, 1);
817
+ add_action('fluent_cart/payments/paddle/webhook_subscription_past_due', [$this, 'handleSubscriptionUpdated'], 10, 1);
818
+ add_action('fluent_cart/payments/paddle/webhook_subscription_payment_received', [$this, 'handleSubscriptionPaymentReceived'], 10, 1);
819
+
820
+ // Refund/adjustment events
821
+ add_action('fluent_cart/payments/paddle/webhook_adjustment_created', [$this, 'handleAdjustmentCreated'], 10, 1);
822
+ add_action('fluent_cart/payments/paddle/webhook_adjustment_updated', [$this, 'handleAdjustmentUpdated'], 10, 1);
823
+ }
824
+
825
+ /**
826
+ * Main webhook entry point and processor
827
+ */
828
+ public function verifyAndProcess()
829
+ {
830
+ $rawPayload = file_get_contents('php://input');
831
+ $payload = json_decode($rawPayload, true);
832
+
833
+ if (!$payload) {
834
+ $this->sendResponse(400, 'Invalid JSON payload');
835
+ return;
836
+ }
837
+
838
+ // Verify webhook signature if not disabled
839
+ if (!$this->settings->isWebhookVerificationDisabled()) {
840
+ $webhookSecret = $this->settings->getWebhookSecret();
841
+ if (empty($webhookSecret)) {
842
+ error_log('Paddle Webhook Failed: Webhook secret not configured');
843
+ $this->sendResponse(500, 'Webhook secret not configured');
844
+ return;
845
+ }
846
+
847
+ $verifier = new WebhookVerifier($webhookSecret);
848
+ $paddleSignature = $_SERVER['HTTP_PADDLE_SIGNATURE'];
849
+
850
+ if (!$verifier->verify($paddleSignature, $rawPayload)) {
851
+ error_log('Paddle Webhook Failed: Invalid webhook signature');
852
+ $this->sendResponse(401, 'Invalid webhook signature');
853
+ return;
854
+ }
855
+ }
856
+
857
+ // Get order from webhook data
858
+ $order = PaddleHelper::getOrderFromWebhookData($payload);
859
+ if (!$order) {
860
+ $this->sendResponse(200, 'Order not found');
861
+ return;
862
+ }
863
+
864
+ $eventType = Arr::get($payload, 'event_type');
865
+
866
+ // Validate accepted events
867
+ $acceptedEvents = [
868
+ 'transaction.paid', 'transaction.completed', 'transaction.payment_failed',
869
+ 'adjustment.created', 'adjustment.updated',
870
+ 'subscription.created', 'subscription.activated', 'subscription.updated',
871
+ 'subscription.canceled', 'subscription.paused', 'subscription.resumed',
872
+ 'subscription.past_due'
873
+ ];
874
+
875
+ if (!in_array($eventType, $acceptedEvents)) {
876
+ $this->sendResponse(200, 'Event type not handled');
877
+ return;
878
+ }
879
+
880
+ // Log webhook for debugging
881
+ do_action('fluent_cart/paddle_webhook_received', [
882
+ 'event_type' => $eventType,
883
+ 'data' => $payload,
884
+ 'raw' => $rawPayload,
885
+ 'order' => $order
886
+ ]);
887
+
888
+ // Process specific webhook event
889
+ $eventTypeFormatted = str_replace('.', '_', $eventType);
890
+
891
+ // Handle subscription renewal detection
892
+ if ($eventTypeFormatted === 'transaction_completed' || $eventTypeFormatted === 'transaction_paid') {
893
+ $paddleTransaction = Arr::get($payload, 'data');
894
+ $vendorSubscriptionId = Arr::get($paddleTransaction, 'subscription_id');
895
+
896
+ if ($vendorSubscriptionId) {
897
+ $eventTypeFormatted = 'subscription_payment_received';
898
+ }
899
+ }
900
+
901
+ // Fire specific event handler
902
+ if (has_action('fluent_cart/payments/paddle/webhook_' . $eventTypeFormatted)) {
903
+ do_action('fluent_cart/payments/paddle/webhook_' . $eventTypeFormatted, [
904
+ 'event_type' => $eventType,
905
+ 'data' => $payload,
906
+ 'raw' => $rawPayload,
907
+ 'order' => $order
908
+ ]);
909
+
910
+ $this->sendResponse(200, 'Webhook processed successfully');
911
+ } else {
912
+ $this->sendResponse(200, 'No handler found for event type');
913
+ }
914
+ }
915
+ }```
916
+
917
+ ### Individual Event Handlers [](#individual-event-handlers)
918
+
919
+ #### Payment Completion Handler [](#payment-completion-handler)
920
+ php
921
+ ```
922
+ public function handleTransactionPaid($webhookData)
923
+ {
924
+ $payload = Arr::get($webhookData, 'data');
925
+ $paddleTransaction = Arr::get($payload, 'data');
926
+ $paddleTransactionId = Arr::get($paddleTransaction, 'id');
927
+
928
+ // Extract custom data for correlation
929
+ $customData = Arr::get($paddleTransaction, 'custom_data', []);
930
+ $transactionHash = Arr::get($customData, 'fct_transaction_hash');
931
+
932
+ // Find transaction by vendor ID or hash
933
+ $transactionModel = OrderTransaction::query()->where('vendor_charge_id', $paddleTransactionId)->first();
934
+
935
+ if (!$transactionModel && $transactionHash) {
936
+ $transactionModel = OrderTransaction::query()->where('uuid', $transactionHash)->first();
937
+ }
938
+
939
+ if (!$transactionModel || $transactionModel->status === Status::TRANSACTION_SUCCEEDED) {
940
+ return false;
941
+ }
942
+
943
+ // Use FluentCart's confirmation service
944
+ (new Confirmations())->confirmPaymentSuccessByCharge($transactionModel, [
945
+ 'vendor_charge_id' => $paddleTransactionId,
946
+ 'charge' => $paddleTransaction
947
+ ]);
948
+
949
+ return true;
950
+ }```
951
+
952
+ #### Subscription Management Handler [](#subscription-management-handler)
953
+ php
954
+ ```
955
+ public function handleSubscriptionActivated($webhookData)
956
+ {
957
+ $data = Arr::get($webhookData, 'data');
958
+ $paddleSubscription = Arr::get($data, 'data');
959
+ $order = Arr::get($webhookData, 'order');
960
+
961
+ $customData = Arr::get($paddleSubscription, 'custom_data', []);
962
+ $subscriptionHash = Arr::get($customData, 'fct_subscription_hash');
963
+ $vendorSubscriptionId = Arr::get($paddleSubscription, 'id');
964
+
965
+ // Find subscription by vendor ID or hash
966
+ $subscription = Subscription::query()->where('vendor_subscription_id', $vendorSubscriptionId)->first();
967
+
968
+ if (!$subscription) {
969
+ $subscription = Subscription::query()->where('uuid', $subscriptionHash)->first();
970
+ }
971
+
972
+ if (!$subscription) {
973
+ return false;
974
+ }
975
+
976
+ // Update subscription with complete data
977
+ $billCount = OrderTransaction::query()->where('subscription_id', $subscription->id)->count();
978
+ $updateData = [
979
+ 'vendor_subscription_id' => Arr::get($paddleSubscription, 'id'),
980
+ 'current_payment_method' => 'paddle',
981
+ 'status' => PaddleHelper::transformSubscriptionStatus(Arr::get($paddleSubscription, 'status')),
982
+ 'bill_count' => $billCount,
983
+ 'next_billing_date' => gmdate('Y-m-d H:i:s', strtotime(Arr::get($paddleSubscription, 'next_billed_at'))),
984
+ 'vendor_response' => json_encode($paddleSubscription)
985
+ ];
986
+
987
+ $oldStatus = $subscription->status;
988
+ $subscription->update($updateData);
989
+
990
+ // Fire subscription activated event for new subscriptions
991
+ if (in_array($subscription->status, [Status::SUBSCRIPTION_ACTIVE, Status::SUBSCRIPTION_TRIALING])
992
+ && !in_array($oldStatus, [Status::SUBSCRIPTION_ACTIVE, Status::SUBSCRIPTION_TRIALING])
993
+ && $subscription->bill_count === 0) {
994
+
995
+ (new SubscriptionActivated($subscription, $order, $order->customer))->dispatch();
996
+ }
997
+
998
+ return true;
999
+ }```
1000
+
1001
+ #### Refund Processing Handler [](#refund-processing-handler)
1002
+ php
1003
+ ```
1004
+ public function handleAdjustmentCreated($webhookData)
1005
+ {
1006
+ $payload = Arr::get($webhookData, 'data');
1007
+ $paddleAdjustment = Arr::get($payload, 'data');
1008
+ $paddleAdjustmentId = Arr::get($paddleAdjustment, 'id');
1009
+ $action = Arr::get($paddleAdjustment, 'action');
1010
+
1011
+ // Only handle refund adjustments
1012
+ if ($action !== 'refund') {
1013
+ return false;
1014
+ }
1015
+
1016
+ $parentTransactionId = Arr::get($paddleAdjustment, 'transaction_id');
1017
+ $parentTransaction = OrderTransaction::query()->where('vendor_charge_id', $parentTransactionId)->first();
1018
+
1019
+ if (!$parentTransaction) {
1020
+ return false;
1021
+ }
1022
+
1023
+ // Calculate refund amount from adjustment items
1024
+ $paddleRefundAmount = 0;
1025
+ foreach (Arr::get($paddleAdjustment, 'items', []) as $item) {
1026
+ $paddleRefundAmount += Arr::get($item, 'totals.total', 0);
1027
+ }
1028
+
1029
+ $status = $this->transformAdjustmentStatus(Arr::get($paddleAdjustment, 'status'));
1030
+
1031
+ // Use FluentCart's refund service
1032
+ return \FluentCart\App\Services\Payments\Refund::createOrRecordRefund([
1033
+ 'vendor_charge_id' => $paddleAdjustmentId,
1034
+ 'payment_method' => 'paddle',
1035
+ 'payment_mode' => $parentTransaction->payment_mode, // Use stored order mode
1036
+ 'status' => $status,
1037
+ 'total' => $paddleRefundAmount,
1038
+ ], $parentTransaction);
1039
+ }
1040
+
1041
+ public function handleAdjustmentUpdated($webhookData)
1042
+ {
1043
+ $payload = Arr::get($webhookData, 'data');
1044
+ $paddleAdjustment = Arr::get($payload, 'data');
1045
+ $paddleAdjustmentId = Arr::get($paddleAdjustment, 'id');
1046
+
1047
+ $adjustmentTransaction = OrderTransaction::query()->where('vendor_charge_id', $paddleAdjustmentId)->first();
1048
+
1049
+ if (!$adjustmentTransaction) {
1050
+ return false;
1051
+ }
1052
+
1053
+ // Update refund status
1054
+ $adjustmentTransaction->update([
1055
+ 'status' => $this->transformAdjustmentStatus(Arr::get($paddleAdjustment, 'status'))
1056
+ ]);
1057
+
1058
+ // Fire refund event if completed
1059
+ if ($adjustmentTransaction->status === Status::TRANSACTION_REFUNDED) {
1060
+ (new OrderRefund($order, $adjustmentTransaction))->dispatch();
1061
+ }
1062
+
1063
+ return true;
1064
+ }```
1065
+
1066
+ #### Subscription Renewal Handler [](#subscription-renewal-handler)
1067
+ php
1068
+ ```
1069
+ public function handleSubscriptionPaymentReceived($webhookData)
1070
+ {
1071
+ $order = Arr::get($webhookData, 'order');
1072
+ $payload = Arr::get($webhookData, 'data');
1073
+ $paddleSubscriptionId = Arr::get($payload, 'data.subscription_id');
1074
+
1075
+ // Find subscription
1076
+ $subscriptionModel = Subscription::query()->where('vendor_subscription_id', $paddleSubscriptionId)->first();
1077
+
1078
+ if (!$subscriptionModel) {
1079
+ $subscriptionModel = Subscription::query()->where('parent_order_id', $order->id)->first();
1080
+ }
1081
+
1082
+ if (!$subscriptionModel) {
1083
+ return false;
1084
+ }
1085
+
1086
+ // Re-sync subscription data from remote
1087
+ $subscriptionModel->reSyncFromRemote();
1088
+
1089
+ return true;
1090
+ }```
1091
+
1092
+ **Key Insights:**
1093
+
1094
+ - **Complete Event Coverage**: Handles all payment, subscription, and refund events
1095
+ - **Smart Event Detection**: Automatically detects subscription renewals vs new payments
1096
+ - **Service Method Integration**: Uses FluentCart's service methods instead of manual hook firing
1097
+ - **Robust Error Handling**: Comprehensive validation and error responses
1098
+ - **Data Correlation**: Uses custom data fields to correlate webhooks with local records
1099
+ - **Status Management**: Proper status transformations and updates
1100
+ - **Signature Verification**: Optional but recommended security verification
1101
+ - **Logging Integration**: Uses FluentCart's action system for debugging
1102
+
1103
+ ## Web Hook Implementation [](#web-hook-implementation)
1104
+
1105
+ ### Signature Verification [](#signature-verification)
1106
+ php
1107
+ ```
1108
+ public static function verifyWebhook($payload = null, $signature = null, $mode = '')
1109
+ {
1110
+ if ($payload === null) {
1111
+ $payload = file_get_contents('php://input');
1112
+ }
1113
+
1114
+ if ($signature === null) {
1115
+ $signature = $_SERVER['HTTP_PADDLE_SIGNATURE'] ?? '';
1116
+ }
1117
+
1118
+ return self::verifyWebhookSignature($payload, $signature, $mode);
1119
+ }
1120
+
1121
+ private static function verifyWebhookSignature($payload, $signature, $mode)
1122
+ {
1123
+ $settings = new PaddleSettings();
1124
+ $secret = $settings->getWebhookSecret($mode);
1125
+
1126
+ if (!$secret || !$signature) {
1127
+ return false;
1128
+ }
1129
+
1130
+ // Paddle-specific signature verification logic
1131
+ // This uses Paddle's signature format and algorithm
1132
+ return hash_equals($expectedSignature, $signature);
1133
+ }```
1134
+
1135
+ **Key Insights:**
1136
+
1137
+ - Flexible parameter handling (allows testing)
1138
+ - Environment-aware secret selection
1139
+ - Uses hash_equals for timing attack protection
1140
+ - Gateway-specific signature algorithms
1141
+
1142
+ ### Event Processing [](#event-processing)
1143
+ php
1144
+ ```
1145
+ class IPN
1146
+ {
1147
+ public function init(): void
1148
+ {
1149
+ // Register webhook event handlers
1150
+ add_action('fluent_cart/payments/paddle/webhook_transaction_paid', [$this, 'handleTransactionPaid'], 10, 1);
1151
+ add_action('fluent_cart/payments/paddle/webhook_transaction_completed', [$this, 'handleTransactionCompleted'], 10, 1);
1152
+ add_action('fluent_cart/payments/paddle/webhook_subscription_created', [$this, 'handleSubscriptionCreated'], 10, 1);
1153
+ // ... more handlers
1154
+ }
1155
+
1156
+ public function verifyAndProcess(): void
1157
+ {
1158
+ $payload = file_get_contents('php://input');
1159
+ $signature = $_SERVER['HTTP_PADDLE_SIGNATURE'] ?? '';
1160
+
1161
+ if (!API::verifyWebhook($payload, $signature)) {
1162
+ http_response_code(401);
1163
+ exit('Unauthorized');
1164
+ }
1165
+
1166
+ $data = json_decode($payload, true);
1167
+ $this->processWebhookEvent($data);
1168
+
1169
+ http_response_code(200);
1170
+ exit('OK');
1171
+ }
1172
+ }```
1173
+
1174
+ **Key Insights:**
1175
+
1176
+ - Uses WordPress action system for event handling
1177
+ - Modular event processing
1178
+ - Proper HTTP response codes
1179
+ - Early exit after processing
1180
+
1181
+ ## Complete Frontend Integration [](#complete-frontend-integration)
1182
+
1183
+ ### Multi-Script Asset Management [](#multi-script-asset-management)
1184
+ php
1185
+ ```
1186
+ public function getEnqueueScriptSrc($hasSubscription = 'no'): array
1187
+ {
1188
+ $paddleJsUrl = 'https://cdn.paddle.com/paddle/v2/paddle.js';
1189
+
1190
+ return [
1191
+ [
1192
+ 'handle' => 'fluent-cart-checkout-sdk-paddle-js',
1193
+ 'src' => $paddleJsUrl,
1194
+ ],
1195
+ [
1196
+ 'handle' => 'fluent-cart-paddle-checkout',
1197
+ 'src' => Vite::getEnqueuePath('public/payment-methods/paddle-checkout.js'),
1198
+ 'deps' => ['fluent-cart-checkout-sdk-paddle-js']
1199
+ ]
1200
+ ];
1201
+ }
1202
+
1203
+ public function getLocalizeData(): array
1204
+ {
1205
+ return [
1206
+ 'fct_paddle_data' => [
1207
+ 'translations' => [
1208
+ 'Paddle SDK is not loaded. Please ensure the Paddle script is included.' => __('Paddle SDK is not loaded...', 'fluent-cart-pro'),
1209
+ 'Paddle client token is missing or invalid.' => __('Paddle client token is missing or invalid.', 'fluent-cart-pro'),
1210
+ 'Pay with Paddle' => __('Pay with Paddle', 'fluent-cart-pro'),
1211
+ 'Secure payment powered by Paddle' => __('Secure payment powered by Paddle', 'fluent-cart-pro'),
1212
+ 'Order creation failed' => __('Order creation failed', 'fluent-cart-pro'),
1213
+ 'Failed to create order' => __('Failed to create order', 'fluent-cart-pro'),
1214
+ 'No Paddle price IDs found in order data. Please ensure Paddle products are properly configured.' => __('No Paddle price IDs found...', 'fluent-cart-pro'),
1215
+ 'Error: Missing transaction ID' => __('Error: Missing transaction ID', 'fluent-cart-pro'),
1216
+ 'Payment failed' => __('Payment failed', 'fluent-cart-pro'),
1217
+ 'An error occurred. Please try again.' => __('An error occurred. Please try again.', 'fluent-cart-pro'),
1218
+ ]
1219
+ ]
1220
+ ];
1221
+ }```
1222
+
1223
+ ### Dynamic Order Information Handling [](#dynamic-order-information-handling)
1224
+ php
1225
+ ```
1226
+ public function getOrderInfo(array $data)
1227
+ {
1228
+ $cart = CartHelper::getCart();
1229
+ $checkOutHelper = new CartCheckoutHelper(true);
1230
+ $shippingChargeData = (new WebCheckoutHandler())->getShippingChargeData($cart);
1231
+ $shippingCharge = Arr::get($shippingChargeData, 'charge');
1232
+ $totalPrice = $checkOutHelper->getItemsAmountTotal(false) + $shippingCharge;
1233
+
1234
+ $items = $checkOutHelper->getItems();
1235
+ $hasSubscription = $this->validateSubscriptions($items);
1236
+
1237
+ $clientToken = $this->settings->getClientToken();
1238
+ $settings = $this->settings->get();
1239
+
1240
+ // Prepare frontend payment arguments
1241
+ $paymentArgs = [
1242
+ 'client_token' => $clientToken ?: '',
1243
+ 'mode' => $this->settings->getMode(), // Current payment mode from settings
1244
+ 'paddle_checkout_button_text' => Arr::get($settings, 'paddle_checkout_button_text', ''),
1245
+ 'paddle_checkout_button_color' => Arr::get($settings, 'paddle_checkout_button_color', ''),
1246
+ 'paddle_checkout_button_hover_color' => Arr::get($settings, 'paddle_checkout_button_hover_color', ''),
1247
+ 'paddle_checkout_button_text_color' => Arr::get($settings, 'paddle_checkout_button_text_color', ''),
1248
+ 'paddle_checkout_button_font_size' => Arr::get($settings, 'paddle_checkout_button_font_size', '')
1249
+ ];
1250
+
1251
+ // Prepare payment details
1252
+ $paymentDetails = [
1253
+ 'mode' => 'payment',
1254
+ 'theme' => Arr::get($settings, 'paddle_checkout_theme', 'light'),
1255
+ 'amount' => Helper::toDecimalWithoutComma($totalPrice),
1256
+ 'currency' => strtoupper(CurrencySettings::get('currency')),
1257
+ 'locale' => (new StoreSettings())->get('locale', 'en'),
1258
+ ];
1259
+
1260
+ if ($hasSubscription) {
1261
+ $paymentDetails['mode'] = 'subscription';
1262
+ }
1263
+
1264
+ $this->checkCurrencySupport();
1265
+
1266
+ wp_send_json([
1267
+ 'status' => 'success',
1268
+ 'payment_args' => $paymentArgs,
1269
+ 'intent' => $paymentDetails,
1270
+ 'has_subscription' => $hasSubscription,
1271
+ 'message' => __('Order info retrieved!', 'fluent-cart-pro')
1272
+ ], 200);
1273
+ }```
1274
+
1275
+ **Key Insights:**
1276
+
1277
+ - **Dynamic Asset Loading**: External SDK + custom integration scripts
1278
+
1279
+ ### Paddle Checkout JavaScript Implementation [](#paddle-checkout-javascript-implementation)
1280
+
1281
+ The frontend JavaScript implementation handles the customer checkout experience:javascript
1282
+ ```
1283
+ // File: resources/public/payment-methods/paddle-checkout.js
1284
+ class PaddleCheckout {
1285
+ constructor(form, orderHandler, response, paymentLoader) {
1286
+ this.form = form;
1287
+ this.orderHandler = orderHandler;
1288
+ this.data = response;
1289
+ this.paymentArgs = response?.payment_args || {};
1290
+ this.intent = response?.intent || {};
1291
+ this.paymentLoader = paymentLoader;
1292
+ this.currentOrderData = null;
1293
+ this.$t = this.translate.bind(this);
1294
+ }
1295
+
1296
+ translate(string) {
1297
+ const translations = window.fct_paddle_data?.translations || {};
1298
+ return translations[string] || string;
1299
+ }
1300
+
1301
+ init() {
1302
+ const paddleButtonContainer = document.querySelector('.fluent-cart-checkout_embed_payment_container_paddle');
1303
+ if (!paddleButtonContainer) {
1304
+ console.error('Paddle container not found');
1305
+ return;
1306
+ }
1307
+
1308
+ // Clear any existing content
1309
+ paddleButtonContainer.innerHTML = '';
1310
+
1311
+ // Initialize Paddle SDK and create button
1312
+ this.initializePaddleSDK()
1313
+ .then(() => {
1314
+ this.createPaddleButton(paddleButtonContainer);
1315
+ })
1316
+ .catch((error) => {
1317
+ console.error('Paddle initialization error:', error);
1318
+ this.displayErrorMessage(paddleButtonContainer, error.message);
1319
+ });
1320
+ }
1321
+
1322
+ async initializePaddleSDK() {
1323
+ if (typeof Paddle === 'undefined') {
1324
+ throw new Error(this.$t('Paddle SDK is not loaded. Please ensure the Paddle script is included.'));
1325
+ }
1326
+
1327
+ const clientToken = this.paymentArgs?.client_token;
1328
+ const environment = this.paymentArgs?.mode === 'test' ? 'sandbox' : 'production';
1329
+
1330
+ if (!clientToken) {
1331
+ throw new Error(this.$t('Paddle client token is missing or invalid.'));
1332
+ }
1333
+
1334
+ Paddle.Environment.set(environment);
1335
+ Paddle.Initialize({
1336
+ token: clientToken.trim(),
1337
+ eventCallback: (data) => {
1338
+ this.handlePaddleEvent(data);
1339
+ }
1340
+ });
1341
+ }
1342
+
1343
+ createPaddleButton(container) {
1344
+ const paddleButton = document.createElement('button');
1345
+ paddleButton.id = 'paddle-pay-button';
1346
+ paddleButton.className = 'paddle-checkout-button';
1347
+ paddleButton.innerHTML = this.$t('Pay with Paddle');
1348
+ paddleButton.style.cssText = `
1349
+ width: 100%;
1350
+ padding: 12px 24px;
1351
+ background: #1a73e8;
1352
+ color: #fff;
1353
+ border: none;
1354
+ border-radius: 6px;
1355
+ font-weight: 500;
1356
+ cursor: pointer;
1357
+ `;
1358
+
1359
+ paddleButton.addEventListener('click', async (e) => {
1360
+ e.preventDefault();
1361
+ await this.handlePaddleButtonClick();
1362
+ });
1363
+
1364
+ container.appendChild(paddleButton);
1365
+ }
1366
+
1367
+ async handlePaddleButtonClick() {
1368
+ try {
1369
+ this.paymentLoader?.changeLoaderStatus('processing');
1370
+
1371
+ if (typeof this.orderHandler === 'function') {
1372
+ const orderData = await this.orderHandler();
1373
+ if (!orderData) {
1374
+ throw new Error(this.$t('Failed to create order'));
1375
+ }
1376
+
1377
+ // Open Paddle overlay checkout
1378
+ await this.openPaddleOverlay(orderData);
1379
+ } else {
1380
+ throw new Error(this.$t('Order handler is not properly configured'));
1381
+ }
1382
+ } catch (error) {
1383
+ this.paymentLoader?.changeLoaderStatus('Error: ' + error.message);
1384
+ this.displayErrorMessage(
1385
+ document.querySelector('.fluent-cart-checkout_embed_payment_container_paddle'),
1386
+ error.message
1387
+ );
1388
+ }
1389
+ }
1390
+
1391
+ async openPaddleOverlay(orderData) {
1392
+ this.currentOrderData = orderData;
1393
+
1394
+ const paddleData = orderData?.response || orderData;
1395
+ const items = paddleData?.paddle_price_ids?.map(item => ({
1396
+ priceId: item.price_id,
1397
+ quantity: parseInt(item.quantity) || 1
1398
+ }));
1399
+
1400
+ if (!items || items.length === 0) {
1401
+ throw new Error(this.$t('No Paddle price IDs found in order data'));
1402
+ }
1403
+
1404
+ Paddle.Checkout.open({
1405
+ settings: {
1406
+ displayMode: 'overlay',
1407
+ theme: this.intent?.theme || 'light',
1408
+ locale: this.intent?.locale || 'en'
1409
+ },
1410
+ items: items,
1411
+ customData: {
1412
+ fct_order_hash: orderData?.data?.order?.hash || '',
1413
+ fct_transaction_hash: orderData?.data?.transaction?.hash || '',
1414
+ }
1415
+ });
1416
+ }
1417
+
1418
+ handlePaddleEvent(eventData) {
1419
+ switch (eventData.name) {
1420
+ case 'checkout.completed':
1421
+ this.handlePaddlePaymentSuccess(eventData.data);
1422
+ break;
1423
+ case 'checkout.closed':
1424
+ this.handlePaddleCheckoutClosed(eventData.data);
1425
+ break;
1426
+ case 'checkout.payment.failed':
1427
+ this.handlePaddlePaymentFailed(eventData.data);
1428
+ break;
1429
+ case 'checkout.error':
1430
+ this.handlePaddleError(eventData.data);
1431
+ break;
1432
+ }
1433
+ }
1434
+
1435
+ async handlePaddlePaymentSuccess(paddleData) {
1436
+ try {
1437
+ this.paymentLoader?.changeLoaderStatus('confirming');
1438
+ const transactionId = paddleData?.transaction_id;
1439
+
1440
+ if (!transactionId) {
1441
+ this.paymentLoader?.changeLoaderStatus(this.$t('Error: Missing transaction ID'));
1442
+ return;
1443
+ }
1444
+
1445
+ const customData = paddleData.custom_data;
1446
+ const confirmResponse = await this.confirmPayment(transactionId, customData);
1447
+
1448
+ if (confirmResponse?.redirect_url) {
1449
+ this.paymentLoader?.changeLoaderStatus('redirecting');
1450
+ window.location.href = confirmResponse.redirect_url;
1451
+ }
1452
+ } catch (error) {
1453
+ this.paymentLoader?.changeLoaderStatus('Error: ' + error.message);
1454
+ }
1455
+ }
1456
+
1457
+ displayErrorMessage(container, message) {
1458
+ const errorDiv = document.createElement('div');
1459
+ errorDiv.style.color = 'red';
1460
+ errorDiv.textContent = message;
1461
+ container.appendChild(errorDiv);
1462
+ }
1463
+ }
1464
+
1465
+ // Initialize when FluentCart triggers the event
1466
+ window.addEventListener("fluent_cart_load_payments_paddle", function (e) {
1467
+ fetch(e.detail.paymentInfoUrl, {
1468
+ method: "POST",
1469
+ headers: {
1470
+ "Content-Type": "application/json",
1471
+ "X-WP-Nonce": e.detail.nonce,
1472
+ },
1473
+ credentials: 'include'
1474
+ }).then(async (response) => {
1475
+ response = await response.json();
1476
+ new PaddleCheckout(e.detail.form, e.detail.orderHandler, response, e.detail.paymentLoader).init();
1477
+ }).catch(error => {
1478
+ console.error('Failed to load Paddle payment info:', error);
1479
+ });
1480
+ });```
1481
+
1482
+ - **Comprehensive Localization**: All user-facing messages translated
1483
+ - **Real-time Order Processing**: Cart data processed on-demand
1484
+ - **Subscription Detection**: Automatic mode switching based on cart contents
1485
+ - **UI Customization**: Extensive theming and styling options
1486
+ - **Currency Validation**: Pre-flight currency support checking
1487
+
1488
+ ## Advanced Production Features [](#advanced-production-features)
1489
+
1490
+ ### Comprehensive Settings with Dynamic Instructions [](#comprehensive-settings-with-dynamic-instructions)
1491
+ php
1492
+ ```
1493
+ public function fields(): array
1494
+ {
1495
+ $webhookInstructions = $this->getWebhookInstructions();
1496
+
1497
+ $testSchema = [
1498
+ 'test_api_key' => array(
1499
+ 'value' => '',
1500
+ 'label' => __('Sandbox API Key', 'fluent-cart-pro'),
1501
+ 'type' => 'password',
1502
+ 'placeholder' => __('Your sandbox API key', 'fluent-cart-pro'),
1503
+ 'help_text' => __('Get your API key from Paddle Dashboard > Developer Tools > Authentication', 'fluent-cart-pro')
1504
+ ),
1505
+ 'test_client_token' => array(
1506
+ 'value' => '',
1507
+ 'label' => __('Sandbox Client Token / Public Key', 'fluent-cart-pro'),
1508
+ 'type' => 'text',
1509
+ 'placeholder' => __('Your sandbox client token', 'fluent-cart-pro'),
1510
+ 'help_text' => __('Optional: Used for frontend checkout integration', 'fluent-cart-pro')
1511
+ ),
1512
+ 'test_webhook_secret' => array(
1513
+ 'value' => '',
1514
+ 'label' => __('Sandbox Webhook Secret', 'fluent-cart-pro'),
1515
+ 'type' => 'password',
1516
+ 'placeholder' => __('Your sandbox webhook secret', 'fluent-cart-pro'),
1517
+ 'help_text' => __('Used to verify webhook signatures', 'fluent-cart-pro')
1518
+ ),
1519
+ 'test_webhook_desc' => array(
1520
+ 'value' => $webhookInstructions,
1521
+ 'label' => __('Webhook Configuration', 'fluent-cart-pro'),
1522
+ 'type' => 'html_attr'
1523
+ ),
1524
+ ];
1525
+
1526
+ // Live schema similar structure...
1527
+
1528
+ return array(
1529
+ 'notice' => [
1530
+ 'value' => $this->renderStoreModeNotice(),
1531
+ 'label' => __('Store Mode notice', 'fluent-cart-pro'),
1532
+ 'type' => 'notice'
1533
+ ],
1534
+ 'beta_notice' => [
1535
+ 'value' => '<p class="text-gray-500">Paddle payment gateway is currently in beta. Please use with caution!</p>',
1536
+ 'label' => __('Beta Notice', 'fluent-cart-pro'),
1537
+ 'type' => 'html_attr'
1538
+ ],
1539
+ 'payment_mode' => [
1540
+ 'type' => 'tabs',
1541
+ 'schema' => [
1542
+ [
1543
+ 'type' => 'tab',
1544
+ 'label' => __('Live credentials', 'fluent-cart-pro'),
1545
+ 'value' => 'live',
1546
+ 'schema' => $liveSchema
1547
+ ],
1548
+ [
1549
+ 'type' => 'tab',
1550
+ 'label' => __('Test credentials', 'fluent-cart-pro'),
1551
+ 'value' => 'test',
1552
+ 'schema' => $testSchema
1553
+ ]
1554
+ ]
1555
+ ],
1556
+ 'paddle_checkout_theme' => [
1557
+ 'value' => 'light',
1558
+ 'label' => __('Paddle Checkout Theme', 'fluent-cart-pro'),
1559
+ 'type' => 'select',
1560
+ 'options' => [
1561
+ 'light' => ['label' => __('Light', 'fluent-cart-pro'), 'value' => 'light'],
1562
+ 'dark' => ['label' => __('Dark', 'fluent-cart-pro'), 'value' => 'dark']
1563
+ ],
1564
+ 'tooltip' => __('Theme to use for Paddle checkout modal', 'fluent-cart-pro')
1565
+ ],
1566
+ 'paddle_checkout_button_text' => [
1567
+ 'value' => __('Pay with Paddle', 'fluent-cart-pro'),
1568
+ 'label' => __('Paddle Checkout Button Text', 'fluent-cart-pro'),
1569
+ 'type' => 'text',
1570
+ 'placeholder' => __('Pay with Paddle', 'fluent-cart-pro'),
1571
+ 'tooltip' => __('Text to display on the Paddle checkout button', 'fluent-cart-pro')
1572
+ ],
1573
+ 'paddle_checkout_button_color' => [
1574
+ 'value' => '',
1575
+ 'label' => __('Paddle Checkout Button Color', 'fluent-cart-pro'),
1576
+ 'type' => 'color',
1577
+ 'tooltip' => __('Color of the Paddle checkout button', 'fluent-cart-pro')
1578
+ ],
1579
+ 'disable_webhook_verification' => [
1580
+ 'value' => 'no',
1581
+ 'label' => __('Disable Webhook Verification', 'fluent-cart-pro'),
1582
+ 'type' => 'checkbox',
1583
+ 'tooltip' => __('Only disable this for testing purposes. Keep enabled for production.', 'fluent-cart-pro')
1584
+ ]
1585
+ );
1586
+ }
1587
+
1588
+ public function getWebhookInstructions()
1589
+ {
1590
+ $webhook_url = $this->getWebhookUrl();
1591
+ $eventsHtml = $this->getEventshtml();
1592
+
1593
+ // Dynamic HTML instructions based on configuration state
1594
+ $instructionsHtml =
1595
+ '<div class="paddle-webhook-instructions" style="padding:12px 0;">'
1596
+ . '<p><strong>' . esc_html__('Webhook URL:', 'fluent-cart-pro') . '</strong> '
1597
+ . '<code class="copyable-content" data-copy="' . esc_attr($webhook_url) . '">' . esc_html($webhook_url) . '</code></p>'
1598
+ . '<p>' . esc_html__('You should configure your Paddle webhooks to get all updates of your payments remotely.', 'fluent-cart-pro') . '</p>'
1599
+ . '<p>' . esc_html__('Select the following events:', 'fluent-cart-pro') . '</p>'
1600
+ . '<p style="display:flex; align-items:center; flex-wrap:wrap; gap:8px 4px;">' . wp_kses_post($eventsHtml) . '</p>'
1601
+ . '</div>';
1602
+
1603
+ return $instructionsHtml;
1604
+ }```
1605
+
1606
+ ### Multi-Environment Support with Security [](#multi-environment-support-with-security)
1607
+ php
1608
+ ```
1609
+ public static function beforeSettingsUpdate($data, $oldSettings): array
1610
+ {
1611
+ $mode = Arr::get($data, 'payment_mode', 'live');
1612
+ $apiKeyField = $mode . '_api_key';
1613
+
1614
+ // Encrypt sensitive data before storage
1615
+ $data[$apiKeyField] = Helper::encryptKey($data[$apiKeyField]);
1616
+
1617
+ return $data;
1618
+ }
1619
+
1620
+ public static function validateSettings($data): array
1621
+ {
1622
+ $mode = Arr::get($data, 'payment_mode', 'live');
1623
+ $apiKey = Arr::get($data, $mode . '_api_key');
1624
+
1625
+ if (empty($apiKey)) {
1626
+ return [
1627
+ 'status' => 'failed',
1628
+ 'message' => __('API key is required.', 'fluent-cart-pro')
1629
+ ];
1630
+ }
1631
+
1632
+ // Could add live API connectivity test here
1633
+ // $testResponse = API::testConnection($apiKey, $mode);
1634
+
1635
+ return [
1636
+ 'status' => 'success',
1637
+ 'message' => __('Paddle gateway credentials verified successfully!', 'fluent-cart-pro')
1638
+ ];
1639
+ }```
1640
+
1641
+ ### Currency and Transaction URL Management [](#currency-and-transaction-url-management)
1642
+ php
1643
+ ```
1644
+ public function isCurrencySupported(): bool
1645
+ {
1646
+ $supportedCurrencies = [
1647
+ 'USD', 'EUR', 'GBP', 'JPY', 'AUD', 'CAD', 'CHF', 'HKD', 'SGD', 'SEK',
1648
+ 'ARS', 'BRL', 'CNY', 'COP', 'CZK', 'DKK', 'HUF', 'ILS', 'INR', 'KRW',
1649
+ 'MXN', 'NOK', 'NZD', 'PLN', 'RUB', 'THB', 'TRY', 'TWD', 'UAH', 'VND', 'ZAR'
1650
+ ];
1651
+
1652
+ return in_array(strtoupper(CurrencySettings::get('currency')), $supportedCurrencies);
1653
+ }
1654
+
1655
+ public function getTransactionUrl($url, $data)
1656
+ {
1657
+ if (Arr::get($data, 'transaction_type') === 'refund') {
1658
+ $parentTransaction = OrderTransaction::query()->where('id', Arr::get($data, 'transaction.meta.parent_id'))->first();
1659
+ $data['vendor_charge_id'] = $parentTransaction->vendor_charge_id;
1660
+ }
1661
+
1662
+ // Use payment_mode from transaction data (stored order mode at checkout time)
1663
+ if (Arr::get($data, 'payment_mode') === 'test') {
1664
+ return 'https://sandbox-vendors.paddle.com/transactions-v2/' . Arr::get($data, 'vendor_charge_id');
1665
+ }
1666
+
1667
+ return 'https://vendors.paddle.com/transactions-v2/' . Arr::get($data, 'vendor_charge_id');
1668
+ }
1669
+
1670
+ public function getSubscriptionUrl($url, $data)
1671
+ {
1672
+ // Use payment_mode from subscription data (stored order mode at checkout time)
1673
+ if (Arr::get($data, 'payment_mode') === 'test') {
1674
+ return 'https://sandbox-vendors.paddle.com/subscriptions-v2/' . Arr::get($data, 'vendor_subscription_id');
1675
+ }
1676
+
1677
+ return 'https://vendors.paddle.com/subscriptions-v2/' . Arr::get($data, 'vendor_subscription_id');
1678
+ }```
1679
+
1680
+ ### Success and Cancel URL Handling [](#success-and-cancel-url-handling)
1681
+ php
1682
+ ```
1683
+ public function getSuccessUrl($transaction, $args = [])
1684
+ {
1685
+ $paymentHelper = new PaymentHelper($this->getMeta('route'));
1686
+ return $paymentHelper->successUrl($transaction->uuid, $args);
1687
+ }
1688
+
1689
+ public static function getCancelUrl(): string
1690
+ {
1691
+ $checkoutPage = (new StoreSettings())->getCheckoutPage();
1692
+ $cartHash = $_GET['fct_cart_hash'] ?? '';
1693
+
1694
+ if ($cartHash) {
1695
+ return add_query_arg([
1696
+ 'fct_cart_hash' => $cartHash
1697
+ ], $checkoutPage);
1698
+ }
1699
+
1700
+ return $checkoutPage;
1701
+ }```
1702
+
1703
+ **Key Insights:**
1704
+
1705
+ - **Dynamic Configuration**: Settings UI changes based on configuration state
1706
+ - **Security-First Approach**: API key encryption and secure storage
1707
+ - **Environment Awareness**: All URLs and endpoints environment-specific
1708
+ - **Comprehensive Validation**: Settings validation with optional API testing
1709
+ - **User Experience**: Helpful instructions and copyable content
1710
+ - **Production-Ready**: Extensive customization options for branding
1711
+ - **URL Management**: Proper success/cancel URL handling with cart state preservation
1712
+
1713
+ ## Registration Pattern [](#registration-pattern)
1714
+ php
1715
+ ```
1716
+ public static function register()
1717
+ {
1718
+ fluent_cart_api()->registerCustomPaymentMethod('paddle', new self());
1719
+ }```
1720
+
1721
+ **Key Insights:**
1722
+
1723
+ - Simple static registration method
1724
+ - Self-instantiation pattern
1725
+ - Called from bootstrap file
1726
+
1727
+ ## Comprehensive Lessons Learned [](#comprehensive-lessons-learned)
1728
+
1729
+ ### 1. **Complete Payment Lifecycle Management** [](#_1-complete-payment-lifecycle-management)
1730
+
1731
+ - **One-time Payments**: Full transaction flow from creation to confirmation
1732
+ - **Subscription Payments**: Complex billing cycles, trials, and renewal handling
1733
+ - **Refund Processing**: Comprehensive adjustment and refund management
1734
+ - **Status Synchronization**: Real-time status updates via webhooks
1735
+
1736
+ ### 2. **Three-Layer Webhook Architecture** [](#_2-three-layer-webhook-architecture)
1737
+
1738
+ - **Entry Point**: Single `handleIPN()` method for all webhook traffic
1739
+ - **Central Processor**: `verifyAndProcess()` with signature verification and routing
1740
+ - **Event Handlers**: Specific handlers for each event type using FluentCart services
1741
+ - **Error Handling**: Comprehensive HTTP response codes and logging
1742
+
1743
+ ### 3. **Service Method Integration** [](#_3-service-method-integration)
1744
+
1745
+ - **StatusHelper**: Automatic order status sync and hook firing
1746
+ - **Refund Service**: Complete refund transaction management
1747
+ - **SubscriptionService**: Subscription lifecycle and renewal processing
1748
+ - **Confirmation Service**: Payment confirmation with complex data handling
1749
+
1750
+ ### 4. **Production-Ready Security** [](#_4-production-ready-security)
1751
+
1752
+ - **Signature Verification**: Optional but recommended webhook signature validation
1753
+ - **API Key Encryption**: Secure storage of sensitive credentials
1754
+ - **Environment Separation**: Complete test/live mode isolation
1755
+ - **Input Validation**: Comprehensive data validation and sanitization
1756
+
1757
+ ### 5. **Advanced Settings Architecture** [](#_5-advanced-settings-architecture)
1758
+
1759
+ - **Dynamic Configuration**: UI that changes based on current settings
1760
+ - **Tabbed Interface**: Clean separation of test/live credentials
1761
+ - **Visual Customization**: Extensive theming and branding options
1762
+ - **Helpful Instructions**: Dynamic webhook setup guidance
1763
+
1764
+ ### 6. **Frontend Integration Excellence** [](#_6-frontend-integration-excellence)
1765
+
1766
+ - **Multi-Script Loading**: External SDK + custom integration scripts
1767
+ - **Comprehensive Localization**: All user-facing messages translated
1768
+ - **Real-time Processing**: Dynamic order and cart processing
1769
+ - **UI Customization**: Extensive checkout appearance options
1770
+
1771
+ ### 7. **Subscription Management Complexity** [](#_7-subscription-management-complexity)
1772
+
1773
+ - **Billing Cycle Mapping**: Complex interval and frequency handling
1774
+ - **Trial Period Support**: Scheduled activation after trial periods
1775
+ - **Renewal Detection**: Smart detection of subscription vs one-time payments
1776
+ - **Status Transformation**: Gateway-specific to FluentCart status mapping
1777
+
1778
+ ### 8. **Data Architecture Patterns** [](#_8-data-architecture-patterns)
1779
+
1780
+ - **Custom Data Fields**: Webhook correlation via custom metadata
1781
+ - **Comprehensive Storage**: Full gateway response storage for debugging
1782
+ - **Status Mapping**: Bidirectional status transformation
1783
+ - **Transaction Relationships**: Parent-child relationships for refunds
1784
+
1785
+ ## Application to Your Gateway Development [](#application-to-your-gateway-development)
1786
+
1787
+ ### Essential Implementation Patterns [](#essential-implementation-patterns)
1788
+
1789
+ -
1790
+ **Gateway Class Structure**php
1791
+ ```
1792
+ // Complete feature declaration
1793
+ public array $supportedFeatures = ['payment', 'refund', 'webhook', 'subscriptions'];
1794
+
1795
+ // Composition over inheritance
1796
+ public function __construct() {
1797
+ parent::__construct(new YourSettings(), new YourSubscriptions());
1798
+ }```
1799
+
1800
+ -
1801
+ **Payment Processing Delegation**php
1802
+ ```
1803
+ // Clean separation of concerns
1804
+ public function makePaymentFromPaymentInstance(PaymentInstance $instance) {
1805
+ if ($instance->subscription) {
1806
+ return (new Processor())->handleSubscriptionPayment($instance);
1807
+ }
1808
+ return (new Processor())->handleSinglePayment($instance);
1809
+ }```
1810
+
1811
+ -
1812
+ **Webhook Architecture Implementation**php
1813
+ ```
1814
+ // Three-layer pattern
1815
+ public function handleIPN() { $this->verifyAndProcess(); }
1816
+ private function verifyAndProcess() { /* verification + routing */ }
1817
+ public function handleSpecificEvent($data) { /* use service methods */ }```
1818
+
1819
+ -
1820
+ **Service Method Usage**php
1821
+ ```
1822
+ // Use FluentCart services instead of manual hooks
1823
+ (new StatusHelper($order))->syncOrderStatuses($transaction);
1824
+ Refund::createOrRecordRefund([...], $parentTransaction);
1825
+ SubscriptionService::recordManualRenewal($subscription, $transaction, $args);```
1826
+
1827
+ -
1828
+ **Environment-Aware Configuration**php
1829
+ ```
1830
+ // Dynamic configuration based on mode
1831
+ public function getApiKey($mode = '') {
1832
+ if (!$mode) $mode = $this->getMode(); // Gets payment mode from settings
1833
+ return $this->get($mode . '_api_key');
1834
+ }
1835
+
1836
+ // API calls should use order mode for consistency
1837
+ API::createTransaction($data, $order->mode); // Use order's mode```
1838
+
1839
+ -
1840
+ **Mode Management Best Practices**php
1841
+ ```
1842
+ // ✅ Correct: Store order mode with transaction
1843
+ $transaction->update(['payment_mode' => $order->mode]);
1844
+
1845
+ // ✅ Correct: Always explicitly pass mode to API calls
1846
+ API::createTransaction($data, $order->mode);
1847
+ API::refundTransaction($transactionId, $order->mode);
1848
+
1849
+ // ✅ Correct: Use payment mode for settings
1850
+ $apiKey = $this->settings->getApiKey($this->settings->getMode());
1851
+
1852
+ // ⚠️ Works but not recommended: Relying on fallback
1853
+ API::createTransaction($data); // Falls back to settings mode
1854
+
1855
+ // ❌ Wrong: Don't mix up the modes
1856
+ $transaction->update(['payment_mode' => $this->settings->getMode()]);```
1857
+
1858
+ ### Critical Success Factors [](#critical-success-factors)
1859
+
1860
+ - **Use FluentCart's Service Layer**: Never manually fire hooks - use service methods
1861
+ - **Implement Complete Webhook Handling**: Cover all payment lifecycle events
1862
+ - **Understand Mode Management**: Use `$order->mode` for API calls, `$this->settings->getMode()` for configuration
1863
+ - **Always Pass Mode Explicitly**: Don't rely on fallbacks - explicitly pass mode to all API calls
1864
+ - **Plan for Subscriptions**: Even if not initial scope, design architecture to support them
1865
+ - **Security First**: Implement signature verification and secure credential storage
1866
+ - **Environment Awareness**: Support test/live modes throughout the entire implementation
1867
+ - **Comprehensive Error Handling**: Proper HTTP responses, logging, and user feedback
1868
+ - **Frontend Integration**: Plan for JavaScript SDK integration and UI customization
1869
+ - **Production Considerations**: Currency support, URL management, transaction linking
1870
+
1871
+ ### Architecture Decisions Framework [](#architecture-decisions-framework)
1872
+
1873
+ - **Composition over Inheritance**: Separate settings, subscriptions, and processing classes
1874
+ - **Service Layer Integration**: Use FluentCart's built-in services for all core operations
1875
+ - **Event-Driven Webhooks**: Use WordPress actions for flexible webhook event handling
1876
+ - **Environment Separation**: Complete isolation between test and live configurations
1877
+ - **Security by Default**: Implement all security measures from the start
1878
+ - **Extensible Design**: Plan for future features like subscriptions and advanced options
1879
+
1880
+ This comprehensive case study demonstrates that a complete payment gateway implementation requires careful attention to **payment lifecycles**, **webhook architecture**, **service integration**, **security**, and **user experience** - all working together in a cohesive, production-ready system.
1881
+ ## Application to Your Gateway [](#application-to-your-gateway)
1882
+
1883
+ ### Code Patterns to Adopt [](#code-patterns-to-adopt)
1884
+
1885
+ -
1886
+ **Settings Structure**php
1887
+ ```
1888
+ // Environment-aware getters
1889
+ public function getApiKey($mode = '') {
1890
+ if (!$mode) $mode = $this->getMode();
1891
+ return $this->get($mode . '_api_key');
1892
+ }```
1893
+
1894
+ -
1895
+ **Error Handling**php
1896
+ ```
1897
+ // Consistent error responses
1898
+ if (is_wp_error($response)) {
1899
+ return new \WP_Error('gateway_error', $response->get_error_message());
1900
+ }```
1901
+
1902
+ -
1903
+ **Web Hook Verification**php
1904
+ ```
1905
+ // Always verify webhooks
1906
+ if (!$this->verifyWebhookSignature($payload, $signature)) {
1907
+ http_response_code(401);
1908
+ exit('Unauthorized');
1909
+ }```
1910
+
1911
+ -
1912
+ **Feature Detection**php
1913
+ ```
1914
+ // Declare supported features clearly
1915
+ public array $supportedFeatures = ['payment', 'refund', 'subscriptions', 'webhook'];```
1916
+
1917
+ ### Architecture Decisions [](#architecture-decisions)
1918
+
1919
+ - **Use composition over inheritance** for complex functionality
1920
+ - **Separate API communication** into dedicated classes
1921
+ - **Implement proper validation** at the settings level
1922
+ - **Plan for localization** from the start
1923
+ - **Design for testability** with dependency injection
1924
+
1925
+ **Next:** [Get Started](https://dev.fluentcart.com/payment-methods-integration/index.html) integrating custom payment gateways with FluentCart.