GoCardless/Client.pm

filter: Statementstmt 97.3% 222 / 228 Branchbran 78.2% 72 / 92 Conditioncond 67.4% 29 / 43 MC/DCmcdc 34.7% 8 / 23 Subroutinesub 97.9% 47 / 48 Podpod 0.0% 0 / 4 totaltotal 86.3% 378 / 438 CC 65 SCAR 19.1
CC
65
Cov
89%
_send_request
15.9
_api_request
15.4
_retry_wait
9.1
CRAP 6.7
« GoCardless/Pro.pm ↑ Summary GoCardless/Exception.pm »
1 package Business::GoCardless::Client;
2  
3 =head1 NAME
4  
5 Business::GoCardless::Client
6  
7 =head1 DESCRIPTION
8  
9 This is a class for the lower level requests to the gocardless API. generally
10 there is nothing you should be doing with this.
11  
12 =cut
13  
14 55 ▶use strict;
Subroutine BEGIN: called CC=1 SCAR=0.0
15 55 ▶use warnings;
Subroutine BEGIN: called CC=1 SCAR=0.0
16 55 ▶use feature qw/ say /;
Subroutine BEGIN: called CC=1 SCAR=0.0
17  
18 55 ▶use Moo;
Subroutine BEGIN: called CC=1 SCAR=0.0
19 55 with 'Business::GoCardless::Utils';
20  
21 55 ▶use Business::GoCardless::Exception;
Subroutine BEGIN: called CC=1 SCAR=0.0
22 55 ▶use Business::GoCardless::Bill;
Subroutine BEGIN: called CC=1 SCAR=0.0
23 55 ▶use Business::GoCardless::Merchant;
Subroutine BEGIN: called CC=1 SCAR=0.0
24 55 ▶use Business::GoCardless::Payout;
Subroutine BEGIN: called CC=1 SCAR=0.0
25 55 ▶use Business::GoCardless::RedirectFlow;
Subroutine BEGIN: called CC=1 SCAR=0.0
26 55 ▶use Business::GoCardless::Subscription;
Subroutine BEGIN: called CC=1 SCAR=0.0
27  
28 55 ▶use Carp qw/ confess /;
Subroutine BEGIN: called CC=1 SCAR=0.0
29 55 ▶use POSIX qw/ strftime /;
Subroutine BEGIN: called CC=1 SCAR=0.0
30 55 ▶use MIME::Base64 qw/ encode_base64 /;
Subroutine BEGIN: called CC=1 SCAR=0.0
31 55 ▶use LWP::UserAgent;
Subroutine BEGIN: called CC=1 SCAR=0.0
32 55 ▶use HTTP::Date ();
Subroutine BEGIN: called CC=1 SCAR=0.0
33 55 ▶use Time::HiRes ();
Subroutine BEGIN: called CC=1 SCAR=0.0
34 55 ▶use UUID 0.34 ();
Subroutine BEGIN: called CC=1 SCAR=0.0
35 55 ▶use JSON ();
Subroutine BEGIN: called CC=1 SCAR=0.0
36  
37 =head1 ATTRIBUTES
38  
39 =head2 token
40  
41 Your gocardless API token, this attribute is required.
42  
43 =head2 base_url
44  
45 The gocardless API URL, defaults to $ENV{GOCARDLESS_URL} or
46 https://gocardless.com.
47  
48 =head2 api_path
49  
50 The gocardless API path, defaults to /api/v1.
51  
52 =head2 app_id
53  
54 Your gocardless app identifier, defaults to $ENV{GOCARDLESS_APP_ID} or will
55 exit if not set.
56  
57 =head2 app_secret
58  
59 Your gocardless app secret, defaults to $ENV{GOCARDLESS_APP_SECRET} or will
60 exit if not set.
61  
62 =head2 webhook_secret
63  
64 Your gocardless webhook secret, defaults to $ENV{GOCARDLESS_WEBHOOK_SECRET} or will
65 exit if not set.
66  
67 This can also be an arrayref of secrets, in which case a webhook is valid if its
68 signature matches any of them. This allows you to rotate your webhook secret, or
69 receive webhooks from more than one webhook endpoint, without rejecting webhooks:
70  
71 webhook_secret => [ $new_secret,$old_secret ],
72  
73 =head2 merchant_id
74  
75 Your gocardless merchant identifier, defaults to $ENV{GOCARDLESS_MERCHANT_ID}
76 or will exit if not set.
77  
78 =head2 user_agent
79  
80 The user agent string used in requests to the gocardless API, defaults to
81 business-gocardless/perl/v . $version_of_this_library . - . $api_version
82  
83 The following attributes only apply to the Pro (v2) API:
84  
85 =head2 max_retries
86  
87 The number of times to retry a request that failed due to a network error, a
88 server error (500, 502, 503, 504), or being rate limited (429). Defaults to 3,
89 set to 0 to disable retries. Retry delays back off exponentially from 0.5s.
90  
91 Requests are only retried if it is safe to do so: GET, PUT, and DELETE requests,
92 and POST requests that create a resource (as these have an idempotency key, see
93 L</IDEMPOTENCY KEYS>). POST requests to actions (e.g. cancelling a payment) are
94 only retried if they were rate limited, as the request will not have been
95 processed by GoCardless in that case.
96  
97 =head2 max_retry_wait
98  
99 When rate limited, requests are retried after the time given in the
100 C<ratelimit-reset> response header. If that is more than this many seconds away
101 the request is not retried and an exception is thrown. Defaults to 60.
102  
103 =head2 raise_on_idempotency_conflict
104  
105 If a create request gets an C<idempotent_creation_conflict> error, which means a
106 resource has already been created with the idempotency key, then by default the
107 existing resource is fetched and returned. Set this to true to throw an exception
108 instead, you can get the ID of the existing resource with the exception's
109 L<Business::GoCardless::Exception/conflicting_resource_id> method.
110  
111 =head2 rate_limit
112  
113 A hashref of the rate limit details from the most recent response from the API,
114 or undef if no request has been made yet:
115  
116 my $rate_limit = $Client->rate_limit;
117  
118 # {
119 # limit => 1000,
120 # remaining => 999,
121 # reset => 'Thu, 03 May 2018 16:00:00 GMT', # as sent by gocardless
122 # reset_at => 1525363200, # reset as epoch seconds
123 # }
124  
125 =cut
126  
127 has api_version => (
128 is => 'ro',
129 required => 0,
130 lazy => 1,
131 15 ▶ default => sub { $ENV{GOCARDLESS_API_VERSION} // 1 },
Subroutine __ANON__: called CC=2 SCAR=7.6
Condition50%1/2
$ENV{"GOCARDLESS_API_VERSION"} // 1
l!l
015
MC/DC0%0/1
$ENV{"GOCARDLESS_API_VERSION"} // 1
$ENV{"GOCARDLESS_API_VERSION"}
Truth table50%1/2
A
A= $ENV{"GOCARDLESS_API_VERSION"}
Aresult
11
00
132 55 );
133  
134 55 has token => (
135 is => 'ro',
136 required => 1,
137 );
138  
139 has base_url => (
140 is => 'ro',
141 required => 0,
142 26 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.4
143 26 my ( $self ) = @_;
144  
145 26 ▶ if ( my $url = $ENV{GOCARDLESS_URL} ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $url = $ENV{'GOCARDLESS_URL'}) { } 0 26 26
146 0 return $url;
147 } else {
148 26 ▶ return $self->api_version == 1
Branch: 1 branch
BranchTrueFalseTotal
$self->api_version == 1 ? : 16 10 26
149 ? 'https://gocardless.com'
150 : 'https://api.gocardless.com';
151 }
152 },
153 55 );
154  
155 has api_path => (
156 is => 'ro',
157 required => 0,
158 lazy => 1,
159 39 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=6.9
160 39 my ( $self ) = @_;
161  
162 39 ▶ if ( $self->api_version == 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->api_version == 1) { } 3 36 39
163 3 return "/api/v" . $self->api_version;
164 } else {
165 36 return '';
166 }
167 },
168 55 );
169  
170 has app_id => (
171 is => 'ro',
172 required => 0,
173 lazy => 1,
174 1 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
175 1 ▶ return undef if shift->api_version > 1;
Branch: 1 branch
BranchTrueFalseTotal
if (shift())->api_version > 1 0 1 1
176 1 ▶ $ENV{'GOCARDLESS_APP_ID'}
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"GOCARDLESS_APP_ID"} or confess("Missing required argument: app_id") 1 0 1
177 or confess( "Missing required argument: app_id" );
178 }
179 55 );
180  
181 has app_secret => (
182 is => 'ro',
183 required => 0,
184 lazy => 1,
185 1 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=12.0
186 1 ▶ return undef if shift->api_version > 1;
Branch: 1 branch
BranchTrueFalseTotal
if (shift())->api_version > 1 0 1 1
187 1 ▶ $ENV{'GOCARDLESS_APP_SECRET'}
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"GOCARDLESS_APP_SECRET"} or confess("Missing required argument: app_secret") 1 0 1
188 or confess( "Missing required argument: app_secret" );
189 }
190 55 );
191  
192 has webhook_secret => (
193 is => 'ro',
194 required => 0,
195 lazy => 1,
196 1 ▶ default => sub {
Subroutine __ANON__: called CC=2 SCAR=7.6
197 1 ▶ $ENV{'GOCARDLESS_WEBHOOK_SECRET'}
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"GOCARDLESS_WEBHOOK_SECRET"} or confess("Missing required argument: webhook_secret") 1 0 1
198 or confess( "Missing required argument: webhook_secret" );
199 }
200 55 );
201  
202 has merchant_id => (
203 is => 'ro',
204 required => 0,
205 lazy => 1,
206 1 ▶ default => sub {
Subroutine __ANON__: called CC=3 SCAR=11.7
207 1 my ( $self ) = @_;
208 1 ▶ return undef if $self->api_version > 1;
Branch: 1 branch
BranchTrueFalseTotal
if $self->api_version > 1 0 1 1
209 1 ▶ $ENV{'GOCARDLESS_MERCHANT_ID'}
Branch: 1 branch
BranchTrueFalseTotal
$ENV{"GOCARDLESS_MERCHANT_ID"} or confess("Missing required argument: merchant_id") 1 0 1
210 or confess( "Missing required argument: merchant_id" );
211 }
212 55 );
213  
214 has user_agent => (
215 is => 'ro',
216 59 ▶ default => sub {
Subroutine __ANON__: called CC=1 SCAR=0.0
217 59 my ( $self ) = @_;
218 # maybe want more info in here, version of perl, platform, and such
219 59 require Business::GoCardless;
220 59 return "business-gocardless/perl/v"
221 . $Business::GoCardless::VERSION
222 . "-" . $self->api_version
223 ;
224 }
225 55 );
226  
227 has max_retries => (
228 is => 'ro',
229 58 ▶ default => sub { 3 },
Subroutine __ANON__: called CC=1 SCAR=0.0
230 55 );
231  
232 has max_retry_wait => (
233 is => 'ro',
234 59 ▶ default => sub { 60 },
Subroutine __ANON__: called CC=1 SCAR=0.0
235 55 );
236  
237 has raise_on_idempotency_conflict => (
238 is => 'ro',
239 58 ▶ default => sub { 0 },
Subroutine __ANON__: called CC=1 SCAR=0.0
240 55 );
241  
242 55 has rate_limit => (
243 is => 'rw',
244 required => 0,
245 );
246  
247 # making these methods "private" to prevent confusion with the
248 # public methods of the same name in Business::GoCardless
249  
250 1 ▶sub _new_bill_url {
Subroutine _new_bill_url: called CC=1 SCAR=0.0
251 1 my ( $self,$params ) = @_;
252 1 return $self->_new_limit_url( 'bill',$params );
253 }
254  
255 1 ▶sub _new_pre_authorization_url {
Subroutine _new_pre_authorization_url: called CC=1 SCAR=0.0
256 1 my ( $self,$params ) = @_;
257 1 return $self->_new_limit_url( 'pre_authorization',$params );
258 }
259  
260 1 ▶sub _new_subscription_url {
Subroutine _new_subscription_url: called CC=1 SCAR=0.0
261 1 my ( $self,$params ) = @_;
262 1 return $self->_new_limit_url( 'subscription',$params );
263 }
264  
265 3 ▶sub _new_limit_url {
Subroutine _new_limit_url: called CC=2 SCAR=6.9
266 3 my ( $self,$type,$limit_params ) = @_;
267  
268 3 $limit_params->{merchant_id} = $self->merchant_id;
269  
270 my $params = {
271 nonce => $self->generate_nonce,
272 timestamp => strftime( "%Y-%m-%dT%H:%M:%SZ",gmtime ),
273 client_id => $self->app_id,
274 3 ( map { ( $limit_params->{$_}
275 12 ▶ ? ( $_ => delete( $limit_params->{$_} ) ) : ()
Branch: 1 branch
BranchTrueFalseTotal
$limit_params->{$_} ? : 9 3 12
276 ) } qw/ redirect_uri cancel_uri cancel_uri state / ),
277 $type => $limit_params,
278 };
279  
280 3 $params->{signature} = $self->sign_params( $params,$self->app_secret );
281  
282 3 return sprintf(
283 "%s/connect/%ss/new?%s",
284 $self->base_url,
285 $type,
286 $self->normalize_params( $params )
287 );
288 }
289  
290 3 ▶sub _new_redirect_flow_url {
Subroutine _new_redirect_flow_url: called CC=1 SCAR=0.0
291 3 my ( $self,$params ) = @_;
292  
293 my $data = $self->api_post(
294 '/redirect_flows',
295 3 { redirect_flows => { %{ $params } } },
296 );
297  
298 my $RedirectFlow = Business::GoCardless::RedirectFlow->new(
299 client => $self,
300 3 %{ $data->{redirect_flows} }
301 );
302  
303 3 return $RedirectFlow->redirect_url;
304 }
305  
306 6 ▶sub _confirm_redirect_flow {
Subroutine _confirm_redirect_flow: called CC=7 SCAR=19.6
307 6 my ( $self,$redirect_flow_id,$session_token ) = @_;
308  
309 # first find the original session token
310 6 my $RedirectFlow = Business::GoCardless::RedirectFlow->new(
311 client => $self,
312 id => $redirect_flow_id,
313 );
314  
315 6 $RedirectFlow->find_with_client( 'redirect_flows' );
316  
317 # only the session that started the redirect flow may confirm it
318 6 ▶ if (
Branch: 1 branch
BranchTrueFalseTotal
if (not length($session_token // "") or ($RedirectFlow->session_token // "") ne $session_token) 3 3 6
Condition71%5/7
not length($session_token // "") or ($RedirectFlow->session_token // "") ne $session_token
l!l&&r!l&&!r
123
$session_token // ""
l!l
60
$RedirectFlow->session_token // ""
l!l
50
MC/DC0%0/2
not length($session_token // "") or ($RedirectFlow->session_token // "") ne $session_token
$session_token $RedirectFlow->session_token
Truth table33%1/3
not(A) or B
A= $session_tokenB= $RedirectFlow->session_token
ABresult
0X1
111
100
319 ! length( $session_token // '' )
320 || ( $RedirectFlow->session_token // '' ) ne $session_token
321 ) {
322 3 Business::GoCardless::Exception->throw({
323 message => "session_token does not match redirect flow $redirect_flow_id",
324 });
325 }
326  
327 # redirect flows backed by a billing request are completed by gocardless
328 # when the billing request is fulfilled, and trying to complete them again
329 # is an error, so if we already have a mandate there's nothing left to do
330 3 ▶ return $RedirectFlow if ( $RedirectFlow->links // {} )->{mandate};
Branch: 1 branch
BranchTrueFalseTotal
if +($RedirectFlow->links // {})->{"mandate"} 2 1 3
Condition50%1/2
$RedirectFlow->links // {}
l!l
30
MC/DC0%0/1
$RedirectFlow->links // {}
$RedirectFlow->links
Truth table50%1/2
A
A= $RedirectFlow->links
Aresult
11
00
331  
332 # now confirm the redirect flow
333 1 my $data = $self->api_post(
334 "/redirect_flows/$redirect_flow_id/actions/complete",
335 { data => { session_token => $RedirectFlow->session_token } },
336 );
337  
338 $RedirectFlow = Business::GoCardless::RedirectFlow->new(
339 client => $self,
340 1 %{ $data->{redirect_flows} }
341 );
342  
343 1 return $RedirectFlow;
344 }
345  
346 4 ▶sub _confirm_resource {
Subroutine _confirm_resource: called CC=3 SCAR=11.0
347 4 my ( $self,$params ) = @_;
348  
349 4 ▶ if ( ! $self->signature_valid( $params,$self->app_secret ) ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($self->signature_valid($params, $self->app_secret)) 1 3 4
350 1 Business::GoCardless::Exception->throw({
351 message => "Invalid signature for confirm_resource"
352 });
353 }
354  
355 my $data = {
356 resource_id => $params->{resource_id},
357 resource_type => $params->{resource_type},
358 3 };
359  
360 3 my $credentials = encode_base64( $self->app_id . ':' . $self->app_secret );
361 3 $credentials =~ s/\s//g;
362  
363 3 my $ua = LWP::UserAgent->new;
364 3 $ua->agent( $self->user_agent );
365  
366 3 my $req = HTTP::Request->new(
367 POST => join( '/',$self->base_url . $self->api_path,'confirm' )
368 );
369  
370 3 $req->header( 'Authorization' => "Basic $credentials" );
371 3 $req->header( 'Accept' => 'application/json' );
372  
373 3 $req->content_type( 'application/x-www-form-urlencoded' );
374 3 $req->content( $self->normalize_params( $data ) );
375  
376 3 my $res = $ua->request( $req );
377  
378 3 ▶ if ( $res->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_success) { } 3 0 3
379
380 3 my $class_suffix = ucfirst( $params->{resource_type} );
381 3 $class_suffix =~ s/_([A-z])/uc($1)/ge;
382 3 my $class = "Business::GoCardless::$class_suffix";
383 my $obj = $class->new(
384 client => $self,
385 id => $params->{resource_id}
386 3 );
387 3 return $obj->find_with_client;
388 }
389 else {
390 0 Business::GoCardless::Exception->throw({
391 message => $res->content,
392 code => $res->code,
393 response => $res->status_line,
394 });
395 }
396 }
397  
398 =head1 METHODS
399  
400 api_get
401 api_post
402 api_put
403 api_delete
404  
405 Make a request to the gocardless API:
406  
407 my $data = $Client->api_get( '/merchants/123ABCD/bills',\%params );
408  
409 In list context returns the links and pagination headers:
410  
411 my ( $data,$links,$info ) = $Client->api_get( ... );
412  
413 All of the methods take an optional hashref of additional headers to send with
414 the request as the third argument:
415  
416 my $data = $Client->api_post(
417 '/payments',
418 { payments => { ... } },
419 { 'Idempotency-Key' => $your_idempotency_key },
420 );
421  
422 Failed requests will throw a L<Business::GoCardless::Exception>, and may be
423 retried before doing so (see L</max_retries>).
424  
425 =head1 IDEMPOTENCY KEYS
426  
427 When using the Pro (v2) API all requests that create a resource (POST requests
428 other than to actions) are sent with an C<Idempotency-Key> header, so that they
429 can be safely retried without creating duplicate resources (payments, etc). A
430 random key is generated for each request, or you can pass your own as shown
431 above if you want to make sure the same resource isn't created across separate
432 calls (for example on resubmission of a form). See
433 L<https://developer.gocardless.com/api-reference/#making-requests-idempotency-keys>
434 and L</raise_on_idempotency_conflict>.
435  
436 =cut
437  
438 132 ▶sub api_get {
Subroutine api_get: called CC=1 SCAR=0.0
Pod undocumented
439 132 my ( $self,$path,$params,$headers ) = @_;
440 132 return $self->_api_request( 'GET',$path,$params,$headers );
441 }
442  
443 109 ▶sub api_post {
Subroutine api_post: called CC=1 SCAR=0.0
Pod undocumented
444 109 my ( $self,$path,$params,$headers ) = @_;
445 109 return $self->_api_request( 'POST',$path,$params,$headers );
446 }
447  
448 20 ▶sub api_put {
Subroutine api_put: called CC=1 SCAR=0.0
Pod undocumented
449 20 my ( $self,$path,$params,$headers ) = @_;
450 20 return $self->_api_request( 'PUT',$path,$params,$headers );
451 }
452  
453 3 ▶sub api_delete {
Subroutine api_delete: called CC=1 SCAR=0.0
Pod undocumented
454 3 my ( $self,$path,$params,$headers ) = @_;
455 3 return $self->_api_request( 'DELETE',$path,$params,$headers );
456 }
457  
458 264 ▶sub _api_request {
Subroutine _api_request: called CC=15 SCAR=27.4
459 264 my ( $self,$method,$path,$params,$headers ) = @_;
460  
461 264 ▶ $headers = { %{ $headers // {} } };
Condition100%2/2
$headers // {}
l!l
31233
MC/DC100%1/1
$headers // {}
$headers
Truth table100%2/2
A
A= $headers
Aresult
11
00
462  
463 # the v1 API is left as it was, the following only applies to v2
464 264 ▶ return $self->_handle_response( $self->_send_request( $method,$path,$params,$headers ) )
Branch: 1 branch
BranchTrueFalseTotal
if $self->api_version < 2 34 230 264
465 if $self->api_version < 2;
466  
467 # creating a resource, as opposed to performing an action on one, so send
468 # an idempotency key to make it safe to retry the request
469 230 ▶ my $is_create = $method eq 'POST' && $path !~ m!/actions/!;
Condition100%3/3
$method eq 'POST' && !($path =~ m[/actions/])
!ll&&!rl&&r
1255748
MC/DC100%2/2
$method eq 'POST' && !($path =~ m[/actions/])
$method eq 'POST' !($path =~ m[/actions/])
Truth table100%3/3
A && not(B)
A= $method eq 'POST'B= !($path =~ m[/actions/])
ABresult
0X0
100
111
470  
471 230 ▶ $headers->{'Idempotency-Key'} //= $self->_generate_idempotency_key
Branch: 1 branch
BranchTrueFalseTotal
if $is_create 48 182 230
Condition66%2/3
$headers->{"Idempotency-Key"} //= $self->_generate_idempotency_key
l!l&&r!l&&!r
23250
MC/DC0%0/2
$headers->{"Idempotency-Key"} //= $self->_generate_idempotency_key
$headers->{"Idempotency-Key"} $self->_generate_idempotency_key
Truth table66%2/3
A //= B
A= $headers->{"Idempotency-Key"}B= $self->_generate_idempotency_key
ABresult
1X1
011
000
472 if $is_create;
473  
474 230 ▶ my $retry_safe = $method ne 'POST' || $is_create;
Condition100%3/3
$method ne 'POST' || $is_create
l!l&&r!l&&!r
1254857
MC/DC100%2/2
$method ne 'POST' || $is_create
$method ne 'POST' $is_create
Truth table100%3/3
A || B
A= $method ne 'POST'B= $is_create
ABresult
1X1
011
000
475  
476 230 for ( my $attempt = 0; ; $attempt++ ) {
477  
478 237 my $res = $self->_send_request( $method,$path,$params,$headers );
479 237 $self->_set_rate_limit( $res );
480  
481 237 ▶ if ( ! $res->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
unless ($res->is_success) 16 221 237
482  
483 16 ▶ if ( defined( my $wait = $self->_retry_wait( $res,$attempt,$retry_safe ) ) ) {
Branch: 1 branch
BranchTrueFalseTotal
if (defined(my $wait = $self->_retry_wait($res, $attempt, $retry_safe))) 7 9 16
484 0 say STDERR "GOCARDLESS retrying in ${wait}s (@{[ $res->status_line ]})"
485 7 ▶ if $ENV{GOCARDLESS_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"GOCARDLESS_DEBUG"} 0 7 7
486 7 $self->_sleep( $wait );
487 7 next;
488 }
489  
490 9 ▶ if ( $is_create && $res->code == 409 && ! $self->raise_on_idempotency_conflict ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($is_create and $res->code == 409 and not $self->raise_on_idempotency_conflict) 1 8 9
Condition100%6/6
$is_create and $res->code == 409 and not $self->raise_on_idempotency_conflict
!ll&&!rl&&r
711
$is_create and $res->code == 409
!ll&&!rl&&r
432
MC/DC100%3/3
$is_create and $res->code == 409 and not $self->raise_on_idempotency_conflict
$is_create $res->code == 409 not $self->raise_on_idempotency_conflict
Truth table100%4/4
A and B and not(C)
A= $is_createB= $res->code == 409C= not $self->raise_on_idempotency_conflict
ABCresult
0XX0
10X0
1100
1111
491  
492 1 my $Exception = $self->_exception( $res );
493  
494 # the resource has already been created (most likely by an
495 # earlier attempt of this request) so return that resource
496 # the resource is in the collection, which is the first part
497 # of the path (e.g. /instalment_schedules/create_with_dates)
498 1 my ( $collection ) = $path =~ m!^(/[^/?]+)!;
499  
500 1 ▶ if ( my $id = $Exception->conflicting_resource_id and $collection ) {
Branch: 1 branch
BranchTrueFalseTotal
if (my $id = $Exception->conflicting_resource_id and $collection) 1 0 1
Condition33%1/3
my $id = $Exception->conflicting_resource_id and $collection
!ll&&!rl&&r
001
MC/DC0%0/2
my $id = $Exception->conflicting_resource_id and $collection
my $id = $Exception->conflicting_resource_id $collection
Truth table33%1/3
A and B
A= my $id = $Exception->conflicting_resource_idB= $collection
ABresult
0X0
100
111
501 1 return $self->api_get( "$collection/$id" );
502 }
503  
504 0 $Exception->throw;
505 }
506 }
507  
508 229 return $self->_handle_response( $res );
509 }
510 }
511  
512 263 ▶sub _handle_response {
Subroutine _handle_response: called CC=6 SCAR=18.0
513 263 my ( $self,$res ) = @_;
514  
515 263 ▶ if ( $res->is_success ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($res->is_success) 254 9 263
516 # the response body is UTF-8 encoded bytes, as is the request body
517 254 my $json = $res->content;
518 254 ▶ my $data = length( $json // '' )
Branch: 1 branch
BranchTrueFalseTotal
length($json // '') ? : 253 1 254
Condition50%1/2
$json // ""
l!l
2540
MC/DC0%0/1
$json // ""
$json
Truth table50%1/2
A
A= $json
Aresult
11
00
519 ? JSON->new->utf8->canonical->decode( $json )
520 : {}; # e.g. 204 No Content
521 254 ▶ say STDERR "GOCARDLESS <- $json" if $ENV{GOCARDLESS_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"GOCARDLESS_DEBUG"} 0 254 254
522 254 my $links = $res->header( 'link' );
523 254 my $info = $res->header( 'x-pagination' );
524 254 ▶ return wantarray ? ( $data,$links,$info ) : $data;
Branch: 1 branch
BranchTrueFalseTotal
wantarray ? : 70 184 254
525 }
526  
527 9 $self->_exception( $res )->throw;
528 }
529  
530 10 ▶sub _exception {
Subroutine _exception: called CC=1 SCAR=0.0
531 10 my ( $self,$res ) = @_;
532  
533 10 return Business::GoCardless::Exception->new({
534 message => $res->content,
535 code => $res->code,
536 response => $res->status_line,
537 });
538 }
539  
540 # returns the number of seconds to wait before retrying the request,
541 # or undef if the request shouldn't be retried
542 16 ▶sub _retry_wait {
Subroutine _retry_wait: called CC=9 SCAR=22.1
543 16 my ( $self,$res,$attempt,$retry_safe ) = @_;
544  
545 16 ▶ return undef if $attempt >= $self->max_retries;
Branch: 1 branch
BranchTrueFalseTotal
if $attempt >= $self->max_retries 2 14 16
546  
547 14 my $code = $res->code;
548 14 my $backoff = 0.5 * ( 2 ** $attempt );
549  
550 14 ▶ if ( $code == 429 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($code == 429) 2 12 14
551 # rate limited requests aren't processed so are always safe to retry
552 2 ▶ my $reset_at = ( $self->rate_limit // {} )->{reset_at};
Condition50%1/2
$self->rate_limit // {}
l!l
20
MC/DC0%0/1
$self->rate_limit // {}
$self->rate_limit
Truth table50%1/2
A
A= $self->rate_limit
Aresult
11
00
553 2 ▶ my $wait = $reset_at ? $reset_at - time : $backoff;
Branch: 1 branch
BranchTrueFalseTotal
$reset_at ? : 2 0 2
554 2 ▶ $wait = 0 if $wait < 0;
Branch: 1 branch
BranchTrueFalseTotal
if $wait < 0 0 2 2
555  
556 2 ▶ return $wait > $self->max_retry_wait ? undef : $wait;
Branch: 1 branch
BranchTrueFalseTotal
$wait > $self->max_retry_wait ? : 1 1 2
557 }
558  
559 12 ▶ return undef if ! $retry_safe;
Branch: 1 branch
BranchTrueFalseTotal
unless $retry_safe 1 11 12
560  
561 # server errors and timeouts. note that LWP will return a 500 response
562 # for connection errors (with a Client-Warning header of "Internal response")
563 11 ▶ return $backoff if grep { $code == $_ } 500,502,503,504;
Branch: 1 branch
BranchTrueFalseTotal
if grep {$code == $_;} 500, 502, 503, 504 6 5 11
564  
565 5 return undef;
566 }
567  
568 0 ▶sub _sleep {
Subroutine _sleep: not called CC=2 SCAR=17.9
569 0 my ( $self,$seconds ) = @_;
570 0 ▶ Time::HiRes::sleep( $seconds ) if $seconds > 0;
Branch: 1 branch
BranchTrueFalseTotal
if $seconds > 0 0 0 0
571 }
572  
573 237 ▶sub _set_rate_limit {
Subroutine _set_rate_limit: called CC=3 SCAR=11.0
574 237 my ( $self,$res ) = @_;
575  
576 237 my $limit = $res->header( 'ratelimit-limit' );
577 237 ▶ return if ! defined $limit;
Branch: 1 branch
BranchTrueFalseTotal
unless defined $limit 234 3 237
578  
579 3 my $reset = $res->header( 'ratelimit-reset' );
580  
581 3 ▶ $self->rate_limit({
Branch: 1 branch
BranchTrueFalseTotal
defined $reset ? : 3 0 3
582 limit => $limit,
583 remaining => $res->header( 'ratelimit-remaining' ),
584 reset => $reset,
585 reset_at => defined $reset ? HTTP::Date::str2time( $reset ) : undef,
586 });
587 }
588  
589 # a v4 UUID, as recommended by gocardless for idempotency keys
590 27 ▶sub _generate_idempotency_key { UUID::uuid4() }
Subroutine _generate_idempotency_key: called CC=1 SCAR=0.0
591  
592 271 ▶sub _send_request {
Subroutine _send_request: called CC=15 SCAR=27.6
593 271 my ( $self,$method,$path,$params,$headers ) = @_;
594  
595 271 my $ua = LWP::UserAgent->new;
596 271 $ua->agent( $self->user_agent );
597  
598 271 ▶ my $req = HTTP::Request->new(
Branch: 1 branch
BranchTrueFalseTotal
$path =~ /^http/ ? : 5 266 271
599 # passing through the absolute URL means we don't build it
600 $method => my $uri = $path =~ /^http/
601 ? $path : join( '/',$self->base_url . $self->api_path . $path ),
602 );
603  
604 271 ▶ say STDERR "GOCARDLESS -> $uri" if $ENV{GOCARDLESS_DEBUG};
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"GOCARDLESS_DEBUG"} 0 271 271
605  
606 271 $req->header( 'Authorization' => "Bearer " . $self->token );
607 271 $req->header( 'Accept' => 'application/json' );
608  
609 271 ▶ if ( $self->api_version > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->api_version > 1) 237 34 271
610 # pegged to a specific version for this library and not user controlled
611 # https://developer.gocardless.com/api-reference/#making-requests-versions
612 237 $req->header( 'GoCardless-Version' => '2015-07-06' );
613 }
614  
615 271 ▶ $req->header( $_ => $headers->{$_} ) for sort keys %{ $headers // {} };
Condition50%1/2
$headers // {}
l!l
2710
MC/DC0%0/1
$headers // {}
$headers
Truth table50%1/2
A
A= $headers
Aresult
11
00
616  
617 271 ▶ if ( $method =~ /POST|PUT/ ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($method =~ /POST|PUT/) 131 140 271
618 131 ▶ if ( $self->api_version > 1 ) {
Branch: 1 branch
BranchTrueFalseTotal
if ($self->api_version > 1) { } 124 7 131
619 124 $req->content_type( 'application/json' );
620 124 my $json;
621 124 ▶ $json = JSON->new->utf8->canonical->encode( $params ) if $params;
Branch: 1 branch
BranchTrueFalseTotal
if $params 83 41 124
622 124 ▶ $req->content( $json ) if $json;
Branch: 1 branch
BranchTrueFalseTotal
if $json 83 41 124
623 124 ▶ $req->header( 'Content-Length' => 0 ) if ! $json; # always have a content length
Branch: 1 branch
BranchTrueFalseTotal
unless $json 41 83 124
624 124 ▶ say STDERR "GOCARDLESS -> $json" if $ENV{GOCARDLESS_DEBUG} && $json;
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"GOCARDLESS_DEBUG"} and $json 0 124 124
Condition33%1/3
$ENV{"GOCARDLESS_DEBUG"} and $json
!ll&&!rl&&r
12400
MC/DC0%0/2
$ENV{"GOCARDLESS_DEBUG"} and $json
$ENV{"GOCARDLESS_DEBUG"} $json
Truth table33%1/3
A and B
A= $ENV{"GOCARDLESS_DEBUG"}B= $json
ABresult
0X0
100
111
625 } else {
626 7 $req->content_type( 'application/x-www-form-urlencoded' );
627 7 $req->content( my $normalize_params = $self->normalize_params( $params ) );
628 7 ▶ say STDERR "GOCARDLESS -> $normalize_params" if $ENV{GOCARDLESS_DEBUG} && $normalize_params;
Branch: 1 branch
BranchTrueFalseTotal
if $ENV{"GOCARDLESS_DEBUG"} and $normalize_params 0 7 7
Condition33%1/3
$ENV{"GOCARDLESS_DEBUG"} and $normalize_params
!ll&&!rl&&r
700
MC/DC0%0/2
$ENV{"GOCARDLESS_DEBUG"} and $normalize_params
$ENV{"GOCARDLESS_DEBUG"} $normalize_params
Truth table33%1/3
A and B
A= $ENV{"GOCARDLESS_DEBUG"}B= $normalize_params
ABresult
0X0
100
111
629 }
630 }
631  
632 271 return $ua->request( $req );
633 }
634  
635 =head1 AUTHOR
636  
637 Lee Johnson - C<lee@payprop.com>
638  
639 This library is free software; you can redistribute it and/or modify it under
640 the same terms as Perl itself. If you would like to contribute documentation,
641 features, bug fixes, or anything else then please raise an issue / pull request:
642  
643 https://github.com/payprop/business-gocardless
644  
645 =cut
646  
647 55 1;
648  
649 # vim: ts=4:sw=4:et
« GoCardless/Pro.pm ↑ Summary GoCardless/Exception.pm »