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