1 package FS::cust_main::Billing_Realtime;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
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 );
13 use FS::cust_pay_pending;
14 use FS::cust_bill_pay;
17 use FS::payment_gateway;
19 $realtime_bop_decline_quiet = 0;
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
25 $me = '[FS::cust_main::Billing_Realtime]';
28 our $BOP_TESTING_SUCCESS = 1;
30 install_callback FS::UID sub {
32 #yes, need it for stuff below (prolly should be cached)
37 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
43 These methods are available on FS::cust_main objects.
49 =item realtime_collect [ OPTION => VALUE ... ]
51 Attempt to collect the customer's current balance with a realtime credit
52 card or electronic check transaction (see realtime_bop() below).
54 Returns the result of realtime_bop(): nothing, an error message, or a
55 hashref of state information for a third-party transaction.
57 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
59 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
60 then it is deduced from the customer record.
62 If no I<amount> is specified, then the customer balance is used.
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.
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.
72 If an I<invnum> is specified, this payment (if successful) is applied to the
75 I<apply> will automatically apply a resulting payment.
77 I<quiet> can be set true to suppress email decline notices.
79 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
80 resulting paynum, if any.
82 I<payunique> is a unique identifier for this payment.
84 I<session_id> is a session identifier associated with this payment.
86 I<depend_jobnum> allows payment capture to unlock export jobs
90 sub realtime_collect {
91 my( $self, %options ) = @_;
93 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
96 warn "$me realtime_collect:\n";
97 warn " $_ => $options{$_}\n" foreach keys %options;
100 $options{amount} = $self->balance unless exists( $options{amount} );
101 return '' unless $options{amount} > 0;
103 $options{method} = FS::payby->payby2bop($self->payby)
104 unless exists( $options{method} );
106 return $self->realtime_bop({%options});
110 =item realtime_bop { [ ARG => VALUE ... ] }
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.
116 Required arguments in the hashref are I<method>, and I<amount>
118 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
120 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
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.
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.
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.
135 I<no_invnum> can be set to true to prevent that default invnum from being set.
137 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
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.)
143 I<quiet> can be set true to surpress email decline notices.
145 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
146 resulting paynum, if any.
148 I<payunique> is a unique identifier for this payment.
150 I<session_id> is a session identifier associated with this payment.
152 I<depend_jobnum> allows payment capture to unlock export jobs
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.
157 A direct (Business::OnlinePayment) transaction will return nothing on success,
158 or an error message on failure.
160 A third-party transaction will return a hashref containing:
162 - popup_url: the URL to which a browser should be redirected to complete
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.
167 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
171 # some helper routines
172 sub _bop_recurring_billing {
173 my( $self, %opt ) = @_;
175 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
177 if ( defined($method) && $method eq 'transaction_is_recur' ) {
179 return 1 if $opt{'trans_is_recur'};
183 # return 1 if the payinfo has been used for another payment
184 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
192 #can run safely as class method if opt payment_gateway already exists
193 sub _payment_gateway {
194 my ($self, $options) = @_;
196 if ( $options->{'fake_gatewaynum'} ) {
197 $options->{payment_gateway} =
198 qsearchs('payment_gateway',
199 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
203 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
204 unless exists($options->{payment_gateway});
206 $options->{payment_gateway};
214 'login' => $options->{payment_gateway}->gateway_username,
215 'password' => $options->{payment_gateway}->gateway_password,
223 $options->{payment_gateway}->gatewaynum
224 ? $options->{payment_gateway}->options
225 : @{ $options->{payment_gateway}->get('options') };
230 my ($self, $options) = @_;
232 unless ( $options->{'description'} ) {
233 if ( $conf->exists('business-onlinepayment-description') ) {
234 my $dtempl = $conf->config('business-onlinepayment-description');
236 my $agent = $self->agent->agent;
238 $options->{'description'} = eval qq("$dtempl");
240 $options->{'description'} = 'Internet services';
244 unless ( exists( $options->{'payinfo'} ) ) {
245 $options->{'payinfo'} = $self->payinfo;
246 $options->{'paymask'} = $self->paymask;
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;
256 $options->{payname} = $self->payname unless exists( $options->{payname} );
259 # can be called as class method,
260 # but can't load default fields as class method
262 my ($self, $options) = @_;
265 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : (ref($self) ? $self->payip : '');
266 $content{customer_ip} = $payip if length($payip);
268 $content{invoice_number} = $options->{'invnum'}
269 if exists($options->{'invnum'}) && length($options->{'invnum'});
271 $content{email_customer} =
272 ( $conf->exists('business-onlinepayment-email_customer')
273 || $conf->exists('business-onlinepayment-email-override') );
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";
287 $content{last_name} = $paylast if $paylast;
288 $content{first_name} = $payfirst if $payfirst;
290 $content{name} = $payname if $payname;
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);
300 $content{city} = exists($options->{city})
302 : (ref($self) ? $self->city : '');
303 $content{state} = exists($options->{state})
305 : (ref($self) ? $self->state : '');
306 $content{zip} = exists($options->{zip})
308 : (ref($self) ? $self->zip : '');
309 $content{country} = exists($options->{country})
310 ? $options->{country}
311 : (ref($self) ? $self->country : '');
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/';
317 # can't set phone if called as class method
318 $content{phone} = $self->daytime || $self->night
321 my $currency = $conf->exists('business-onlinepayment-currency')
322 && $conf->config('business-onlinepayment-currency');
323 $content{currency} = $currency if $currency;
328 # updates payinfo option & cust_main with token from transaction
329 # can be called as a class method
331 my ($self,$transaction,$options) = @_;
332 if ( $transaction->can('card_token')
333 and $transaction->card_token
334 and !FS::payinfo_Mixin->tokenized($options->{'payinfo'})
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;
344 my %bop_method2payby = (
353 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
355 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
358 if (ref($_[0]) eq 'HASH') {
361 my ( $method, $amount ) = ( shift, shift );
363 $options{method} = $method;
364 $options{amount} = $amount;
369 # optional credit card surcharge
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';
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)?
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 ));
390 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
391 $options{'cc_surcharge'} = $cc_surcharge;
395 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
396 warn " cc_surcharge = $cc_surcharge\n";
399 warn " $_ => $options{$_}\n" foreach keys %options;
402 return $self->fake_bop(\%options) if $options{'fake'};
404 $self->_bop_defaults(\%options);
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;
420 # set trans_is_recur based on invnum if there is one
423 my $trans_is_recur = 0;
424 if ( $options{'invnum'} ) {
426 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
427 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
433 $cust_bill->cust_bill_pkg;
436 if grep { $_->freq ne '0' } @part_pkg;
444 my $payment_gateway = $self->_payment_gateway( \%options );
445 my $namespace = $payment_gateway->gateway_namespace;
447 eval "use $namespace";
451 # check for banned credit card/ACH
454 my $ban = FS::banned_pay->ban_search(
455 'payby' => $bop_method2payby{$options{method}},
456 'payinfo' => $options{payinfo},
458 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
461 # check for term discount validity
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(
470 months => $discount_term
471 ) or return "No discount available for term '$discount_term'";
473 if ( $plan->discounted_total != $options{amount} ) {
474 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
482 my $bop_content = $self->_bop_content(\%options);
483 return $bop_content unless ref($bop_content);
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;
492 my $email = ($conf->exists('business-onlinepayment-email-override'))
493 ? $conf->config('business-onlinepayment-email-override')
494 : $invoicing_list[0];
499 if ( $namespace eq 'Business::OnlinePayment' ) {
501 if ( $options{method} eq 'CC' ) {
503 $content{card_number} = $options{payinfo};
504 $paydate = exists($options{'paydate'})
505 ? $options{'paydate'}
507 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
508 $content{expiration} = "$2/$1";
510 my $paycvv = exists($options{'paycvv'})
513 $content{cvv2} = $paycvv
516 my $paystart_month = exists($options{'paystart_month'})
517 ? $options{'paystart_month'}
518 : $self->paystart_month;
520 my $paystart_year = exists($options{'paystart_year'})
521 ? $options{'paystart_year'}
522 : $self->paystart_year;
524 $content{card_start} = "$paystart_month/$paystart_year"
525 if $paystart_month && $paystart_year;
527 my $payissue = exists($options{'payissue'})
528 ? $options{'payissue'}
530 $content{issue_number} = $payissue if $payissue;
532 if ( $self->_bop_recurring_billing(
533 'payinfo' => $options{'payinfo'},
534 'trans_is_recur' => $trans_is_recur,
538 $content{recurring_billing} = 'YES';
539 $content{acct_code} = 'rebill'
540 if $conf->exists('credit_card-recurring_billing_acct_code');
543 } elsif ( $options{method} eq 'ECHECK' ){
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';
556 $content{company} = $self->company if $self->company;
558 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
559 $content{account_name} = $self->company;
561 $content{account_name} = $self->getfield('first'). ' '.
562 $self->getfield('last');
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'})
577 die "unknown method ". $options{method};
580 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
583 die "unknown namespace $namespace";
590 my $balance = exists( $options{'balance'} )
591 ? $options{'balance'}
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;
598 #the checks here are intended to catch concurrent payments
599 #double-form-submission prevention is taken care of in cust_pay_pending::check
602 return "The customer's balance has changed; $options{method} transaction aborted."
603 if $self->balance < $balance;
605 #also check and make sure there aren't *other* pending payments for this cust
607 my @pending = qsearch('cust_pay_pending', {
608 'custnum' => $self->custnum,
609 'status' => { op=>'!=', value=>'done' }
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"
621 @pending = grep { $_->status ne 'thirdparty' } @pending;
624 return "A payment is already being processed for this customer (".
625 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
626 "); $options{method} transaction aborted."
629 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
631 my $cust_pay_pending = new FS::cust_pay_pending {
632 'custnum' => $self->custnum,
633 'paid' => $options{amount},
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'},
642 'gatewaynum' => $payment_gateway->gatewaynum || '',
643 'session_id' => $options{session_id} || '',
644 'jobnum' => $options{depend_jobnum} || '',
646 $cust_pay_pending->payunique( $options{payunique} )
647 if defined($options{payunique}) && length($options{payunique});
649 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
651 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
652 return $cpp_new_err if $cpp_new_err;
654 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
656 warn Dumper($cust_pay_pending) if $DEBUG > 2;
658 my( $action1, $action2 ) =
659 split( /\s*\,\s*/, $payment_gateway->gateway_action );
661 my $transaction = new $namespace( $payment_gateway->gateway_module,
662 _bop_options(\%options),
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,
674 'reference' => $cust_pay_pending->paypendingnum, #for now
675 'callback_url' => $payment_gateway->gateway_callback_url,
676 'cancel_url' => $payment_gateway->gateway_cancel_url,
681 $cust_pay_pending->status('pending');
682 my $cpp_pending_err = $cust_pay_pending->replace;
683 return $cpp_pending_err if $cpp_pending_err;
685 warn Dumper($transaction) if $DEBUG > 2;
687 unless ( $BOP_TESTING ) {
688 $transaction->test_transaction(1)
689 if $conf->exists('business-onlinepayment-test_transaction');
690 $transaction->submit();
692 if ( $BOP_TESTING_SUCCESS ) {
693 $transaction->is_success(1);
694 $transaction->authorization('fake auth');
696 $transaction->is_success(0);
697 $transaction->error_message('fake failure');
701 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
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 ) };
709 } elsif ( $transaction->is_success() && $action2 ) {
711 $cust_pay_pending->status('authorized');
712 my $cpp_authorized_err = $cust_pay_pending->replace;
713 return $cpp_authorized_err if $cpp_authorized_err;
715 my $auth = $transaction->authorization;
716 my $ordernum = $transaction->can('order_number')
717 ? $transaction->order_number
721 new Business::OnlinePayment( $payment_gateway->gateway_module,
722 _bop_options(\%options),
727 type => $options{method},
729 _bop_auth(\%options),
730 order_number => $ordernum,
731 amount => $options{amount},
732 authorization => $auth,
733 description => $options{'description'},
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);
743 $capture->content( %capture );
745 $capture->test_transaction(1)
746 if $conf->exists('business-onlinepayment-test_transaction');
749 unless ( $capture->is_success ) {
750 my $e = "Authorization successful but capture failed, custnum #".
751 $self->custnum. ': '. $capture->result_code.
752 ": ". $capture->error_message;
760 # remove paycvv after initial transaction
763 #false laziness w/misc/process/payment.cgi - check both to make sure working
765 if ( length($self->paycvv)
766 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
768 my $error = $self->remove_cvv;
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";
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 ( $transaction->can('card_token') && $transaction->card_token ) {
783 if ( $options{'payinfo'} eq $self->payinfo ) {
784 $self->payinfo($transaction->card_token);
785 my $error = $self->replace;
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";
799 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
811 if (ref($_[0]) eq 'HASH') {
814 my ( $method, $amount ) = ( shift, shift );
816 $options{method} = $method;
817 $options{amount} = $amount;
820 if ( $options{'fake_failure'} ) {
821 return "Error: No error; test failure requested with fake_failure";
824 my $cust_pay = new FS::cust_pay ( {
825 'custnum' => $self->custnum,
826 'invnum' => $options{'invnum'},
827 'paid' => $options{amount},
829 'payby' => $bop_method2payby{$options{method}},
830 'payinfo' => '4111111111111111',
831 'paydate' => '2012-05-01',
832 'processor' => 'FakeProcessor',
834 'order_number' => '32',
836 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
839 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
840 warn " $_ => $options{$_}\n" foreach keys %options;
843 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
846 $cust_pay->invnum(''); #try again with no specific invnum
847 my $error2 = $cust_pay->insert( $options{'manual'} ?
848 ( 'manual' => 1 ) : ()
851 # gah, even with transactions.
852 my $e = 'WARNING: Card/ACH debited but database not updated - '.
853 "error inserting (fake!) payment: $error2".
854 " (previously tried insert with invnum #$options{'invnum'}" .
861 if ( $options{'paynum_ref'} ) {
862 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
870 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
872 # Wraps up processing of a realtime credit card or ACH (electronic check)
875 sub _realtime_bop_result {
876 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
878 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
881 warn "$me _realtime_bop_result: pending transaction ".
882 $cust_pay_pending->paypendingnum. "\n";
883 warn " $_ => $options{$_}\n" foreach keys %options;
886 my $payment_gateway = $options{payment_gateway}
887 or return "no payment gateway in arguments to _realtime_bop_result";
889 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
890 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
891 return $cpp_captured_err if $cpp_captured_err;
893 if ( $transaction->is_success() ) {
895 my $order_number = $transaction->order_number
896 if $transaction->can('order_number');
898 my $cust_pay = new FS::cust_pay ( {
899 'custnum' => $self->custnum,
900 'invnum' => $options{'invnum'},
901 'paid' => $cust_pay_pending->paid,
903 'payby' => $cust_pay_pending->payby,
904 'payinfo' => $options{'payinfo'},
905 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
906 'paydate' => $cust_pay_pending->paydate,
907 'pkgnum' => $cust_pay_pending->pkgnum,
908 'discount_term' => $options{'discount_term'},
909 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
910 'processor' => $payment_gateway->gateway_module,
911 'auth' => $transaction->authorization,
912 'order_number' => $order_number || '',
913 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
915 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
916 $cust_pay->payunique( $options{payunique} )
917 if defined($options{payunique}) && length($options{payunique});
919 my $oldAutoCommit = $FS::UID::AutoCommit;
920 local $FS::UID::AutoCommit = 0;
923 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
925 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
928 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
929 $cust_pay->invnum(''); #try again with no specific invnum
930 $cust_pay->paynum('');
931 my $error2 = $cust_pay->insert( $options{'manual'} ?
932 ( 'manual' => 1 ) : ()
935 # gah. but at least we have a record of the state we had to abort in
936 # from cust_pay_pending now.
937 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
938 my $e = "WARNING: $options{method} captured but payment not recorded -".
939 " error inserting payment (". $payment_gateway->gateway_module.
941 " (previously tried insert with invnum #$options{'invnum'}" .
942 ": $error ) - pending payment saved as paypendingnum ".
943 $cust_pay_pending->paypendingnum. "\n";
949 my $jobnum = $cust_pay_pending->jobnum;
951 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
953 unless ( $placeholder ) {
954 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
955 my $e = "WARNING: $options{method} captured but job $jobnum not ".
956 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
961 $error = $placeholder->delete;
964 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
965 my $e = "WARNING: $options{method} captured but could not delete ".
966 "job $jobnum for paypendingnum ".
967 $cust_pay_pending->paypendingnum. ": $error\n";
974 if ( $options{'paynum_ref'} ) {
975 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
978 $cust_pay_pending->status('done');
979 $cust_pay_pending->statustext('captured');
980 $cust_pay_pending->paynum($cust_pay->paynum);
981 my $cpp_done_err = $cust_pay_pending->replace;
983 if ( $cpp_done_err ) {
985 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
986 my $e = "WARNING: $options{method} captured but payment not recorded - ".
987 "error updating status for paypendingnum ".
988 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
994 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
996 if ( $options{'apply'} ) {
997 my $apply_error = $self->apply_payments_and_credits;
998 if ( $apply_error ) {
999 warn "WARNING: error applying payment: $apply_error\n";
1000 #but we still should return no error cause the payment otherwise went
1005 # have a CC surcharge portion --> one-time charge
1006 if ( $options{'cc_surcharge'} > 0 ) {
1007 # XXX: this whole block needs to be in a transaction?
1010 $invnum = $options{'invnum'} if $options{'invnum'};
1011 unless ( $invnum ) { # probably from a payment screen
1012 # do we have any open invoices? pick earliest
1013 # uses the fact that cust_main->cust_bill sorts by date ascending
1014 my @open = $self->open_cust_bill;
1015 $invnum = $open[0]->invnum if scalar(@open);
1018 unless ( $invnum ) { # still nothing? pick last closed invoice
1019 # again uses fact that cust_main->cust_bill sorts by date ascending
1020 my @closed = $self->cust_bill;
1021 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1024 unless ( $invnum ) {
1025 # XXX: unlikely case - pre-paying before any invoices generated
1026 # what it should do is create a new invoice and pick it
1027 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1032 my $charge_error = $self->charge({
1033 'amount' => $options{'cc_surcharge'},
1034 'pkg' => 'Credit Card Surcharge',
1036 'cust_pkg_ref' => \$cust_pkg,
1039 warn 'Unable to add CC surcharge cust_pkg';
1043 $cust_pkg->setup(time);
1044 my $cp_error = $cust_pkg->replace;
1046 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1050 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1051 unless ( $cust_bill ) {
1052 warn "race condition + invoice deletion just happened";
1057 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1059 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1063 return ''; #no error
1069 my $perror = $payment_gateway->gateway_module. " error: ".
1070 $transaction->error_message;
1072 my $jobnum = $cust_pay_pending->jobnum;
1074 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1076 if ( $placeholder ) {
1077 my $error = $placeholder->depended_delete;
1078 $error ||= $placeholder->delete;
1079 warn "error removing provisioning jobs after declined paypendingnum ".
1080 $cust_pay_pending->paypendingnum. ": $error\n";
1082 my $e = "error finding job $jobnum for declined paypendingnum ".
1083 $cust_pay_pending->paypendingnum. "\n";
1089 unless ( $transaction->error_message ) {
1092 if ( $transaction->can('response_page') ) {
1094 'page' => ( $transaction->can('response_page')
1095 ? $transaction->response_page
1098 'code' => ( $transaction->can('response_code')
1099 ? $transaction->response_code
1102 'headers' => ( $transaction->can('response_headers')
1103 ? $transaction->response_headers
1109 "No additional debugging information available for ".
1110 $payment_gateway->gateway_module;
1113 $perror .= "No error_message returned from ".
1114 $payment_gateway->gateway_module. " -- ".
1115 ( ref($t_response) ? Dumper($t_response) : $t_response );
1119 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1120 && $conf->exists('emaildecline', $self->agentnum)
1121 && grep { $_ ne 'POST' } $self->invoicing_list
1122 && ! grep { $transaction->error_message =~ /$_/ }
1123 $conf->config('emaildecline-exclude', $self->agentnum)
1126 # Send a decline alert to the customer.
1127 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1130 # include the raw error message in the transaction state
1131 $cust_pay_pending->setfield('error', $transaction->error_message);
1132 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1133 $error = $msg_template->send( 'cust_main' => $self,
1134 'object' => $cust_pay_pending );
1138 my @templ = $conf->config('declinetemplate');
1139 my $template = new Text::Template (
1141 SOURCE => [ map "$_\n", @templ ],
1142 ) or return "($perror) can't create template: $Text::Template::ERROR";
1143 $template->compile()
1144 or return "($perror) can't compile template: $Text::Template::ERROR";
1148 scalar( $conf->config('company_name', $self->agentnum ) ),
1149 'company_address' =>
1150 join("\n", $conf->config('company_address', $self->agentnum ) ),
1151 'error' => $transaction->error_message,
1154 my $error = send_email(
1155 'from' => $conf->invoice_from_full( $self->agentnum ),
1156 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
1157 'subject' => 'Your payment could not be processed',
1158 'body' => [ $template->fill_in(HASH => $templ_hash) ],
1162 $perror .= " (also received error sending decline notification: $error)"
1167 $cust_pay_pending->status('done');
1168 $cust_pay_pending->statustext("declined: $perror");
1169 my $cpp_done_err = $cust_pay_pending->replace;
1170 if ( $cpp_done_err ) {
1171 my $e = "WARNING: $options{method} declined but pending payment not ".
1172 "resolved - error updating status for paypendingnum ".
1173 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1175 $perror = "$e ($perror)";
1183 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1185 Verifies successful third party processing of a realtime credit card or
1186 ACH (electronic check) transaction via a
1187 Business::OnlineThirdPartyPayment realtime gateway. See
1188 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1190 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1192 The additional options I<payname>, I<city>, I<state>,
1193 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1194 if set, will override the value from the customer record.
1196 I<description> is a free-text field passed to the gateway. It defaults to
1197 "Internet services".
1199 If an I<invnum> is specified, this payment (if successful) is applied to the
1200 specified invoice. If you don't specify an I<invnum> you might want to
1201 call the B<apply_payments> method.
1203 I<quiet> can be set true to surpress email decline notices.
1205 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1206 resulting paynum, if any.
1208 I<payunique> is a unique identifier for this payment.
1210 Returns a hashref containing elements bill_error (which will be undefined
1211 upon success) and session_id of any associated session.
1215 sub realtime_botpp_capture {
1216 my( $self, $cust_pay_pending, %options ) = @_;
1218 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1221 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1222 warn " $_ => $options{$_}\n" foreach keys %options;
1225 eval "use Business::OnlineThirdPartyPayment";
1229 # select the gateway
1232 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1234 my $payment_gateway;
1235 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1236 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1237 { gatewaynum => $gatewaynum }
1239 : $self->agent->payment_gateway( 'method' => $method,
1240 # 'invnum' => $cust_pay_pending->invnum,
1241 # 'payinfo' => $cust_pay_pending->payinfo,
1244 $options{payment_gateway} = $payment_gateway; # for the helper subs
1250 my @invoicing_list = $self->invoicing_list_emailonly;
1251 if ( $conf->exists('emailinvoiceautoalways')
1252 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1253 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1254 push @invoicing_list, $self->all_emails;
1257 my $email = ($conf->exists('business-onlinepayment-email-override'))
1258 ? $conf->config('business-onlinepayment-email-override')
1259 : $invoicing_list[0];
1263 $content{email_customer} =
1264 ( $conf->exists('business-onlinepayment-email_customer')
1265 || $conf->exists('business-onlinepayment-email-override') );
1268 # run transaction(s)
1272 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1273 _bop_options(\%options),
1276 $transaction->reference({ %options });
1278 $transaction->content(
1280 _bop_auth(\%options),
1281 'action' => 'Post Authorization',
1282 'description' => $options{'description'},
1283 'amount' => $cust_pay_pending->paid,
1284 #'invoice_number' => $options{'invnum'},
1285 'customer_id' => $self->custnum,
1287 #3.0 is a good a time as any to get rid of this... add a config to pass it
1288 # if anyone still needs it
1289 #'referer' => 'http://cleanwhisker.420.am/',
1291 'reference' => $cust_pay_pending->paypendingnum,
1293 'phone' => $self->daytime || $self->night,
1295 # plus whatever is required for bogus capture avoidance
1298 $transaction->submit();
1301 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1303 if ( $options{'apply'} ) {
1304 my $apply_error = $self->apply_payments_and_credits;
1305 if ( $apply_error ) {
1306 warn "WARNING: error applying payment: $apply_error\n";
1311 bill_error => $error,
1312 session_id => $cust_pay_pending->session_id,
1317 =item default_payment_gateway
1319 DEPRECATED -- use agent->payment_gateway
1323 sub default_payment_gateway {
1324 my( $self, $method ) = @_;
1326 die "Real-time processing not enabled\n"
1327 unless $conf->exists('business-onlinepayment');
1329 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1332 my $bop_config = 'business-onlinepayment';
1333 $bop_config .= '-ach'
1334 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1335 my ( $processor, $login, $password, $action, @bop_options ) =
1336 $conf->config($bop_config);
1337 $action ||= 'normal authorization';
1338 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1339 die "No real-time processor is enabled - ".
1340 "did you set the business-onlinepayment configuration value?\n"
1343 ( $processor, $login, $password, $action, @bop_options )
1346 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1348 Refunds a realtime credit card or ACH (electronic check) transaction
1349 via a Business::OnlinePayment realtime gateway. See
1350 L<http://420.am/business-onlinepayment> for supported gateways.
1352 Available methods are: I<CC> or I<ECHECK>
1354 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1356 Most gateways require a reference to an original payment transaction to refund,
1357 so you probably need to specify a I<paynum>.
1359 I<amount> defaults to the original amount of the payment if not specified.
1361 I<reasonnum> specifies a reason for the refund.
1363 I<paydate> specifies the expiration date for a credit card overriding the
1364 value from the customer record or the payment record. Specified as yyyy-mm-dd
1366 Implementation note: If I<amount> is unspecified or equal to the amount of the
1367 orignal payment, first an attempt is made to "void" the transaction via
1368 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1369 the normal attempt is made to "refund" ("credit") the transaction via the
1370 gateway is attempted. No attempt to "void" the transaction is made if the
1371 gateway has introspection data and doesn't support void.
1373 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1374 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1375 #if set, will override the value from the customer record.
1377 #If an I<invnum> is specified, this payment (if successful) is applied to the
1378 #specified invoice. If you don't specify an I<invnum> you might want to
1379 #call the B<apply_payments> method.
1383 #some false laziness w/realtime_bop, not enough to make it worth merging
1384 #but some useful small subs should be pulled out
1385 sub realtime_refund_bop {
1388 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1391 if (ref($_[0]) eq 'HASH') {
1392 %options = %{$_[0]};
1396 $options{method} = $method;
1399 my ($reason, $reason_text);
1400 if ( $options{'reasonnum'} ) {
1401 # do this here, because we need the plain text reason string in case we
1403 $reason = FS::reason->by_key($options{'reasonnum'});
1404 $reason_text = $reason->reason;
1406 # support old 'reason' string parameter in case it's still used,
1407 # or else set a default
1408 $reason_text = $options{'reason'} || 'card or ACH refund';
1410 $reason = FS::reason->new_or_existing(
1411 reason => $reason_text,
1412 type => 'Refund reason',
1416 return "failed to add refund reason: $@";
1421 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1422 warn " $_ => $options{$_}\n" foreach keys %options;
1428 # look up the original payment and optionally a gateway for that payment
1432 my $amount = $options{'amount'};
1434 my( $processor, $login, $password, @bop_options, $namespace ) ;
1435 my( $auth, $order_number ) = ( '', '', '' );
1436 my $gatewaynum = '';
1438 if ( $options{'paynum'} ) {
1440 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1441 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1442 or return "Unknown paynum $options{'paynum'}";
1443 $amount ||= $cust_pay->paid;
1445 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1446 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1448 if ( $cust_pay->get('processor') ) {
1449 ($gatewaynum, $processor, $auth, $order_number) =
1451 $cust_pay->gatewaynum,
1452 $cust_pay->processor,
1454 $cust_pay->order_number,
1457 # this payment wasn't upgraded, which probably means this won't work,
1459 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1460 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1461 $cust_pay->paybatch;
1462 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1465 my $payment_gateway;
1466 if ( $gatewaynum ) { #gateway for the payment to be refunded
1469 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1470 die "payment gateway $gatewaynum not found"
1471 unless $payment_gateway;
1473 $processor = $payment_gateway->gateway_module;
1474 $login = $payment_gateway->gateway_username;
1475 $password = $payment_gateway->gateway_password;
1476 $namespace = $payment_gateway->gateway_namespace;
1477 @bop_options = $payment_gateway->options;
1479 } else { #try the default gateway
1483 $self->agent->payment_gateway('method' => $options{method});
1485 ( $conf_processor, $login, $password, $namespace ) =
1486 map { my $method = "gateway_$_"; $payment_gateway->$method }
1487 qw( module username password namespace );
1489 @bop_options = $payment_gateway->gatewaynum
1490 ? $payment_gateway->options
1491 : @{ $payment_gateway->get('options') };
1492 my %bop_options = @bop_options;
1494 return "processor of payment $options{'paynum'} $processor does not".
1495 " match default processor $conf_processor"
1496 unless ($processor eq $conf_processor)
1497 || (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}));
1499 $processor = $conf_processor;
1503 # if gateway has switched to CardFortress but token_check hasn't run yet,
1504 # tokenize just this record now, so that token gets passed/set appropriately
1505 if ($cust_pay->payby eq 'CARD' && !$cust_pay->tokenized) {
1507 'payment_gateway' => $payment_gateway,
1509 'payinfo' => $cust_pay->payinfo,
1510 'paydate' => $cust_pay->paydate,
1512 my $error = $self->realtime_tokenize(\%tokenopts); # no-op unless gateway can tokenize
1513 if ($self->tokenized($tokenopts{'payinfo'})) { # implies no error
1514 warn " tokenizing cust_pay\n" if $DEBUG > 1;
1515 $cust_pay->payinfo($tokenopts{'payinfo'});
1516 $error = $cust_pay->replace;
1518 return $error if $error;
1521 } else { # didn't specify a paynum, so look for agent gateway overrides
1522 # like a normal transaction
1524 my $payment_gateway =
1525 $self->agent->payment_gateway( 'method' => $options{method} );
1526 my( $processor, $login, $password, $namespace ) =
1527 map { my $method = "gateway_$_"; $payment_gateway->$method }
1528 qw( module username password namespace );
1530 my @bop_options = $payment_gateway->gatewaynum
1531 ? $payment_gateway->options
1532 : @{ $payment_gateway->get('options') };
1535 return "neither amount nor paynum specified" unless $amount;
1537 eval "use $namespace";
1542 'type' => $options{method},
1544 'password' => $password,
1545 'order_number' => $order_number,
1546 'amount' => $amount,
1548 #3.0 is a good a time as any to get rid of this... add a config to pass it
1549 # if anyone still needs it
1550 #'referer' => 'http://cleanwhisker.420.am/',
1552 $content{authorization} = $auth
1553 if length($auth); #echeck/ACH transactions have an order # but no auth
1554 #(at least with authorize.net)
1556 my $currency = $conf->exists('business-onlinepayment-currency')
1557 && $conf->config('business-onlinepayment-currency');
1558 $content{currency} = $currency if $currency;
1560 my $disable_void_after;
1561 if ($conf->exists('disable_void_after')
1562 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1563 $disable_void_after = $1;
1566 #first try void if applicable
1567 my $void = new Business::OnlinePayment( $processor, @bop_options );
1570 if ($void->can('info')) {
1572 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1573 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1574 my %supported_actions = $void->info('supported_actions');
1576 if ( %supported_actions && $paytype
1577 && defined($supported_actions{$paytype})
1578 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1581 if ( $cust_pay && $cust_pay->paid == $amount
1583 ( not defined($disable_void_after) )
1584 || ( time < ($cust_pay->_date + $disable_void_after ) )
1588 warn " attempting void\n" if $DEBUG > 1;
1589 if ( $void->can('info') ) {
1590 if ( $cust_pay->payby eq 'CARD'
1591 && $void->info('CC_void_requires_card') )
1593 $content{'card_number'} = $cust_pay->payinfo;
1594 } elsif ( $cust_pay->payby eq 'CHEK'
1595 && $void->info('ECHECK_void_requires_account') )
1597 ( $content{'account_number'}, $content{'routing_code'} ) =
1598 split('@', $cust_pay->payinfo);
1599 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1602 if ( $cust_pay->payby eq 'CARD'
1603 && !$content{'card_number'}
1604 && $cust_pay->tokenized
1606 $content{'card_token'} = $cust_pay->payinfo;
1608 $void->content( 'action' => 'void', %content );
1609 $void->test_transaction(1)
1610 if $conf->exists('business-onlinepayment-test_transaction');
1612 if ( $void->is_success ) {
1613 my $error = $cust_pay->void($reason_text);
1615 # gah, even with transactions.
1616 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1617 "error voiding payment: $error";
1621 warn " void successful\n" if $DEBUG > 1;
1626 warn " void unsuccessful, trying refund\n"
1630 my $address = $self->address1;
1631 $address .= ", ". $self->address2 if $self->address2;
1633 my($payname, $payfirst, $paylast);
1634 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1635 $payname = $self->payname;
1636 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1637 or return "Illegal payname $payname";
1638 ($payfirst, $paylast) = ($1, $2);
1640 $payfirst = $self->getfield('first');
1641 $paylast = $self->getfield('last');
1642 $payname = "$payfirst $paylast";
1645 my @invoicing_list = $self->invoicing_list_emailonly;
1646 if ( $conf->exists('emailinvoiceautoalways')
1647 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1648 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1649 push @invoicing_list, $self->all_emails;
1652 my $email = ($conf->exists('business-onlinepayment-email-override'))
1653 ? $conf->config('business-onlinepayment-email-override')
1654 : $invoicing_list[0];
1656 my $payip = exists($options{'payip'})
1659 $content{customer_ip} = $payip
1663 my $paymask = ''; # for refund record
1664 if ( $options{method} eq 'CC' ) {
1667 $content{card_number} = $payinfo = $cust_pay->payinfo;
1668 $paymask = $cust_pay->paymask;
1669 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1670 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1671 ($content{expiration} = "$2/$1"); # where available
1673 $content{card_number} = $payinfo = $self->payinfo;
1674 $paymask = $self->paymask;
1675 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1676 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1677 $content{expiration} = "$2/$1";
1680 } elsif ( $options{method} eq 'ECHECK' ) {
1683 $payinfo = $cust_pay->payinfo;
1685 $payinfo = $self->payinfo;
1687 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1688 $content{bank_name} = $self->payname;
1689 $content{account_type} = 'CHECKING';
1690 $content{account_name} = $payname;
1691 $content{customer_org} = $self->company ? 'B' : 'I';
1692 $content{customer_ssn} = $self->ss;
1697 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1698 my %sub_content = $refund->content(
1699 'action' => 'credit',
1700 'customer_id' => $self->custnum,
1701 'last_name' => $paylast,
1702 'first_name' => $payfirst,
1704 'address' => $address,
1705 'city' => $self->city,
1706 'state' => $self->state,
1707 'zip' => $self->zip,
1708 'country' => $self->country,
1710 'phone' => $self->daytime || $self->night,
1713 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1715 $refund->test_transaction(1)
1716 if $conf->exists('business-onlinepayment-test_transaction');
1719 return "$processor error: ". $refund->error_message
1720 unless $refund->is_success();
1722 $order_number = $refund->order_number if $refund->can('order_number');
1724 # change this to just use $cust_pay->delete_cust_bill_pay?
1725 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1726 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1727 last unless @cust_bill_pay;
1728 my $cust_bill_pay = pop @cust_bill_pay;
1729 my $error = $cust_bill_pay->delete;
1733 my $cust_refund = new FS::cust_refund ( {
1734 'custnum' => $self->custnum,
1735 'paynum' => $options{'paynum'},
1736 'source_paynum' => $options{'paynum'},
1737 'refund' => $amount,
1739 'payby' => $bop_method2payby{$options{method}},
1740 'payinfo' => $payinfo,
1741 'paymask' => $paymask,
1742 'reasonnum' => $reason->reasonnum,
1743 'gatewaynum' => $gatewaynum, # may be null
1744 'processor' => $processor,
1745 'auth' => $refund->authorization,
1746 'order_number' => $order_number,
1748 my $error = $cust_refund->insert;
1750 $cust_refund->paynum(''); #try again with no specific paynum
1751 $cust_refund->source_paynum('');
1752 my $error2 = $cust_refund->insert;
1754 # gah, even with transactions.
1755 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1756 "error inserting refund ($processor): $error2".
1757 " (previously tried insert with paynum #$options{'paynum'}" .
1768 =item realtime_verify_bop [ OPTION => VALUE ... ]
1770 Runs an authorization-only transaction for $1 against this credit card (if
1771 successful, immediatly reverses the authorization).
1773 Returns the empty string if the authorization was sucessful, or an error
1780 I<paydate> specifies the expiration date for a credit card overriding the
1781 value from the customer record or the payment record. Specified as yyyy-mm-dd
1783 #The additional options I<address1>, I<address2>, I<city>, I<state>,
1784 #I<zip> are also available. Any of these options,
1785 #if set, will override the value from the customer record.
1789 #Available methods are: I<CC> or I<ECHECK>
1791 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1792 #it worth merging but some useful small subs should be pulled out
1793 sub realtime_verify_bop {
1796 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1797 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1800 if (ref($_[0]) eq 'HASH') {
1801 %options = %{$_[0]};
1807 warn "$me realtime_verify_bop\n";
1808 warn " $_ => $options{$_}\n" foreach keys %options;
1811 # possibly run a separate transaction to tokenize card number,
1812 # so that we never store tokenized card info in cust_pay_pending
1813 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1814 my $token_error = $self->realtime_tokenize(\%options);
1815 return $token_error if $token_error;
1816 #important that we not replace cust_main here,
1817 #because cust_main->replace uses realtime_verify_bop!
1824 my $payment_gateway = $self->_payment_gateway( \%options );
1825 my $namespace = $payment_gateway->gateway_namespace;
1827 eval "use $namespace";
1831 # check for banned credit card/ACH
1834 my $ban = FS::banned_pay->ban_search(
1835 'payby' => $bop_method2payby{'CC'},
1836 'payinfo' => $options{payinfo} || $self->payinfo,
1838 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1844 my $bop_content = $self->_bop_content(\%options);
1845 return $bop_content unless ref($bop_content);
1847 my @invoicing_list = $self->invoicing_list_emailonly;
1848 if ( $conf->exists('emailinvoiceautoalways')
1849 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1850 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1851 push @invoicing_list, $self->all_emails;
1854 my $email = ($conf->exists('business-onlinepayment-email-override'))
1855 ? $conf->config('business-onlinepayment-email-override')
1856 : $invoicing_list[0];
1861 if ( $namespace eq 'Business::OnlinePayment' ) {
1863 if ( $options{method} eq 'CC' ) {
1865 $content{card_number} = $options{payinfo} || $self->payinfo;
1866 $paydate = exists($options{'paydate'})
1867 ? $options{'paydate'}
1869 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1870 $content{expiration} = "$2/$1";
1872 my $paycvv = exists($options{'paycvv'})
1873 ? $options{'paycvv'}
1875 $content{cvv2} = $paycvv
1878 my $paystart_month = exists($options{'paystart_month'})
1879 ? $options{'paystart_month'}
1880 : $self->paystart_month;
1882 my $paystart_year = exists($options{'paystart_year'})
1883 ? $options{'paystart_year'}
1884 : $self->paystart_year;
1886 $content{card_start} = "$paystart_month/$paystart_year"
1887 if $paystart_month && $paystart_year;
1889 my $payissue = exists($options{'payissue'})
1890 ? $options{'payissue'}
1892 $content{issue_number} = $payissue if $payissue;
1894 } elsif ( $options{method} eq 'ECHECK' ){
1895 #cannot verify, move along (though it shouldn't be called...)
1898 return "unknown method ". $options{method};
1900 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1901 #cannot verify, move along
1904 return "unknown namespace $namespace";
1908 # run transaction(s)
1912 my $transaction; #need this back so we can do _tokenize_card
1914 # don't mutex the customer here, because they might be uncommitted. and
1915 # this is only verification. it doesn't matter if they have other
1916 # unfinished verifications.
1918 my $cust_pay_pending = new FS::cust_pay_pending {
1919 'custnum_pending' => 1,
1922 'payby' => $bop_method2payby{'CC'},
1923 'payinfo' => $options{payinfo} || $self->payinfo,
1924 'paymask' => $options{paymask} || $self->paymask,
1925 'paydate' => $paydate,
1926 'pkgnum' => $options{'pkgnum'},
1928 'gatewaynum' => $payment_gateway->gatewaynum || '',
1929 'session_id' => $options{session_id} || '',
1931 $cust_pay_pending->payunique( $options{payunique} )
1932 if defined($options{payunique}) && length($options{payunique});
1935 # open a separate handle for creating/updating the cust_pay_pending
1937 local $FS::UID::dbh = myconnect();
1938 local $FS::UID::AutoCommit = 1;
1940 # if this is an existing customer (and we can tell now because
1941 # this is a fresh transaction), it's safe to assign their custnum
1942 # to the cust_pay_pending record, and then the verification attempt
1943 # will remain linked to them even if it fails.
1944 if ( FS::cust_main->by_key($self->custnum) ) {
1945 $cust_pay_pending->set('custnum', $self->custnum);
1948 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1951 # if this fails, just return; everything else will still allow the
1952 # cust_pay_pending to have its custnum set later
1953 my $cpp_new_err = $cust_pay_pending->insert;
1954 return $cpp_new_err if $cpp_new_err;
1956 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1958 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1960 $transaction = new $namespace( $payment_gateway->gateway_module,
1961 _bop_options(\%options),
1964 $transaction->content(
1966 _bop_auth(\%options),
1967 'action' => 'Authorization Only',
1968 'description' => $options{'description'},
1970 'customer_id' => $self->custnum,
1972 'reference' => $cust_pay_pending->paypendingnum, #for now
1977 $cust_pay_pending->status('pending');
1978 my $cpp_pending_err = $cust_pay_pending->replace;
1979 return $cpp_pending_err if $cpp_pending_err;
1981 warn Dumper($transaction) if $DEBUG > 2;
1983 unless ( $BOP_TESTING ) {
1984 $transaction->test_transaction(1)
1985 if $conf->exists('business-onlinepayment-test_transaction');
1986 $transaction->submit();
1988 if ( $BOP_TESTING_SUCCESS ) {
1989 $transaction->is_success(1);
1990 $transaction->authorization('fake auth');
1992 $transaction->is_success(0);
1993 $transaction->error_message('fake failure');
1997 if ( $transaction->is_success() ) {
1999 $cust_pay_pending->status('authorized');
2000 my $cpp_authorized_err = $cust_pay_pending->replace;
2001 return $cpp_authorized_err if $cpp_authorized_err;
2003 my $auth = $transaction->authorization;
2004 my $ordernum = $transaction->can('order_number')
2005 ? $transaction->order_number
2008 my $reverse = new $namespace( $payment_gateway->gateway_module,
2009 _bop_options(\%options),
2012 $reverse->content( 'action' => 'Reverse Authorization',
2013 _bop_auth(\%options),
2017 'authorization' => $transaction->authorization,
2018 'order_number' => $ordernum,
2021 'result_code' => $transaction->result_code,
2022 'txn_date' => $transaction->txn_date,
2026 $reverse->test_transaction(1)
2027 if $conf->exists('business-onlinepayment-test_transaction');
2030 if ( $reverse->is_success ) {
2032 $cust_pay_pending->status('done');
2033 $cust_pay_pending->statustext('reversed');
2034 my $cpp_reversed_err = $cust_pay_pending->replace;
2035 return $cpp_reversed_err if $cpp_reversed_err;
2039 my $e = "Authorization successful but reversal failed, custnum #".
2040 $self->custnum. ': '. $reverse->result_code.
2041 ": ". $reverse->error_message;
2048 ### Address Verification ###
2050 # Single-letter codes vary by cardtype.
2052 # Erring on the side of accepting cards if avs is not available,
2053 # only rejecting if avs occurred and there's been an explicit mismatch
2055 # Charts below taken from vSecure documentation,
2056 # shows codes for Amex/Dscv/MC/Visa
2058 # ACCEPTABLE AVS RESPONSES:
2059 # Both Address and 5-digit postal code match Y A Y Y
2060 # Both address and 9-digit postal code match Y A X Y
2061 # United Kingdom – Address and postal code match _ _ _ F
2062 # International transaction – Address and postal code match _ _ _ D/M
2064 # ACCEPTABLE, BUT ISSUE A WARNING:
2065 # Ineligible transaction; or message contains a content error _ _ _ E
2066 # System unavailable; retry R U R R
2067 # Information unavailable U W U U
2068 # Issuer does not support AVS S U S S
2069 # AVS is not applicable _ _ _ S
2070 # Incompatible formats – Not verified _ _ _ C
2071 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2072 # International transaction – address not verified _ G _ G/I
2074 # UNACCEPTABLE AVS RESPONSES:
2075 # Only Address matches A Y A A
2076 # Only 5-digit postal code matches Z Z Z Z
2077 # Only 9-digit postal code matches Z Z W W
2078 # Neither address nor postal code matches N N N N
2080 if (my $avscode = uc($transaction->avs_code)) {
2082 # map codes to accept/warn/reject
2084 'American Express card' => {
2093 'Discover card' => {
2132 my $cardtype = cardtype($content{card_number});
2133 if ($avs->{$cardtype}) {
2134 my $avsact = $avs->{$cardtype}->{$avscode};
2136 if ($avsact eq 'r') {
2137 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2138 } elsif ($avsact eq 'w') {
2139 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2140 } elsif (!$avsact) {
2141 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2142 } # else $avsact eq 'a'
2144 $log->warning($warning);
2147 } # else $cardtype avs handling not implemented
2148 } # else !$transaction->avs_code
2150 } else { # is not success
2152 # status is 'done' not 'declined', as in _realtime_bop_result
2153 $cust_pay_pending->status('done');
2154 $error = $transaction->error_message || 'Unknown error';
2155 $cust_pay_pending->statustext($error);
2156 # could also record failure_status here,
2157 # but it's not supported by B::OP::vSecureProcessing...
2158 # need a B::OP module with (reverse) auth only to test it with
2159 my $cpp_declined_err = $cust_pay_pending->replace;
2160 return $cpp_declined_err if $cpp_declined_err;
2164 } # end of IMMEDIATE; we now have our $error and $transaction
2167 # Save the custnum (as part of the main transaction, so it can reference
2171 if (!$cust_pay_pending->custnum) {
2172 $cust_pay_pending->set('custnum', $self->custnum);
2173 my $set_custnum_err = $cust_pay_pending->replace;
2174 if ($set_custnum_err) {
2175 $log->error($set_custnum_err);
2176 $error ||= $set_custnum_err;
2177 # but if there was a real verification error also, return that one
2182 # remove paycvv here? need to find out if a reversed auth
2183 # counts as an initial transaction for paycvv retention requirements
2190 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2191 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2192 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2193 $cust_pay_pending->payinfo($card_token);
2194 my $cpp_token_err = $cust_pay_pending->replace;
2195 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2196 return $cpp_token_err if $cpp_token_err;
2197 #important that we not replace cust_main here,
2198 #because cust_main->replace uses realtime_verify_bop!
2206 # $error contains the transaction error_message, if is_success was false.
2212 =item realtime_tokenize [ OPTION => VALUE ... ]
2214 If possible and necessary, runs a tokenize transaction.
2215 In order to be possible, a credit card
2216 and a Business::OnlinePayment gateway capable
2217 of Tokenize transactions must be configured for this user.
2218 Is only necessary if payinfo is not yet tokenized.
2220 Returns the empty string if the authorization was sucessful
2221 or was not possible/necessary (thus allowing this to be safely called with
2222 non-tokenizable records/gateways, without having to perform separate tests),
2223 or an error message otherwise.
2225 Customer object payinfo will be tokenized if possible, but that change will not be
2226 updated in database (must be inserted/replaced afterwards.)
2228 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2229 may be passed. If options are passed as a hashref, I<payinfo>
2230 will be updated as appropriate in the passed hashref. Customer
2231 object will only be updated if passed payinfo matches customer payinfo.
2233 Can be run as a class method if option I<payment_gateway> is passed,
2234 but default customer info can't be set in that case. This
2235 is really only intended for tokenizing old records on upgrade.
2239 # careful--might be run as a class method
2240 sub realtime_tokenize {
2243 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2244 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2247 my $outoptions; #for returning payinfo
2248 if (ref($_[0]) eq 'HASH') {
2249 %options = %{$_[0]};
2250 $outoptions = $_[0];
2253 $outoptions = \%options;
2256 # set fields from passed cust_main
2257 unless ($options{'payinfo'}) {
2258 $options{'method'} = FS::payby->payby2bop( $self->payby );
2259 $options{$_} = $self->$_()
2260 for qw( payinfo paycvv paymask paystart_month paystart_year paydate
2261 payissue payname paystate paytype payip );
2262 $outoptions->{'payinfo'} = $options{'payinfo'};
2264 return '' unless $options{method} eq 'CC';
2265 return '' if FS::payinfo_Mixin->tokenized($options{payinfo}); #already tokenized
2271 $options{'nofatal'} = 1;
2272 my $payment_gateway = $self->_payment_gateway( \%options );
2273 return '' unless $payment_gateway;
2274 my $namespace = $payment_gateway->gateway_namespace;
2275 return '' unless $namespace eq 'Business::OnlinePayment';
2277 eval "use $namespace";
2281 # check for tokenize ability
2284 my $transaction = new $namespace( $payment_gateway->gateway_module,
2285 _bop_options(\%options),
2288 return '' unless $transaction->can('info');
2290 my %supported_actions = $transaction->info('supported_actions');
2291 return '' unless $supported_actions{'CC'} and grep(/^Tokenize$/,@{$supported_actions{'CC'}});
2294 # check for banned credit card/ACH
2297 my $ban = FS::banned_pay->ban_search(
2298 'payby' => $bop_method2payby{'CC'},
2299 'payinfo' => $options{payinfo},
2301 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2307 ### Currently, cardfortress only keys in on card number and exp date.
2308 ### We pass everything we'd pass to a normal transaction,
2309 ### for ease of current and future development,
2310 ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2312 my $bop_content = $self->_bop_content(\%options);
2313 return $bop_content unless ref($bop_content);
2318 $content{card_number} = $options{payinfo};
2319 $paydate = $options{'paydate'};
2320 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2321 $content{expiration} = "$2/$1";
2323 $content{cvv2} = $options{'paycvv'}
2324 if length($options{'paycvv'});
2326 my $paystart_month = $options{'paystart_month'};
2327 my $paystart_year = $options{'paystart_year'};
2329 $content{card_start} = "$paystart_month/$paystart_year"
2330 if $paystart_month && $paystart_year;
2332 my $payissue = $options{'payissue'};
2333 $content{issue_number} = $payissue if $payissue;
2335 $content{customer_id} = $self->custnum
2344 # no cust_pay_pending---this is not a financial transaction
2346 $transaction->content(
2348 _bop_auth(\%options),
2349 'action' => 'Tokenize',
2350 'description' => $options{'description'},
2355 # no $BOP_TESTING handling for this
2356 $transaction->test_transaction(1)
2357 if $conf->exists('business-onlinepayment-test_transaction');
2358 $transaction->submit();
2360 if ( $transaction->card_token() ) { # no is_success flag
2362 # realtime_tokenize should not clear paycvv at this time. it might be
2363 # needed for the first transaction, and a tokenize isn't actually a
2364 # transaction that hits the gateway. at some point in the future, card
2365 # fortress should take on the "store paycvv until first transaction"
2366 # functionality and we should fix this in freeside, but i that's a bigger
2367 # project for another time.
2369 #important that we not replace cust_main here,
2370 #because cust_main->replace uses realtime_tokenize!
2371 $self->_tokenize_card($transaction,$outoptions);
2375 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2383 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2385 NOT A METHOD. Acts on all customers. Placed here because it makes
2386 use of module-internal methods, and to keep everything that uses
2387 Billing::OnlinePayment all in one place.
2389 Tokenizes all tokenizable card numbers from payinfo in cust_main and
2390 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2392 If the I<queue> flag is set, newly tokenized records will be immediately
2393 committed, regardless of AutoCommit, so as to release the mutex on the record.
2395 If all configured gateways have the ability to tokenize, detection of an
2396 untokenizable record will cause a fatal error. However, if the I<queue> flag
2397 is set, this will instead cause a critical error to be recorded in the log,
2398 and any other tokenizable records will still be committed.
2400 If the I<daily> flag is also set, detection of existing untokenized records will
2401 record a critical error in the system log (because they should have never appeared
2402 in the first place.) Tokenization will still be attempted.
2404 If any configured gateways do NOT have the ability to tokenize, or if a
2405 default gateway is not configured, then untokenized records are not considered
2406 a threat, and no critical errors will be generated in the log.
2411 #acts on all customers
2413 my $debug = !$opt{'quiet'} || $DEBUG;
2415 warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2417 # force some explicitness when invoking this method
2418 die "token_check must run with queue flag if run with daily flag"
2419 if $opt{'daily'} && !$opt{'queue'};
2421 my $conf = FS::Conf->new;
2423 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2425 my $cache = {}; #cache for module info
2427 # look for a gateway that can't tokenize
2428 my $require_tokenized = 1;
2429 foreach my $gateway (
2430 FS::payment_gateway->all_gateways(
2437 # no default gateway, no promise to tokenize
2438 # can just load other gateways as-needeed below
2439 $require_tokenized = 0;
2442 my $info = _token_check_gateway_info($cache,$gateway);
2443 die $info unless ref($info); # means it's an error message
2444 unless ($info->{'can_tokenize'}) {
2445 # a configured gateway can't tokenize, that's all we need to know right now
2446 # can just load other gateways as-needeed below
2447 $require_tokenized = 0;
2452 warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2454 # upgrade does not call this with autocommit turned on,
2455 # and autocommit will be ignored if opt queue is set,
2456 # but might as well be thorough...
2457 my $oldAutoCommit = $FS::UID::AutoCommit;
2458 local $FS::UID::AutoCommit = 0;
2461 # for retrieving data in chunks
2465 ### Tokenize cust_main
2469 while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2470 my $cust_main = FS::cust_main->by_key($custnum);
2471 next unless $cust_main->payby =~ /^(CARD|DCRD)$/;
2473 # see if it's already tokenized
2474 if ($cust_main->tokenized) {
2475 warn "cust_main ".$cust_main->custnum." already tokenized" if $debug;
2479 if ($require_tokenized && $opt{'daily'}) {
2480 $log->critical("Untokenized card number detected in cust_main ".$cust_main->custnum);
2481 $dbh->commit or die $dbh->errstr; # commit log message
2485 my $payment_gateway = $cust_main->_payment_gateway({
2488 'nofatal' => 1, # handle lack of gateway smoothly below
2490 unless ($payment_gateway) {
2491 # no reason to have untokenized card numbers saved if no gateway,
2492 # but only a problem if we expected everyone to tokenize card numbers
2493 unless ($require_tokenized) {
2494 warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2497 my $error = "No gateway found for custnum ".$cust_main->custnum;
2498 if ($opt{'queue'}) {
2499 $log->critical($error);
2500 $dbh->commit or die $dbh->errstr; # commit error message
2503 $dbh->rollback if $oldAutoCommit;
2507 my $info = _token_check_gateway_info($cache,$payment_gateway);
2508 unless (ref($info)) {
2509 # only throws error if Business::OnlinePayment won't load,
2510 # which is just cause to abort this whole process, even if queue
2511 $dbh->rollback if $oldAutoCommit;
2512 die $info; # error message
2514 # no fail here--a configured gateway can't tokenize, so be it
2515 unless ($info->{'can_tokenize'}) {
2516 warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2521 $cust_main = $cust_main->select_for_update;
2523 'payment_gateway' => $payment_gateway,
2525 my $error = $cust_main->realtime_tokenize(\%tokenopts);
2526 if ($cust_main->tokenized) { # implies no error
2527 $error = $cust_main->replace;
2529 $error ||= 'Unknown error';
2532 $error = "Error tokenizing cust_main ".$cust_main->custnum.": ".$error;
2533 if ($opt{'queue'}) {
2534 $log->critical($error);
2535 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2538 $dbh->rollback if $oldAutoCommit;
2541 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2542 warn "TOKENIZED cust_main ".$cust_main->custnum if $debug;
2545 ### Tokenize/mask transaction tables
2547 # allow tokenization of closed cust_pay/cust_refund records
2548 local $FS::payinfo_Mixin::allow_closed_replace = 1;
2551 # $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2552 foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2553 warn "Checking $table" if $debug;
2555 # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2556 # loading only record ids, then loading individual records one at a time
2557 my $tclass = 'FS::'.$table;
2561 while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2562 my $record = $tclass->by_key($recnum);
2563 if (FS::payinfo_Mixin->tokenized($record->payinfo)) {
2564 warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2567 if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2568 warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2571 if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2572 warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2576 if ($require_tokenized && $opt{'daily'}) {
2577 $log->critical("Untokenized card number detected in $table ".$record->get($record->primary_key));
2578 $dbh->commit or die $dbh->errstr; # commit log message
2581 my $cust_main = $record->cust_main;
2583 # might happen for cust_pay_pending from failed verify records,
2584 # in which case we attempt tokenization without cust_main
2585 # everything else should absolutely have a cust_main
2586 if ($table eq 'cust_pay_pending' and !$record->custnum ) {
2587 # override the usual safety check and allow the record to be
2588 # updated even without a custnum.
2589 $record->set('custnum_pending', 1);
2591 my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2592 if ($opt{'queue'}) {
2593 $log->critical($error);
2594 $dbh->commit or die $dbh->errstr; # commit log message
2597 $dbh->rollback if $oldAutoCommit;
2604 # use the gatewaynum specified by the record if possible
2605 $gateway = FS::payment_gateway->by_key_with_namespace(
2606 'gatewaynum' => $record->gatewaynum,
2607 ) if $record->gateway;
2609 # otherwise use the cust agent gateway if possible (which realtime_refund_bop would do)
2610 # otherwise just use default gateway
2613 $gateway = $cust_main
2614 ? $cust_main->agent->payment_gateway
2615 : FS::payment_gateway->default_gateway;
2617 # check for processor mismatch
2618 unless ($table eq 'cust_pay_pending') { # has no processor table
2619 if (my $processor = $record->processor) {
2621 my $conf_processor = $gateway->gateway_module;
2622 my %bop_options = $gateway->gatewaynum
2624 : @{ $gateway->get('options') };
2626 # this is the same standard used by realtime_refund_bop
2628 ($processor eq $conf_processor) ||
2629 (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}))
2632 # processors don't match, so refund already cannot be run on this object,
2633 # regardless of what we do now...
2634 # but unless we gotta tokenize everything, just leave well enough alone
2635 unless ($require_tokenized) {
2636 warn "Skipping mismatched processor for $table ".$record->get($record->primary_key) if $debug;
2639 ### no error--we'll tokenize using the new gateway, just to remove stored payinfo,
2640 ### because refunds are already impossible for this record, anyway
2642 } # end processor mismatch
2644 } # end record has processor
2645 } # end not cust_pay_pending
2649 # means no default gateway, no promise to tokenize, can skip
2651 warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2655 my $info = _token_check_gateway_info($cache,$gateway);
2656 unless (ref($info)) {
2657 # only throws error if Business::OnlinePayment won't load,
2658 # which is just cause to abort this whole process, even if queue
2659 $dbh->rollback if $oldAutoCommit;
2660 die $info; # error message
2663 # a configured gateway can't tokenize, move along
2664 unless ($info->{'can_tokenize'}) {
2665 warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2669 warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug && !$cust_main;
2671 # if we got this far, time to mutex
2672 $record->select_for_update;
2674 # no clear record of name/address/etc used for transaction,
2675 # but will load name/phone/id from customer if run as an object method,
2676 # so we try that if we can
2678 'payment_gateway' => $gateway,
2680 'payinfo' => $record->payinfo,
2681 'paydate' => $record->paydate,
2683 my $error = $cust_main
2684 ? $cust_main->realtime_tokenize(\%tokenopts)
2685 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2686 if (FS::payinfo_Mixin->tokenized($tokenopts{'payinfo'})) { # implies no error
2687 $record->payinfo($tokenopts{'payinfo'});
2688 $error = $record->replace;
2690 $error ||= 'Unknown error';
2693 $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2694 if ($opt{'queue'}) {
2695 $log->critical($error);
2696 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2699 $dbh->rollback if $oldAutoCommit;
2702 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2703 warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2708 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2714 sub _token_check_next_recnum {
2715 my ($dbh,$table,$step,$offset,$recnums) = @_;
2716 my $recnum = shift @$recnums;
2717 return $recnum if $recnum;
2718 my $tclass = 'FS::'.$table;
2719 my $sth = $dbh->prepare('SELECT '.$tclass->primary_key.' FROM '.$table.' ORDER BY '.$tclass->primary_key.' LIMIT '.$step.' OFFSET '.$$offset) or die $dbh->errstr;
2720 $sth->execute() or die $sth->errstr;
2722 while (my $rec = $sth->fetchrow_hashref) {
2723 push @$recnums, $rec->{$tclass->primary_key};
2727 return shift @$recnums;
2731 sub _token_check_gateway_info {
2732 my ($cache,$payment_gateway) = @_;
2734 return $cache->{$payment_gateway->gateway_module}
2735 if $cache->{$payment_gateway->gateway_module};
2738 $cache->{$payment_gateway->gateway_module} = $info;
2740 my $namespace = $payment_gateway->gateway_namespace;
2741 return $info unless $namespace eq 'Business::OnlinePayment';
2742 $info->{'is_bop'} = 1;
2744 # only need to load this once,
2745 # don't want to load if nothing is_bop
2746 unless ($cache->{'Business::OnlinePayment'}) {
2747 eval "use $namespace";
2748 return "Error initializing Business:OnlinePayment: ".$@ if $@;
2749 $cache->{'Business::OnlinePayment'} = 1;
2752 my $transaction = new $namespace( $payment_gateway->gateway_module,
2753 _bop_options({ 'payment_gateway' => $payment_gateway }),
2756 return $info unless $transaction->can('info');
2757 $info->{'can_info'} = 1;
2759 my %supported_actions = $transaction->info('supported_actions');
2760 $info->{'can_tokenize'} = 1
2761 if $supported_actions{'CC'}
2762 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2764 # not using this any more, but for future reference...
2765 $info->{'void_requires_card'} = 1
2766 if $transaction->info('CC_void_requires_card');
2777 L<FS::cust_main>, L<FS::cust_main::Billing>