71513: Card tokenization [upgrade implemented]
[freeside.git] / FS / FS / cust_main / Billing_Realtime.pm
1 package FS::cust_main::Billing_Realtime;
2
3 use strict;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
6 use Carp;
7 use Data::Dumper;
8 use Business::CreditCard 0.35;
9 use FS::UID qw( dbh myconnect );
10 use FS::Record qw( qsearch qsearchs );
11 use FS::payby;
12 use FS::cust_pay;
13 use FS::cust_pay_pending;
14 use FS::cust_bill_pay;
15 use FS::cust_refund;
16 use FS::banned_pay;
17 use FS::payment_gateway;
18
19 $realtime_bop_decline_quiet = 0;
20
21 # 1 is mostly method/subroutine entry and options
22 # 2 traces progress of some operations
23 # 3 is even more information including possibly sensitive data
24 $DEBUG = 0;
25 $me = '[FS::cust_main::Billing_Realtime]';
26
27 our $BOP_TESTING = 0;
28 our $BOP_TESTING_SUCCESS = 1;
29
30 install_callback FS::UID sub { 
31   $conf = new FS::Conf;
32   #yes, need it for stuff below (prolly should be cached)
33 };
34
35 =head1 NAME
36
37 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
38
39 =head1 SYNOPSIS
40
41 =head1 DESCRIPTION
42
43 These methods are available on FS::cust_main objects.
44
45 =head1 METHODS
46
47 =over 4
48
49 =item realtime_cust_payby
50
51 =cut
52
53 sub realtime_cust_payby {
54   my( $self, %options ) = @_;
55
56   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
57
58   $options{amount} = $self->balance unless exists( $options{amount} );
59
60   my @cust_payby = $self->cust_payby('CARD','CHEK');
61                                                    
62   my $error;
63   foreach my $cust_payby (@cust_payby) {
64     $error = $cust_payby->realtime_bop( %options, );
65     last unless $error;
66   }
67
68   #XXX what about the earlier errors?
69
70   $error;
71
72 }
73
74 =item realtime_collect [ OPTION => VALUE ... ]
75
76 Attempt to collect the customer's current balance with a realtime credit 
77 card or electronic check transaction (see realtime_bop() below).
78
79 Returns the result of realtime_bop(): nothing, an error message, or a 
80 hashref of state information for a third-party transaction.
81
82 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
83
84 I<method> is one of: I<CC> or I<ECHECK>.  If none is specified
85 then it is deduced from the customer record.
86
87 If no I<amount> is specified, then the customer balance is used.
88
89 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
90 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
91 if set, will override the value from the customer record.
92
93 I<description> is a free-text field passed to the gateway.  It defaults to
94 the value defined by the business-onlinepayment-description configuration
95 option, or "Internet services" if that is unset.
96
97 If an I<invnum> is specified, this payment (if successful) is applied to the
98 specified invoice.
99
100 I<apply> will automatically apply a resulting payment.
101
102 I<quiet> can be set true to suppress email decline notices.
103
104 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
105 resulting paynum, if any.
106
107 I<payunique> is a unique identifier for this payment.
108
109 I<session_id> is a session identifier associated with this payment.
110
111 I<depend_jobnum> allows payment capture to unlock export jobs
112
113 =cut
114
115 # Currently only used by ClientAPI
116 # NOT 4.x COMPATIBLE (see below)
117 sub realtime_collect {
118   my( $self, %options ) = @_;
119
120   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
121
122   if ( $DEBUG ) {
123     warn "$me realtime_collect:\n";
124     warn "  $_ => $options{$_}\n" foreach keys %options;
125   }
126
127   $options{amount} = $self->balance unless exists( $options{amount} );
128   return '' unless $options{amount} > 0;
129
130   #### NOT 4.x COMPATIBLE
131   $options{method} = FS::payby->payby2bop($self->payby)
132     unless exists( $options{method} );
133
134   return $self->realtime_bop({%options});
135
136 }
137
138 =item realtime_bop { [ ARG => VALUE ... ] }
139
140 Runs a realtime credit card or ACH (electronic check) transaction
141 via a Business::OnlinePayment realtime gateway.  See
142 L<http://420.am/business-onlinepayment> for supported gateways.
143
144 Required arguments in the hashref are I<amount> and either
145 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
146 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
147
148 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
149
150 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
151
152 I<description> is a free-text field passed to the gateway.  It defaults to
153 the value defined by the business-onlinepayment-description configuration
154 option, or "Internet services" if that is unset.
155
156 If an I<invnum> is specified, this payment (if successful) is applied to the
157 specified invoice.  If the customer has exactly one open invoice, that 
158 invoice number will be assumed.  If you don't specify an I<invnum> you might 
159 want to call the B<apply_payments> method or set the I<apply> option.
160
161 I<no_invnum> can be set to true to prevent that default invnum from being set.
162
163 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
164
165 I<no_auto_apply> can be set to true to set that flag on the resulting payment
166 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
167 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
168
169 I<quiet> can be set true to surpress email decline notices.
170
171 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
172 resulting paynum, if any.
173
174 I<payunique> is a unique identifier for this payment.
175
176 I<session_id> is a session identifier associated with this payment.
177
178 I<depend_jobnum> allows payment capture to unlock export jobs
179
180 I<discount_term> attempts to take a discount by prepaying for discount_term.
181 The payment will fail if I<amount> is incorrect for this discount term.
182
183 A direct (Business::OnlinePayment) transaction will return nothing on success,
184 or an error message on failure.
185
186 A third-party transaction will return a hashref containing:
187
188 - popup_url: the URL to which a browser should be redirected to complete 
189   the transaction.
190 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
191 - reference: a reference ID for the transaction, to show the customer.
192
193 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
194
195 =cut
196
197 # some helper routines
198 #
199 # _bop_recurring_billing: Checks whether this payment should have the 
200 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
201 # vSecure, etc.). This works in two different modes:
202 # - actual_oncard (default): treat the payment as recurring if the customer
203 #   has made a payment using this card before.
204 # - transaction_is_recur: treat the payment as recurring if the invoice
205 #   being paid has any recurring package charges.
206
207 sub _bop_recurring_billing {
208   my( $self, %opt ) = @_;
209
210   my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
211
212   if ( defined($method) && $method eq 'transaction_is_recur' ) {
213
214     return 1 if $opt{'trans_is_recur'};
215
216   } else {
217
218     # return 1 if the payinfo has been used for another payment
219     return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
220
221   }
222
223   return 0;
224
225 }
226
227 #can run safely as class method if opt payment_gateway already exists
228 sub _payment_gateway {
229   my ($self, $options) = @_;
230
231   if ( $options->{'fake_gatewaynum'} ) {
232         $options->{payment_gateway} =
233             qsearchs('payment_gateway',
234                       { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
235                     );
236   }
237
238   $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
239     unless exists($options->{payment_gateway});
240
241   $options->{payment_gateway};
242 }
243
244 # not a method!!!
245 sub _bop_auth {
246   my ($options) = @_;
247
248   (
249     'login'    => $options->{payment_gateway}->gateway_username,
250     'password' => $options->{payment_gateway}->gateway_password,
251   );
252 }
253
254 ### not a method!
255 sub _bop_options {
256   my ($options) = @_;
257
258   $options->{payment_gateway}->gatewaynum
259     ? $options->{payment_gateway}->options
260     : @{ $options->{payment_gateway}->get('options') };
261
262 }
263
264 sub _bop_defaults {
265   my ($self, $options) = @_;
266
267   unless ( $options->{'description'} ) {
268     if ( $conf->exists('business-onlinepayment-description') ) {
269       my $dtempl = $conf->config('business-onlinepayment-description');
270
271       my $agent = $self->agent->agent;
272       #$pkgs... not here
273       $options->{'description'} = eval qq("$dtempl");
274     } else {
275       $options->{'description'} = 'Internet services';
276     }
277   }
278
279   # Default invoice number if the customer has exactly one open invoice.
280   unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
281     $options->{'invnum'} = '';
282     my @open = $self->open_cust_bill;
283     $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
284   }
285
286 }
287
288 # not a method!
289 sub _bop_cust_payby_options {
290   my ($options) = @_;
291   my $cust_payby = $options->{'cust_payby'};
292   if ($cust_payby) {
293
294     $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
295
296     if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
297       # false laziness with cust_payby->check
298       #   which might not have been run yet
299       my( $m, $y );
300       if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
301         ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
302       } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
303         ( $m, $y ) = ( $2, "19$1" );
304       } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
305         ( $m, $y ) = ( $3, "20$2" );
306       } else {
307         return "Illegal expiration date: ". $cust_payby->paydate;
308       }
309       $m = sprintf('%02d',$m);
310       $options->{paydate} = "$y-$m-01";
311     } else {
312       $options->{paydate} = '';
313     }
314
315     $options->{$_} = $cust_payby->$_() 
316       for qw( payinfo paycvv paymask paystart_month paystart_year 
317               payissue payname paystate paytype payip );
318
319     if ( $cust_payby->locationnum ) {
320       my $cust_location = $cust_payby->cust_location;
321       $options->{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
322     }
323   }
324 }
325
326 # can be called as class method,
327 # but can't load default name/phone fields as class method
328 sub _bop_content {
329   my ($self, $options) = @_;
330   my %content = ();
331
332   my $payip = $options->{'payip'};
333   $content{customer_ip} = $payip if length($payip);
334
335   $content{invoice_number} = $options->{'invnum'}
336     if exists($options->{'invnum'}) && length($options->{'invnum'});
337
338   $content{email_customer} = 
339     (    $conf->exists('business-onlinepayment-email_customer')
340       || $conf->exists('business-onlinepayment-email-override') );
341       
342   my ($payname, $payfirst, $paylast);
343   if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
344     ($payname = $options->{payname}) =~
345       /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
346       or return "Illegal payname $payname";
347     ($payfirst, $paylast) = ($1, $2);
348   } elsif (ref($self)) { # can't set payname if called as class method
349     $payfirst = $self->getfield('first');
350     $paylast = $self->getfield('last');
351     $payname = "$payfirst $paylast";
352   }
353
354   $content{last_name} = $paylast if $paylast;
355   $content{first_name} = $payfirst if $payfirst;
356
357   $content{name} = $payname if $payname;
358
359   $content{address} = $options->{'address1'};
360   my $address2 = $options->{'address2'};
361   $content{address} .= ", ". $address2 if length($address2);
362
363   $content{city} = $options->{'city'};
364   $content{state} = $options->{'state'};
365   $content{zip} = $options->{'zip'};
366   $content{country} = $options->{'country'};
367
368   # can't set phone if called as class method
369   $content{phone} = $self->daytime || $self->night
370     if ref($self);
371
372   my $currency =    $conf->exists('business-onlinepayment-currency')
373                  && $conf->config('business-onlinepayment-currency');
374   $content{currency} = $currency if $currency;
375
376   \%content;
377 }
378
379 # updates payinfo and cust_payby options with token from transaction
380 # can be called as a class method
381 sub _tokenize_card {
382   my ($self,$transaction,$options) = @_;
383   if ( $transaction->can('card_token') 
384        and $transaction->card_token 
385        and !$self->tokenized($options->{'payinfo'})
386   ) {
387     $options->{'payinfo'} = $transaction->card_token;
388     $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
389     return $transaction->card_token;
390   }
391   return '';
392 }
393
394 my %bop_method2payby = (
395   'CC'     => 'CARD',
396   'ECHECK' => 'CHEK',
397   'PAYPAL' => 'PPAL',
398 );
399
400 sub realtime_bop {
401   my $self = shift;
402
403   confess "Can't call realtime_bop within another transaction ".
404           '($FS::UID::AutoCommit is false)'
405     unless $FS::UID::AutoCommit;
406
407   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
408
409   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
410  
411   my %options = ();
412   if (ref($_[0]) eq 'HASH') {
413     %options = %{$_[0]};
414   } else {
415     my ( $method, $amount ) = ( shift, shift );
416     %options = @_;
417     $options{method} = $method;
418     $options{amount} = $amount;
419   }
420
421   # set fields from passed cust_payby
422   _bop_cust_payby_options(\%options);
423
424   # possibly run a separate transaction to tokenize card number,
425   #   so that we never store tokenized card info in cust_pay_pending
426   if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
427     my $token_error = $self->realtime_tokenize(\%options);
428     return $token_error if $token_error;
429     # in theory, all cust_payby will be tokenized during original save,
430     # so we shouldn't get here with opt cust_payby...but just in case...
431     if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
432       $token_error = $options{'cust_payby'}->replace;
433       return $token_error if $token_error;
434     }
435     return "Cannot tokenize card info"
436       if $conf->exists('no_saved_cardnumbers') && !$self->tokenized($options{'payinfo'});
437   }
438
439   ### 
440   # optional credit card surcharge
441   ###
442
443   my $cc_surcharge = 0;
444   my $cc_surcharge_pct = 0;
445   $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum) 
446     if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
447     && $options{method} eq 'CC';
448
449   # always add cc surcharge if called from event 
450   if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
451       $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
452       $options{'amount'} += $cc_surcharge;
453       $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
454   }
455   elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a 
456                                  # payment screen), so consider the given 
457                                  # amount as post-surcharge
458     $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
459   }
460   
461   $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
462   $options{'cc_surcharge'} = $cc_surcharge;
463
464
465   if ( $DEBUG ) {
466     warn "$me realtime_bop (new): $options{method} $options{amount}\n";
467     warn " cc_surcharge = $cc_surcharge\n";
468   }
469   if ( $DEBUG > 2 ) {
470     warn "  $_ => $options{$_}\n" foreach keys %options;
471   }
472
473   return $self->fake_bop(\%options) if $options{'fake'};
474
475   $self->_bop_defaults(\%options);
476
477   return "Missing payinfo"
478     unless $options{'payinfo'};
479
480   ###
481   # set trans_is_recur based on invnum if there is one
482   ###
483
484   my $trans_is_recur = 0;
485   if ( $options{'invnum'} ) {
486
487     my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
488     die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
489
490     my @part_pkg =
491       map  { $_->part_pkg }
492       grep { $_ }
493       map  { $_->cust_pkg }
494       $cust_bill->cust_bill_pkg;
495
496     $trans_is_recur = 1
497       if grep { $_->freq ne '0' } @part_pkg;
498
499   }
500
501   ###
502   # select a gateway
503   ###
504
505   my $payment_gateway =  $self->_payment_gateway( \%options );
506   my $namespace = $payment_gateway->gateway_namespace;
507
508   eval "use $namespace";  
509   die $@ if $@;
510
511   ###
512   # check for banned credit card/ACH
513   ###
514
515   my $ban = FS::banned_pay->ban_search(
516     'payby'   => $bop_method2payby{$options{method}},
517     'payinfo' => $options{payinfo},
518   );
519   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
520
521   ###
522   # check for term discount validity
523   ###
524
525   my $discount_term = $options{discount_term};
526   if ( $discount_term ) {
527     my $bill = ($self->cust_bill)[-1]
528       or return "Can't apply a term discount to an unbilled customer";
529     my $plan = FS::discount_plan->new(
530       cust_bill => $bill,
531       months    => $discount_term
532     ) or return "No discount available for term '$discount_term'";
533     
534     if ( $plan->discounted_total != $options{amount} ) {
535       return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
536     }
537   }
538
539   ###
540   # massage data
541   ###
542
543   my $bop_content = $self->_bop_content(\%options);
544   return $bop_content unless ref($bop_content);
545
546   my @invoicing_list = $self->invoicing_list_emailonly;
547   if ( $conf->exists('emailinvoiceautoalways')
548        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
549        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
550     push @invoicing_list, $self->all_emails;
551   }
552
553   my $email = ($conf->exists('business-onlinepayment-email-override'))
554               ? $conf->config('business-onlinepayment-email-override')
555               : $invoicing_list[0];
556
557   my $paydate = '';
558   my %content = ();
559
560   if ( $namespace eq 'Business::OnlinePayment' ) {
561
562     if ( $options{method} eq 'CC' ) {
563
564       $content{card_number} = $options{payinfo};
565       $paydate = $options{'paydate'};
566       $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
567       $content{expiration} = "$2/$1";
568
569       $content{cvv2} = $options{'paycvv'}
570         if length($options{'paycvv'});
571
572       my $paystart_month = $options{'paystart_month'};
573       my $paystart_year  = $options{'paystart_year'};
574       $content{card_start} = "$paystart_month/$paystart_year"
575         if $paystart_month && $paystart_year;
576
577       my $payissue       = $options{'payissue'};
578       $content{issue_number} = $payissue if $payissue;
579
580       if ( $self->_bop_recurring_billing(
581              'payinfo'        => $options{'payinfo'},
582              'trans_is_recur' => $trans_is_recur,
583            )
584          )
585       {
586         $content{recurring_billing} = 'YES';
587         $content{acct_code} = 'rebill'
588           if $conf->exists('credit_card-recurring_billing_acct_code');
589       }
590
591     } elsif ( $options{method} eq 'ECHECK' ){
592
593       ( $content{account_number}, $content{routing_code} ) =
594         split('@', $options{payinfo});
595       $content{bank_name} = $options{payname};
596       $content{bank_state} = $options{'paystate'};
597       $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
598
599       $content{company} = $self->company if $self->company;
600
601       if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
602         $content{account_name} = $self->company;
603       } else {
604         $content{account_name} = $self->getfield('first'). ' '.
605                                  $self->getfield('last');
606       }
607
608       $content{customer_org} = $self->company ? 'B' : 'I';
609       $content{state_id}       = exists($options{'stateid'})
610                                    ? $options{'stateid'}
611                                    : $self->getfield('stateid');
612       $content{state_id_state} = exists($options{'stateid_state'})
613                                    ? $options{'stateid_state'}
614                                    : $self->getfield('stateid_state');
615       $content{customer_ssn} = exists($options{'ss'})
616                                  ? $options{'ss'}
617                                  : $self->ss;
618
619     } else {
620       die "unknown method ". $options{method};
621     }
622
623   } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
624     #move along
625   } else {
626     die "unknown namespace $namespace";
627   }
628
629   ###
630   # run transaction(s)
631   ###
632
633   my $balance = exists( $options{'balance'} )
634                   ? $options{'balance'}
635                   : $self->balance;
636
637   warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
638   $self->select_for_update; #mutex ... just until we get our pending record in
639   warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
640
641   #the checks here are intended to catch concurrent payments
642   #double-form-submission prevention is taken care of in cust_pay_pending::check
643
644   #check the balance
645   return "The customer's balance has changed; $options{method} transaction aborted."
646     if $self->balance < $balance;
647
648   #also check and make sure there aren't *other* pending payments for this cust
649
650   my @pending = qsearch('cust_pay_pending', {
651     'custnum' => $self->custnum,
652     'status'  => { op=>'!=', value=>'done' } 
653   });
654
655   #for third-party payments only, remove pending payments if they're in the 
656   #'thirdparty' (waiting for customer action) state.
657   if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
658     foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
659       my $error = $_->delete;
660       warn "error deleting unfinished third-party payment ".
661           $_->paypendingnum . ": $error\n"
662         if $error;
663     }
664     @pending = grep { $_->status ne 'thirdparty' } @pending;
665   }
666
667   return "A payment is already being processed for this customer (".
668          join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
669          "); $options{method} transaction aborted."
670     if scalar(@pending);
671
672   #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
673
674   my $cust_pay_pending = new FS::cust_pay_pending {
675     'custnum'           => $self->custnum,
676     'paid'              => $options{amount},
677     '_date'             => '',
678     'payby'             => $bop_method2payby{$options{method}},
679     'payinfo'           => $options{payinfo},
680     'paymask'           => $options{paymask},
681     'paydate'           => $paydate,
682     'recurring_billing' => $content{recurring_billing},
683     'pkgnum'            => $options{'pkgnum'},
684     'status'            => 'new',
685     'gatewaynum'        => $payment_gateway->gatewaynum || '',
686     'session_id'        => $options{session_id} || '',
687     'jobnum'            => $options{depend_jobnum} || '',
688   };
689   $cust_pay_pending->payunique( $options{payunique} )
690     if defined($options{payunique}) && length($options{payunique});
691
692   warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
693     if $DEBUG > 1;
694   my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
695   return $cpp_new_err if $cpp_new_err;
696
697   warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
698     if $DEBUG > 1;
699   warn Dumper($cust_pay_pending) if $DEBUG > 2;
700
701   my( $action1, $action2 ) =
702     split( /\s*\,\s*/, $payment_gateway->gateway_action );
703
704   my $transaction = new $namespace( $payment_gateway->gateway_module,
705                                     _bop_options(\%options),
706                                   );
707
708   $transaction->content(
709     'type'           => $options{method},
710     _bop_auth(\%options),          
711     'action'         => $action1,
712     'description'    => $options{'description'},
713     'amount'         => $options{amount},
714     #'invoice_number' => $options{'invnum'},
715     'customer_id'    => $self->custnum,
716     %$bop_content,
717     'reference'      => $cust_pay_pending->paypendingnum, #for now
718     'callback_url'   => $payment_gateway->gateway_callback_url,
719     'cancel_url'     => $payment_gateway->gateway_cancel_url,
720     'email'          => $email,
721     %content, #after
722   );
723
724   $cust_pay_pending->status('pending');
725   my $cpp_pending_err = $cust_pay_pending->replace;
726   return $cpp_pending_err if $cpp_pending_err;
727
728   warn Dumper($transaction) if $DEBUG > 2;
729
730   unless ( $BOP_TESTING ) {
731     $transaction->test_transaction(1)
732       if $conf->exists('business-onlinepayment-test_transaction');
733     $transaction->submit();
734   } else {
735     if ( $BOP_TESTING_SUCCESS ) {
736       $transaction->is_success(1);
737       $transaction->authorization('fake auth');
738     } else {
739       $transaction->is_success(0);
740       $transaction->error_message('fake failure');
741     }
742   }
743
744   if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
745
746     $cust_pay_pending->status('thirdparty');
747     my $cpp_err = $cust_pay_pending->replace;
748     return { error => $cpp_err } if $cpp_err;
749     return { reference => $cust_pay_pending->paypendingnum,
750              map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
751
752   } elsif ( $transaction->is_success() && $action2 ) {
753
754     $cust_pay_pending->status('authorized');
755     my $cpp_authorized_err = $cust_pay_pending->replace;
756     return $cpp_authorized_err if $cpp_authorized_err;
757
758     my $auth = $transaction->authorization;
759     my $ordernum = $transaction->can('order_number')
760                    ? $transaction->order_number
761                    : '';
762
763     my $capture =
764       new Business::OnlinePayment( $payment_gateway->gateway_module,
765                                    _bop_options(\%options),
766                                  );
767
768     my %capture = (
769       %content,
770       type           => $options{method},
771       action         => $action2,
772       _bop_auth(\%options),          
773       order_number   => $ordernum,
774       amount         => $options{amount},
775       authorization  => $auth,
776       description    => $options{'description'},
777     );
778
779     foreach my $field (qw( authorization_source_code returned_ACI
780                            transaction_identifier validation_code           
781                            transaction_sequence_num local_transaction_date    
782                            local_transaction_time AVS_result_code          )) {
783       $capture{$field} = $transaction->$field() if $transaction->can($field);
784     }
785
786     $capture->content( %capture );
787
788     $capture->test_transaction(1)
789       if $conf->exists('business-onlinepayment-test_transaction');
790     $capture->submit();
791
792     unless ( $capture->is_success ) {
793       my $e = "Authorization successful but capture failed, custnum #".
794               $self->custnum. ': '.  $capture->result_code.
795               ": ". $capture->error_message;
796       warn $e;
797       return $e;
798     }
799
800   }
801
802   ###
803   # remove paycvv after initial transaction
804   ###
805
806   # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
807   if ( length($options{'paycvv'})
808        && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
809   ) {
810     my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
811     if ( $error ) {
812       $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
813       #not returning error, should at least attempt to handle results of an otherwise valid transaction
814       warn "WARNING: error removing cvv: $error\n";
815     }
816   }
817
818   ###
819   # Tokenize
820   ###
821
822   # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
823   #   if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
824   if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
825     # cpp will be replaced in _realtime_bop_result
826     $cust_pay_pending->payinfo($card_token);
827     if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
828       $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
829       #not returning error, should at least attempt to handle results of an otherwise valid transaction
830       #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
831     }
832   }
833
834   ###
835   # result handling
836   ###
837
838   $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
839
840 }
841
842 =item fake_bop
843
844 =cut
845
846 sub fake_bop {
847   my $self = shift;
848
849   my %options = ();
850   if (ref($_[0]) eq 'HASH') {
851     %options = %{$_[0]};
852   } else {
853     my ( $method, $amount ) = ( shift, shift );
854     %options = @_;
855     $options{method} = $method;
856     $options{amount} = $amount;
857   }
858   
859   if ( $options{'fake_failure'} ) {
860      return "Error: No error; test failure requested with fake_failure";
861   }
862
863   my $cust_pay = new FS::cust_pay ( {
864      'custnum'  => $self->custnum,
865      'invnum'   => $options{'invnum'},
866      'paid'     => $options{amount},
867      '_date'    => '',
868      'payby'    => $bop_method2payby{$options{method}},
869      'payinfo'  => '4111111111111111',
870      'paydate'  => '2012-05-01',
871      'processor'      => 'FakeProcessor',
872      'auth'           => '54',
873      'order_number'   => '32',
874   } );
875   $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
876
877   if ( $DEBUG ) {
878       warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
879       warn "  $_ => $options{$_}\n" foreach keys %options;
880   }
881
882   my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
883
884   if ( $error ) {
885     $cust_pay->invnum(''); #try again with no specific invnum
886     my $error2 = $cust_pay->insert( $options{'manual'} ?
887                                     ( 'manual' => 1 ) : ()
888                                   );
889     if ( $error2 ) {
890       # gah, even with transactions.
891       my $e = 'WARNING: Card/ACH debited but database not updated - '.
892               "error inserting (fake!) payment: $error2".
893               " (previously tried insert with invnum #$options{'invnum'}" .
894               ": $error )";
895       warn $e;
896       return $e;
897     }
898   }
899
900   if ( $options{'paynum_ref'} ) {
901     ${ $options{'paynum_ref'} } = $cust_pay->paynum;
902   }
903
904   return ''; #no error
905
906 }
907
908
909 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
910
911 # Wraps up processing of a realtime credit card or ACH (electronic check)
912 # transaction.
913
914 sub _realtime_bop_result {
915   my( $self, $cust_pay_pending, $transaction, %options ) = @_;
916
917   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
918
919   if ( $DEBUG ) {
920     warn "$me _realtime_bop_result: pending transaction ".
921       $cust_pay_pending->paypendingnum. "\n";
922     warn "  $_ => $options{$_}\n" foreach keys %options;
923   }
924
925   my $payment_gateway = $options{payment_gateway}
926     or return "no payment gateway in arguments to _realtime_bop_result";
927
928   $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
929   my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
930   return $cpp_captured_err if $cpp_captured_err;
931
932   if ( $transaction->is_success() ) {
933
934     my $order_number = $transaction->order_number
935       if $transaction->can('order_number');
936
937     my $cust_pay = new FS::cust_pay ( {
938        'custnum'  => $self->custnum,
939        'invnum'   => $options{'invnum'},
940        'paid'     => $cust_pay_pending->paid,
941        '_date'    => '',
942        'payby'    => $cust_pay_pending->payby,
943        'payinfo'  => $options{'payinfo'},
944        'paymask'  => $options{'paymask'} || $cust_pay_pending->paymask,
945        'paydate'  => $cust_pay_pending->paydate,
946        'pkgnum'   => $cust_pay_pending->pkgnum,
947        'discount_term'  => $options{'discount_term'},
948        'gatewaynum'     => ($payment_gateway->gatewaynum || ''),
949        'processor'      => $payment_gateway->gateway_module,
950        'auth'           => $transaction->authorization,
951        'order_number'   => $order_number || '',
952        'no_auto_apply'  => $options{'no_auto_apply'} ? 'Y' : '',
953     } );
954     #doesn't hurt to know, even though the dup check is in cust_pay_pending now
955     $cust_pay->payunique( $options{payunique} )
956       if defined($options{payunique}) && length($options{payunique});
957
958     my $oldAutoCommit = $FS::UID::AutoCommit;
959     local $FS::UID::AutoCommit = 0;
960     my $dbh = dbh;
961
962     #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
963
964     my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
965
966     if ( $error ) {
967       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
968       $cust_pay->invnum(''); #try again with no specific invnum
969       $cust_pay->paynum('');
970       my $error2 = $cust_pay->insert( $options{'manual'} ?
971                                       ( 'manual' => 1 ) : ()
972                                     );
973       if ( $error2 ) {
974         # gah.  but at least we have a record of the state we had to abort in
975         # from cust_pay_pending now.
976         $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
977         my $e = "WARNING: $options{method} captured but payment not recorded -".
978                 " error inserting payment (". $payment_gateway->gateway_module.
979                 "): $error2".
980                 " (previously tried insert with invnum #$options{'invnum'}" .
981                 ": $error ) - pending payment saved as paypendingnum ".
982                 $cust_pay_pending->paypendingnum. "\n";
983         warn $e;
984         return $e;
985       }
986     }
987
988     my $jobnum = $cust_pay_pending->jobnum;
989     if ( $jobnum ) {
990        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
991       
992        unless ( $placeholder ) {
993          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
994          my $e = "WARNING: $options{method} captured but job $jobnum not ".
995              "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
996          warn $e;
997          return $e;
998        }
999
1000        $error = $placeholder->delete;
1001
1002        if ( $error ) {
1003          $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1004          my $e = "WARNING: $options{method} captured but could not delete ".
1005               "job $jobnum for paypendingnum ".
1006               $cust_pay_pending->paypendingnum. ": $error\n";
1007          warn $e;
1008          return $e;
1009        }
1010
1011        $cust_pay_pending->set('jobnum','');
1012
1013     }
1014     
1015     if ( $options{'paynum_ref'} ) {
1016       ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1017     }
1018
1019     $cust_pay_pending->status('done');
1020     $cust_pay_pending->statustext('captured');
1021     $cust_pay_pending->paynum($cust_pay->paynum);
1022     my $cpp_done_err = $cust_pay_pending->replace;
1023
1024     if ( $cpp_done_err ) {
1025
1026       $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1027       my $e = "WARNING: $options{method} captured but payment not recorded - ".
1028               "error updating status for paypendingnum ".
1029               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1030       warn $e;
1031       return $e;
1032
1033     } else {
1034
1035       $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1036
1037       if ( $options{'apply'} ) {
1038         my $apply_error = $self->apply_payments_and_credits;
1039         if ( $apply_error ) {
1040           warn "WARNING: error applying payment: $apply_error\n";
1041           #but we still should return no error cause the payment otherwise went
1042           #through...
1043         }
1044       }
1045
1046       # have a CC surcharge portion --> one-time charge
1047       if ( $options{'cc_surcharge'} > 0 ) { 
1048             # XXX: this whole block needs to be in a transaction?
1049
1050           my $invnum;
1051           $invnum = $options{'invnum'} if $options{'invnum'};
1052           unless ( $invnum ) { # probably from a payment screen
1053              # do we have any open invoices? pick earliest
1054              # uses the fact that cust_main->cust_bill sorts by date ascending
1055              my @open = $self->open_cust_bill;
1056              $invnum = $open[0]->invnum if scalar(@open);
1057           }
1058             
1059           unless ( $invnum ) {  # still nothing? pick last closed invoice
1060              # again uses fact that cust_main->cust_bill sorts by date ascending
1061              my @closed = $self->cust_bill;
1062              $invnum = $closed[$#closed]->invnum if scalar(@closed);
1063           }
1064
1065           unless ( $invnum ) {
1066             # XXX: unlikely case - pre-paying before any invoices generated
1067             # what it should do is create a new invoice and pick it
1068                 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1069                 return '';
1070           }
1071
1072           my $cust_pkg;
1073           my $charge_error = $self->charge({
1074                                     'amount'    => $options{'cc_surcharge'},
1075                                     'pkg'       => 'Credit Card Surcharge',
1076                                     'setuptax'  => 'Y',
1077                                     'cust_pkg_ref' => \$cust_pkg,
1078                                 });
1079           if($charge_error) {
1080                 warn 'Unable to add CC surcharge cust_pkg';
1081                 return '';
1082           }
1083
1084           $cust_pkg->setup(time);
1085           my $cp_error = $cust_pkg->replace;
1086           if($cp_error) {
1087               warn 'Unable to set setup time on cust_pkg for cc surcharge';
1088             # but keep going...
1089           }
1090                                     
1091           my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1092           unless ( $cust_bill ) {
1093               warn "race condition + invoice deletion just happened";
1094               return '';
1095           }
1096
1097           my $grand_error = 
1098             $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1099
1100           warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1101             if $grand_error;
1102       }
1103
1104       return ''; #no error
1105
1106     }
1107
1108   } else {
1109
1110     my $perror = $transaction->error_message;
1111     #$payment_gateway->gateway_module. " error: ".
1112     # removed for conciseness
1113
1114     my $jobnum = $cust_pay_pending->jobnum;
1115     if ( $jobnum ) {
1116        my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1117       
1118        if ( $placeholder ) {
1119          my $error = $placeholder->depended_delete;
1120          $error ||= $placeholder->delete;
1121          $cust_pay_pending->set('jobnum','');
1122          warn "error removing provisioning jobs after declined paypendingnum ".
1123            $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1124        } else {
1125          my $e = "error finding job $jobnum for declined paypendingnum ".
1126               $cust_pay_pending->paypendingnum. "\n";
1127          warn $e;
1128        }
1129
1130     }
1131     
1132     unless ( $transaction->error_message ) {
1133
1134       my $t_response;
1135       if ( $transaction->can('response_page') ) {
1136         $t_response = {
1137                         'page'    => ( $transaction->can('response_page')
1138                                          ? $transaction->response_page
1139                                          : ''
1140                                      ),
1141                         'code'    => ( $transaction->can('response_code')
1142                                          ? $transaction->response_code
1143                                          : ''
1144                                      ),
1145                         'headers' => ( $transaction->can('response_headers')
1146                                          ? $transaction->response_headers
1147                                          : ''
1148                                      ),
1149                       };
1150       } else {
1151         $t_response .=
1152           "No additional debugging information available for ".
1153             $payment_gateway->gateway_module;
1154       }
1155
1156       $perror .= "No error_message returned from ".
1157                    $payment_gateway->gateway_module. " -- ".
1158                  ( ref($t_response) ? Dumper($t_response) : $t_response );
1159
1160     }
1161
1162     if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1163          && $conf->exists('emaildecline', $self->agentnum)
1164          && grep { $_ ne 'POST' } $self->invoicing_list
1165          && ! grep { $transaction->error_message =~ /$_/ }
1166                    $conf->config('emaildecline-exclude', $self->agentnum)
1167     ) {
1168
1169       # Send a decline alert to the customer.
1170       my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1171       my $error = '';
1172       if ( $msgnum ) {
1173         # include the raw error message in the transaction state
1174         $cust_pay_pending->setfield('error', $transaction->error_message);
1175         my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1176         $error = $msg_template->send( 'cust_main' => $self,
1177                                       'object'    => $cust_pay_pending );
1178       }
1179
1180
1181       $perror .= " (also received error sending decline notification: $error)"
1182         if $error;
1183
1184     }
1185
1186     $cust_pay_pending->status('done');
1187     $cust_pay_pending->statustext($perror);
1188     #'declined:': no, that's failure_status
1189     if ( $transaction->can('failure_status') ) {
1190       $cust_pay_pending->failure_status( $transaction->failure_status );
1191     }
1192     my $cpp_done_err = $cust_pay_pending->replace;
1193     if ( $cpp_done_err ) {
1194       my $e = "WARNING: $options{method} declined but pending payment not ".
1195               "resolved - error updating status for paypendingnum ".
1196               $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1197       warn $e;
1198       $perror = "$e ($perror)";
1199     }
1200
1201     return $perror;
1202   }
1203
1204 }
1205
1206 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1207
1208 Verifies successful third party processing of a realtime credit card or
1209 ACH (electronic check) transaction via a
1210 Business::OnlineThirdPartyPayment realtime gateway.  See
1211 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1212
1213 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1214
1215 The additional options I<payname>, I<city>, I<state>,
1216 I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
1217 if set, will override the value from the customer record.
1218
1219 I<description> is a free-text field passed to the gateway.  It defaults to
1220 "Internet services".
1221
1222 If an I<invnum> is specified, this payment (if successful) is applied to the
1223 specified invoice.  If you don't specify an I<invnum> you might want to
1224 call the B<apply_payments> method.
1225
1226 I<quiet> can be set true to surpress email decline notices.
1227
1228 I<paynum_ref> can be set to a scalar reference.  It will be filled in with the
1229 resulting paynum, if any.
1230
1231 I<payunique> is a unique identifier for this payment.
1232
1233 Returns a hashref containing elements bill_error (which will be undefined
1234 upon success) and session_id of any associated session.
1235
1236 =cut
1237
1238 sub realtime_botpp_capture {
1239   my( $self, $cust_pay_pending, %options ) = @_;
1240
1241   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1242
1243   if ( $DEBUG ) {
1244     warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1245     warn "  $_ => $options{$_}\n" foreach keys %options;
1246   }
1247
1248   eval "use Business::OnlineThirdPartyPayment";  
1249   die $@ if $@;
1250
1251   ###
1252   # select the gateway
1253   ###
1254
1255   my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1256
1257   my $payment_gateway;
1258   my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1259   $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1260                 { gatewaynum => $gatewaynum }
1261               )
1262     : $self->agent->payment_gateway( 'method' => $method,
1263                                      # 'invnum'  => $cust_pay_pending->invnum,
1264                                      # 'payinfo' => $cust_pay_pending->payinfo,
1265                                    );
1266
1267   $options{payment_gateway} = $payment_gateway; # for the helper subs
1268
1269   ###
1270   # massage data
1271   ###
1272
1273   my @invoicing_list = $self->invoicing_list_emailonly;
1274   if ( $conf->exists('emailinvoiceautoalways')
1275        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1276        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1277     push @invoicing_list, $self->all_emails;
1278   }
1279
1280   my $email = ($conf->exists('business-onlinepayment-email-override'))
1281               ? $conf->config('business-onlinepayment-email-override')
1282               : $invoicing_list[0];
1283
1284   my %content = ();
1285
1286   $content{email_customer} = 
1287     (    $conf->exists('business-onlinepayment-email_customer')
1288       || $conf->exists('business-onlinepayment-email-override') );
1289       
1290   ###
1291   # run transaction(s)
1292   ###
1293
1294   my $transaction =
1295     new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1296                                            _bop_options(\%options),
1297                                          );
1298
1299   $transaction->reference({ %options }); 
1300
1301   $transaction->content(
1302     'type'           => $method,
1303     _bop_auth(\%options),
1304     'action'         => 'Post Authorization',
1305     'description'    => $options{'description'},
1306     'amount'         => $cust_pay_pending->paid,
1307     #'invoice_number' => $options{'invnum'},
1308     'customer_id'    => $self->custnum,
1309     'reference'      => $cust_pay_pending->paypendingnum,
1310     'email'          => $email,
1311     'phone'          => $self->daytime || $self->night,
1312     %content, #after
1313     # plus whatever is required for bogus capture avoidance
1314   );
1315
1316   $transaction->submit();
1317
1318   my $error =
1319     $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1320
1321   if ( $options{'apply'} ) {
1322     my $apply_error = $self->apply_payments_and_credits;
1323     if ( $apply_error ) {
1324       warn "WARNING: error applying payment: $apply_error\n";
1325     }
1326   }
1327
1328   return {
1329     bill_error => $error,
1330     session_id => $cust_pay_pending->session_id,
1331   }
1332
1333 }
1334
1335 =item default_payment_gateway
1336
1337 DEPRECATED -- use agent->payment_gateway
1338
1339 =cut
1340
1341 sub default_payment_gateway {
1342   my( $self, $method ) = @_;
1343
1344   die "Real-time processing not enabled\n"
1345     unless $conf->exists('business-onlinepayment');
1346
1347   #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1348
1349   #load up config
1350   my $bop_config = 'business-onlinepayment';
1351   $bop_config .= '-ach'
1352     if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1353   my ( $processor, $login, $password, $action, @bop_options ) =
1354     $conf->config($bop_config);
1355   $action ||= 'normal authorization';
1356   pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1357   die "No real-time processor is enabled - ".
1358       "did you set the business-onlinepayment configuration value?\n"
1359     unless $processor;
1360
1361   ( $processor, $login, $password, $action, @bop_options )
1362 }
1363
1364 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1365
1366 Refunds a realtime credit card or ACH (electronic check) transaction
1367 via a Business::OnlinePayment realtime gateway.  See
1368 L<http://420.am/business-onlinepayment> for supported gateways.
1369
1370 Available methods are: I<CC> or I<ECHECK>
1371
1372 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1373
1374 Most gateways require a reference to an original payment transaction to refund,
1375 so you probably need to specify a I<paynum>.
1376
1377 I<amount> defaults to the original amount of the payment if not specified.
1378
1379 I<reasonnum> specified an existing refund reason for the refund
1380
1381 I<paydate> specifies the expiration date for a credit card overriding the
1382 value from the customer record or the payment record. Specified as yyyy-mm-dd
1383
1384 Implementation note: If I<amount> is unspecified or equal to the amount of the
1385 orignal payment, first an attempt is made to "void" the transaction via
1386 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1387 the normal attempt is made to "refund" ("credit") the transaction via the
1388 gateway is attempted. No attempt to "void" the transaction is made if the 
1389 gateway has introspection data and doesn't support void.
1390
1391 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1392 #I<zip>, I<payinfo> and I<paydate> are also available.  Any of these options,
1393 #if set, will override the value from the customer record.
1394
1395 #If an I<invnum> is specified, this payment (if successful) is applied to the
1396 #specified invoice.  If you don't specify an I<invnum> you might want to
1397 #call the B<apply_payments> method.
1398
1399 =cut
1400
1401 #some false laziness w/realtime_bop, not enough to make it worth merging
1402 #but some useful small subs should be pulled out
1403 sub realtime_refund_bop {
1404   my $self = shift;
1405
1406   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1407
1408   my %options = ();
1409   if (ref($_[0]) eq 'HASH') {
1410     %options = %{$_[0]};
1411   } else {
1412     my $method = shift;
1413     %options = @_;
1414     $options{method} = $method;
1415   }
1416
1417   if ( $DEBUG ) {
1418     warn "$me realtime_refund_bop (new): $options{method} refund\n";
1419     warn "  $_ => $options{$_}\n" foreach keys %options;
1420   }
1421
1422   return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1423
1424   my %content = ();
1425
1426   ###
1427   # look up the original payment and optionally a gateway for that payment
1428   ###
1429
1430   my $cust_pay = '';
1431   my $amount = $options{'amount'};
1432
1433   my( $processor, $login, $password, @bop_options, $namespace ) ;
1434   my( $auth, $order_number ) = ( '', '', '' );
1435   my $gatewaynum = '';
1436
1437   if ( $options{'paynum'} ) {
1438
1439     warn "  paynum: $options{paynum}\n" if $DEBUG > 1;
1440     $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1441       or return "Unknown paynum $options{'paynum'}";
1442     $amount ||= $cust_pay->paid;
1443
1444     my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1445     $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1446
1447     if ( $cust_pay->get('processor') ) {
1448       ($gatewaynum, $processor, $auth, $order_number) =
1449       (
1450         $cust_pay->gatewaynum,
1451         $cust_pay->processor,
1452         $cust_pay->auth,
1453         $cust_pay->order_number,
1454       );
1455     } else {
1456       # this payment wasn't upgraded, which probably means this won't work,
1457       # but try it anyway
1458       $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1459         or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1460                   $cust_pay->paybatch;
1461       ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1462     }
1463
1464     if ( $gatewaynum ) { #gateway for the payment to be refunded
1465
1466       my $payment_gateway =
1467         qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1468       die "payment gateway $gatewaynum not found"
1469         unless $payment_gateway;
1470
1471       $processor   = $payment_gateway->gateway_module;
1472       $login       = $payment_gateway->gateway_username;
1473       $password    = $payment_gateway->gateway_password;
1474       $namespace   = $payment_gateway->gateway_namespace;
1475       @bop_options = $payment_gateway->options;
1476
1477     } else { #try the default gateway
1478
1479       my $conf_processor;
1480       my $payment_gateway =
1481         $self->agent->payment_gateway('method' => $options{method});
1482
1483       ( $conf_processor, $login, $password, $namespace ) =
1484         map { my $method = "gateway_$_"; $payment_gateway->$method }
1485           qw( module username password namespace );
1486
1487       @bop_options = $payment_gateway->gatewaynum
1488                        ? $payment_gateway->options
1489                        : @{ $payment_gateway->get('options') };
1490
1491       return "processor of payment $options{'paynum'} $processor does not".
1492              " match default processor $conf_processor"
1493         unless $processor eq $conf_processor;
1494
1495     }
1496
1497
1498   } else { # didn't specify a paynum, so look for agent gateway overrides
1499            # like a normal transaction 
1500  
1501     my $payment_gateway =
1502       $self->agent->payment_gateway( 'method'  => $options{method},
1503                                      #'payinfo' => $payinfo,
1504                                    );
1505     my( $processor, $login, $password, $namespace ) =
1506       map { my $method = "gateway_$_"; $payment_gateway->$method }
1507         qw( module username password namespace );
1508
1509     my @bop_options = $payment_gateway->gatewaynum
1510                         ? $payment_gateway->options
1511                         : @{ $payment_gateway->get('options') };
1512
1513   }
1514   return "neither amount nor paynum specified" unless $amount;
1515
1516   eval "use $namespace";  
1517   die $@ if $@;
1518
1519   %content = (
1520     %content,
1521     'type'           => $options{method},
1522     'login'          => $login,
1523     'password'       => $password,
1524     'order_number'   => $order_number,
1525     'amount'         => $amount,
1526   );
1527   $content{authorization} = $auth
1528     if length($auth); #echeck/ACH transactions have an order # but no auth
1529                       #(at least with authorize.net)
1530
1531   my $currency =    $conf->exists('business-onlinepayment-currency')
1532                  && $conf->config('business-onlinepayment-currency');
1533   $content{currency} = $currency if $currency;
1534
1535   my $disable_void_after;
1536   if ($conf->exists('disable_void_after')
1537       && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1538     $disable_void_after = $1;
1539   }
1540
1541   #first try void if applicable
1542   my $void = new Business::OnlinePayment( $processor, @bop_options );
1543
1544   my $tryvoid = 1;
1545   if ($void->can('info')) {
1546       my $paytype = '';
1547       $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1548       $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1549       my %supported_actions = $void->info('supported_actions');
1550       $tryvoid = 0 
1551         if ( %supported_actions && $paytype 
1552                 && defined($supported_actions{$paytype}) 
1553                 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1554   }
1555
1556   if ( $cust_pay && $cust_pay->paid == $amount
1557     && (
1558       ( not defined($disable_void_after) )
1559       || ( time < ($cust_pay->_date + $disable_void_after ) )
1560     )
1561     && $tryvoid
1562   ) {
1563     warn "  attempting void\n" if $DEBUG > 1;
1564     if ( $void->can('info') ) {
1565       if ( $cust_pay->payby eq 'CARD'
1566            && $void->info('CC_void_requires_card') )
1567       {
1568         $content{'card_number'} = $cust_pay->payinfo;
1569       } elsif ( $cust_pay->payby eq 'CHEK'
1570                 && $void->info('ECHECK_void_requires_account') )
1571       {
1572         ( $content{'account_number'}, $content{'routing_code'} ) =
1573           split('@', $cust_pay->payinfo);
1574         $content{'name'} = $self->get('first'). ' '. $self->get('last');
1575       }
1576     }
1577     $void->content( 'action' => 'void', %content );
1578     $void->test_transaction(1)
1579       if $conf->exists('business-onlinepayment-test_transaction');
1580     $void->submit();
1581     if ( $void->is_success ) {
1582       # specified as a refund reason, but now we want a payment void reason
1583       # extract just the reason text, let cust_pay::void handle new_or_existing
1584       my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1585       my $error;
1586       $error = 'Reason could not be loaded' unless $reason;      
1587       $error = $cust_pay->void($reason->reason) unless $error;
1588       if ( $error ) {
1589         # gah, even with transactions.
1590         my $e = 'WARNING: Card/ACH voided but database not updated - '.
1591                 "error voiding payment: $error";
1592         warn $e;
1593         return $e;
1594       }
1595       warn "  void successful\n" if $DEBUG > 1;
1596       return '';
1597     }
1598   }
1599
1600   warn "  void unsuccessful, trying refund\n"
1601     if $DEBUG > 1;
1602
1603   #massage data
1604   my $address = $self->address1;
1605   $address .= ", ". $self->address2 if $self->address2;
1606
1607   my($payname, $payfirst, $paylast);
1608   if ( $self->payname && $options{method} ne 'ECHECK' ) {
1609     $payname = $self->payname;
1610     $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1611       or return "Illegal payname $payname";
1612     ($payfirst, $paylast) = ($1, $2);
1613   } else {
1614     $payfirst = $self->getfield('first');
1615     $paylast = $self->getfield('last');
1616     $payname =  "$payfirst $paylast";
1617   }
1618
1619   my @invoicing_list = $self->invoicing_list_emailonly;
1620   if ( $conf->exists('emailinvoiceautoalways')
1621        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1622        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1623     push @invoicing_list, $self->all_emails;
1624   }
1625
1626   my $email = ($conf->exists('business-onlinepayment-email-override'))
1627               ? $conf->config('business-onlinepayment-email-override')
1628               : $invoicing_list[0];
1629
1630   my $payip = exists($options{'payip'})
1631                 ? $options{'payip'}
1632                 : $self->payip;
1633   $content{customer_ip} = $payip
1634     if length($payip);
1635
1636   my $payinfo = '';
1637   if ( $options{method} eq 'CC' ) {
1638
1639     if ( $cust_pay ) {
1640       $content{card_number} = $payinfo = $cust_pay->payinfo;
1641       (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1642         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1643         ($content{expiration} = "$2/$1");  # where available
1644     } else {
1645       $content{card_number} = $payinfo = $self->payinfo;
1646       (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1647         =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1648       $content{expiration} = "$2/$1";
1649     }
1650
1651   } elsif ( $options{method} eq 'ECHECK' ) {
1652
1653     if ( $cust_pay ) {
1654       $payinfo = $cust_pay->payinfo;
1655     } else {
1656       $payinfo = $self->payinfo;
1657     } 
1658     ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1659     $content{bank_name} = $self->payname;
1660     $content{account_type} = 'CHECKING';
1661     $content{account_name} = $payname;
1662     $content{customer_org} = $self->company ? 'B' : 'I';
1663     $content{customer_ssn} = $self->ss;
1664
1665   }
1666
1667   #then try refund
1668   my $refund = new Business::OnlinePayment( $processor, @bop_options );
1669   my %sub_content = $refund->content(
1670     'action'         => 'credit',
1671     'customer_id'    => $self->custnum,
1672     'last_name'      => $paylast,
1673     'first_name'     => $payfirst,
1674     'name'           => $payname,
1675     'address'        => $address,
1676     'city'           => $self->city,
1677     'state'          => $self->state,
1678     'zip'            => $self->zip,
1679     'country'        => $self->country,
1680     'email'          => $email,
1681     'phone'          => $self->daytime || $self->night,
1682     %content, #after
1683   );
1684   warn join('', map { "  $_ => $sub_content{$_}\n" } keys %sub_content )
1685     if $DEBUG > 1;
1686   $refund->test_transaction(1)
1687     if $conf->exists('business-onlinepayment-test_transaction');
1688   $refund->submit();
1689
1690   return "$processor error: ". $refund->error_message
1691     unless $refund->is_success();
1692
1693   $order_number = $refund->order_number if $refund->can('order_number');
1694
1695   # change this to just use $cust_pay->delete_cust_bill_pay?
1696   while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1697     my @cust_bill_pay = $cust_pay->cust_bill_pay;
1698     last unless @cust_bill_pay;
1699     my $cust_bill_pay = pop @cust_bill_pay;
1700     my $error = $cust_bill_pay->delete;
1701     last if $error;
1702   }
1703
1704   my $cust_refund = new FS::cust_refund ( {
1705     'custnum'  => $self->custnum,
1706     'paynum'   => $options{'paynum'},
1707     'source_paynum' => $options{'paynum'},
1708     'refund'   => $amount,
1709     '_date'    => '',
1710     'payby'    => $bop_method2payby{$options{method}},
1711     'payinfo'  => $payinfo,
1712     'reasonnum'     => $options{'reasonnum'},
1713     'gatewaynum'    => $gatewaynum, # may be null
1714     'processor'     => $processor,
1715     'auth'          => $refund->authorization,
1716     'order_number'  => $order_number,
1717   } );
1718   my $error = $cust_refund->insert;
1719   if ( $error ) {
1720     $cust_refund->paynum(''); #try again with no specific paynum
1721     $cust_refund->source_paynum('');
1722     my $error2 = $cust_refund->insert;
1723     if ( $error2 ) {
1724       # gah, even with transactions.
1725       my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1726               "error inserting refund ($processor): $error2".
1727               " (previously tried insert with paynum #$options{'paynum'}" .
1728               ": $error )";
1729       warn $e;
1730       return $e;
1731     }
1732   }
1733
1734   ''; #no error
1735
1736 }
1737
1738 =item realtime_verify_bop [ OPTION => VALUE ... ]
1739
1740 Runs an authorization-only transaction for $1 against this credit card (if
1741 successful, immediatly reverses the authorization).
1742
1743 Returns the empty string if the authorization was sucessful, or an error
1744 message otherwise.
1745
1746 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1747 Object will be tokenized if possible, but that change will not be
1748 updated in database (must be inserted/replaced afterwards.)
1749
1750 Currently only succeeds for Business::OnlinePayment CC transactions.
1751
1752 =cut
1753
1754 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1755 #it worth merging but some useful small subs should be pulled out
1756 sub realtime_verify_bop {
1757   my $self = shift;
1758
1759   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1760   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1761
1762   my %options = ();
1763   if (ref($_[0]) eq 'HASH') {
1764     %options = %{$_[0]};
1765   } else {
1766     %options = @_;
1767   }
1768
1769   if ( $DEBUG ) {
1770     warn "$me realtime_verify_bop\n";
1771     warn "  $_ => $options{$_}\n" foreach keys %options;
1772   }
1773
1774   # set fields from passed cust_payby
1775   return "No cust_payby" unless $options{'cust_payby'};
1776   _bop_cust_payby_options(\%options);
1777
1778   # possibly run a separate transaction to tokenize card number,
1779   #   so that we never store tokenized card info in cust_pay_pending
1780   if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1781     my $token_error = $self->realtime_tokenize(\%options);
1782     return $token_error if $token_error;
1783     #important that we not replace cust_payby here,
1784     #because cust_payby->replace uses realtime_verify_bop!
1785     return "Cannot tokenize card info"
1786       if $conf->exists('no_saved_cardnumbers') && !$self->tokenized($options{'payinfo'});
1787   }
1788
1789   ###
1790   # select a gateway
1791   ###
1792
1793   my $payment_gateway =  $self->_payment_gateway( \%options );
1794   my $namespace = $payment_gateway->gateway_namespace;
1795
1796   eval "use $namespace";  
1797   die $@ if $@;
1798
1799   ###
1800   # check for banned credit card/ACH
1801   ###
1802
1803   my $ban = FS::banned_pay->ban_search(
1804     'payby'   => $bop_method2payby{'CC'},
1805     'payinfo' => $options{payinfo},
1806   );
1807   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1808
1809   ###
1810   # massage data
1811   ###
1812
1813   my $bop_content = $self->_bop_content(\%options);
1814   return $bop_content unless ref($bop_content);
1815
1816   my @invoicing_list = $self->invoicing_list_emailonly;
1817   if ( $conf->exists('emailinvoiceautoalways')
1818        || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1819        || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1820     push @invoicing_list, $self->all_emails;
1821   }
1822
1823   my $email = ($conf->exists('business-onlinepayment-email-override'))
1824               ? $conf->config('business-onlinepayment-email-override')
1825               : $invoicing_list[0];
1826
1827   my $paydate = '';
1828   my %content = ();
1829
1830   if ( $namespace eq 'Business::OnlinePayment' ) {
1831
1832     if ( $options{method} eq 'CC' ) {
1833
1834       $content{card_number} = $options{payinfo};
1835       $paydate = $options{'paydate'};
1836       $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1837       $content{expiration} = "$2/$1";
1838
1839       $content{cvv2} = $options{'paycvv'}
1840         if length($options{'paycvv'});
1841
1842       my $paystart_month = $options{'paystart_month'};
1843       my $paystart_year  = $options{'paystart_year'};
1844
1845       $content{card_start} = "$paystart_month/$paystart_year"
1846         if $paystart_month && $paystart_year;
1847
1848       my $payissue       = $options{'payissue'};
1849       $content{issue_number} = $payissue if $payissue;
1850
1851     } elsif ( $options{method} eq 'ECHECK' ){
1852       #cannot verify, move along (though it shouldn't be called...)
1853       return '';
1854     } else {
1855       return "unknown method ". $options{method};
1856     }
1857   } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1858     #cannot verify, move along
1859     return '';
1860   } else {
1861     return "unknown namespace $namespace";
1862   }
1863
1864   ###
1865   # run transaction(s)
1866   ###
1867
1868   my $error;
1869   my $transaction; #need this back so we can do _tokenize_card
1870
1871   # don't mutex the customer here, because they might be uncommitted. and
1872   # this is only verification. it doesn't matter if they have other
1873   # unfinished verifications.
1874
1875   my $cust_pay_pending = new FS::cust_pay_pending {
1876     'custnum_pending'   => 1,
1877     'paid'              => '1.00',
1878     '_date'             => '',
1879     'payby'             => $bop_method2payby{'CC'},
1880     'payinfo'           => $options{payinfo},
1881     'paymask'           => $options{paymask},
1882     'paydate'           => $paydate,
1883     'pkgnum'            => $options{'pkgnum'},
1884     'status'            => 'new',
1885     'gatewaynum'        => $payment_gateway->gatewaynum || '',
1886     'session_id'        => $options{session_id} || '',
1887   };
1888   $cust_pay_pending->payunique( $options{payunique} )
1889     if defined($options{payunique}) && length($options{payunique});
1890
1891   IMMEDIATE: {
1892     # open a separate handle for creating/updating the cust_pay_pending
1893     # record
1894     local $FS::UID::dbh = myconnect();
1895     local $FS::UID::AutoCommit = 1;
1896
1897     # if this is an existing customer (and we can tell now because
1898     # this is a fresh transaction), it's safe to assign their custnum
1899     # to the cust_pay_pending record, and then the verification attempt
1900     # will remain linked to them even if it fails.
1901     if ( FS::cust_main->by_key($self->custnum) ) {
1902       $cust_pay_pending->set('custnum', $self->custnum);
1903     }
1904
1905     warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1906       if $DEBUG > 1;
1907
1908     # if this fails, just return; everything else will still allow the
1909     # cust_pay_pending to have its custnum set later
1910     my $cpp_new_err = $cust_pay_pending->insert;
1911     return $cpp_new_err if $cpp_new_err;
1912
1913     warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1914       if $DEBUG > 1;
1915     warn Dumper($cust_pay_pending) if $DEBUG > 2;
1916
1917     $transaction = new $namespace( $payment_gateway->gateway_module,
1918                                    _bop_options(\%options),
1919                                     );
1920
1921     $transaction->content(
1922       'type'           => 'CC',
1923       _bop_auth(\%options),          
1924       'action'         => 'Authorization Only',
1925       'description'    => $options{'description'},
1926       'amount'         => '1.00',
1927       'customer_id'    => $self->custnum,
1928       %$bop_content,
1929       'reference'      => $cust_pay_pending->paypendingnum, #for now
1930       'email'          => $email,
1931       %content, #after
1932     );
1933
1934     $cust_pay_pending->status('pending');
1935     my $cpp_pending_err = $cust_pay_pending->replace;
1936     return $cpp_pending_err if $cpp_pending_err;
1937
1938     warn Dumper($transaction) if $DEBUG > 2;
1939
1940     unless ( $BOP_TESTING ) {
1941       $transaction->test_transaction(1)
1942         if $conf->exists('business-onlinepayment-test_transaction');
1943       $transaction->submit();
1944     } else {
1945       if ( $BOP_TESTING_SUCCESS ) {
1946         $transaction->is_success(1);
1947         $transaction->authorization('fake auth');
1948       } else {
1949         $transaction->is_success(0);
1950         $transaction->error_message('fake failure');
1951       }
1952     }
1953
1954     if ( $transaction->is_success() ) {
1955
1956       $cust_pay_pending->status('authorized');
1957       my $cpp_authorized_err = $cust_pay_pending->replace;
1958       return $cpp_authorized_err if $cpp_authorized_err;
1959
1960       my $auth = $transaction->authorization;
1961       my $ordernum = $transaction->can('order_number')
1962                      ? $transaction->order_number
1963                      : '';
1964
1965       my $reverse = new $namespace( $payment_gateway->gateway_module,
1966                                     _bop_options(\%options),
1967                                   );
1968
1969       $reverse->content( 'action'        => 'Reverse Authorization',
1970                          _bop_auth(\%options),          
1971
1972                          # B:OP
1973                          'amount'        => '1.00',
1974                          'authorization' => $transaction->authorization,
1975                          'order_number'  => $ordernum,
1976
1977                          # vsecure
1978                          'result_code'   => $transaction->result_code,
1979                          'txn_date'      => $transaction->txn_date,
1980
1981                          %content,
1982                        );
1983       $reverse->test_transaction(1)
1984         if $conf->exists('business-onlinepayment-test_transaction');
1985       $reverse->submit();
1986
1987       if ( $reverse->is_success ) {
1988
1989         $cust_pay_pending->status('done');
1990         $cust_pay_pending->statustext('reversed');
1991         my $cpp_reversed_err = $cust_pay_pending->replace;
1992         return $cpp_reversed_err if $cpp_reversed_err;
1993
1994       } else {
1995
1996         my $e = "Authorization successful but reversal failed, custnum #".
1997                 $self->custnum. ': '.  $reverse->result_code.
1998                 ": ". $reverse->error_message;
1999         $log->warning($e);
2000         warn $e;
2001         return $e;
2002
2003       }
2004
2005       ### Address Verification ###
2006       #
2007       # Single-letter codes vary by cardtype.
2008       #
2009       # Erring on the side of accepting cards if avs is not available,
2010       # only rejecting if avs occurred and there's been an explicit mismatch
2011       #
2012       # Charts below taken from vSecure documentation,
2013       #    shows codes for Amex/Dscv/MC/Visa
2014       #
2015       # ACCEPTABLE AVS RESPONSES:
2016       # Both Address and 5-digit postal code match Y A Y Y
2017       # Both address and 9-digit postal code match Y A X Y
2018       # United Kingdom â€“ Address and postal code match _ _ _ F
2019       # International transaction â€“ Address and postal code match _ _ _ D/M
2020       #
2021       # ACCEPTABLE, BUT ISSUE A WARNING:
2022       # Ineligible transaction; or message contains a content error _ _ _ E
2023       # System unavailable; retry R U R R
2024       # Information unavailable U W U U
2025       # Issuer does not support AVS S U S S
2026       # AVS is not applicable _ _ _ S
2027       # Incompatible formats â€“ Not verified _ _ _ C
2028       # Incompatible formats â€“ Address not verified; postal code matches _ _ _ P
2029       # International transaction â€“ address not verified _ G _ G/I
2030       #
2031       # UNACCEPTABLE AVS RESPONSES:
2032       # Only Address matches A Y A A
2033       # Only 5-digit postal code matches Z Z Z Z
2034       # Only 9-digit postal code matches Z Z W W
2035       # Neither address nor postal code matches N N N N
2036
2037       if (my $avscode = uc($transaction->avs_code)) {
2038
2039         # map codes to accept/warn/reject
2040         my $avs = {
2041           'American Express card' => {
2042             'A' => 'r',
2043             'N' => 'r',
2044             'R' => 'w',
2045             'S' => 'w',
2046             'U' => 'w',
2047             'Y' => 'a',
2048             'Z' => 'r',
2049           },
2050           'Discover card' => {
2051             'A' => 'a',
2052             'G' => 'w',
2053             'N' => 'r',
2054             'U' => 'w',
2055             'W' => 'w',
2056             'Y' => 'r',
2057             'Z' => 'r',
2058           },
2059           'MasterCard' => {
2060             'A' => 'r',
2061             'N' => 'r',
2062             'R' => 'w',
2063             'S' => 'w',
2064             'U' => 'w',
2065             'W' => 'r',
2066             'X' => 'a',
2067             'Y' => 'a',
2068             'Z' => 'r',
2069           },
2070           'VISA card' => {
2071             'A' => 'r',
2072             'C' => 'w',
2073             'D' => 'a',
2074             'E' => 'w',
2075             'F' => 'a',
2076             'G' => 'w',
2077             'I' => 'w',
2078             'M' => 'a',
2079             'N' => 'r',
2080             'P' => 'w',
2081             'R' => 'w',
2082             'S' => 'w',
2083             'U' => 'w',
2084             'W' => 'r',
2085             'Y' => 'a',
2086             'Z' => 'r',
2087           },
2088         };
2089         my $cardtype = cardtype($content{card_number});
2090         if ($avs->{$cardtype}) {
2091           my $avsact = $avs->{$cardtype}->{$avscode};
2092           my $warning = '';
2093           if ($avsact eq 'r') {
2094             return "AVS code verification failed, cardtype $cardtype, code $avscode";
2095           } elsif ($avsact eq 'w') {
2096             $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2097           } elsif (!$avsact) {
2098             $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2099           } # else $avsact eq 'a'
2100           if ($warning) {
2101             $log->warning($warning);
2102             warn $warning;
2103           }
2104         } # else $cardtype avs handling not implemented
2105       } # else !$transaction->avs_code
2106
2107     } else { # is not success
2108
2109       # status is 'done' not 'declined', as in _realtime_bop_result
2110       $cust_pay_pending->status('done');
2111       $error = $transaction->error_message || 'Unknown error';
2112       $cust_pay_pending->statustext($error);
2113       # could also record failure_status here,
2114       #   but it's not supported by B::OP::vSecureProcessing...
2115       #   need a B::OP module with (reverse) auth only to test it with
2116       my $cpp_declined_err = $cust_pay_pending->replace;
2117       return $cpp_declined_err if $cpp_declined_err;
2118
2119     }
2120
2121   } # end of IMMEDIATE; we now have our $error and $transaction
2122
2123   ###
2124   # Save the custnum (as part of the main transaction, so it can reference
2125   # the cust_main)
2126   ###
2127
2128   if (!$cust_pay_pending->custnum) {
2129     $cust_pay_pending->set('custnum', $self->custnum);
2130     my $set_custnum_err = $cust_pay_pending->replace;
2131     if ($set_custnum_err) {
2132       $log->error($set_custnum_err);
2133       $error ||= $set_custnum_err;
2134       # but if there was a real verification error also, return that one
2135     }
2136   }
2137
2138   ###
2139   # remove paycvv here?  need to find out if a reversed auth
2140   #   counts as an initial transaction for paycvv retention requirements
2141   ###
2142
2143   ###
2144   # Tokenize
2145   ###
2146
2147   # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2148   #   if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2149   if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2150     $cust_pay_pending->payinfo($card_token);
2151     my $cpp_token_err = $cust_pay_pending->replace;
2152     #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2153     return $cpp_token_err if $cpp_token_err;
2154     #important that we not replace cust_payby here,
2155     #because cust_payby->replace uses realtime_verify_bop!
2156   }
2157
2158   ###
2159   # result handling
2160   ###
2161
2162   # $error contains the transaction error_message, if is_success was false.
2163  
2164   return $error;
2165
2166 }
2167
2168 =item realtime_tokenize [ OPTION => VALUE ... ]
2169
2170 If possible and necessary, runs a tokenize transaction.
2171 In order to be possible, a credit card cust_payby record
2172 must be passed and a Business::OnlinePayment gateway capable
2173 of Tokenize transactions must be configured for this user.
2174 Is only necessary if payinfo is not yet tokenized.
2175
2176 Returns the empty string if the authorization was sucessful
2177 or was not possible/necessary (thus allowing this to be safely called with
2178 non-tokenizable records/gateways, without having to perform separate tests),
2179 or an error message otherwise.
2180
2181 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2182 Object will be tokenized if possible, but that change will not be
2183 updated in database (must be inserted/replaced afterwards.)
2184
2185 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2186 may be passed.  If options are passed as a hashref, I<payinfo>
2187 will be updated as appropriate in the passed hashref.
2188
2189 Can be run as a class method if option I<payment_gateway> is passed,
2190 but default customer id/name/phone can't be set in that case.  This
2191 is really only intended for tokenizing old records on upgrade.
2192
2193 =cut
2194
2195 # careful--might be run as a class method
2196 sub realtime_tokenize {
2197   my $self = shift;
2198
2199   local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2200   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2201
2202   my %options = ();
2203   my $outoptions; #for returning cust_payby/payinfo
2204   if (ref($_[0]) eq 'HASH') {
2205     %options = %{$_[0]};
2206     $outoptions = $_[0];
2207   } else {
2208     %options = @_;
2209     $outoptions = \%options;
2210   }
2211
2212   # set fields from passed cust_payby
2213   _bop_cust_payby_options(\%options);
2214   return '' unless $options{method} eq 'CC';
2215   return '' if $self->tokenized($options{payinfo}); #already tokenized
2216
2217   ###
2218   # select a gateway
2219   ###
2220
2221   $options{'nofatal'} = 1;
2222   my $payment_gateway =  $self->_payment_gateway( \%options );
2223   return '' unless $payment_gateway;
2224   my $namespace = $payment_gateway->gateway_namespace;
2225   return '' unless $namespace eq 'Business::OnlinePayment';
2226
2227   eval "use $namespace";  
2228   return $@ if $@;
2229
2230   ###
2231   # check for tokenize ability
2232   ###
2233
2234   my $transaction = new $namespace( $payment_gateway->gateway_module,
2235                                     _bop_options(\%options),
2236                                   );
2237
2238   return '' unless $transaction->can('info');
2239
2240   my %supported_actions = $transaction->info('supported_actions');
2241   return '' unless $supported_actions{'CC'}
2242                 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2243
2244   ###
2245   # check for banned credit card/ACH
2246   ###
2247
2248   my $ban = FS::banned_pay->ban_search(
2249     'payby'   => $bop_method2payby{'CC'},
2250     'payinfo' => $options{payinfo},
2251   );
2252   return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2253
2254   ###
2255   # massage data
2256   ###
2257
2258   ### Currently, cardfortress only keys in on card number and exp date.
2259   ### We pass everything we'd pass to a normal transaction,
2260   ### for ease of current and future development,
2261   ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2262
2263   my $bop_content = $self->_bop_content(\%options);
2264   return $bop_content unless ref($bop_content);
2265
2266   my $paydate = '';
2267   my %content = ();
2268
2269   $content{card_number} = $options{payinfo};
2270   $paydate = $options{'paydate'};
2271   $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2272   $content{expiration} = "$2/$1";
2273
2274   $content{cvv2} = $options{'paycvv'}
2275     if length($options{'paycvv'});
2276
2277   my $paystart_month = $options{'paystart_month'};
2278   my $paystart_year  = $options{'paystart_year'};
2279
2280   $content{card_start} = "$paystart_month/$paystart_year"
2281     if $paystart_month && $paystart_year;
2282
2283   my $payissue       = $options{'payissue'};
2284   $content{issue_number} = $payissue if $payissue;
2285
2286   $content{customer_id} = $self->custnum
2287     if ref($self);
2288
2289   ###
2290   # run transaction
2291   ###
2292
2293   my $error;
2294
2295   # no cust_pay_pending---this is not a financial transaction
2296
2297   $transaction->content(
2298     'type'           => 'CC',
2299     _bop_auth(\%options),          
2300     'action'         => 'Tokenize',
2301     'description'    => $options{'description'},
2302     %$bop_content,
2303     %content, #after
2304   );
2305
2306   # no $BOP_TESTING handling for this
2307   $transaction->test_transaction(1)
2308     if $conf->exists('business-onlinepayment-test_transaction');
2309   $transaction->submit();
2310
2311   if ( $transaction->card_token() ) { # no is_success flag
2312
2313     # realtime_tokenize should not clear paycvv at this time.  it might be
2314     # needed for the first transaction, and a tokenize isn't actually a
2315     # transaction that hits the gateway.  at some point in the future, card
2316     # fortress should take on the "store paycvv until first transaction"
2317     # functionality and we should fix this in freeside, but i that's a bigger
2318     # project for another time.
2319
2320     #important that we not replace cust_payby here, 
2321     #because cust_payby->replace uses realtime_tokenize!
2322     $self->_tokenize_card($transaction,$outoptions);
2323
2324   } else {
2325
2326     $error = $transaction->error_message || 'Unknown error when tokenizing card';
2327
2328   }
2329
2330   return $error;
2331
2332 }
2333
2334
2335 =item tokenized PAYINFO
2336
2337 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2338
2339 PAYINFO is required.
2340
2341 Can be run as class or object method, never loads from object.
2342
2343 =cut
2344
2345 sub tokenized {
2346   my $this = shift;
2347   my $payinfo = shift;
2348   FS::cust_pay->tokenized($payinfo);
2349 }
2350
2351 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2352
2353 NOT A METHOD.  Acts on all customers.  Placed here because it makes
2354 use of module-internal methods, and to keep everything that uses
2355 Billing::OnlinePayment all in one place.
2356
2357 Tokenizes all tokenizable card numbers from payinfo in cust_payby and 
2358 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2359
2360 If the I<queue> flag is set, newly tokenized records will be immediately
2361 committed, regardless of AutoCommit, so as to release the mutex on the record.
2362
2363 If all configured gateways have the ability to tokenize, detection of an 
2364 untokenizable record will cause a fatal error.  However, if the I<queue> flag 
2365 is set, this will instead cause a critical error to be recorded in the log, 
2366 and any other tokenizable records will still be committed.
2367
2368 If the I<daily> flag is also set, detection of existing untokenized records will 
2369 record a critical error in the system log (because they should have never appeared 
2370 in the first place.)  Tokenization will still be attempted.
2371
2372 If any configured gateways do NOT have the ability to tokenize, or if a
2373 default gateway is not configured, then untokenized records are not considered 
2374 a threat, and no critical errors will be generated in the log.
2375
2376 =cut
2377
2378 sub token_check {
2379   #acts on all customers
2380   my %opt = @_;
2381   my $debug = !$opt{'quiet'} || $DEBUG;
2382
2383   warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2384
2385   # force some explicitness when invoking this method
2386   die "token_check must run with queue flag if run with daily flag"
2387     if $opt{'daily'} && !$opt{'queue'};
2388
2389   my $conf = FS::Conf->new;
2390
2391   my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2392
2393   my $cache = {}; #cache for module info
2394
2395   # look for a gateway that can't tokenize
2396   my $require_tokenized = 1;
2397   foreach my $gateway (
2398     FS::payment_gateway->all_gateways(
2399       'method'  => 'CC',
2400       'conf'    => $conf,
2401       'nofatal' => 1,
2402     )
2403   ) {
2404     if (!$gateway) {
2405       # no default gateway, no promise to tokenize
2406       # can just load other gateways as-needeed below
2407       $require_tokenized = 0;
2408       last;
2409     }
2410     my $info = _token_check_gateway_info($cache,$gateway);
2411     die $info unless ref($info); # means it's an error message
2412     unless ($info->{'can_tokenize'}) {
2413       # a configured gateway can't tokenize, that's all we need to know right now
2414       # can just load other gateways as-needeed below
2415       $require_tokenized = 0;
2416       last;
2417     }
2418   }
2419
2420   warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2421
2422   # upgrade does not call this with autocommit turned on,
2423   # and autocommit will be ignored if opt queue is set,
2424   # but might as well be thorough...
2425   my $oldAutoCommit = $FS::UID::AutoCommit;
2426   local $FS::UID::AutoCommit = 0;
2427   my $dbh = dbh;
2428
2429   # for retrieving data in chunks
2430   my $step = 500;
2431   my $offset = 0;
2432
2433   ### Tokenize cust_payby
2434
2435   my @recnums;
2436
2437 CUSTLOOP:
2438   while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2439     my $cust_main = FS::cust_main->by_key($custnum);
2440     my $payment_gateway;
2441     foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2442
2443       # see if it's already tokenized
2444       if ($cust_payby->tokenized) {
2445         warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2446         next;
2447       }
2448
2449       if ($require_tokenized && $opt{'daily'}) {
2450         $log->critical("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum);
2451         $dbh->commit or die $dbh->errstr; # commit log message
2452       }
2453
2454       # only load gateway if we need to, and only need to load it once
2455       my $payment_gateway ||= $cust_main->_payment_gateway({
2456         'method'  => 'CC',
2457         'conf'    => $conf,
2458         'nofatal' => 1, # handle lack of gateway smoothly below
2459       });
2460       unless ($payment_gateway) {
2461         # no reason to have untokenized card numbers saved if no gateway,
2462         #   but only a problem if we expected everyone to tokenize card numbers
2463         unless ($require_tokenized) {
2464           warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2465           next CUSTLOOP; # can skip rest of customer
2466         }
2467         my $error = "No gateway found for custnum ".$cust_main->custnum;
2468         if ($opt{'queue'}) {
2469           $log->critical($error);
2470           $dbh->commit or die $dbh->errstr; # commit error message
2471           next; # not next CUSTLOOP, want to record error for every cust_payby
2472         }
2473         $dbh->rollback if $oldAutoCommit;
2474         die $error;
2475       }
2476
2477       my $info = _token_check_gateway_info($cache,$payment_gateway);
2478       unless (ref($info)) {
2479         # only throws error if Business::OnlinePayment won't load,
2480         #   which is just cause to abort this whole process, even if queue
2481         $dbh->rollback if $oldAutoCommit;
2482         die $info; # error message
2483       }
2484       # no fail here--a configured gateway can't tokenize, so be it
2485       unless ($info->{'can_tokenize'}) {
2486         warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2487         next;
2488       }
2489
2490       # time to tokenize
2491       $cust_payby = $cust_payby->select_for_update;
2492       my %tokenopts = (
2493         'payment_gateway' => $payment_gateway,
2494         'cust_payby'      => $cust_payby,
2495       );
2496       my $error = $cust_main->realtime_tokenize(\%tokenopts);
2497       if ($cust_payby->tokenized) { # implies no error
2498         $error = $cust_payby->replace;
2499       } else {
2500         $error ||= 'Unknown error';
2501       }
2502       if ($error) {
2503         $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2504         if ($opt{'queue'}) {
2505           $log->critical($error);
2506           $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2507           next; # not next CUSTLOOP, want to record error for every cust_payby
2508         }
2509         $dbh->rollback if $oldAutoCommit;
2510         die $error;
2511       }
2512       $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2513       warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2514     }
2515     warn "cust_payby upgraded for custnum ".$cust_main->custnum if $debug;
2516
2517   }
2518
2519   ### Tokenize/mask transaction tables
2520
2521   # allow tokenization of closed cust_pay/cust_refund records
2522   local $FS::payinfo_Mixin::allow_closed_replace = 1;
2523
2524   # grep assistance:
2525   #   $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2526   foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2527     warn "Checking $table" if $debug;
2528
2529     # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2530     # loading only record ids, then loading individual records one at a time
2531     my $tclass = 'FS::'.$table;
2532     $offset = 0;
2533     @recnums = ();
2534
2535     while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2536       my $record = $tclass->by_key($recnum);
2537       if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2538         warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2539         next;
2540       }
2541       if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2542         warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2543         next;
2544       }
2545       if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2546         warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2547         next;
2548       }
2549
2550       if ($require_tokenized && $opt{'daily'}) {
2551         $log->critical("Untokenized card number detected in $table ".$record->get($record->primary_key));
2552         $dbh->commit or die $dbh->errstr; # commit log message
2553       }
2554
2555       # don't use customer agent gateway here, use the gatewaynum specified by the record
2556       my $gateway = FS::payment_gateway->by_key_or_default( 
2557         'method'     => 'CC',
2558         'conf'       => $conf,
2559         'nofatal'    => 1,
2560         'gatewaynum' => $record->gatewaynum || '',
2561       );
2562       unless ($gateway) {
2563         # means no default gateway, no promise to tokenize, can skip
2564         warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2565         next;
2566       }
2567
2568       my $info = _token_check_gateway_info($cache,$gateway);
2569       unless (ref($info)) {
2570         # only throws error if Business::OnlinePayment won't load,
2571         #   which is just cause to abort this whole process, even if queue
2572         $dbh->rollback if $oldAutoCommit;
2573         die $info; # error message
2574       }
2575
2576       # a configured gateway can't tokenize, move along
2577       unless ($info->{'can_tokenize'}) {
2578         warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2579         next;
2580       }
2581
2582       my $cust_main = $record->cust_main;
2583       if (!$cust_main) {
2584         # might happen for cust_pay_pending from failed verify records,
2585         #   in which case we attempt tokenization without cust_main
2586         # everything else should absolutely have a cust_main
2587         if ($table eq 'cust_pay_pending' && $record->{'custnum_pending'}) {
2588           warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug;
2589         } else {
2590           my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2591           if ($opt{'queue'}) {
2592             $log->critical($error);
2593             $dbh->commit or die $dbh->errstr; # commit log message
2594             next;
2595           }
2596           $dbh->rollback if $oldAutoCommit;
2597           die $error;
2598         }
2599       }
2600
2601       # if we got this far, time to mutex
2602       $record = $record->select_for_update;
2603
2604       # no clear record of name/address/etc used for transaction,
2605       # but will load name/phone/id from customer if run as an object method,
2606       # so we try that if we can
2607       my %tokenopts = (
2608         'payment_gateway' => $gateway,
2609         'method'          => 'CC',
2610         'payinfo'         => $record->payinfo,
2611         'paydate'         => $record->paydate,
2612       );
2613       my $error = $cust_main
2614                 ? $cust_main->realtime_tokenize(\%tokenopts)
2615                 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2616       if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2617         $record->payinfo($tokenopts{'payinfo'});
2618         $error = $record->replace;
2619       } else {
2620         $error ||= 'Unknown error';
2621       }
2622       if ($error) {
2623         $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2624         if ($opt{'queue'}) {
2625           $log->critical($error);
2626           $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2627           next;
2628         }
2629         $dbh->rollback if $oldAutoCommit;
2630         die $error;
2631       }
2632       $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2633       warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2634
2635     } # end record loop
2636   } # end table loop
2637
2638   $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2639
2640   return '';
2641 }
2642
2643 # not a method!
2644 sub _token_check_next_recnum {
2645   my ($dbh,$table,$step,$offset,$recnums) = @_;
2646   my $recnum = shift @$recnums;
2647   return $recnum if $recnum;
2648   my $tclass = 'FS::'.$table;
2649   my $sth = $dbh->prepare('SELECT '.$tclass->primary_key.' FROM '.$table.' ORDER BY '.$tclass->primary_key.' LIMIT '.$step.' OFFSET '.$$offset) or die $dbh->errstr;
2650   $sth->execute() or die $sth->errstr;
2651   my @recnums;
2652   while (my $rec = $sth->fetchrow_hashref) {
2653     push @$recnums, $rec->{$tclass->primary_key};
2654   }
2655   $sth->finish();
2656   $$offset += $step;
2657   return shift @$recnums;
2658 }
2659
2660 # not a method!
2661 sub _token_check_gateway_info {
2662   my ($cache,$payment_gateway) = @_;
2663
2664   return $cache->{$payment_gateway->gateway_module}
2665     if $cache->{$payment_gateway->gateway_module};
2666
2667   my $info = {};
2668   $cache->{$payment_gateway->gateway_module} = $info;
2669
2670   my $namespace = $payment_gateway->gateway_namespace;
2671   return $info unless $namespace eq 'Business::OnlinePayment';
2672   $info->{'is_bop'} = 1;
2673
2674   # only need to load this once,
2675   # don't want to load if nothing is_bop
2676   unless ($cache->{'Business::OnlinePayment'}) {
2677     eval "use $namespace";  
2678     return "Error initializing Business:OnlinePayment: ".$@ if $@;
2679     $cache->{'Business::OnlinePayment'} = 1;
2680   }
2681
2682   my $transaction = new $namespace( $payment_gateway->gateway_module,
2683                                     _bop_options({ 'payment_gateway' => $payment_gateway }),
2684                                   );
2685
2686   return $info unless $transaction->can('info');
2687   $info->{'can_info'} = 1;
2688
2689   my %supported_actions = $transaction->info('supported_actions');
2690   $info->{'can_tokenize'} = 1
2691     if $supported_actions{'CC'}
2692       && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2693
2694   # not using this any more, but for future reference...
2695   $info->{'void_requires_card'} = 1
2696     if $transaction->info('CC_void_requires_card');
2697
2698   return $info;
2699 }
2700
2701 =back
2702
2703 =head1 BUGS
2704
2705 =head1 SEE ALSO
2706
2707 L<FS::cust_main>, L<FS::cust_main::Billing>
2708
2709 =cut
2710
2711 1;