-
Notifications
You must be signed in to change notification settings - Fork 14
/
Stripe.pm
973 lines (700 loc) · 27.3 KB
/
Stripe.pm
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
package Business::Stripe;
use strict;
use warnings;
use JSON;
use LWP::UserAgent;
use HTTP::Request::Common qw/DELETE GET POST/;
use MIME::Base64 qw(encode_base64);
our $VERSION = '0.07';
use constant URL => 'https://api.stripe.com/v1/';
=encoding utf8
=head1 NAME
Business::Stripe - Interface for Stripe payment system.
=head1 SYNOPSIS
my $stripe = Business::Stripe->new(
-api_key => 'your-api-key-here',
);
## get the payment token from Stripe.js, then:
$stripe->charges_create(
amount => 400,
source => 'tok_5EuIyKyCTc0f2V',
description => 'Ice cream'
) and return $stripe->success;
say $stripe->error->{message};
=head1 DESCRIPTION
This module provides common bindings for the Stripe payment system.
Any API calls that do not have bindings can be accessed through the
generic C<api> method.
=head2 General Methods
=head3 new (I<%options>)
Creates a new Business::Stripe object for you to use. The only
B<< required argument >> is C<-api_key>, which was given to you
as part of your Stripe account to access the API.
Other (optional) arguments are:
=over 4
=item C<-version> Sets a Stripe API version to use, overriding your
account's default. You can use this to test if new versions of
the API work with your code. To support marketplaces, for instance, you
should use at least C<'2014-11-05'>.
=item C<-ua_args> Hashref of options that will be passed directly as
arguments to LWP::UserAgent. Example:
my $stripe = Business::Stripe->new(
-api_key => 'xxxxxxxxx',
-ua_args => {
timeout => 10,
env_proxy => 1,
agent => 'myApp',
ssl_opts => { verify_hostname => 0 },
},
);
=item C<-ua> Completely overrides the default user agent object (L<LWP::UserAgent>).
Note that your object I<must> accept HTTPS, and provide a C<request()> method
accepting L<HTTP::Request> objects and returning L<HTTP::Response>-compatible
objects. You can use this to have a common user agent make all requests in
your code. The example above works exactly like:
my $ua = LWP::UserAgent->new(
timeout => 10,
env_proxy => 1,
agent => 'myApp',
ssl_opts => { verify_hostname => 0 },
);
my $stripe = Business::Stripe->new(
-api_key => 'xxxxxxxx',
-ua => $ua,
);
=item C<-url> Overrides the default API endpoint (C<https://api.stripe.com/v1/>)
=item C<-stripe_account> If you use the
L<< OAauth authentication flow for managed accounts|https://stripe.com/docs/connect/authentication >>
You can use this argument to make operations on behalf of a managed account.
=back
=cut
sub new {
my $class = shift;
my $self = { @_ };
bless $self, $class;
$self->_init;
return $self;
}
=head3 api (I<$method>, I<$path>, I<%params>)
Generic function that sends requests to Stripe.
Check the L<< Stripe API Reference|https://stripe.com/docs/api >>
for specific calls.
The first argument is the HTTP method: C<"post">, C<"get"> or C<"delete">.
The second is the target path, like "tokens", "plans", "customers"
or even complex paths like "customers/$id/subscriptions". Check the
Stripe API Reference for a list of all available paths.
Use the optional third argument to send a hash of data with your API call.
This is usually required on all C<"post"> calls to the API.
On success, it returns a true value. If the returned data structure contains
an C<id> field, this is the value returned. Otherwise, "1" is returned and
you should check L<< $stripe->success() | /success >> for the actual data
structure.
In case of failures, it returns false (0) and you should then check
L<< $stripe->error() | /error >> for the appropriate data structure.
Examples:
=over 4
=item get a credit card source token on the server side (without using Stripe.js)
my $token_id = $stripe->api('post', 'tokens',
'card[number]' => '4242424242424242',
'card[exp_month]' => 12,
'card[exp_year]' => 2022,
'card[cvc]' => 123
) or die $stripe->error->{message};
=item create a new customer (with the $token_id from above)
my $customer = $stripe->api('post', 'customers',
email => 'myuser@example.com',
name => 'Jane S. Customer',
description => 'Displayed alongside the customer on your dashboard',
source => $token_id,
) and $stripe->success;
die $stripe->error unless $customer;
=item create a new plan to subscribe your customers
my $plan_id = $stripe->api('post', 'plans',
'amount' => 999, # *IN CENTS* (999 = 9.99). Use 0 for a free plan!
'id' => 'my-plan', # Optional. Must be unique in your account
'currency' => 'usd', # See https://stripe.com/docs/currencies
'interval' => 'month', # Also: 'day', 'week', 'year'
'product[name]' => 'My Plan',
) or die $stripe->error->{message};
=item subscribe the customer to a plan (using examples above)
my $subscription = $stripe->api('post', 'subscriptions',
'customer' => $customer->{id},
'items[0][plan]' => $plan_id,
) ? $stripe->success : $stripe_error;
=item cancel a subscription immediately
$stripe->api('delete', "subscriptions/" . $subscription->{id})
or die "error canceling subscription: " . $stripe->error->{message};
=back
As you can see, all actions can be performed by using only this method.
The other methods provided by this class are just helper wrappers around this,
for frequently made calls.
=cut
sub api {
my $self = shift;
my $method = shift;
my $path = shift;
return undef unless $self->{-auth};
undef $self->{-success};
undef $self->{-error};
my $url = $self->{-url} . $path;
### in simple requests, we let users compose their call as
### api('delete','plans','gold') or api('get', 'subscriptions', 17)
### instead of api('delete', 'plans/gold') or 'subscriptions/17'.
### But it only works for a single parameter.
if (@_ == 1) { $url .= '/' . shift }
my @params = @_;
my @headers = $self->_fetch_headers(\@params);
my $request;
if ($method eq 'post') {
$request = POST $url, @headers, Content => \@params;
}
elsif ($method eq 'delete') {
$request = DELETE $url, @headers;
}
elsif ($method eq 'get') {
my %params = @params;
my $query = join '&', map {
$_ . '=' . (defined $params{$_} ? $params{$_} : '')
} sort keys %params;
$url .= '?' . $query if $query;
$request = GET $url, @headers;
}
else {
warn "don't know how to handle $method";
return;
}
my $res = $self->{-ua}->request($request);
if ($res->is_success) {
$self->{-success} = decode_json($res->content);
return $self->{-success}->{id} || 1;
}
$self->{-error} = decode_json($res->content);
return 0;
}
=head3 error
All API and helper methods return C<0> when they encounter error conditions.
The JSON object returned by Stripe can be retrieved via this method.
say $stripe->error->{message};
Most error messages include C<message>, C<code>, C<type> and C<doc_url>.
=cut
sub error {
return shift->{-error}->{error};
}
=head3 success
All API and helper methods return either C<1> or the object's ID on success.
Use this method to get access to the complete JSON object returned on the
last call made by your object. See Stripe's API Documentation for details
on what is returned on each call.
say $stripe->success->{data}->[0]->{description};
=cut
sub success {
return shift->{-success};
}
=head2 Charges
Set of methods that handle credit/debit card such as charging a card,
refund, retrieve specific charge and list charges.
B<Note:> Charges will likely fail for new cards added if the new SCA
applies. The flow should be switched to payment_intents (see below).
Existing payment methods should continue to work.
=head3 charges_create (I<%params>)
my $success = $stripe->charges_create(
amount => 100, # <-- amount in cents
source => 'tok_Wzm6ewTBrkVvC3',
description => 'customer@example.com'
);
Charges a credit card or other payment sources. This is exactly
the same as C<< $stripe->api('post', 'charges', %params) >>,
except that it defaults to 'usd' if you don't provide a currency.
It returns the C<id> of the charge on success, or 0 on error.
You may also check L<< $stripe->success | /success >> or
L<< $stripe->error | /error >> for the complete JSON.
Please see Stripe's API Documentation for which parameters are
accepted by your current API version.
B<Note:> The C<amount> field is in the I<< currency's smallest unit >>.
For currencies that allow cents (like USD), an amount of 100 means $1.00,
1000 mean $10.00 and so on. For zero-decimal currencies (like JPY) you don't
have to multiply, as an amount of 100 mean ¥100.
B<Note:> Older (2015-ish) versions of Stripe's API support the C<card>
parameter containing the source token from Stripe.js. This has since
been deprecated in favour of the C<source> parameter, shown in the
example above.
=cut
sub charges_create {
my $self = shift;
my %param = (@_);
$param{currency} ||= 'usd';
return $self->_compose('charges', %param);
}
=head3 charges_retrieve (I<$id>)
my $charge_data = $stripe->charges_retrieve('ch_uxLBSIZB8azrSr')
and $stripe->success;
Takes the charge C<id> value and yields data about the charge, available
on L<< $stripe->success | /success >>.
This is exactly the same as C<< $stripe->api('get', "charges/$charge_id") >>.
=cut
sub charges_retrieve {
my $self = shift;
my $id = shift;
return $self->_compose('charges/'.$id);
}
=head3 charges_refund (I<$id>, [I<$amount>])
Refunds a specific C<amount> (or if omitted, issues a full refund)
to the charge C<id>. Remember: the C<amount> parameter is I<in cents>
whenever the currency supports cents.
### refunds full amount
$stripe->charges_refund('ch_uxLBSIZB8azrSr')
or die $stripe->error->{message};
### refunds $5 over a bigger charge
$stripe->charges_refund('ch_uxLBSIZB8azrSr', 500)
or die $stripe->error->{message};
=cut
sub charges_refund {
my ($self,$id,$amount) = (@_);
return $self->_compose(
'charges/'.$id.'/refunds',
$amount ? (amount => $amount) : []
);
}
=head3 charges_list (I<%params>)
List all the charges, with pagination.
### lists next 5 charges
my $charges = $stripe->charges_list(limit => 5)
? $stripe->success : die $stripe->error->{message};
foreach my $charge (@{$charges->{data}}) {
say $charge->{amount} . $charge->{currency};
}
if ($charges->{has_more}) {
say "there are more charges to show if you raise the limit"
. " or change the 'starting_after' argument.";
}
Pass on the customer's ID to only get charges made to that customer:
$stripe->charges_list(customer => 'cus_gpj0mzwbQKBI7c')
or die "error fetching customer charges: " . $stripe->error;
my $charges = $stripe->success;
=cut
sub charges_list {
my $self = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('charges' . ($qs ? "?$qs" : ''));
}
=head2 Payment Intents
Set of methods that handle colling payments from a customer. These help build
a payment flow, including possible authentication steps that may be required.
Payment intents are superceding the charges api for new SCA regulations.
If this is an off session payment, it may be helpful to create a setup intent
first on a website (using stripe.js), see below.
=head3 payment_intents_create (I<%params>)
my $success = $stripe->payment_intents_create(
customer => '<customer_id>',
description => 'A payment intent',
amount => '40',
);
Creates a payment intent. You will need to attach a payment method now, or later
when confirming the intent (see confirm below).
C<< confirm => 'true' >> will create and confirm the intent all in the same call.
C<amount> is required
C<currency> is required, but will default to usd in this module.
=cut
sub payment_intents_create {
my $self = shift;
my %params = (@_);
$params{currency} ||= 'usd';
return $self->_compose('payment_intents', %params);
}
=head3 payment_intents_retrieve (I<$id>)
my $payment_intents_data = $stripe->payment_intents_retrieve('pi_xxxx')
and $stripe->success;
=cut
sub payment_intents_retrieve {
my $self = shift;
my $id = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('payment_intents/'.$id . ($qs ? "?$qs" : ''));
}
=head3 payment_intents_update (I<%params>)
my $success = $stripe->payment_intents_update( $payment_intents_id,
'description' => 'An updated payments intent' );
Takes the payment intent value and update it with some new information
=cut
sub payment_intents_update {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose('payment_intents/'.$id, %params);
}
=head3 payment_intents_confirm (I<%params>)
my $success = $stripe->payment_intents_confirm( $payment_intents_id,
payment_method => 'pm_card_visa' );
Confirm a payment intent. It can be used just the id and no parameters if simply
confirming, or you may want to attach a payment_method for example.
=cut
sub payment_intents_confirm {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose(
'payment_intents/'.$id.'/confirm',
@_ ? %params : []
);
}
=head3 payment_intents_capture (I<%params>)
my $success = $stripe->payment_intents_capture( $payment_intents_id,
amount_to_capture => 10 );
Capture an amount from a payment intent. Defaults to capture the full amount,
but you can capture a smaller amount like in the example. Payment intents are
cancelled if not captured within 7 days.
=cut
sub payment_intents_capture {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose(
'payment_intents/'.$id.'/capture',
@_ ? %params : []
);
}
=head3 payment_intents_cancel (I<%params>)
my $success = $stripe->payment_intents_cancel( $payment_intents_id );
Simply cancel the payment intent, params are optional, you can give it a reason
for the cancellation if wanted.
=cut
sub payment_intents_cancel {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose(
'payment_intents/'.$id.'/cancel',
@_ ? %params : []
);
}
=head3 payment_intents_list (I<%params>)
my $intent_list = $stripe->payment_intents_list( 'customer' => '<some_customer_id>' );
Grab a list of the payment intents, by some field. Will return a dictionary with a C<data>
element, which will be an arrayref you can loop over.
=cut
sub payment_intents_list {
my $self = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('payment_intents' . ($qs ? "?$qs" : ''));
}
=head2 Setup Intents
Setup Intents are useful if you want to capture off-session payments.
For example, you may want to integrate stripe.js in the browser, get
Stripe to capture a card for future payments. An example flow, may be
to create a setup intent at the back end, and pass the C<client_secret>
it returns to the front end, to include in the stripe.js form, when
getting Stripe to capture the card for future payments. This will help
with the authentication later hopefully making payments more likely to
go through without issue.
=head3 setup_intents_create (I<%params>)
my $setup_intent = $stripe->setup_intents_create(
customer => '<some_customer_id',
description => 'A setup intent',
);
Create a setup intent, which can be used for setting up payment
credentials for later use.
=cut
sub setup_intents_create {
my $self = shift;
my %params = (@_);
return $self->_compose('setup_intents', %params);
}
=head3 setup_intents_retrieve (I<$id>)
my $setup_intents_data = $stripe->setup_intents_retrieve('seti_xxxx')
and $stripe->success;
Takes the setup intent <id> value and yields data about the intent, available
on L<< $stripe->success | /success >>.
=cut
sub setup_intents_retrieve {
my $self = shift;
my $id = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('setup_intents/'.$id . ($qs ? "?$qs" : ''));
}
=head3 setup_intents_update (I<$id>)
my $updated_intent = $stripe->setup_intents_update( $setup_intent_id,
'description' => 'An updated setup intent' );
Update a setup intent. Returns the setup_intent object.
=cut
sub setup_intents_update {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose('setup_intents/'.$id, %params);
}
=head3 setup_intents_confirm (I<$id>)
my $confirmed_intent = $stripe->setup_intents_confirm( $setup_intent_id );
Confirm a setup intent, for example with a payment method, but parameters not
required.
=cut
sub setup_intents_confirm {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose(
'setup_intents/'.$id.'/confirm',
@_ ? %params : []
);
}
=head3 setup_intents_cancel (I<$id>)
my $setup_intent = $stripe->setup_intents_cancel( $setup_intent_id );
Cancel a setup intent. will return the intent, or an error if already cancelled.
This doesn't need any params, but you can specify a cancellation_reason if wanted.
=cut
sub setup_intents_cancel {
my $self = shift;
my $id = shift;
my %params = (@_);
return $self->_compose(
'setup_intents/'.$id.'/cancel',
@_ ? %params : []
);
}
=head3 setup_intents_list (I<$id>)
my $intents_list = $stripe->setup_intents_list( 'customer' => '<some_customer_id>' );
Grab a list of setup intents, by some parameter, or no parameters to get them all. You can
include a C<limit> parameter if needed.
=cut
sub setup_intents_list {
my $self = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('setup_intents' . ($qs ? "?$qs" : ''));
}
=head2 Customers
Some operations require you create a customer. Also, by creating a customer,
you don't have to ask for credit card information on every charge.
=head3 customers_create (I<%params>)
Creates a new customer according to the credit card information or token given.
Use this method to create a customer-ID for the given C<card>
(token when used in conjunction with Stripe.js).
The customer-ID can be passed to C<charges_create>'s C<customer> parameter
instead of C<source> so that you don't have to ask for credit card info again.
my $customer_id = $stripe->customers_create(
source => 'tok_Wzm6ewTBrkVvC3',
email => 'customer@example.com',
description => 'userid-123456'
) or die $stripe->error;
### charges the customer $5
$stripe->charges_create(
customer => $customer_id,
amount => 500,
description => 'userid-123456 paid $5'
);
Returns the customer's ID if successful. As usual, you may check the
full JSON object returned on L<< $stripe->success | /success >>.
=cut
sub customers_create {
my $self = shift;
return $self->_compose('customers', @_);
}
=head3 customers_retrieve (I<$id>)
Gets the customer's object. Returns the id (which you already have) so
make sure to fetch the actual object using L<< $stripe->success | /success >>.
my $customer = $stripe->customers_retrieve('cus_gpj0mzwbQKBI7c')
and $stripe->success;
die $stripe->error unless $customer;
=cut
sub customers_retrieve {
my $self = shift;
my $id = shift;
return $self->_compose('customers/'.$id);
}
=head3 customers_update (I<$id>, [I<%params>])
Updates customer's information.
$stripe->customers_update('cus_gpj0mzwbQKBI7c',
email => 'newemail@example.com',
);
B<Note:> If you update the C<source> of a customer, Stripe will create
a source object with the new value, make it the default source, and
I<delete the old customer default> if it exists. If you just want to
add extra sources for that customer, refer to Stripe's
L<< card creation API | https://stripe.com/docs/api#create_card >>.
=cut
sub customers_update {
my $self = shift;
return $self->_compose('customers/'.(shift), @_);
}
=head3 customers_delete (I<$id>)
Deletes the customer.
$stripe->customers_delete('cus_gpj0mzwbQKBI7c')
or die $stripe->error;
=cut
sub customers_delete {
my $self = shift;
return $self->_compose('customers/'.(shift), 'delete');
}
=head3 customers_list (I<%params>)
List all customers.
$stripe->customers_list(limit => 20);
=cut
sub customers_list {
my $self = shift;
my %params = (@_);
my $qs = join '&', map {
$_ . '=' . ($params{$_}||'')
} sort keys %params;
return $self->_compose('customers' . ($qs ? "?$qs" : ''));
}
=head3 customers_subscribe (I<$id>, I<%params>)
Subscribes a customer to a specified plan:
$stripe->customers_subscribe('cus_YrUZejr9oojQjs',
'items[0][plan]' => $some_plan_id,
'prorate' => 'false'
);
Assuming C<$some_plan_id> is the id of a plan already created in your
Stripe account.
B<Note:> pass C<'items[0][quantity]'> with a value of 2 or more to subscribe
the same user to 2 or more of the same plan. It defaults to 1.
B<Note:> This method will I<< replace all your user's subscriptions >> with
the new data provided. To subscribe the user to more than one plan, write:
$stripe->api('post', 'subscriptions',
'customer' => $customer_id,
'items[0][plan]' => $plan_id_to_add,
);
Note that this will keep all previous billing cycles (and associated fees)
for any other subscription already present and add a new billing cycle (and fee)
for this new one. If you want to subscribe the customer to more than one plan
I<< with a single billing cycle >>, pass each plan as a separate item:
$stripe->customers_subscribe('cus_YrUZejr9oojQjs',
'items[0][plan]' => $some_plan_id,
'items[1][plan]' => $other_plan_id,
) or die "error subscribing customer: " . $stripe->error->{message};
=cut
sub customers_subscribe {
my $self = shift;
my $id = shift;
return $self->_compose("customers/$id/subscriptions", @_);
}
=head3 customers_unsubscribe (I<$id>)
Immediately unsubscribe the customer from all currently subscribed plans.
Useful for terminating accounts (or paid subscriptions).
NOTE: As per Stripe's documentation, any pending invoice items that you’ve
created will still be charged for at the end of the period, unless manually
deleted. If you’ve set the subscription to cancel at the end of the period,
any pending prorations will also be left in place and collected at the end
of the period. But if the subscription is set to cancel immediately, pending
prorations will be removed.
$stripe->customers_unsubscribe('cus_YrUZejr9oojQjs')
or die "error unsubscribing customer: " . $stripe->error->{message};
=cut
sub customers_unsubscribe {
my $self = shift;
my $id = shift;
return $self->_compose("customers/$id/subscriptions", 'delete');
}
sub _init {
my $self = shift;
$self->{-url} ||= URL;
$self->{-api_key} and
$self->{-auth} = 'Basic ' . encode_base64($self->{-api_key}) . ':';
if (!$self->{-ua}) {
$self->{-ua} = LWP::UserAgent->new(
(ref $self->{-ua_args} eq 'HASH' ? %{$self->{-ua_args}} : ())
);
}
return;
}
# _compose() was once public, we keep it now only for backwards compatibility.
# Previous behaviour was:
# _compose( $somepath, 'delete' ) makes a DELETE request;
# _compose( $somepath, [...] ) makes a POST request;
# _compose( $somepath, @two_or_more ) makes a POST request;
# _compose( $somepath ) makes a GET request;
# _compose( $somepath, $single_value ) makes a GET request (and ignores $single_value);
sub _compose {
my $self = shift;
my $resource = shift;
if ($_[0] and $_[0] eq 'delete') {
return $self->api('delete', $resource);
} elsif (scalar @_ > 1 || (@_ == 1 && ref $_[0] eq 'ARRAY')) {
return $self->api('post', $resource, @_ == 1 ? @{$_[0]} : @_);
} else {
return $self->api('get', $resource);
}
}
sub _fetch_headers {
my ($self, $params) = @_;
my %headers = ( Authorization => $self->{-auth} );
if ($self->{-version}) {
$headers{'Stripe-Version'} = $self->{-version};
}
if ($self->{-stripe_account}) {
# for managed 'oauth' accounts.
# https://stripe.com/docs/connect/authentication
$headers{'Stripe-Account'} = $self->{-stripe_account};
}
# we could have just casted it to a hash, but we don't
# want to mess with the ordering.
my $i = 0;
while ($i < $#{$params}) {
my $key = $params->[$i];
my $value = $params->[$i+1];
# dynamic header found (-somekey => ...)
if (substr($key, 0, 1) eq '-') {
my %header_for = (
'-authorization' => 'Authorization',
'-auth' => 'Authorization',
'-stripe_version' => 'Stripe-Version',
'-version' => 'Stripe-Version',
'-stripe_account' => 'Stripe-Account',
'-idempotency_key' => 'Idempotency-Key',
);
if (exists $header_for{$key}) {
$headers{ $header_for{$key} } = $value;
}
else {
warn "don't know how to handle key '$key'. Ignored.";
}
# remove key from params
splice @$params, $i, 2;
}
else {
$i += 2;
}
}
return %headers;
}
=head1 REPOSITORY
L<https://github.com/aquaron/Business-Stripe>
=head1 SEE ALSO
Stripe.js Documentation L<https://stripe.com/docs/stripe.js>.
Stripe Full API Reference L<https://stripe.com/docs/api>.
Full featured implementation by Luke Closs L<Net::Stripe>.
=head1 SINGLE FILE INSTALLATION
This module is implemented as a single-file package.
If you don't want to use the CPAN distribution, you can download C<Stripe.pm>
from the root directory and renamed it to C<BusinessStripe.pm>:
mv Stripe.pm BusinessStripe.pm
Edit C<BusinessStripe.pm> and remove the C<::> between the package name on
the first line to:
package BusinessStripe;
Include the file in your program:
use BusinessStripe;
my $stripe = BusinessStripe->new(
-api_key => 'c6EiNIusHip8x5hkdIjtur7KNUA3TTpE',
-env_proxy => 1,
);
$stripe->charges_list;
=head1 AUTHOR
Paul Pham (@phamnp)
=head1 COPYRIGHT AND LICENSE
Copyright (C) 2012-2019 Aquaron. All Rights Reserved.
This program and library is free software;
you can redistribute it and/or modify it under the same terms as Perl itself.
=cut
1;