7ddaff25859ecd57b96758938521968009dbaf0f
[freeside.git] / FS / FS / pay_batch / paymentech.pm
1 package FS::pay_batch::paymentech;
2
3 use strict;
4 use vars qw(@ISA %import_info %export_info $name);
5 use FS::Record 'qsearchs';
6 use Time::Local;
7 use Date::Format 'time2str';
8 use Date::Parse 'str2time';
9 use Tie::IxHash;
10 use FS::Conf;
11 use FS::Misc 'bytes_substr';
12
13 my $conf;
14 my ($bin, $merchantID, $terminalID, $username, $password, $with_recurringInd);
15 $name = 'paymentech';
16
17 my $gateway;
18
19 %import_info = (
20   filetype    => 'XML',
21   xmlrow         => [ qw(transResponse newOrderResp) ],
22   fields      => [
23     'paybatchnum',
24     '_date',
25     'approvalStatus',
26     'order_number',
27     'auth',
28     'procStatus',
29     'procStatusMessage',
30     'respCodeMessage',
31     ],
32   xmlkeys     => [
33     'orderID',
34     'respDateTime',
35     'approvalStatus',
36     'txRefNum',
37     'authorizationCode',
38     'procStatus',
39     'procStatusMessage',
40     'respCodeMessage',
41     ],
42   'hook'        => sub {
43       if ( !$gateway ) {
44         # find a gateway configuration that has the same merchantID 
45         # as the batch config, if there is one.  If not, leave 
46         # gateway out entirely.
47         my $merchant = (FS::Conf->new->config('batchconfig-paymentech'))[2];
48         $gateway = qsearchs({
49               'table'     => 'payment_gateway',
50               'addl_from' => ' JOIN payment_gateway_option USING (gatewaynum) ',
51               'hashref'   => {  disabled    => '',
52                                 optionname  => 'merchant_id',
53                                 optionvalue => $merchant,
54                               },
55               });
56       }
57       my ($hash, $oldhash) = @_;
58       $hash->{'gatewaynum'} = $gateway->gatewaynum if $gateway;
59       $hash->{'processor'} = 'PaymenTech';
60       my ($mon, $day, $year, $hour, $min, $sec) = 
61         $hash->{'_date'} =~ /^(..)(..)(....)(..)(..)(..)$/;
62       $hash->{'_date'} = timelocal($sec, $min, $hour, $day, $mon-1, $year);
63       $hash->{'paid'} = $oldhash->{'amount'};
64       if ( $hash->{'procStatus'} == 0 ) {
65         $hash->{'error_message'} = $hash->{'respCodeMessage'};
66       } else {
67         $hash->{'error_message'} = $hash->{'procStatusMessage'};
68       }
69     },
70   'approved'    => sub { shift->{'approvalStatus'} == 1 },
71   'declined'    => sub { shift->{'approvalStatus'} != 1 },
72 );
73
74 my %paytype = (
75   'personal checking' => 'C',
76   'personal savings'  => 'S',
77   'business checking' => 'X',
78   'business savings'  => 'X',
79 );
80
81 my %paymentech_countries = map { $_ => 1 } qw( US CA GB UK );
82
83 %export_info = (
84   init  => sub {
85 # Load this at run time
86     eval "use XML::Writer";
87     die $@ if $@;
88     my $conf = shift;
89     ($bin, $terminalID, $merchantID, $username, $password, $with_recurringInd) =
90        $conf->config('batchconfig-paymentech');
91     },
92 # Here we do all the work in the header function.
93   header => sub {
94     my $pay_batch = shift;
95     my @cust_pay_batch = @{(shift)};
96     my $count = 1;
97     my $output;
98     my $xml = XML::Writer->new(
99       OUTPUT => \$output,
100       DATA_MODE => 1,
101       DATA_INDENT => 2,
102       ENCODING => 'utf-8'
103     );
104     $xml->xmlDecl(); # it is in the spec
105     $xml->startTag('transRequest', RequestCount => scalar(@cust_pay_batch) + 1);
106     $xml->startTag('batchFileID');
107     $xml->dataElement(userID => $username);
108     $xml->dataElement(fileDateTime => time2str('%Y%m%d%H%M%S', time));
109     $xml->dataElement(fileID => 'FILEID');
110     $xml->endTag('batchFileID');
111
112     foreach (@cust_pay_batch) {
113       $xml->startTag('newOrder', BatchRequestNo => $count++);
114       my $status = $_->cust_main->status;
115       tie my %order, 'Tie::IxHash', (
116         industryType    => 'EC',
117         transType       => 'AC',
118         bin             => $bin,
119         merchantID      => $merchantID,
120         terminalID      => $terminalID,
121         ($_->payby eq 'CARD') ? (
122           ccAccountNum    => $_->payinfo,
123           ccExp           => $_->expmmyy,
124         ) : (
125           ecpCheckRT      => ($_->payinfo =~ /@(\d+)/),
126           ecpCheckDDA     => ($_->payinfo =~ /(\d+)@/),
127           ecpBankAcctType => $paytype{lc($_->cust_main->paytype)},
128           ecpDelvMethod   => 'A',
129         ),
130         avsZip          => bytes_substr($_->zip,      0, 10),
131         avsAddress1     => bytes_substr($_->address1, 0, 30),
132         avsAddress2     => bytes_substr($_->address2, 0, 30),
133         avsCity         => bytes_substr($_->city,     0, 20),
134         avsState        => bytes_substr($_->state,    0, 2),
135         avsName         => bytes_substr($_->first. ' '. $_->last, 0, 30),
136         ( $paymentech_countries{ $_->country }
137           ? ( avsCountryCode  => $_->country )
138           : ()
139         ),
140         orderID           => $_->paybatchnum,
141         amount            => $_->amount * 100,
142         );
143       # only do this if recurringInd is enabled in config, 
144       # and the customer has at least one non-canceled recurring package
145       if ( $with_recurringInd and $status =~ /^active|suspended|ordered$/ ) {
146         # then send RF if this is the first payment on this payinfo,
147         # RS otherwise.
148         $order{'recurringInd'} = $_->payinfo_used ? 'RS' : 'RF';
149       }
150       foreach my $key (keys %order) {
151         $xml->dataElement($key, $order{$key})
152       }
153       $xml->endTag('newOrder');
154     }
155     $xml->startTag('endOfDay', BatchRequestNo => $count);
156     $xml->dataElement(bin => $bin);
157     $xml->dataElement(merchantID => $merchantID);
158     $xml->dataElement(terminalID => $terminalID);
159     $xml->endTag('endOfDay');
160     $xml->endTag('transRequest');
161     return $output;
162   },
163   row => sub {},
164 );
165
166 # Including this means that there is a Business::BatchPayment module for
167 # this gateway and we want to upgrade it.
168 # Must return the name of the module, followed by a hash of options.
169
170 sub _upgrade_gateway {
171   my $conf = FS::Conf->new;
172   my @batchconfig = $conf->config('batchconfig-paymentech');
173   my %options;
174   @options{ qw(
175     bin
176     terminalID
177     merchantID
178     login
179     password
180     with_recurringInd
181   ) } = @batchconfig;
182   $options{'industryType'} = 'EC';
183   ( 'Paymentech', %options );
184 }
185
186 1;