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