-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpaddle-billing.php
1805 lines (1596 loc) · 72.5 KB
/
paddle-billing.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* Paddle Billing
* Author: R Woodgate, Cogmentis Ltd.
* Author URI: https://www.cogmentis.com/.
*
* @desc Paddle Billing is the evolution of Paddle Classic, and is the default billing API for Paddle accounts created after August 8th, 2023.
*
* @am_payment_api 6.0
*/
class Am_Paysystem_PaddleBilling extends Am_Paysystem_Abstract
{
public const PLUGIN_STATUS = self::STATUS_BETA;
public const PLUGIN_REVISION = '2.6';
public const CUSTOM_DATA_INV = 'am_invoice';
public const PRICE_ID = 'paddle-billing_pri_id';
public const SUBSCRIPTION_ID = 'paddle-billing_sub_id';
public const ADDRESS_ID = 'paddle-billing_add_id';
public const BUSINESS_ID = 'paddle-billing_biz_id';
public const CUSTOMER_ID = 'paddle-billing_ctm_id';
public const INV_XCURR = 'paddle-billing-xcurrency';
public const INV_XRATE = 'paddle-billing_xrate';
public const INV_TXNITM = 'paddle-billing_txnitm';
public const TAX_CATEGORY = 'paddle-billing_tax_cat';
public const TAX_MODE = 'paddle-billing_tax_mode';
public const LIVE_URL = 'https://api.paddle.com/';
public const SANDBOX_URL = 'https://sandbox-api.paddle.com/';
public const PADDLEJS_URL = 'https://cdn.paddle.com/paddle/v2/paddle.js';
public const API_VERSION = 1;
protected $defaultTitle = 'Paddle Billing';
protected $defaultDescription = 'Payment via Paddle Billing gateway';
protected $_canAutoCreate = true;
private $taxCategories = [
'standard', 'digital-goods', 'ebooks', 'implementation-services', 'professional-services', 'saas', 'software-programming-services', 'training-services', 'website-hosting',
];
private $taxModes = [
'account_setting' => 'Use Paddle account setting',
'internal' => 'Prices INCLUDE tax',
'external' => 'Add Tax to Prices',
];
public function init(): void
{
$this->getDi()->productTable->customFields()->add(
new Am_CustomFieldSelect(
static::TAX_CATEGORY,
'Paddle Billing: Tax Category',
'Optional. Category <a href="https://vendors.paddle.com/taxable-categories" target="_blank">MUST be approved</a> in your Paddle account (Default: standard). <a href="https://www.paddle.com/help/start/intro-to-paddle/why-do-i-need-to-select-\'taxable-categories\'-for-my-products" target="_blank">Learn more</a>',
null,
['empty_title' => 'Use Plugin Default', 'options' => array_combine($this->taxCategories, $this->taxCategories)]
)
);
$this->getDi()->billingPlanTable->customFields()->add(
new Am_CustomFieldText(
static::PRICE_ID,
'Paddle Billing: Price ID',
'Optional. Lets you link and use Paddle Catalog items you have created. Only required if you <a href="'.$this->getDi()->url('admin-setup/paddle-billing#auto_create-0').'">accept direct payments</a>.',
null,
['placeholder' => 'pri_abc123', 'size' => 32]
)
);
$this->getDi()->billingPlanTable->customFields()->add(
new Am_CustomFieldSelect(
static::TAX_MODE,
'Paddle Billing: Tax Mode',
'Optional. How tax is calculated for this billing plan.',
null,
['empty_title' => 'Use Plugin Default', 'options' => $this->taxModes]
)
);
$this->getDi()->blocks->add(
'thanks/success',
new Am_Block_Base('Paddle Statement', 'paddle-statement', $this, [$this, 'renderStatement'])
);
$this->getDi()->blocks->add(
'admin/user/invoice/details',
new Am_Block_Base('Paddle Subscription ID', 'paddle-subid', $this, function (Am_View $v) {
$sub_id = $v->invoice->data()->get(static::SUBSCRIPTION_ID);
if ($sub_id && $v->invoice->paysys_id == $this->getId()) {
$ret = 'Paddle Subscription ID: <a href="https://vendors.paddle.com/subscriptions-v2/'.$sub_id.'" target="_blank">'.$sub_id.'</a>';
$icurr = $v->invoice->currency;
$xcurr = $v->invoice->data()->get(static::INV_XCURR);
$xrate = $v->invoice->data()->get(static::INV_XRATE);
if ($xcurr) {
$ret .= "<br>Paddle Payment Currency: {$xcurr}";
$ret .= "<br>Exchange Rate: {$xrate} {$xcurr}/{$icurr}";
}
return $ret;
}
})
);
}
public function renderStatement(Am_View $v)
{
if (isset($v->invoice) && $v->invoice->paysys_id == $this->getId()) {
$msg = ___('This order was processed by our online reseller & Merchant of Record, Paddle.com, who also handle order related inquiries and returns. The payment will appear on your bank/card statement as:');
return <<<CUT
<div class="am-block am-paddle-statement">
<p>{$msg} <strong>PADDLE.NET*{$this->getConfig('statement_desc')}</strong></p>
</div>
CUT;
}
}
// NB: This hook ONLY fires on pages where payment systems are loaded
// such as signup forms, payment history page, and directAction pages
// If a CC module plugin is enabled, also on member home page
public function onBeforeRender(Am_Event $e): void
{
// Add PaddleJS
if (!defined('AM_ADMIN')) {
static $init = 0;
if (!$init++) {
$hs = $e->getView()->headScript();
$hs->appendFile(static::PADDLEJS_URL);
$hs->appendScript($this->paddleJsSetupCode());
}
}
// Inject Paddle Payment Update URL into detailed subscriptions widget
if (false !== strpos($e->getTemplateName(), 'blocks/member-history-detailedsubscriptions')) {
$v = $e->getView();
foreach ($v->activeInvoices as &$invoice) {
if ($invoice->paysys_id == $this->getId()) {
if ($_ = $invoice->data()->get(static::SUBSCRIPTION_ID)) {
$invoice->_updateCcUrl = $this->getDi()->url(
'payment/'.$this->getId().'/update',
[
'id' => $invoice->getSecureId($this->getId()),
'sub' => $_,
]
);
}
}
}
}
// Inject Paddle receipt download link into payment history widget
if (false !== strpos($e->getTemplateName(), 'blocks/member-history-paymenttable')) {
$v = $e->getView();
foreach ($v->payments as &$p) {
if ($p->paysys_id == $this->getId()) {
$invoice = $p->getInvoice();
$p->_invoice_url = $this->getDi()->url(
'payment/'.$this->getId().'/invoice',
[
'id' => $invoice->getSecureId($this->getId()),
'txn' => $p->receipt_id,
]
);
}
}
}
}
public function allowPartialRefunds()
{
// Payments *can* be partially refunded via Paddle, but we can't allow
// that via aMember because Paddle subscription payments can be made in
// customer's local currency, which may be different to the aMember
// invoice currency. Also, partial refunds need to be allocated across
// the items in the transaction @see processRefund()
return false;
}
public function getRecurringType()
{
return self::REPORTS_REBILL;
}
public function getSupportedCurrencies()
{
// @see https://developer.paddle.com/concepts/sell/supported-currencies
return ['USD', 'EUR', 'GBP', 'JPY', 'AUD', 'CAD', 'CHF', 'HKD', 'SGD', 'SEK', 'ARS', 'BRL', 'CNY', 'COP', 'CZK', 'DKK', 'HUF', 'ILS', 'INR', 'KRW', 'MXN', 'NOK', 'NZD', 'PLN', 'RUB', 'THB', 'TRY', 'TWD', 'UAH'];
}
public function _initSetupForm(Am_Form_Setup $form): void
{
$form->addSecretText('api_key', ['class' => 'am-el-wide'])
->setLabel("API Key\n".'Use your default API key or generate a new one from the Developer Tools > <a href="https://vendors.paddle.com/authentication-v2" target="_blank">Authentication menu</a> menu of your Paddle Dashboard.')
->addRule('required')
;
$form->addText('client_token', ['class' => 'am-el-wide'])
->setLabel("Client-Side Token\n".'From the Developer Tools > <a href="https://vendors.paddle.com/authentication-v2" target="_blank">Authentication menu</a> of your Paddle Dashboard.')
->addRule('required')
;
$form->addText('secret_key', ['class' => 'am-el-wide'])
->setLabel("Webhook Secret Key\n".'From the Developer Tools > <a href="https://vendors.paddle.com/notifications" target="_blank">Notifications menu</a> of your Paddle Dashboard. <a href="https://developer.paddle.com/webhooks/signature-verification#get-secret-key" target="_blank">Detailed Instructions</a>')
->addRule('required')
;
$form->addText('retain_key', ['class' => 'am-el-wide'])
->setLabel("Retain Public Token (Optional)\n".'From the Retain > Account Settings > <a href="https://www2.profitwell.com/app/account/integrations" target="_blank">Integrations</a> > API keys/Dev Kit of your Paddle Dashboard.')
;
// Add Sandbox warning
if ($this->isSandbox()) {
$form->addProlog("<div class='warning_box'>You are currently using Sandbox credentials. All transactions are tests, meaning they're simulated and any money isn't real.</div>");
}
// Add Extra fields
$fs = $this->getExtraSettingsFieldSet($form);
$fs->addAdvCheckbox('allow_localize')->setLabel('Allow Currency Localization
If checked, will allow payment in the user\'s local currency. Leave disabled to force payment in the invoice currency.');
$fs->addAdvCheckbox('cbw_lock')->setLabel('Lock User Account on Chargeback Warning
If checked, will add a note and lock the user account if Paddle gets a warning of an upcoming chargeback.');
$fs->addAdvCheckbox('cbk_lock')->setLabel('Lock User Account on Chargeback
If checked, will add a note and lock the user account if a chargeback is received.');
$fs->addAdvCheckbox('cbr_unlock')->setLabel('Unlock User Account on Chargeback Reversal
If checked, will add a note and unlock the user account if a chargeback is reversed.');
$fs->addAdvCheckbox('show_grid')->setLabel(___("Show Plans in Product Grid\nIf checked, the plugin will add a column to the Manage Products grid"));
$fs->addText('image_url', [
'class' => 'am-el-wide',
'placeholder' => $this->getDi()->url('path/to/my_logo.png', null, false, true),
])->setLabel("Default Image URL\nAn absolute URL to a square image of your brand or product. Recommended minimum size is 128x128px. Supported image types are: .gif, .jpeg, and .png. Will be used for single payments where the optional Paddle Product ID is not supplied.");
$fs->addText('statement_desc')->setLabel("Statement Description\nThe Statement Description from your Paddle Dashboard > Checkout > <a href='https://vendors.paddle.com/checkout-settings' target='_blank'>Checkout Settings</a> page. Shown on the thanks page to help alert customer as to what will appear on their card statement.");
$fs->addSelect(static::TAX_CATEGORY)
->setLabel('Default Tax Category'."\n".
'Optional. Category <a href="https://vendors.paddle.com/taxable-categories" target="_blank">MUST be approved</a> in your Paddle account (Default: standard). <a href="https://www.paddle.com/help/start/intro-to-paddle/why-do-i-need-to-select-\'taxable-categories\'-for-my-products" target="_blank">Learn more</a>', )
->loadOptions(array_combine($this->taxCategories, $this->taxCategories))
;
$form->setDefault(static::TAX_CATEGORY, 'standard');
$fs->addSelect(static::TAX_MODE)
->setLabel('Default Tax Mode'."\n".
'Optional. Lets you override your Paddle Account <a href="https://vendors.paddle.com/tax" target="_blank">Sales Tax setting</a>.', )
->loadOptions($this->taxModes)
;
$form->setDefault(static::TAX_MODE, 'account_setting');
}
public function isConfigured()
{
return $this->getConfig('client_token') && $this->getConfig('api_key');
}
public function isSandbox()
{
return 0 === strpos($this->getConfig('client_token'), 'test_');
}
public function _process($invoice, $request, $result): void
{
// Paddle lets us bill for non-catalog products and prices using the
// Create Transaction API. This means we do not have to create/sync
// products in Paddle. @see: https://developer.paddle.com/build/transactions/bill-create-custom-items-prices-products
// Create/Update the Paddle customer/address entities
$this->updatePaddleCustomer($invoice);
// Prepare transaction params
$params = ['custom_data' => [static::CUSTOM_DATA_INV => $invoice->public_id]];
// Force payment in invoice currency?
if (!$this->getConfig('allow_localize')) {
$params['currency_code'] = $invoice->currency;
}
// Filter to allow advanced customisation of the custom data
// @see: https://docs.amember.com/API/HookManager/
// Example code for site.php:
// Am_Di::getInstance()->hook->add('PaddleBillingCustomData', function(Am_Event $e) {
// // Vars
// $invoice = $e->getInvoice();
// $user = $e->getUser();
//
// // Add custom data kvps
// $e->addReturn('email', 'utm_medium');
// $e->addReturn('closed-deal', 'utm_content');
// $e->addReturn('AA-123', 'integration_id');
// });
$custom = Am_Di::getInstance()->hook->filter(
[],
$this->getId().'CustomData',
['invoice' => $invoice, 'user' => $invoice->getUser()]
);
if (!is_array($custom)) {
throw new Am_Exception_InputError($this->getId().'CustomData Filter: Expected the custom filter to return an array, '.gettype($custom).' received');
}
foreach ($custom as $k => $v) {
// Make sure we only add proper KVPs, and avoid overwriting invoice!
if (!is_int($k) && static::CUSTOM_DATA_INV != $k) {
$params['custom_data'][$k] = $v;
}
}
// Get default image if available and correctly formatted
// Choose the cart default (if set) over plugin default
if ($default_img = $this->getDi()->config->get('cart.img_cart_default_path')) {
$default_img = $this->getDi()->url('data/public/'.$default_img, null, false, true);
} else {
$default_img = $this->getConfig('image_url');
}
if ('' == parse_url($default_img, PHP_URL_SCHEME)) {
$default_img = null;
}
// Add invoice items to Paddle Transaction
// @var $item InvoiceItem
foreach ($invoice->getItems() as $item) {
// Init vars
$rebill = null;
$fptext = ': '.$this->getText($item->first_period);
$sptext = ': '.$this->getRebillText($item->rebill_times);
$product = $item->tryLoadProduct();
if (!$product) {
continue; // should never happen, but...
}
// Get product tax category, fall back to plugin default
$tax_category = $product->data()->get(static::TAX_CATEGORY);
if (!$tax_category) {
$tax_category = $this->getConfig(static::TAX_CATEGORY, 'standard');
}
// Get product tax mode, fall back to plugin default
$tax_mode = $product->getBillingPlan()->data()->get(static::TAX_MODE);
if (!$tax_mode) {
$tax_mode = $this->getConfig(static::TAX_MODE, 'account_setting');
}
// Try get product specific image, fall back to default if needed
if ($image_url = $product->img_cart_path) {
$image_url = $this->getDi()->url('data/public/'.$image_url, null, false, true);
} else {
$image_url = $default_img;
}
// Build the core transaction item payload
$txnitm = [
'quantity' => (int) $item->qty,
'price' => [
'description' => $product->getBillingPlan()->getTerms(),
'name' => ___('Subscription').$sptext,
'billing_cycle' => [
'interval' => $this->getInterval($item->second_period),
'frequency' => $this->getFrequency($item->second_period),
],
'trial_period' => [
'interval' => $this->getInterval($item->first_period),
'frequency' => $this->getFrequency($item->first_period),
],
'tax_mode' => $tax_mode,
'unit_price' => [
'amount' => $this->getAmount(
$item->second_total,
$item->currency
),
'currency_code' => $item->currency,
],
'quantity' => [
'minimum' => (int) $item->qty,
'maximum' => (int) $item->qty,
],
'custom_data' => [
'invoice_item' => $item->item_id,
'period' => 'first_period',
],
'product' => [
'name' => $item->item_title,
'description' => $item->item_description,
'tax_category' => $tax_category,
'image_url' => $image_url,
],
],
];
// Handle one-time payments (ie: no rebill/trial)
if (!$item->second_period) {
$txnitm['price']['name'] = (($item->first_total)
? ___('Purchase') : ___('Free')).$fptext;
unset($txnitm['price']['billing_cycle'], $txnitm['price']['trial_period']);
$txnitm['price']['unit_price']['amount'] = $this->getAmount(
$item->first_total,
$item->currency
);
$params['items'][] = $txnitm;
continue;
}
// Handle free first period products (free trials)
// Use the core transaction item payload as is
if (0 == $item->first_total) {
$params['items'][] = $txnitm;
continue;
}
// Handle simple rebills (same first and second price/period)
if ($item->first_total == $item->second_total
&& $item->first_period == $item->second_period
) {
unset($txnitm['price']['trial_period']);
$params['items'][] = $txnitm;
continue;
}
// Handle complex rebills (different first and second price/period)
// Paddle doesn't support subscriptions with different prices/periods
// so we have to treat the first period as a one-time payment
// and add the second period as a seperate item starting
// at the end of the first period using a Paddle Trial.
$rebill = $txnitm; // Copy core transaction item
$txnitm['price']['name'] = ___('First Payment').$fptext;
$txnitm['price']['unit_price']['amount'] = $this->getAmount(
$item->first_total,
$item->currency
);
unset($txnitm['price']['billing_cycle'], $txnitm['price']['trial_period']);
$rebill['price']['custom_data']['period'] = 'second_period';
$params['items'][] = $txnitm;
$params['items'][] = $rebill;
}
// Generate the draft transaction
$this->invoice = $invoice; // For log
$resp = $this->_sendRequest('transactions', $params, 'DRAFT TRANSACTION');
// Decode and check transaction ID
$body = @json_decode($resp->getBody(), true);
if (empty($body['data']['id'])) {
throw new Am_Exception_InternalError('Bad response: '.$resp->getBody());
}
// Make sure Paddle returned the products with "custom" type
// This might just be a temporary bug in some accounts...
// but we don't want to pollute the product catalog!
foreach ($body['data']['details']['line_items'] as $txnitm) {
if ('custom' != $txnitm['product']['type']) {
$this->_sendRequest(
'products/'.$txnitm['product']['id'],
['type' => 'custom'],
'FIX PRODUCT TYPE',
'PATCH'
);
}
}
// Open pay page
$a = new Am_Paysystem_Action_HtmlTemplate('pay.phtml');
$a->invoice = $invoice;
$environment = $this->isSandbox() ? 'Paddle.Environment.set("sandbox");' : '';
$config = [
'transactionId' => $body['data']['id'],
'settings' => [
'displayMode' => 'inline',
'theme' => 'light',
'locale' => 'en',
'frameTarget' => 'checkout-container',
'frameInitialHeight' => '450',
'frameStyle' => 'width:100%; min-width:312px; background-color:transparent; border:none;',
'showAddTaxId' => true,
'allowLogout' => false,
'showAddDiscounts' => false,
'successUrl' => $this->getReturnUrl(),
],
];
$user = $invoice->getUser();
if ($ctm = $user->data()->get(static::CUSTOMER_ID)) {
$config['customer'] = ['id' => $ctm];
// Address requires customer
if (($add = $user->data()->get(static::ADDRESS_ID))
&& !empty($user->country) && !empty($user->zip)
) {
$config['customer']['address'] = ['id' => $add];
// Business requires an address
if ($biz = $user->data()->get(static::BUSINESS_ID)) {
$config['customer']['business'] = ['id' => $biz];
}
}
}
$config = json_encode($config);
$conversion_msg = sprintf(
'%1$s : <span class="currency">%2$s</span>',
___('Payment Currency'),
$invoice->currency
);
$a->form = <<<CUT
<div style="text-align:center;background-color:#d3dce3;padding:10px;margin:10px 0;" id="conversion-block">
<div><strong style="font-size:1.2em;">{$conversion_msg}</strong></div>
<div><strong>To Pay Today:</strong> <span class="currency">USD</span><span id="total">0.00</span></div>
<div style="font-size:0.8em;">(Includes Tax: <span class="currency">USD</span><span id="tax">0.00</span>)</div>
<div id="recurring-block" style="display:none;">
<div><strong>Recurring amount:</strong> <span class="currency">USD</span><span id="recurring-total">0.00</span></div>
<div style="font-size:0.8em;">(Includes Tax: <span class="currency">USD</span><span id="recurring-tax">0.00</span>)</div>
</div>
</div>
<div class="checkout-container"></div>
<script>
// DOM queries
const currencyLabels = document.querySelectorAll(".currency");
const taxEl = document.getElementById("tax");
const totalEl = document.getElementById("total");
const recurringTaxEl = document.getElementById("recurring-tax");
const recurringTotalEl = document.getElementById("recurring-total");
const recurringBlock = document.getElementById("recurring-block");
// Paddle engine
{$environment}
Paddle.Checkout.open(JSON.parse('{$config}'));
// Callbacks
window.addEventListener('paddleBillingEvent', function(e) {
if (e.detail.data) {
displayTotals(e.detail.data);
}
});
function displayTotals(data) {
let currency_code = data.currency_code;
let totals = data.totals;
let recurring_totals = data.recurring_totals;
// currency labels
for (var currencyLabel of currencyLabels) {
currencyLabel.innerHTML = currency_code + " ";
}
// today total
taxEl.innerHTML = totals.tax.toFixed(2);
totalEl.innerHTML = totals.total.toFixed(2);
// recurring total
if (typeof recurring_totals !== "undefined") {
recurringBlock.style.display = "block";
recurringTaxEl.innerHTML = recurring_totals.tax.toFixed(2);
recurringTotalEl.innerHTML = recurring_totals.total.toFixed(2);
}
}
</script>
CUT;
$result->setAction($a);
}
public function createTransaction($request, $response, array $invokeArgs)
{
return Am_Paysystem_Transaction_PaddleBilling_Webhook::create($this, $request, $response, $invokeArgs);
}
public function directAction($request, $response, $invokeArgs)
{
// Default payment link page
// @see: https://developer.paddle.com/build/transactions/default-payment-link
if ('pay' == $request->getActionName()) {
$ptxn = $request->getParam('_ptxn');
$view = $this->getDi()->view;
$view->title = 'Paddle Billing';
$mem_url = $this->getDi()->surl('login');
$msg = ___("Enjoy your membership. Please click %shere%s to access your member's area.", '<a href="'.$mem_url.'">', '</a>');
$view->content = '<div style="display:flex;align-items: center;justify-content:center;height:100%;max-width:800px;margin:0 auto;text-align:center;padding:2em;"><strong style="font-size:20px;font-weight:bold">'.$msg.'</strong></div>';
$view->display('layout-blank.phtml');
return;
}
// Download Invoice
if ('invoice' == $request->getActionName()) {
// Get vars
$inv_id = $request->getFiltered('id');
$txn_id = $request->getFiltered('txn');
$this->invoice = $this->getDi()->invoiceTable->findBySecureId($inv_id, $this->getId());
if (!$this->invoice) {
throw new Am_Exception_InputError('Invalid link');
}
// Make request
$resp = $this->_sendRequest(
"transactions/{$txn_id}/invoice",
null,
'PDF INVOICE',
Am_HttpRequest::METHOD_GET
);
// Check response
$body = @json_decode($resp->getBody(), true);
if (200 !== $resp->getStatus() || empty($body['data']['url'])) {
throw new Am_Exception_InputError('An error occurred while downloading: '.$body['error']['detail']);
}
// Download PDF
set_time_limit(0);
ini_set('memory_limit', AM_HEAVY_MEMORY_LIMIT);
header('Content-Type: application/pdf');
$filename = strtok(basename($body['data']['url']), '?');
header("Content-Disposition: attachment; filename={$filename}");
readfile($body['data']['url']);
exit;
}
// Update Payment Details
if ('update' == $request->getActionName()) {
// Get vars
$inv_id = $request->getFiltered('id');
$sub_id = $request->getFiltered('sub');
$this->invoice = $this->getDi()->invoiceTable->findBySecureId($inv_id, $this->getId());
if (!$this->invoice) {
throw new Am_Exception_InputError('Invalid link');
}
// Make request
$resp = $this->_sendRequest(
"subscriptions/{$sub_id}/update-payment-method-transaction",
null,
'CARD UPDATE',
Am_HttpRequest::METHOD_GET
);
// Check response
$body = @json_decode($resp->getBody(), true);
if (200 !== $resp->getStatus() || empty($body['data']['checkout']['url'])) {
throw new Am_Exception_InputError('An error occurred: '.$body['error']['detail']);
}
// Redirect to checkout URL
return $response->redirectLocation($body['data']['checkout']['url']);
}
// Let parent process it
return parent::directAction($request, $response, $invokeArgs);
}
public function cancelAction(Invoice $invoice, $actionName, Am_Paysystem_Result $result)
{
// Get subscription
$subscription_id = $invoice->data()->get(static::SUBSCRIPTION_ID);
if (!$subscription_id) {
$result->setFailed('Can not find subscription id');
return;
}
// Make request
$this->invoice = $invoice; // For log
$resp = $this->_sendRequest(
"subscriptions/{$subscription_id}/cancel",
['effective_from' => 'immediately'],
'CANCEL'
);
// Check response
$body = @json_decode($resp->getBody(), true);
if (200 !== $resp->getStatus()) {
$code = $body['error']['code'] ?? null;
if (!in_array($code, ['subscription_update_when_canceled', 'subscription_is_canceled_action_invalid'])) {
$result->setFailed($body['error']['detail']);
return;
}
}
$invoice->setCancelled(true);
$result->setSuccess();
}
public function processRefund(InvoicePayment $payment, Am_Paysystem_Result $result, $amount)
{
// Paddle refunds are not instantaneous - they get requested via API
// and approved by Paddle staff. They are usually approved, but may be
// rejected if they find evidence of fraud, refund abuse, or other
// manipulative behaviour that entitles Paddle to counterclaim the refund.
// @see: https://www.paddle.com/legal/checkout-buyer-terms
// Get the Paddle Transaction Item(s)
// and build the items payload
$items = [];
$this->invoice = $payment->getInvoice(); // for log
$txnitms = $this->invoice->data()->get(static::INV_TXNITM);
foreach ($txnitms as $txnitm) {
$items[] = [
'type' => 'full',
'item_id' => $txnitm,
];
}
// Make request
$resp = $this->_sendRequest(
'adjustments',
[
'action' => 'refund',
'items' => $items,
'transaction_id' => $payment->receipt_id,
'reason' => 'Refund requested by user ('.$payment->getUser()->login.')',
],
'REFUND'
);
// Check response
if (201 !== $resp->getStatus()) {
$body = @json_decode($resp->getBody(), true);
$result->setFailed($body['error']['detail']);
return;
}
$result->setSuccess();
// We will not add refund record here because it will be handled by
// IPN script once the refund adjustment record is created by Paddle.
}
/**
* Show Paddle plans on the Manage Products grid.
*/
public function onGridProductInitGrid(Am_Event_Grid $event): void
{
if (!$this->getConfig('show_grid')) {
return;
}
$grid = $event->getGrid();
$grid->addField(new Am_Grid_Field(static::PRICE_ID, ___('Paddle ID'), false, 'right'))
->setRenderFunction(function (Product $product) {
$ret = [];
foreach ($product->getBillingPlans() as $plan) {
$data = $plan->data()->get(static::PRICE_ID);
$ret[] = ($data) ? $data : '–';
}
$ret = implode('<br />', $ret);
return '<td style="text-align:right">'.$ret.'</td>';
})
;
}
/**
* Convenience method to add a user note.
*
* @param Am_Record|string $user aMember user or email
* @param string $content The note content
*
* @return null|Am_Record The aMember user or null
*/
public function addUserNote($user, $content)
{
// Lookup user by email if needed
if (!$user instanceof Am_Record) {
$user = $this->getDi()->userTable->findFirstByEmail($user);
if (!$user) {
return null; // user not found
}
}
// Build and insert note
$note = $this->getDi()->userNoteRecord;
$note->user_id = $user->user_id;
$note->dattm = $this->getDi()->sqlDateTime;
$note->content = $content;
$note->insert();
return $user;
}
public function getReadme()
{
$version = self::PLUGIN_REVISION;
$whk_url = $this->getPluginUrl('ipn');
$pay_url = $this->getPluginUrl('pay');
$paddleJs = $this->paddleJsSetupCode(true);
$ilog_url = Am_Di::getInstance()->url('default/admin-logs/p/invoice');
$elog_url = Am_Di::getInstance()->url('default/admin-logs/');
return <<<README
<strong>Paddle Billing Plugin v{$version}</strong>
Paddle Billing is the evolution of Paddle Classic, and is the default billing API for Paddle accounts created after August 8th, 2023.
If you signed up for Paddle before this date, <a href="https://developer.paddle.com/changelog/2023/enable-paddle-billing" target="_blank">you need to opt-in</a> to Paddle Billing. After you opt in, you can toggle between Paddle Billing and Paddle Classic, and run the two side by side for as long as you need.
<strong>Instructions</strong>
1. Upload this plugin's folder and files to the <strong>amember/application/default/plugins/payment/</strong> folder of your aMember installatiion.
2. Enable the plugin at <strong>aMember Admin -> Setup/Configuration -> Plugins</strong>
3. Configure the plugin at <strong>aMember Admin -> Setup/Configuration -> Paddle Billing.</strong>
4. In the Developer > <a href="https://vendors.paddle.com/notifications" target="_blank">Notifications</a> menu of your Paddle account, set the following webhook endpoint to listen for these webhook events:
• <code>transaction.completed</code>
• <code>subscription.canceled</code>
• <code>subscription.updated</code>
• <code>adjustment.created</code>
• <code>adjustment.updated</code>
Webhook Endpoint: <input type="text" value="{$whk_url}" size="50" onclick="this.select();"></input>
You will then need to copy Paddle's secret key for this webhook back to your plugin settings to complete configuration.
5. In the Checkout > <a href='https://vendors.paddle.com/checkout-settings' target="_blank">Checkout Settings</a> menu of your Paddle account, set the Default Payment Link to:
<input type="text" value="{$pay_url}" size="50" onclick="this.select();"></input>
This link is used when customers update their payment details, and for payment links generated from within Paddle.
<strong>OPTIONAL RETAIN SNIPPET:</strong>
If you are using Paddle Retain, you can optionally insert the following snippet on your website pages to show retry payment forms for customers in dunning, and card update reminders.
<textarea onclick="this.select();" style="width:100%;" rows="8">{$paddleJs}</textarea>
<strong>TROUBLESHOOTING</strong>
This plugin writes Paddle responses to the aMember <a href="{$ilog_url}">Invoice log</a>.
In case of an error, please check there as well as in the aMember <a href="{$elog_url}">Error log</a>.
-------------------------------------------------------------------------------
Copyright 2024 (c) Rob Woodgate, Cogmentis Ltd.
This plugin is provided under the MIT License.
This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING
WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
<strong>Like this plugin?</strong> <a href="https://donate.cogmentis.com" target="_blank">Buy me a coffee</a>
-------------------------------------------------------------------------------
README;
}
/**
* Securely gets transaction data from the Paddle API for transaction handling
* without making the entire API public.
*
* @see Am_Paysystem_PaddleBilling_Webhook_Transaction::fetchUserInfo()
*
* @param string $txn_id Paddle Transaction ID
* @param null|Invoice $invoice aMember invoice | null
*
* @return HTTP_Request2_Response The API Response
*/
public function getPaddleTransaction($txn_id, ?Invoice $invoice = null)
{
return $this->_sendRequest('transactions/'.$txn_id.'?include=address,business,customer', null, 'GET TRANSACTION', Am_HttpRequest::METHOD_GET, $invoice);
}
/**
* Convenience method to send authenticated Paddle API requests.
*
* @param mixed $url
* @param mixed $method
*/
protected function _sendRequest(
$url,
?array $params = null,
?string $logTitle = null,
$method = Am_HttpRequest::METHOD_POST,
?Invoice $invoice = null
): HTTP_Request2_Response {
$req = $this->createHttpRequest();
$req->setUrl(($this->isSandbox() ? static::SANDBOX_URL : static::LIVE_URL).$url);
$req->setMethod($method);
// Add headers
$req->setHeader([
'Accept' => 'application/json',
'Content-Type' => 'application/json',
'User-Agent' => 'paddlebilling-amember/v'.self::PLUGIN_REVISION,
'Authorization' => 'Bearer '.$this->getConfig('api_key'),
'Paddle-Version' => static::API_VERSION,
]);
// Add params and send
if (!is_null($params)) {
$req->setBody(json_encode($params));
}
$resp = $req->send();
// Log it?
if ($logTitle) {
$log = $this->getDi()->invoiceLogTable->createRecord();
if ($this->getConfig('disable_postback_log')) {
$log->toggleDisablePostbackLog(true);
}
$invoice ??= $this->invoice;
if ($invoice) {
$log->setInvoice($invoice);
}
$log->paysys_id = $this->getId();
$log->remote_addr = $_SERVER['REMOTE_ADDR'];
$log->type = self::LOG_REQUEST;
$log->title = $logTitle;
$log->mask($this->getConfig('api_key'), '***api_key***');
$log->add($req);
$log->add($resp);
}
// Return response
return $resp;
}
/**
* Override the standard ipn logging to include event type.
*
* @param mixed $request
* @param mixed $response
*/
protected function _logDirectAction(/* Am_Mvc_Request */ $request, /* Am_Mvc_Response */ $response, array $invokeArgs)
{
$event = json_decode($request->getRawBody(), true);
$type = $event['event_type'] ?? htmlentities($request->getActionName());
return $this->logRequest($request, "POSTBACK [{$type}]");
}
protected function updatePaddleCustomer(Invoice $invoice): void
{
// Vars
$user = $invoice->getUser();
$add = $user->data()->get(static::ADDRESS_ID);
$biz = $user->data()->get(static::BUSINESS_ID);
$ctm = $user->data()->get(static::CUSTOMER_ID);
// Create/fetch customer - if exists (409), the ctm_id is in the error
// @see: https://developer.paddle.com/errors/customers/customer_already_exists
// NB: We are purposely not reactivating archived users. This allows
// customers to be "banned" from ordering in Paddle by archiving them.
if (!$ctm) {
$resp = $this->_sendRequest(
'customers',
['email' => $user->email, 'name' => $user->getName()],
'CUSTOMER UPDATE'
);
$body = @json_decode($resp->getBody(), true);
if (in_array($resp->getStatus(), [201, 409])) {
$ctm = $body['data']['id'] ?? null; // created
$code = $body['error']['code'] ?? null;
if ('customer_already_exists' == $code) {
$ctm = substr($body['error']['detail'], 45); // existing
}
$user->data()->set(static::CUSTOMER_ID, $ctm)->update();
} else {
// Something bad happened... bail!
throw new Am_Exception_InternalError('Customer error: '.$resp->getBody());
}
}
// Create/Update Address, unarchiving existing if needed
if ($ctm && !empty($user->country) && !empty($user->zip)) {
$params = [
'country_code' => $user->country, // req
'description' => $this->getDi()->config->get('site_title').' (aMember)',
'first_line' => $user->street,
'second_line' => $user->street2,
'city' => $user->city,
'postal_code' => $user->zip, // req
'region' => Am_SimpleTemplate::state($user->state),
];
if ($add) {
$params['status'] = 'active'; // in case archived!
}
$update = ($add) ? "/{$add}" : '';
$method = ($add) ? 'PATCH' : Am_HttpRequest::METHOD_POST; // no METHOD_PATCH!
$resp = $this->_sendRequest(
"customers/{$ctm}/addresses".$update,
$params,
'ADDRESS UPDATE',
$method
);
if (in_array($resp->getStatus(), [200, 201])) {
$body = @json_decode($resp->getBody(), true);
$user->data()->set(static::ADDRESS_ID, $body['data']['id'])->update();
}
}
// Fetch Business ID
// NB: We don't create businesses here as a Business name is required,
// but aMember only requests a VAT ID, not the name. So just see if
// one has been previously registered with Paddle for their VAT ID
// Note: The API search param doesn't work, so we have to loop!
if (!$biz && $user->tax_id) {
$resp = $this->_sendRequest(
"customers/{$ctm}/businesses?per_page=200",
null,
'GET BUSINESS',
Am_HttpRequest::METHOD_GET
);
if (200 == $resp->getStatus()) {
$body = @json_decode($resp->getBody(), true);
foreach ($body['data'] as $biz) {
if (false !== strpos($biz['tax_identifier'], $user->tax_id)) {
$user->data()->set(static::BUSINESS_ID, $biz['id'])->update();
break; // done
}
}
}
}
}
protected function getAmount($amount, $currency = 'USD'): string
{
return (string) ($amount * pow(10, Am_Currency::$currencyList[$currency]['precision']));
}
protected function getText($period): string