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