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