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