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