1 package Business::OnlinePayment::InternetSecure;
9 use Net::SSLeay qw(make_form post_https);
10 use XML::Simple qw(xml_in xml_out);
12 use base qw(Business::OnlinePayment Exporter);
15 our $VERSION = '0.01';
18 use constant CARD_TYPES => {
21 AX => 'American Express', # FIXME: AM?
27 # Convenience functions to avoid undefs and escape products strings
28 sub _def($) { defined $_[0] ? $_[0] : '' }
29 sub _esc($) { local $_ = shift; tr/|:/ /s; tr/"`/'/s; return $_ }
35 $self->server('secure.internetsecure.com');
37 $self->path('/process.cgi');
40 receipt_number sales_number uuid guid
44 avs_response cvv2_response
48 # OnlinePayment's get_fields now filters out undefs in 3.x. :(
51 my ($self, @fields) = @_;
53 my %content = $self->content;
55 my %new = map +($_ => $content{$_}), @fields;
60 # Combine get_fields and remap_fields for convenience
62 sub get_remap_fields {
63 my ($self, %map) = @_;
65 $self->remap_fields(reverse %map);
66 my %data = $self->get_fields(keys %map);
71 # Since there's no standard format for expiration dates, we try to do our best
74 my ($self, $str) = @_;
80 if (/^(\d{4})\W(\d{1,2})$/ || # YYYY.MM or YYYY-M
81 /^(\d\d)\W(\d)$/ || # YY/M or YY-M
82 /^(\d\d)[.-](\d\d)$/) { # YY-MM
84 } elsif (/^(\d{1,2})\W(\d{4})$/ || # MM-YYYY or M/YYYY
85 /^(\d)\W(\d\d)$/ || # M/YY or M-YY
86 /^(\d\d)\/?(\d\d)$/) { # MM/YY or MMYY
89 croak "Unable to parse expiration date: $str";
92 $y += 2000 if $y < 2000; # Aren't we glad Y2K is behind us?
97 # Convert a single product into a product string
100 my ($self, $currency, %data) = @_;
102 croak "Missing amount in product" unless defined $data{amount};
104 my @flags = ($currency);
106 foreach (split ' ' => uc($data{taxes} || '')) {
107 croak "Unknown tax code $_" unless /^(GST|PST|HST)$/;
111 if ($self->test_transaction) {
112 push @flags, $self->test_transaction < 0 ? 'TESTD' : 'TEST';
116 sprintf('%.2f' => $data{amount}),
117 $data{quantity} || 1,
118 _esc _def $data{sku},
119 _esc _def $data{description},
120 join('' => map "{$_}" => @flags),
124 # Generate the XML document for this transaction
129 my %content = $self->content;
131 $self->required_fields(qw(action card_number exp_date));
133 croak 'Unsupported transaction type'
134 if $content{type} && $content{type} !~
135 /^(Visa|MasterCard|American Express|Discover)$/i;
137 croak 'Unsupported action'
138 unless $content{action} =~ /^Normal Authori[zs]ation$/i;
140 $content{currency} = uc($content{currency} || 'CAD');
141 croak "Unknown currency code ", $content{currency}
142 unless $content{currency} =~ /^(CAD|USD)$/;
144 $content{taxes} = uc($content{taxes} || '');
146 my %data = $self->get_remap_fields(qw(
147 xxxCard_Number card_number
159 xxxShippingName ship_name
160 xxxShippingCompany ship_company
161 xxxShippingAddress ship_address
162 xxxShippingCity ship_city
163 xxxShippingProvince ship_state
164 xxxShippingPostal ship_zip
165 xxxShippingCountry ship_country
166 xxxShippingPhone ship_phone
167 xxxShippingEmail ship_email
170 $data{MerchantNumber} = $self->merchant_id;
172 $data{xxxCard_Number} =~ tr/ //d;
173 $data{xxxCard_Number} =~ s/^[^3-6]/4/ if $self->test_transaction;
175 my ($y, $m) = $self->parse_expdate($content{exp_date});
176 $data{xxxCCYear} = sprintf '%.4u' => $y;
177 $data{xxxCCMonth} = sprintf '%.2u' => $m;
179 if (defined $content{cvv2} && $content{cvv2} ne '') {
181 $data{CVV2Indicator} = $content{cvv2};
184 $data{CVV2Indicator} = '';
187 if (ref $content{description}) {
188 $data{Products} = join '|' => map $self->prod_string(
190 taxes => $content{taxes},
192 @{ $content{description} };
194 $self->required_fields(qw(amount));
195 $data{Products} = $self->prod_string(
197 taxes => $content{taxes},
198 amount => $content{amount},
199 description => $content{description},
206 RootName => 'TranxRequest',
207 SuppressEmpty => undef,
208 XMLDecl => '<?xml version="1.0" encoding="iso-8859-1" standalone="yes"?>',
212 # Map the various fields from the response, and put their values into our
213 # object for retrieval.
216 my ($self, $data, %map) = @_;
218 while (my ($k, $v) = each %map) {
220 $self->$k($data->{$v});
224 # Parse the server's response and set various fields
227 my ($self, $response) = @_;
229 $self->server_response($response);
231 local $/ = "\n"; # Make sure to avoid bug #17687
233 $response = xml_in($response,
234 ForceArray => [qw(product flag)],
235 GroupTags => { qw(Products product flags flag) },
237 SuppressEmpty => undef,
240 my $code = $self->result_code($response->{Page});
241 $self->is_success($code eq '2000' || $code eq '90000' || $code eq '900P1');
243 $self->infuse($response,
244 result_code => 'Page',
245 error_message => 'Verbiage',
246 authorization => 'ApprovalCode',
247 avs_response => 'AVSResponseCode',
248 cvv2_response => 'CVV2ResponseCode',
250 receipt_number => 'ReceiptNumber',
251 sales_number => 'SalesOrderNumber',
256 cardholder => 'xxxName',
257 card_type => 'CardType',
258 total_amount => 'TotalAmount',
261 # Completely undocumented field that sometimes override <Verbiage>
262 $self->error_message($response->{Error}) if $response->{Error};
264 $self->card_type(CARD_TYPES->{$self->card_type});
266 $self->{products_raw} = $response->{Products};
274 croak "Missing required argument 'merchant_id'"
275 unless defined $self->{merchant_id};
277 my ($page, $response, %headers) =
284 xxxRequestMode => 'X',
285 xxxRequestData => $self->to_xml,
289 croak 'Error connecting to server' unless $page;
290 croak 'Server responded, but not in XML' unless $page =~ /^<\?xml/;
292 # The response is marked UTF-8, but it's really Latin-1. Sigh.
293 $page =~ s/^(<\?xml.*?) encoding="utf-8"/$1 encoding="iso-8859-1"/si;
295 $self->parse_response($page);
306 Business::OnlinePayment::InternetSecure - InternetSecure backend for Business::OnlinePayment
310 use Business::OnlinePayment;
312 $txn = new Business::OnlinePayment 'InternetSecure',
313 merchant_id => '0000';
316 action => 'Normal Authorization',
318 type => 'Visa', # Optional
319 card_number => '4111 1111 1111 1111',
320 exp_date => '2004-07',
321 cvv2 => '000', # Optional
323 name => "Fr\x{e9}d\x{e9}ric Bri\x{e8}re",
325 address => '123 Street',
326 city => 'Metropolis',
330 phone => '(555) 555-1212',
331 email => 'fbriere@fbriere.net',
336 description => 'Test transaction',
341 if ($txn->is_success) {
342 print "Card processed successfully: " . $tx->authorization . "\n";
344 print "Card was rejected: " . $tx->error_message . "\n";
349 C<Business::OnlinePayment::InternetSecure> is an implementation of
350 C<Business::OnlinePayment> that allows for processing online credit card
351 payments through InternetSecure.
353 See L<Business::OnlinePayment> for more information about the generic
354 Business::OnlinePayment interface.
358 Object creation is done via C<Business::OnlinePayment>; see its manpage for
359 details. The B<merchant_id> processor option is required, and corresponds
360 to the merchant ID assigned to you by InternetSecure.
364 =head2 Transaction setup and transmission
368 =item content( CONTENT )
370 Sets up the data prior to a transaction. CONTENT is an associative array
371 (hash), containing some of the following fields:
375 =item action (required)
377 What to do with the transaction. Only C<Normal Authorization> is supported
382 Transaction type, being one of the following:
390 =item - American Express
396 (This is actually ignored for the moment, and can be left blank or undefined.)
398 =item card_number (required)
400 Credit card number. Spaces are allowed, and will be automatically removed.
402 =item exp_date (required)
404 Credit card expiration date. Since C<Business::OnlinePayment> does not specify
405 any syntax, this module is rather lax regarding what it will accept. The
406 recommended syntax is C<YYYY-MM>, but forms such as C<MM/YYYY> or C<MMYY> are
411 Three- or four-digit verification code printed on the card. This can be left
412 blank or undefined, in which case no check will be performed. Whether or not a
413 transaction will be declined in case of a mismatch depends on the merchant
414 account configuration.
416 This number may be called Card Verification Value (CVV2), Card Validation
417 Code (CVC2) or Card Identification number (CID), depending on the card issuer.
421 A short description of the transaction. See L<"Products list syntax"> for
422 an alternate syntax that allows a list of products to be specified.
424 =item amount (usually required)
426 Total amount to be billed, excluding taxes if they are to be added separately
429 This field is required if B<description> is a string, but should be left
430 undefined if B<description> contains a list of products instead, as outlined
431 in L<"Products list syntax">.
435 Currency of all amounts for this order. This can currently be either
436 C<CAD> (default) or C<USD>.
440 Taxes to be added automatically to B<amount> by InternetSecure.
442 Available taxes are C<GST>, C<PST> and C<HST>. Multiple taxes can specified
443 by concatenating them with spaces, such as C<GST HST>.
445 =item name / company / address / city / state / zip / country / phone / email
447 Customer information. B<country> should be a two-letter code taken from ISO
454 Submit the transaction to InternetSecure.
458 =head2 Post-submission methods
464 Returns true if the transaction was submitted successfully.
468 Response code returned by InternetSecure.
470 =item error_message()
472 Text description of the response code. (Do not rely on this to check for
473 errors, as a description will also be returned for successful transactions.
474 Use B<is_success>() instead.)
476 =item receipt_number()
478 Receipt number (a string, actually) of this transaction, unique to all
479 InternetSecure transactions.
483 Sales order number of this transaction. This is a number, unique to each
484 merchant, which is incremented by 1 each time.
488 Universally Unique Identifier associated to this transaction. This is a
489 128-bit value returned as a 36-character string such as
490 C<f81d4fae-7dec-11d0-a765-00a0c91e6bf6>. See RFC 4122 for more details on
493 B<guid>() is provided as an alias to this method.
495 =item authorization()
497 Authorization code for this transaction.
499 =item avs_response() / cvv2_response()
501 Results of the AVS and CVV2 checks. See the InternetSecure documentation for
502 the list of possible values.
506 Date and time of the transaction. Format is C<YYYY/MM/DD hh:mm:ss>.
510 Total amount billed for this order, including taxes.
514 Cardholder's name. This is currently a mere copy of the B<name> field passed
519 Type of the credit card used for the submitted order, being one of the
528 =item - American Express
544 =head2 Products list syntax
546 Optionally, the B<description> field of B<content>() can contain a reference
547 to an array of products, instead of a simple string. Each element of this
548 array represents a different product, and must be a reference to a hash with
549 the following fields:
555 Unit price of this product.
559 Ordered quantity of this product.
563 Internal code for this product.
567 Description of this product
571 Taxes that should be automatically added to this product. If specified, this
572 overrides the B<taxes> field passed to B<content>().
576 When using a products list, the B<amount> field passed to B<content>() should
580 =head2 Character encoding
582 Since communication to/from InternetSecure is encoded with UTF-8, all Unicode
583 characters are theoretically available when submitting information via
584 B<submit>(). (Further restrictions may be imposed by InternetSecure itself.)
586 When using non-ASCII characters, all data provided to B<submit>() should either
587 be in the current native encoding (typically latin-1, unless it was modified
588 via the C<encoding> pragma), or be decoded via the C<Encode> module.
589 Conversely, all data returned after calling B<submit>() will be automatically
600 L<Business::OnlinePayment>
604 Frédéric Brière, E<lt>fbriere@fbriere.netE<gt>
606 =head1 COPYRIGHT AND LICENSE
608 Copyright (C) 2006 by Frédéric Brière
610 This library is free software; you can redistribute it and/or modify
611 it under the same terms as Perl itself, either Perl version 5.8.4 or,
612 at your option, any later version of Perl 5 you may have available.