Paytrail.pm untested

filter: Statementstmt 0.0% 0 / 110 Branchbran 0.0% 0 / 40 Conditioncond 0.0% 0 / 7 MC/DCmcdc 0.0% 0 / 4 Subroutinesub 0.0% 0 / 11 Podpod 0.0% 0 / 4 totaltotal 0.0% 0 / 176 CC 21 SCAR 42.9
CC
21
Cov
0%
submit
110.0
verify_return
110.0
return_authcode
12.0
CRAP 72.6
1 package Finance::Bank::Paytrail;
2 BEGIN {
3 $Finance::Bank::Paytrail::AUTHORITY = 'cpan:OKKO';
4 }
5 $Finance::Bank::Paytrail::VERSION = '0.010';
6 use Moose;
7 use utf8;
8  
9 use Data::Dumper;
10 use JSON::XS;
11 use Net::SSLeay qw/post_https make_headers/;
12 use Digest::MD5 qw/md5_hex/;
13 use MIME::Base64;
14  
15 # These are used when test_transaction() is set to true to signal a test payment is in effect.
16 has 'test_merchant_id' => ( is => 'ro', default => '13466' );
17 has 'test_merchant_secret' => ( is => 'ro', default => '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ' );
18  
19 =encoding utf-8
20 =cut
21  
22 # ABSTRACT: Process payments through JSON API of Paytrail (Suomen Verkkomaksut) in Finland. Payments from all Finnish Banks online: Nordea, Osuuspankki, Sampo, Tapiola, Aktia, Nooa, Paikallisosuuspankit, Säästöpankit, Handelsbanken, S-Pankki, Ålandsbanken, also from Visa, Visa Electron, MasterCard credit cards through Luottokunta, and PayPal, billing through Collector and Klarna.
23  
24 =head1 NAME
25  
26 Finance::Bank::Paytrail - Process payments through JSON API of Paytrail (Suomen Verkkomaksut) in Finland. Payments from all Finnish Banks online: Nordea, Osuuspankki, Sampo, Tapiola, Aktia, Nooa, Paikallisosuuspankit, Säästöpankit, Handelsbanken, S-Pankki, Ålandsbanken, also from Visa, Visa Electron, MasterCard credit cards through Luottokunta, and PayPal, billing through Collector and Klarna.
27  
28 =head1 SYNOPSIS
29  
30 use Finance::Bank::Paytrail;
31  
32 # Creating a new payment
33 my $tx = Finance::Bank::Paytrail->new({merchant_id => 'XXX', merchant_secret => 'YYY'});
34 # All content in accordance to http://docs.paytrail.com/ field specs
35 $tx->content({
36 orderNumber => 1,
37 referenceNumber => 13,
38 description => 'Order 1',
39 currency => 'EUR',
40 locale => 'fi_FI',
41 urlSet => {success => $c->uri_for('/payment/success').'/',
42 failure => $c->uri_for('/payment/failure').'/',
43 pending => $c->uri_for('/payment/pending').'/',
44 notification => $c->uri_for('/payment/notification').'/',
45 },
46 orderDetails => {
47 includeVat => 1,
48 contact => {
49 firstName => 'First',
50 lastName => 'Last',
51 email => 'first@example.com',
52 telephone => '555123',
53 address => {
54 street => 'Street 123',
55 postalCode => '00100',
56 postalOffice => 'Helsinki',
57 country => 'FI',
58 }
59 },
60 products => [
61 {
62 "title" => 'Product title',
63 "amount" => "1.00",
64 "price" => 123,
65 "vat" => "0.00",
66 "discount" => "0.00",
67 "type" => "1", # 1=normal product row
68 },
69 ],
70 },
71  
72 });
73  
74 # set to 1 when you are developing, 0 in production
75 $tx->test_transaction(1);
76  
77 my $submit_result = $tx->submit();
78 if ($submit_result) {
79 print "Please go to ". $tx->url() ." $url to pay your order number ". $tx->order_number().', see you soon.';
80 } else {
81 die 'Failed to generate payment';
82 }
83  
84 # Verifying the payment when the user returns or when the notify address receives a request
85 my $tx = Finance::Bank::Paytrail->new({merchant_id => 'XXX', merchant_secret => 'YYY'});
86 my $checksum_matches = $tx->verify_return({
87 ORDER_NUMBER => $c->req->params->{ORDER_NUMBER},
88 TIMESTAMP => $c->req->params->{TIMESTAMP},
89 PAID => $c->req->params->{PAID},
90 METHOD => $c->req->params->{METHOD},
91 RETURN_AUTHCODE => $c->req->params->{RETURN_AUTHCODE}
92 });
93 if ($checksum_matches) {
94 # depending on the return address, mark payment as paid (if returned to RETURN_ADDRESS),
95 # as pending (if returned to PENDING_ADDRESS) or as canceled (if returned to CANCEL_ADDRESS).
96 if ($url eq $return_url) {
97 # &ship_products();
98 }
99 } else {
100 print "Checksum mismatch, returning not processed. Please contact our customer service if you believe this to be an error.";
101 }
102  
103 =cut
104  
105 =head2 merchant_id
106  
107 The merchant id given to you by Paytrail when you make the contract. Defaults to the test merchant account.
108  
109 =cut
110  
111 has 'merchant_id' => ( is => 'rw', default => '13466' );
112  
113 =head2 merchant_secret
114  
115 The merchant secret given to you by Paytrail. Defaults to the test merchant account.
116  
117 =cut
118  
119 has 'merchant_secret' => ( is => 'rw', default => '6pKF4jkv97zmqBJ3ZL8gUw5DfT2NMQ' );
120  
121 =head2 test_transaction
122  
123 Set to 1 to mark the mode as a test. In that case the test merchant account of Paytrail is used and no real money is transferred. Intended for testing.
124  
125 =cut
126  
127 has 'test_transaction' => ( is => 'rw', default => 0 );
128  
129 =head2 debug
130  
131 Set to 1 to get debug warnings. Defaults to 0, no debug.
132  
133 =cut
134  
135 has 'debug' => ( is => 'rw', default => 0 );
136  
137 =head2 content
138  
139 Set the content to be sent to Paytrail API. All content must be in accordance to http://docs.paytrail.com/ field specs, as a Perl data structure.
140  
141 =cut
142  
143 has 'content' => ( is => 'rw', default => sub { {}; } );
144  
145 =head2 submit
146  
147 Submits the content to Paytrail API. Populates is_success, url, server_response_json, server_response, result_code, error_message, token and order_number.
148  
149 =cut
150  
151 sub submit {
152 my $self = shift;
153  
154 my $user = $self->merchant_id();
155 my $pass = $self->merchant_secret();
156  
157 # Replace user and password with the test merchant settings if test mode implied
158 if ( $self->test_transaction() ) {
159 warn 'Paytrail in test_transaction mode.' if ( $self->debug() );
160 $user = $self->test_merchant_id();
161 $pass = $self->test_merchant_secret();
162 }
163 else {
164 warn 'Paytrail in production mode.' if ( $self->debug() );
165 }
166  
167 my $json_content = JSON::XS::encode_json( $self->content() );
168  
169 if ( $self->debug() ) {
170 warn 'Paytrail submitting JSON content ' . $json_content;
171 warn 'Paytrail using user ' . $user;
172  
173 # $Net::SSLeay::trace = 3;
174 }
175  
176 my ( $page, $server_response, %headers ) = post_https(
177 $self->server(),
178 $self->port(),
179 $self->path(),
180 make_headers(
181 'Authorization' => 'Basic ' . MIME::Base64::encode( "$user:$pass", '' ),
182 'X-Verkkomaksut-Api-Version' => $self->api_version(),
183 ),
184 $json_content,
185 'application/json',
186 );
187  
188 # call server_response() with a copy of the entire unprocessed
189 # response, to be stored in case the user needs it in the future.
190 $self->server_response_json($page);
191  
192 warn 'Paytrail server response ' . Dumper($server_response) if ( $self->debug() );
193 warn 'Paytrail server response headers ' . Dumper( \%headers ) if ( $self->debug() );
194 warn 'Paytrail server response content ' . Dumper($page) if ( $self->debug() );
195  
196 # * call is_success() with either a true or false value, indicating
197 # if the transaction was successful or not.
198 $server_response =~ m/.*? (\d+) .*/;
199 my $server_response_status_code = $1;
200 if ( $server_response_status_code eq '200' or $server_response_status_code eq '201' ) {
201 $self->is_success(1);
202 }
203 else {
204 $self->is_success(0);
205  
206 # * If the transaction was not successful, call error_message()
207 # with either the processor provided error message, or some
208 # error message to indicate why it failed.
209 $self->error_message( $server_response . ' ' . $page );
210 }
211  
212 # * call result_code() with the servers result code (this is
213 # generally one field from the response indicating that it was
214 # successful or a failure, most processors provide many possible
215 # result codes to differentiate different types of success and
216 # failure).
217 $self->result_code($server_response_status_code);
218  
219 if ( $self->is_success() ) {
220 my $json_content = JSON::XS::decode_json( $self->server_response_json() );
221 # TODO: What if json is invalid
222 $self->server_response( JSON::XS::decode_json($page) );
223 $self->url( $json_content->{url} );
224 $self->token( $json_content->{token} );
225 $self->order_number( $json_content->{orderNumber} );
226 }
227 return 1;
228 }
229  
230 =head2 is_success
231  
232 Populated when you call submit. Status of the submission.
233  
234 =cut
235  
236 has 'is_success' => ( is => 'rw' );
237  
238 =head2 url
239  
240 Populated when you call submit. This is the URL the user should go to to make the payment.
241  
242 =cut
243  
244 has 'url' => ( is => 'rw' );
245  
246 =head2 token
247  
248 (Nice-to-have) Populated when you call submit and the submission is succesful.
249  
250 =cut
251  
252 has 'token' => ( is => 'rw' );
253  
254 =head2 order_number
255  
256 (Nice-to-have) Populated when you call submit and the submission is succesful.
257  
258 =cut
259  
260 has 'order_number' => ( is => 'rw' ); # the reply order number
261  
262 =head2 server_response_json
263  
264 (Nice-to-have) Populated when you call submit and the submission is succesful.
265  
266 =cut
267  
268 has 'server_response_json' => ( is => 'rw' ); # the json string as it came from the server, unprocessed
269  
270 =head2 server_response
271  
272 (Nice-to-have) Populated when you call submit. The entire unprocessed response content.
273  
274 =cut
275  
276 has 'server_response' => ( is => 'rw' ); # the response as a perl data structure, decoded from json
277  
278 =head2 result_code
279  
280 (Nice-to-have) Populated when you call submit. The HTTP status code of the reply.
281  
282 =cut
283 has 'result_code' => ( is => 'rw' );
284  
285 =head2 error_message
286  
287 Populated when you call submit and the submission is not succesful. Contains the error message from Paytrail.
288  
289 =cut
290  
291 has 'error_message' => ( is => 'rw' );
292  
293 =head2 verify_return
294  
295 When the end-user has completed the payment he will return to your specified RETURN_ADDRESS,
296 CANCEL_ADDRESS or PENDING_ADDRESS. Before you process the returning any further you must
297 check that the parameters given to this address have the correct checksum.
298  
299 This method verifies the checksum and returns true or false stating if the checksum matched or did not.
300  
301 After you know that the checksum matched you can mark the payment as paid (if returned to RETURN_ADDRESS),
302 as pending (if returned to PENDING_ADDRESS) or canceled (if returned to CANCEL_ADDRESS).
303  
304 Also your NOTIFY_ADDRESS should call verify_return first to verify the checksum and only if the verification
305 is passed proceed with the information received.
306  
307 =cut
308  
309 sub verify_return {
310 my $self = shift;
311 my $args = shift;
312 my $type = $args->{type} || 'success';
313 my $order_number = $args->{ORDER_NUMBER};
314 my $timestamp = $args->{TIMESTAMP};
315 my $paid = $args->{PAID};
316 my $method = $args->{METHOD};
317 my $their_return_authcode = $args->{RETURN_AUTHCODE};
318  
319 # use test_merchant_secret if in test mode, otherwise use the real merchant_secret.
320 my $secret = $self->test_transaction() ? $self->test_merchant_secret() : $self->merchant_secret();
321  
322 warn 'Paytrail verify_return got ' . Dumper($args) if ( $self->debug() );
323  
324 my $our_return_authcode;
325 if ( $type eq 'failure' ) {
326 warn 'Paytrail: type eq failure.' if ( $self->debug() );
327 $our_return_authcode = uc( md5_hex( join( '|', $order_number, $timestamp, $secret ) ) );
328 }
329 else {
330 warn 'Paytrail: type defaulting to success.' if ( $self->debug() );
331  
332 # default: type eq 'success'
333 $our_return_authcode = uc( md5_hex( join( '|', $order_number, $timestamp, $paid, $method, $secret ) ) );
334 }
335 warn 'Paytrail: our return authcode: ' . $our_return_authcode if ( $self->debug() );
336 warn 'Paytrail: their return authcode: ' . $their_return_authcode if ( $self->debug() );
337  
338 my $result = ( $our_return_authcode eq $their_return_authcode ) ? 1 : 0;
339 warn 'Paytrail: verify_return result ' . $result if ( $self->debug() );
340 return $result;
341 }
342  
343  
344 =head2 return_authcode
345 Gives the authcode for payment return. You can use this to link directly to the
346 "success" or "failure" return pages without ever going to the bank, or to give a link
347 in for example e-mail confirmations.
348 =cut
349  
350 sub return_authcode {
351 my $self = shift;
352 my $args = shift;
353 my $type = $args->{type} || 'success';
354 my $order_number = $args->{ORDER_NUMBER};
355 my $timestamp = $args->{TIMESTAMP};
356 my $paid = $args->{PAID};
357 my $method = $args->{METHOD};
358 my $their_return_authcode = $args->{RETURN_AUTHCODE};
359  
360 # use test_merchant_secret if in test mode, otherwise use the real merchant_secret.
361 my $secret = $self->test_transaction() ? $self->test_merchant_secret() : $self->merchant_secret();
362  
363 my $our_return_authcode;
364 if ( $type eq 'failure' ) {
365 $our_return_authcode = uc( md5_hex( join( '|', $order_number, $timestamp, $secret ) ) );
366 }
367 else {
368 # default: type eq 'success'
369 $our_return_authcode = uc( md5_hex( join( '|', $order_number, $timestamp, $paid, $method, $secret ) ) );
370 }
371 return $our_return_authcode;
372 }
373  
374  
375 =head2 port
376  
377 The port where the submission is sent to. Defaults to 443.
378  
379 =cut
380  
381 has port => ( is => 'rw', default => '443' );
382  
383 =head2 server
384  
385 The server host name where the submission is sent to. Defaults to payment.paytrail.com.
386  
387 =cut
388  
389 has server => ( is => 'rw', default => 'payment.paytrail.com' );
390  
391 =head2 path
392  
393 The URL path where the submission is sent to. Defaults to /api-payment/create.
394  
395 =cut
396  
397 has path => ( is => 'rw', default => '/api-payment/create' );
398  
399 =head2 api_version
400  
401 The REST API version of Paytrail. Defaults to 1.
402  
403 =cut
404  
405 has 'api_version' => ( is => 'rw', default => '1' );
406  
407 =head1 SECURITY
408  
409 Don't allow user to set the test_transaction to true! If the user can set it to true when returning he
410 will get his payment registered as processed.
411  
412 Don't allow user to set the 'type' parameter of verify_return.
413  
414 =head1 SEE ALSO
415  
416 http://www.paytrail.com/
417 http://docs.paytrail.com/
418 http://www.frantic.com/
419  
420 =head1 AUTHOR
421  
422 Oskari Okko Ojala E<lt>okko@cpan.orgE<gt>, Frantic Oy http://www.frantic.com/
423  
424 =head1 COPYRIGHT AND LICENSE
425  
426 Copyright (C) Oskari Ojala 2011-2014.
427  
428 This library is free software; you can redistribute it and/or modify
429 it under the same terms as Perl itself, either Perl version 5.8.8 or,
430 at your option, any later version of Perl you may have available.
431  
432 =cut
433  
434 __PACKAGE__->meta->make_immutable;
435  
436 1;