1 package FS::cust_main::Billing_Realtime;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
8 use Business::CreditCard 0.35;
9 use FS::UID qw( dbh myconnect );
10 use FS::Record qw( qsearch qsearchs );
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_cust_payby
53 sub realtime_cust_payby {
54 my( $self, %options ) = @_;
56 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
58 $options{amount} = $self->balance unless exists( $options{amount} );
60 my @cust_payby = $self->cust_payby('CARD','CHEK');
63 foreach my $cust_payby (@cust_payby) {
64 $error = $cust_payby->realtime_bop( %options, );
68 #XXX what about the earlier errors?
74 =item realtime_collect [ OPTION => VALUE ... ]
76 Attempt to collect the customer's current balance with a realtime credit
77 card or electronic check transaction (see realtime_bop() below).
79 Returns the result of realtime_bop(): nothing, an error message, or a
80 hashref of state information for a third-party transaction.
82 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
84 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
85 then it is deduced from the customer record.
87 If no I<amount> is specified, then the customer balance is used.
89 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
90 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
91 if set, will override the value from the customer record.
93 I<description> is a free-text field passed to the gateway. It defaults to
94 the value defined by the business-onlinepayment-description configuration
95 option, or "Internet services" if that is unset.
97 If an I<invnum> is specified, this payment (if successful) is applied to the
100 I<apply> will automatically apply a resulting payment.
102 I<quiet> can be set true to suppress email decline notices.
104 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
105 resulting paynum, if any.
107 I<payunique> is a unique identifier for this payment.
109 I<session_id> is a session identifier associated with this payment.
111 I<depend_jobnum> allows payment capture to unlock export jobs
115 # Currently only used by ClientAPI
116 # NOT 4.x COMPATIBLE (see below)
117 sub realtime_collect {
118 my( $self, %options ) = @_;
120 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
123 warn "$me realtime_collect:\n";
124 warn " $_ => $options{$_}\n" foreach keys %options;
127 $options{amount} = $self->balance unless exists( $options{amount} );
128 return '' unless $options{amount} > 0;
130 #### NOT 4.x COMPATIBLE
131 $options{method} = FS::payby->payby2bop($self->payby)
132 unless exists( $options{method} );
134 return $self->realtime_bop({%options});
138 =item realtime_bop { [ ARG => VALUE ... ] }
140 Runs a realtime credit card or ACH (electronic check) transaction
141 via a Business::OnlinePayment realtime gateway. See
142 L<http://420.am/business-onlinepayment> for supported gateways.
144 Required arguments in the hashref are I<amount> and either
145 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
146 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
148 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
150 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
152 I<description> is a free-text field passed to the gateway. It defaults to
153 the value defined by the business-onlinepayment-description configuration
154 option, or "Internet services" if that is unset.
156 If an I<invnum> is specified, this payment (if successful) is applied to the
157 specified invoice. If the customer has exactly one open invoice, that
158 invoice number will be assumed. If you don't specify an I<invnum> you might
159 want to call the B<apply_payments> method or set the I<apply> option.
161 I<no_invnum> can be set to true to prevent that default invnum from being set.
163 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
165 I<no_auto_apply> can be set to true to set that flag on the resulting payment
166 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
167 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
169 I<quiet> can be set true to surpress email decline notices.
171 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
172 resulting paynum, if any.
174 I<payunique> is a unique identifier for this payment.
176 I<session_id> is a session identifier associated with this payment.
178 I<depend_jobnum> allows payment capture to unlock export jobs
180 I<discount_term> attempts to take a discount by prepaying for discount_term.
181 The payment will fail if I<amount> is incorrect for this discount term.
183 A direct (Business::OnlinePayment) transaction will return nothing on success,
184 or an error message on failure.
186 A third-party transaction will return a hashref containing:
188 - popup_url: the URL to which a browser should be redirected to complete
190 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
191 - reference: a reference ID for the transaction, to show the customer.
193 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
197 # some helper routines
199 # _bop_recurring_billing: Checks whether this payment should have the
200 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
201 # vSecure, etc.). This works in two different modes:
202 # - actual_oncard (default): treat the payment as recurring if the customer
203 # has made a payment using this card before.
204 # - transaction_is_recur: treat the payment as recurring if the invoice
205 # being paid has any recurring package charges.
207 sub _bop_recurring_billing {
208 my( $self, %opt ) = @_;
210 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
212 if ( defined($method) && $method eq 'transaction_is_recur' ) {
214 return 1 if $opt{'trans_is_recur'};
218 # return 1 if the payinfo has been used for another payment
219 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
227 #can run safely as class method if opt payment_gateway already exists
228 sub _payment_gateway {
229 my ($self, $options) = @_;
231 if ( $options->{'fake_gatewaynum'} ) {
232 $options->{payment_gateway} =
233 qsearchs('payment_gateway',
234 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
238 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
239 unless exists($options->{payment_gateway});
241 $options->{payment_gateway};
249 'login' => $options->{payment_gateway}->gateway_username,
250 'password' => $options->{payment_gateway}->gateway_password,
258 $options->{payment_gateway}->gatewaynum
259 ? $options->{payment_gateway}->options
260 : @{ $options->{payment_gateway}->get('options') };
265 my ($self, $options) = @_;
267 unless ( $options->{'description'} ) {
268 if ( $conf->exists('business-onlinepayment-description') ) {
269 my $dtempl = $conf->config('business-onlinepayment-description');
271 my $agent = $self->agent->agent;
273 $options->{'description'} = eval qq("$dtempl");
275 $options->{'description'} = 'Internet services';
279 # Default invoice number if the customer has exactly one open invoice.
280 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
281 $options->{'invnum'} = '';
282 my @open = $self->open_cust_bill;
283 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
289 sub _bop_cust_payby_options {
291 my $cust_payby = $options->{'cust_payby'};
294 $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
296 if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
297 # false laziness with cust_payby->check
298 # which might not have been run yet
300 if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
301 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
302 } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
303 ( $m, $y ) = ( $2, "19$1" );
304 } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
305 ( $m, $y ) = ( $3, "20$2" );
307 return "Illegal expiration date: ". $cust_payby->paydate;
309 $m = sprintf('%02d',$m);
310 $options->{paydate} = "$y-$m-01";
312 $options->{paydate} = '';
315 $options->{$_} = $cust_payby->$_()
316 for qw( payinfo paycvv paymask paystart_month paystart_year
317 payissue payname paystate paytype payip );
319 if ( $cust_payby->locationnum ) {
320 my $cust_location = $cust_payby->cust_location;
321 $options->{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
326 # can be called as class method,
327 # but can't load default name/phone fields as class method
329 my ($self, $options) = @_;
332 my $payip = $options->{'payip'};
333 $content{customer_ip} = $payip if length($payip);
335 $content{invoice_number} = $options->{'invnum'}
336 if exists($options->{'invnum'}) && length($options->{'invnum'});
338 $content{email_customer} =
339 ( $conf->exists('business-onlinepayment-email_customer')
340 || $conf->exists('business-onlinepayment-email-override') );
342 my ($payname, $payfirst, $paylast);
343 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
344 ($payname = $options->{payname}) =~
345 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
346 or return "Illegal payname $payname";
347 ($payfirst, $paylast) = ($1, $2);
348 } elsif (ref($self)) { # can't set payname if called as class method
349 $payfirst = $self->getfield('first');
350 $paylast = $self->getfield('last');
351 $payname = "$payfirst $paylast";
354 $content{last_name} = $paylast if $paylast;
355 $content{first_name} = $payfirst if $payfirst;
357 $content{name} = $payname if $payname;
359 $content{address} = $options->{'address1'};
360 my $address2 = $options->{'address2'};
361 $content{address} .= ", ". $address2 if length($address2);
363 $content{city} = $options->{'city'};
364 $content{state} = $options->{'state'};
365 $content{zip} = $options->{'zip'};
366 $content{country} = $options->{'country'};
368 # can't set phone if called as class method
369 $content{phone} = $self->daytime || $self->night
372 my $currency = $conf->exists('business-onlinepayment-currency')
373 && $conf->config('business-onlinepayment-currency');
374 $content{currency} = $currency if $currency;
379 # updates payinfo and cust_payby options with token from transaction
380 # can be called as a class method
382 my ($self,$transaction,$options) = @_;
383 if ( $transaction->can('card_token')
384 and $transaction->card_token
385 and !$self->tokenized($options->{'payinfo'})
387 $options->{'payinfo'} = $transaction->card_token;
388 $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
389 return $transaction->card_token;
394 my %bop_method2payby = (
403 confess "Can't call realtime_bop within another transaction ".
404 '($FS::UID::AutoCommit is false)'
405 unless $FS::UID::AutoCommit;
407 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
409 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
412 if (ref($_[0]) eq 'HASH') {
415 my ( $method, $amount ) = ( shift, shift );
417 $options{method} = $method;
418 $options{amount} = $amount;
421 # set fields from passed cust_payby
422 _bop_cust_payby_options(\%options);
424 # possibly run a separate transaction to tokenize card number,
425 # so that we never store tokenized card info in cust_pay_pending
426 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
427 my $token_error = $self->realtime_tokenize(\%options);
428 return $token_error if $token_error;
429 # in theory, all cust_payby will be tokenized during original save,
430 # so we shouldn't get here with opt cust_payby...but just in case...
431 if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
432 $token_error = $options{'cust_payby'}->replace;
433 return $token_error if $token_error;
435 return "Cannot tokenize card info"
436 if $conf->exists('no_saved_cardnumbers') && !$self->tokenized($options{'payinfo'});
440 # optional credit card surcharge
443 my $cc_surcharge = 0;
444 my $cc_surcharge_pct = 0;
445 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum)
446 if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
447 && $options{method} eq 'CC';
449 # always add cc surcharge if called from event
450 if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
451 $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
452 $options{'amount'} += $cc_surcharge;
453 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
455 elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a
456 # payment screen), so consider the given
457 # amount as post-surcharge
458 $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
461 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
462 $options{'cc_surcharge'} = $cc_surcharge;
466 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
467 warn " cc_surcharge = $cc_surcharge\n";
470 warn " $_ => $options{$_}\n" foreach keys %options;
473 return $self->fake_bop(\%options) if $options{'fake'};
475 $self->_bop_defaults(\%options);
477 return "Missing payinfo"
478 unless $options{'payinfo'};
481 # set trans_is_recur based on invnum if there is one
484 my $trans_is_recur = 0;
485 if ( $options{'invnum'} ) {
487 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
488 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
494 $cust_bill->cust_bill_pkg;
497 if grep { $_->freq ne '0' } @part_pkg;
505 my $payment_gateway = $self->_payment_gateway( \%options );
506 my $namespace = $payment_gateway->gateway_namespace;
508 eval "use $namespace";
512 # check for banned credit card/ACH
515 my $ban = FS::banned_pay->ban_search(
516 'payby' => $bop_method2payby{$options{method}},
517 'payinfo' => $options{payinfo},
519 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
522 # check for term discount validity
525 my $discount_term = $options{discount_term};
526 if ( $discount_term ) {
527 my $bill = ($self->cust_bill)[-1]
528 or return "Can't apply a term discount to an unbilled customer";
529 my $plan = FS::discount_plan->new(
531 months => $discount_term
532 ) or return "No discount available for term '$discount_term'";
534 if ( $plan->discounted_total != $options{amount} ) {
535 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
543 my $bop_content = $self->_bop_content(\%options);
544 return $bop_content unless ref($bop_content);
546 my @invoicing_list = $self->invoicing_list_emailonly;
547 if ( $conf->exists('emailinvoiceautoalways')
548 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
549 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
550 push @invoicing_list, $self->all_emails;
553 my $email = ($conf->exists('business-onlinepayment-email-override'))
554 ? $conf->config('business-onlinepayment-email-override')
555 : $invoicing_list[0];
560 if ( $namespace eq 'Business::OnlinePayment' ) {
562 if ( $options{method} eq 'CC' ) {
564 $content{card_number} = $options{payinfo};
565 $paydate = $options{'paydate'};
566 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
567 $content{expiration} = "$2/$1";
569 $content{cvv2} = $options{'paycvv'}
570 if length($options{'paycvv'});
572 my $paystart_month = $options{'paystart_month'};
573 my $paystart_year = $options{'paystart_year'};
574 $content{card_start} = "$paystart_month/$paystart_year"
575 if $paystart_month && $paystart_year;
577 my $payissue = $options{'payissue'};
578 $content{issue_number} = $payissue if $payissue;
580 if ( $self->_bop_recurring_billing(
581 'payinfo' => $options{'payinfo'},
582 'trans_is_recur' => $trans_is_recur,
586 $content{recurring_billing} = 'YES';
587 $content{acct_code} = 'rebill'
588 if $conf->exists('credit_card-recurring_billing_acct_code');
591 } elsif ( $options{method} eq 'ECHECK' ){
593 ( $content{account_number}, $content{routing_code} ) =
594 split('@', $options{payinfo});
595 $content{bank_name} = $options{payname};
596 $content{bank_state} = $options{'paystate'};
597 $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
599 $content{company} = $self->company if $self->company;
601 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
602 $content{account_name} = $self->company;
604 $content{account_name} = $self->getfield('first'). ' '.
605 $self->getfield('last');
608 $content{customer_org} = $self->company ? 'B' : 'I';
609 $content{state_id} = exists($options{'stateid'})
610 ? $options{'stateid'}
611 : $self->getfield('stateid');
612 $content{state_id_state} = exists($options{'stateid_state'})
613 ? $options{'stateid_state'}
614 : $self->getfield('stateid_state');
615 $content{customer_ssn} = exists($options{'ss'})
620 die "unknown method ". $options{method};
623 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
626 die "unknown namespace $namespace";
633 my $balance = exists( $options{'balance'} )
634 ? $options{'balance'}
637 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
638 $self->select_for_update; #mutex ... just until we get our pending record in
639 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
641 #the checks here are intended to catch concurrent payments
642 #double-form-submission prevention is taken care of in cust_pay_pending::check
645 return "The customer's balance has changed; $options{method} transaction aborted."
646 if $self->balance < $balance;
648 #also check and make sure there aren't *other* pending payments for this cust
650 my @pending = qsearch('cust_pay_pending', {
651 'custnum' => $self->custnum,
652 'status' => { op=>'!=', value=>'done' }
655 #for third-party payments only, remove pending payments if they're in the
656 #'thirdparty' (waiting for customer action) state.
657 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
658 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
659 my $error = $_->delete;
660 warn "error deleting unfinished third-party payment ".
661 $_->paypendingnum . ": $error\n"
664 @pending = grep { $_->status ne 'thirdparty' } @pending;
667 return "A payment is already being processed for this customer (".
668 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
669 "); $options{method} transaction aborted."
672 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
674 my $cust_pay_pending = new FS::cust_pay_pending {
675 'custnum' => $self->custnum,
676 'paid' => $options{amount},
678 'payby' => $bop_method2payby{$options{method}},
679 'payinfo' => $options{payinfo},
680 'paymask' => $options{paymask},
681 'paydate' => $paydate,
682 'recurring_billing' => $content{recurring_billing},
683 'pkgnum' => $options{'pkgnum'},
685 'gatewaynum' => $payment_gateway->gatewaynum || '',
686 'session_id' => $options{session_id} || '',
687 'jobnum' => $options{depend_jobnum} || '',
689 $cust_pay_pending->payunique( $options{payunique} )
690 if defined($options{payunique}) && length($options{payunique});
692 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
694 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
695 return $cpp_new_err if $cpp_new_err;
697 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
699 warn Dumper($cust_pay_pending) if $DEBUG > 2;
701 my( $action1, $action2 ) =
702 split( /\s*\,\s*/, $payment_gateway->gateway_action );
704 my $transaction = new $namespace( $payment_gateway->gateway_module,
705 _bop_options(\%options),
708 $transaction->content(
709 'type' => $options{method},
710 _bop_auth(\%options),
711 'action' => $action1,
712 'description' => $options{'description'},
713 'amount' => $options{amount},
714 #'invoice_number' => $options{'invnum'},
715 'customer_id' => $self->custnum,
717 'reference' => $cust_pay_pending->paypendingnum, #for now
718 'callback_url' => $payment_gateway->gateway_callback_url,
719 'cancel_url' => $payment_gateway->gateway_cancel_url,
724 $cust_pay_pending->status('pending');
725 my $cpp_pending_err = $cust_pay_pending->replace;
726 return $cpp_pending_err if $cpp_pending_err;
728 warn Dumper($transaction) if $DEBUG > 2;
730 unless ( $BOP_TESTING ) {
731 $transaction->test_transaction(1)
732 if $conf->exists('business-onlinepayment-test_transaction');
733 $transaction->submit();
735 if ( $BOP_TESTING_SUCCESS ) {
736 $transaction->is_success(1);
737 $transaction->authorization('fake auth');
739 $transaction->is_success(0);
740 $transaction->error_message('fake failure');
744 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
746 $cust_pay_pending->status('thirdparty');
747 my $cpp_err = $cust_pay_pending->replace;
748 return { error => $cpp_err } if $cpp_err;
749 return { reference => $cust_pay_pending->paypendingnum,
750 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
752 } elsif ( $transaction->is_success() && $action2 ) {
754 $cust_pay_pending->status('authorized');
755 my $cpp_authorized_err = $cust_pay_pending->replace;
756 return $cpp_authorized_err if $cpp_authorized_err;
758 my $auth = $transaction->authorization;
759 my $ordernum = $transaction->can('order_number')
760 ? $transaction->order_number
764 new Business::OnlinePayment( $payment_gateway->gateway_module,
765 _bop_options(\%options),
770 type => $options{method},
772 _bop_auth(\%options),
773 order_number => $ordernum,
774 amount => $options{amount},
775 authorization => $auth,
776 description => $options{'description'},
779 foreach my $field (qw( authorization_source_code returned_ACI
780 transaction_identifier validation_code
781 transaction_sequence_num local_transaction_date
782 local_transaction_time AVS_result_code )) {
783 $capture{$field} = $transaction->$field() if $transaction->can($field);
786 $capture->content( %capture );
788 $capture->test_transaction(1)
789 if $conf->exists('business-onlinepayment-test_transaction');
792 unless ( $capture->is_success ) {
793 my $e = "Authorization successful but capture failed, custnum #".
794 $self->custnum. ': '. $capture->result_code.
795 ": ". $capture->error_message;
803 # remove paycvv after initial transaction
806 # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
807 if ( length($options{'paycvv'})
808 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
810 my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
812 $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
813 #not returning error, should at least attempt to handle results of an otherwise valid transaction
814 warn "WARNING: error removing cvv: $error\n";
822 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
823 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
824 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
825 # cpp will be replaced in _realtime_bop_result
826 $cust_pay_pending->payinfo($card_token);
827 if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
828 $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
829 #not returning error, should at least attempt to handle results of an otherwise valid transaction
830 #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
838 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
850 if (ref($_[0]) eq 'HASH') {
853 my ( $method, $amount ) = ( shift, shift );
855 $options{method} = $method;
856 $options{amount} = $amount;
859 if ( $options{'fake_failure'} ) {
860 return "Error: No error; test failure requested with fake_failure";
863 my $cust_pay = new FS::cust_pay ( {
864 'custnum' => $self->custnum,
865 'invnum' => $options{'invnum'},
866 'paid' => $options{amount},
868 'payby' => $bop_method2payby{$options{method}},
869 'payinfo' => '4111111111111111',
870 'paydate' => '2012-05-01',
871 'processor' => 'FakeProcessor',
873 'order_number' => '32',
875 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
878 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
879 warn " $_ => $options{$_}\n" foreach keys %options;
882 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
885 $cust_pay->invnum(''); #try again with no specific invnum
886 my $error2 = $cust_pay->insert( $options{'manual'} ?
887 ( 'manual' => 1 ) : ()
890 # gah, even with transactions.
891 my $e = 'WARNING: Card/ACH debited but database not updated - '.
892 "error inserting (fake!) payment: $error2".
893 " (previously tried insert with invnum #$options{'invnum'}" .
900 if ( $options{'paynum_ref'} ) {
901 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
909 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
911 # Wraps up processing of a realtime credit card or ACH (electronic check)
914 sub _realtime_bop_result {
915 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
917 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
920 warn "$me _realtime_bop_result: pending transaction ".
921 $cust_pay_pending->paypendingnum. "\n";
922 warn " $_ => $options{$_}\n" foreach keys %options;
925 my $payment_gateway = $options{payment_gateway}
926 or return "no payment gateway in arguments to _realtime_bop_result";
928 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
929 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
930 return $cpp_captured_err if $cpp_captured_err;
932 if ( $transaction->is_success() ) {
934 my $order_number = $transaction->order_number
935 if $transaction->can('order_number');
937 my $cust_pay = new FS::cust_pay ( {
938 'custnum' => $self->custnum,
939 'invnum' => $options{'invnum'},
940 'paid' => $cust_pay_pending->paid,
942 'payby' => $cust_pay_pending->payby,
943 'payinfo' => $options{'payinfo'},
944 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
945 'paydate' => $cust_pay_pending->paydate,
946 'pkgnum' => $cust_pay_pending->pkgnum,
947 'discount_term' => $options{'discount_term'},
948 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
949 'processor' => $payment_gateway->gateway_module,
950 'auth' => $transaction->authorization,
951 'order_number' => $order_number || '',
952 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
954 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
955 $cust_pay->payunique( $options{payunique} )
956 if defined($options{payunique}) && length($options{payunique});
958 my $oldAutoCommit = $FS::UID::AutoCommit;
959 local $FS::UID::AutoCommit = 0;
962 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
964 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
967 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
968 $cust_pay->invnum(''); #try again with no specific invnum
969 $cust_pay->paynum('');
970 my $error2 = $cust_pay->insert( $options{'manual'} ?
971 ( 'manual' => 1 ) : ()
974 # gah. but at least we have a record of the state we had to abort in
975 # from cust_pay_pending now.
976 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
977 my $e = "WARNING: $options{method} captured but payment not recorded -".
978 " error inserting payment (". $payment_gateway->gateway_module.
980 " (previously tried insert with invnum #$options{'invnum'}" .
981 ": $error ) - pending payment saved as paypendingnum ".
982 $cust_pay_pending->paypendingnum. "\n";
988 my $jobnum = $cust_pay_pending->jobnum;
990 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
992 unless ( $placeholder ) {
993 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
994 my $e = "WARNING: $options{method} captured but job $jobnum not ".
995 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
1000 $error = $placeholder->delete;
1003 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1004 my $e = "WARNING: $options{method} captured but could not delete ".
1005 "job $jobnum for paypendingnum ".
1006 $cust_pay_pending->paypendingnum. ": $error\n";
1011 $cust_pay_pending->set('jobnum','');
1015 if ( $options{'paynum_ref'} ) {
1016 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1019 $cust_pay_pending->status('done');
1020 $cust_pay_pending->statustext('captured');
1021 $cust_pay_pending->paynum($cust_pay->paynum);
1022 my $cpp_done_err = $cust_pay_pending->replace;
1024 if ( $cpp_done_err ) {
1026 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1027 my $e = "WARNING: $options{method} captured but payment not recorded - ".
1028 "error updating status for paypendingnum ".
1029 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1035 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1037 if ( $options{'apply'} ) {
1038 my $apply_error = $self->apply_payments_and_credits;
1039 if ( $apply_error ) {
1040 warn "WARNING: error applying payment: $apply_error\n";
1041 #but we still should return no error cause the payment otherwise went
1046 # have a CC surcharge portion --> one-time charge
1047 if ( $options{'cc_surcharge'} > 0 ) {
1048 # XXX: this whole block needs to be in a transaction?
1051 $invnum = $options{'invnum'} if $options{'invnum'};
1052 unless ( $invnum ) { # probably from a payment screen
1053 # do we have any open invoices? pick earliest
1054 # uses the fact that cust_main->cust_bill sorts by date ascending
1055 my @open = $self->open_cust_bill;
1056 $invnum = $open[0]->invnum if scalar(@open);
1059 unless ( $invnum ) { # still nothing? pick last closed invoice
1060 # again uses fact that cust_main->cust_bill sorts by date ascending
1061 my @closed = $self->cust_bill;
1062 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1065 unless ( $invnum ) {
1066 # XXX: unlikely case - pre-paying before any invoices generated
1067 # what it should do is create a new invoice and pick it
1068 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1073 my $charge_error = $self->charge({
1074 'amount' => $options{'cc_surcharge'},
1075 'pkg' => 'Credit Card Surcharge',
1077 'cust_pkg_ref' => \$cust_pkg,
1080 warn 'Unable to add CC surcharge cust_pkg';
1084 $cust_pkg->setup(time);
1085 my $cp_error = $cust_pkg->replace;
1087 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1091 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1092 unless ( $cust_bill ) {
1093 warn "race condition + invoice deletion just happened";
1098 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1100 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1104 return ''; #no error
1110 my $perror = $transaction->error_message;
1111 #$payment_gateway->gateway_module. " error: ".
1112 # removed for conciseness
1114 my $jobnum = $cust_pay_pending->jobnum;
1116 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1118 if ( $placeholder ) {
1119 my $error = $placeholder->depended_delete;
1120 $error ||= $placeholder->delete;
1121 $cust_pay_pending->set('jobnum','');
1122 warn "error removing provisioning jobs after declined paypendingnum ".
1123 $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1125 my $e = "error finding job $jobnum for declined paypendingnum ".
1126 $cust_pay_pending->paypendingnum. "\n";
1132 unless ( $transaction->error_message ) {
1135 if ( $transaction->can('response_page') ) {
1137 'page' => ( $transaction->can('response_page')
1138 ? $transaction->response_page
1141 'code' => ( $transaction->can('response_code')
1142 ? $transaction->response_code
1145 'headers' => ( $transaction->can('response_headers')
1146 ? $transaction->response_headers
1152 "No additional debugging information available for ".
1153 $payment_gateway->gateway_module;
1156 $perror .= "No error_message returned from ".
1157 $payment_gateway->gateway_module. " -- ".
1158 ( ref($t_response) ? Dumper($t_response) : $t_response );
1162 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1163 && $conf->exists('emaildecline', $self->agentnum)
1164 && grep { $_ ne 'POST' } $self->invoicing_list
1165 && ! grep { $transaction->error_message =~ /$_/ }
1166 $conf->config('emaildecline-exclude', $self->agentnum)
1169 # Send a decline alert to the customer.
1170 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1173 # include the raw error message in the transaction state
1174 $cust_pay_pending->setfield('error', $transaction->error_message);
1175 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1176 $error = $msg_template->send( 'cust_main' => $self,
1177 'object' => $cust_pay_pending );
1181 $perror .= " (also received error sending decline notification: $error)"
1186 $cust_pay_pending->status('done');
1187 $cust_pay_pending->statustext($perror);
1188 #'declined:': no, that's failure_status
1189 if ( $transaction->can('failure_status') ) {
1190 $cust_pay_pending->failure_status( $transaction->failure_status );
1192 my $cpp_done_err = $cust_pay_pending->replace;
1193 if ( $cpp_done_err ) {
1194 my $e = "WARNING: $options{method} declined but pending payment not ".
1195 "resolved - error updating status for paypendingnum ".
1196 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1198 $perror = "$e ($perror)";
1206 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1208 Verifies successful third party processing of a realtime credit card or
1209 ACH (electronic check) transaction via a
1210 Business::OnlineThirdPartyPayment realtime gateway. See
1211 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1213 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1215 The additional options I<payname>, I<city>, I<state>,
1216 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1217 if set, will override the value from the customer record.
1219 I<description> is a free-text field passed to the gateway. It defaults to
1220 "Internet services".
1222 If an I<invnum> is specified, this payment (if successful) is applied to the
1223 specified invoice. If you don't specify an I<invnum> you might want to
1224 call the B<apply_payments> method.
1226 I<quiet> can be set true to surpress email decline notices.
1228 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1229 resulting paynum, if any.
1231 I<payunique> is a unique identifier for this payment.
1233 Returns a hashref containing elements bill_error (which will be undefined
1234 upon success) and session_id of any associated session.
1238 sub realtime_botpp_capture {
1239 my( $self, $cust_pay_pending, %options ) = @_;
1241 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1244 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1245 warn " $_ => $options{$_}\n" foreach keys %options;
1248 eval "use Business::OnlineThirdPartyPayment";
1252 # select the gateway
1255 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1257 my $payment_gateway;
1258 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1259 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1260 { gatewaynum => $gatewaynum }
1262 : $self->agent->payment_gateway( 'method' => $method,
1263 # 'invnum' => $cust_pay_pending->invnum,
1264 # 'payinfo' => $cust_pay_pending->payinfo,
1267 $options{payment_gateway} = $payment_gateway; # for the helper subs
1273 my @invoicing_list = $self->invoicing_list_emailonly;
1274 if ( $conf->exists('emailinvoiceautoalways')
1275 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1276 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1277 push @invoicing_list, $self->all_emails;
1280 my $email = ($conf->exists('business-onlinepayment-email-override'))
1281 ? $conf->config('business-onlinepayment-email-override')
1282 : $invoicing_list[0];
1286 $content{email_customer} =
1287 ( $conf->exists('business-onlinepayment-email_customer')
1288 || $conf->exists('business-onlinepayment-email-override') );
1291 # run transaction(s)
1295 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1296 _bop_options(\%options),
1299 $transaction->reference({ %options });
1301 $transaction->content(
1303 _bop_auth(\%options),
1304 'action' => 'Post Authorization',
1305 'description' => $options{'description'},
1306 'amount' => $cust_pay_pending->paid,
1307 #'invoice_number' => $options{'invnum'},
1308 'customer_id' => $self->custnum,
1309 'reference' => $cust_pay_pending->paypendingnum,
1311 'phone' => $self->daytime || $self->night,
1313 # plus whatever is required for bogus capture avoidance
1316 $transaction->submit();
1319 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1321 if ( $options{'apply'} ) {
1322 my $apply_error = $self->apply_payments_and_credits;
1323 if ( $apply_error ) {
1324 warn "WARNING: error applying payment: $apply_error\n";
1329 bill_error => $error,
1330 session_id => $cust_pay_pending->session_id,
1335 =item default_payment_gateway
1337 DEPRECATED -- use agent->payment_gateway
1341 sub default_payment_gateway {
1342 my( $self, $method ) = @_;
1344 die "Real-time processing not enabled\n"
1345 unless $conf->exists('business-onlinepayment');
1347 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1350 my $bop_config = 'business-onlinepayment';
1351 $bop_config .= '-ach'
1352 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1353 my ( $processor, $login, $password, $action, @bop_options ) =
1354 $conf->config($bop_config);
1355 $action ||= 'normal authorization';
1356 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1357 die "No real-time processor is enabled - ".
1358 "did you set the business-onlinepayment configuration value?\n"
1361 ( $processor, $login, $password, $action, @bop_options )
1364 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1366 Refunds a realtime credit card or ACH (electronic check) transaction
1367 via a Business::OnlinePayment realtime gateway. See
1368 L<http://420.am/business-onlinepayment> for supported gateways.
1370 Available methods are: I<CC> or I<ECHECK>
1372 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1374 Most gateways require a reference to an original payment transaction to refund,
1375 so you probably need to specify a I<paynum>.
1377 I<amount> defaults to the original amount of the payment if not specified.
1379 I<reasonnum> specified an existing refund reason for the refund
1381 I<paydate> specifies the expiration date for a credit card overriding the
1382 value from the customer record or the payment record. Specified as yyyy-mm-dd
1384 Implementation note: If I<amount> is unspecified or equal to the amount of the
1385 orignal payment, first an attempt is made to "void" the transaction via
1386 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1387 the normal attempt is made to "refund" ("credit") the transaction via the
1388 gateway is attempted. No attempt to "void" the transaction is made if the
1389 gateway has introspection data and doesn't support void.
1391 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1392 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1393 #if set, will override the value from the customer record.
1395 #If an I<invnum> is specified, this payment (if successful) is applied to the
1396 #specified invoice. If you don't specify an I<invnum> you might want to
1397 #call the B<apply_payments> method.
1401 #some false laziness w/realtime_bop, not enough to make it worth merging
1402 #but some useful small subs should be pulled out
1403 sub realtime_refund_bop {
1406 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1409 if (ref($_[0]) eq 'HASH') {
1410 %options = %{$_[0]};
1414 $options{method} = $method;
1418 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1419 warn " $_ => $options{$_}\n" foreach keys %options;
1422 return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1427 # look up the original payment and optionally a gateway for that payment
1431 my $amount = $options{'amount'};
1433 my( $processor, $login, $password, @bop_options, $namespace ) ;
1434 my( $auth, $order_number ) = ( '', '', '' );
1435 my $gatewaynum = '';
1437 if ( $options{'paynum'} ) {
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;
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;
1447 if ( $cust_pay->get('processor') ) {
1448 ($gatewaynum, $processor, $auth, $order_number) =
1450 $cust_pay->gatewaynum,
1451 $cust_pay->processor,
1453 $cust_pay->order_number,
1456 # this payment wasn't upgraded, which probably means this won't work,
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 );
1464 if ( $gatewaynum ) { #gateway for the payment to be refunded
1466 my $payment_gateway =
1467 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1468 die "payment gateway $gatewaynum not found"
1469 unless $payment_gateway;
1471 $processor = $payment_gateway->gateway_module;
1472 $login = $payment_gateway->gateway_username;
1473 $password = $payment_gateway->gateway_password;
1474 $namespace = $payment_gateway->gateway_namespace;
1475 @bop_options = $payment_gateway->options;
1477 } else { #try the default gateway
1480 my $payment_gateway =
1481 $self->agent->payment_gateway('method' => $options{method});
1483 ( $conf_processor, $login, $password, $namespace ) =
1484 map { my $method = "gateway_$_"; $payment_gateway->$method }
1485 qw( module username password namespace );
1487 @bop_options = $payment_gateway->gatewaynum
1488 ? $payment_gateway->options
1489 : @{ $payment_gateway->get('options') };
1491 return "processor of payment $options{'paynum'} $processor does not".
1492 " match default processor $conf_processor"
1493 unless $processor eq $conf_processor;
1498 } else { # didn't specify a paynum, so look for agent gateway overrides
1499 # like a normal transaction
1501 my $payment_gateway =
1502 $self->agent->payment_gateway( 'method' => $options{method},
1503 #'payinfo' => $payinfo,
1505 my( $processor, $login, $password, $namespace ) =
1506 map { my $method = "gateway_$_"; $payment_gateway->$method }
1507 qw( module username password namespace );
1509 my @bop_options = $payment_gateway->gatewaynum
1510 ? $payment_gateway->options
1511 : @{ $payment_gateway->get('options') };
1514 return "neither amount nor paynum specified" unless $amount;
1516 eval "use $namespace";
1521 'type' => $options{method},
1523 'password' => $password,
1524 'order_number' => $order_number,
1525 'amount' => $amount,
1527 $content{authorization} = $auth
1528 if length($auth); #echeck/ACH transactions have an order # but no auth
1529 #(at least with authorize.net)
1531 my $currency = $conf->exists('business-onlinepayment-currency')
1532 && $conf->config('business-onlinepayment-currency');
1533 $content{currency} = $currency if $currency;
1535 my $disable_void_after;
1536 if ($conf->exists('disable_void_after')
1537 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1538 $disable_void_after = $1;
1541 #first try void if applicable
1542 my $void = new Business::OnlinePayment( $processor, @bop_options );
1545 if ($void->can('info')) {
1547 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1548 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1549 my %supported_actions = $void->info('supported_actions');
1551 if ( %supported_actions && $paytype
1552 && defined($supported_actions{$paytype})
1553 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1556 if ( $cust_pay && $cust_pay->paid == $amount
1558 ( not defined($disable_void_after) )
1559 || ( time < ($cust_pay->_date + $disable_void_after ) )
1563 warn " attempting void\n" if $DEBUG > 1;
1564 if ( $void->can('info') ) {
1565 if ( $cust_pay->payby eq 'CARD'
1566 && $void->info('CC_void_requires_card') )
1568 $content{'card_number'} = $cust_pay->payinfo;
1569 } elsif ( $cust_pay->payby eq 'CHEK'
1570 && $void->info('ECHECK_void_requires_account') )
1572 ( $content{'account_number'}, $content{'routing_code'} ) =
1573 split('@', $cust_pay->payinfo);
1574 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1577 $void->content( 'action' => 'void', %content );
1578 $void->test_transaction(1)
1579 if $conf->exists('business-onlinepayment-test_transaction');
1581 if ( $void->is_success ) {
1582 # specified as a refund reason, but now we want a payment void reason
1583 # extract just the reason text, let cust_pay::void handle new_or_existing
1584 my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1586 $error = 'Reason could not be loaded' unless $reason;
1587 $error = $cust_pay->void($reason->reason) unless $error;
1589 # gah, even with transactions.
1590 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1591 "error voiding payment: $error";
1595 warn " void successful\n" if $DEBUG > 1;
1600 warn " void unsuccessful, trying refund\n"
1604 my $address = $self->address1;
1605 $address .= ", ". $self->address2 if $self->address2;
1607 my($payname, $payfirst, $paylast);
1608 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1609 $payname = $self->payname;
1610 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1611 or return "Illegal payname $payname";
1612 ($payfirst, $paylast) = ($1, $2);
1614 $payfirst = $self->getfield('first');
1615 $paylast = $self->getfield('last');
1616 $payname = "$payfirst $paylast";
1619 my @invoicing_list = $self->invoicing_list_emailonly;
1620 if ( $conf->exists('emailinvoiceautoalways')
1621 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1622 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1623 push @invoicing_list, $self->all_emails;
1626 my $email = ($conf->exists('business-onlinepayment-email-override'))
1627 ? $conf->config('business-onlinepayment-email-override')
1628 : $invoicing_list[0];
1630 my $payip = exists($options{'payip'})
1633 $content{customer_ip} = $payip
1637 if ( $options{method} eq 'CC' ) {
1640 $content{card_number} = $payinfo = $cust_pay->payinfo;
1641 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1642 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1643 ($content{expiration} = "$2/$1"); # where available
1645 $content{card_number} = $payinfo = $self->payinfo;
1646 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1647 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1648 $content{expiration} = "$2/$1";
1651 } elsif ( $options{method} eq 'ECHECK' ) {
1654 $payinfo = $cust_pay->payinfo;
1656 $payinfo = $self->payinfo;
1658 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1659 $content{bank_name} = $self->payname;
1660 $content{account_type} = 'CHECKING';
1661 $content{account_name} = $payname;
1662 $content{customer_org} = $self->company ? 'B' : 'I';
1663 $content{customer_ssn} = $self->ss;
1668 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1669 my %sub_content = $refund->content(
1670 'action' => 'credit',
1671 'customer_id' => $self->custnum,
1672 'last_name' => $paylast,
1673 'first_name' => $payfirst,
1675 'address' => $address,
1676 'city' => $self->city,
1677 'state' => $self->state,
1678 'zip' => $self->zip,
1679 'country' => $self->country,
1681 'phone' => $self->daytime || $self->night,
1684 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1686 $refund->test_transaction(1)
1687 if $conf->exists('business-onlinepayment-test_transaction');
1690 return "$processor error: ". $refund->error_message
1691 unless $refund->is_success();
1693 $order_number = $refund->order_number if $refund->can('order_number');
1695 # change this to just use $cust_pay->delete_cust_bill_pay?
1696 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1697 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1698 last unless @cust_bill_pay;
1699 my $cust_bill_pay = pop @cust_bill_pay;
1700 my $error = $cust_bill_pay->delete;
1704 my $cust_refund = new FS::cust_refund ( {
1705 'custnum' => $self->custnum,
1706 'paynum' => $options{'paynum'},
1707 'source_paynum' => $options{'paynum'},
1708 'refund' => $amount,
1710 'payby' => $bop_method2payby{$options{method}},
1711 'payinfo' => $payinfo,
1712 'reasonnum' => $options{'reasonnum'},
1713 'gatewaynum' => $gatewaynum, # may be null
1714 'processor' => $processor,
1715 'auth' => $refund->authorization,
1716 'order_number' => $order_number,
1718 my $error = $cust_refund->insert;
1720 $cust_refund->paynum(''); #try again with no specific paynum
1721 $cust_refund->source_paynum('');
1722 my $error2 = $cust_refund->insert;
1724 # gah, even with transactions.
1725 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1726 "error inserting refund ($processor): $error2".
1727 " (previously tried insert with paynum #$options{'paynum'}" .
1738 =item realtime_verify_bop [ OPTION => VALUE ... ]
1740 Runs an authorization-only transaction for $1 against this credit card (if
1741 successful, immediatly reverses the authorization).
1743 Returns the empty string if the authorization was sucessful, or an error
1746 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1747 Object will be tokenized if possible, but that change will not be
1748 updated in database (must be inserted/replaced afterwards.)
1750 Currently only succeeds for Business::OnlinePayment CC transactions.
1754 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1755 #it worth merging but some useful small subs should be pulled out
1756 sub realtime_verify_bop {
1759 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1760 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1763 if (ref($_[0]) eq 'HASH') {
1764 %options = %{$_[0]};
1770 warn "$me realtime_verify_bop\n";
1771 warn " $_ => $options{$_}\n" foreach keys %options;
1774 # set fields from passed cust_payby
1775 return "No cust_payby" unless $options{'cust_payby'};
1776 _bop_cust_payby_options(\%options);
1778 # possibly run a separate transaction to tokenize card number,
1779 # so that we never store tokenized card info in cust_pay_pending
1780 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1781 my $token_error = $self->realtime_tokenize(\%options);
1782 return $token_error if $token_error;
1783 #important that we not replace cust_payby here,
1784 #because cust_payby->replace uses realtime_verify_bop!
1785 return "Cannot tokenize card info"
1786 if $conf->exists('no_saved_cardnumbers') && !$self->tokenized($options{'payinfo'});
1793 my $payment_gateway = $self->_payment_gateway( \%options );
1794 my $namespace = $payment_gateway->gateway_namespace;
1796 eval "use $namespace";
1800 # check for banned credit card/ACH
1803 my $ban = FS::banned_pay->ban_search(
1804 'payby' => $bop_method2payby{'CC'},
1805 'payinfo' => $options{payinfo},
1807 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1813 my $bop_content = $self->_bop_content(\%options);
1814 return $bop_content unless ref($bop_content);
1816 my @invoicing_list = $self->invoicing_list_emailonly;
1817 if ( $conf->exists('emailinvoiceautoalways')
1818 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1819 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1820 push @invoicing_list, $self->all_emails;
1823 my $email = ($conf->exists('business-onlinepayment-email-override'))
1824 ? $conf->config('business-onlinepayment-email-override')
1825 : $invoicing_list[0];
1830 if ( $namespace eq 'Business::OnlinePayment' ) {
1832 if ( $options{method} eq 'CC' ) {
1834 $content{card_number} = $options{payinfo};
1835 $paydate = $options{'paydate'};
1836 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1837 $content{expiration} = "$2/$1";
1839 $content{cvv2} = $options{'paycvv'}
1840 if length($options{'paycvv'});
1842 my $paystart_month = $options{'paystart_month'};
1843 my $paystart_year = $options{'paystart_year'};
1845 $content{card_start} = "$paystart_month/$paystart_year"
1846 if $paystart_month && $paystart_year;
1848 my $payissue = $options{'payissue'};
1849 $content{issue_number} = $payissue if $payissue;
1851 } elsif ( $options{method} eq 'ECHECK' ){
1852 #cannot verify, move along (though it shouldn't be called...)
1855 return "unknown method ". $options{method};
1857 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1858 #cannot verify, move along
1861 return "unknown namespace $namespace";
1865 # run transaction(s)
1869 my $transaction; #need this back so we can do _tokenize_card
1871 # don't mutex the customer here, because they might be uncommitted. and
1872 # this is only verification. it doesn't matter if they have other
1873 # unfinished verifications.
1875 my $cust_pay_pending = new FS::cust_pay_pending {
1876 'custnum_pending' => 1,
1879 'payby' => $bop_method2payby{'CC'},
1880 'payinfo' => $options{payinfo},
1881 'paymask' => $options{paymask},
1882 'paydate' => $paydate,
1883 'pkgnum' => $options{'pkgnum'},
1885 'gatewaynum' => $payment_gateway->gatewaynum || '',
1886 'session_id' => $options{session_id} || '',
1888 $cust_pay_pending->payunique( $options{payunique} )
1889 if defined($options{payunique}) && length($options{payunique});
1892 # open a separate handle for creating/updating the cust_pay_pending
1894 local $FS::UID::dbh = myconnect();
1895 local $FS::UID::AutoCommit = 1;
1897 # if this is an existing customer (and we can tell now because
1898 # this is a fresh transaction), it's safe to assign their custnum
1899 # to the cust_pay_pending record, and then the verification attempt
1900 # will remain linked to them even if it fails.
1901 if ( FS::cust_main->by_key($self->custnum) ) {
1902 $cust_pay_pending->set('custnum', $self->custnum);
1905 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1908 # if this fails, just return; everything else will still allow the
1909 # cust_pay_pending to have its custnum set later
1910 my $cpp_new_err = $cust_pay_pending->insert;
1911 return $cpp_new_err if $cpp_new_err;
1913 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1915 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1917 $transaction = new $namespace( $payment_gateway->gateway_module,
1918 _bop_options(\%options),
1921 $transaction->content(
1923 _bop_auth(\%options),
1924 'action' => 'Authorization Only',
1925 'description' => $options{'description'},
1927 'customer_id' => $self->custnum,
1929 'reference' => $cust_pay_pending->paypendingnum, #for now
1934 $cust_pay_pending->status('pending');
1935 my $cpp_pending_err = $cust_pay_pending->replace;
1936 return $cpp_pending_err if $cpp_pending_err;
1938 warn Dumper($transaction) if $DEBUG > 2;
1940 unless ( $BOP_TESTING ) {
1941 $transaction->test_transaction(1)
1942 if $conf->exists('business-onlinepayment-test_transaction');
1943 $transaction->submit();
1945 if ( $BOP_TESTING_SUCCESS ) {
1946 $transaction->is_success(1);
1947 $transaction->authorization('fake auth');
1949 $transaction->is_success(0);
1950 $transaction->error_message('fake failure');
1954 if ( $transaction->is_success() ) {
1956 $cust_pay_pending->status('authorized');
1957 my $cpp_authorized_err = $cust_pay_pending->replace;
1958 return $cpp_authorized_err if $cpp_authorized_err;
1960 my $auth = $transaction->authorization;
1961 my $ordernum = $transaction->can('order_number')
1962 ? $transaction->order_number
1965 my $reverse = new $namespace( $payment_gateway->gateway_module,
1966 _bop_options(\%options),
1969 $reverse->content( 'action' => 'Reverse Authorization',
1970 _bop_auth(\%options),
1974 'authorization' => $transaction->authorization,
1975 'order_number' => $ordernum,
1978 'result_code' => $transaction->result_code,
1979 'txn_date' => $transaction->txn_date,
1983 $reverse->test_transaction(1)
1984 if $conf->exists('business-onlinepayment-test_transaction');
1987 if ( $reverse->is_success ) {
1989 $cust_pay_pending->status('done');
1990 $cust_pay_pending->statustext('reversed');
1991 my $cpp_reversed_err = $cust_pay_pending->replace;
1992 return $cpp_reversed_err if $cpp_reversed_err;
1996 my $e = "Authorization successful but reversal failed, custnum #".
1997 $self->custnum. ': '. $reverse->result_code.
1998 ": ". $reverse->error_message;
2005 ### Address Verification ###
2007 # Single-letter codes vary by cardtype.
2009 # Erring on the side of accepting cards if avs is not available,
2010 # only rejecting if avs occurred and there's been an explicit mismatch
2012 # Charts below taken from vSecure documentation,
2013 # shows codes for Amex/Dscv/MC/Visa
2015 # ACCEPTABLE AVS RESPONSES:
2016 # Both Address and 5-digit postal code match Y A Y Y
2017 # Both address and 9-digit postal code match Y A X Y
2018 # United Kingdom – Address and postal code match _ _ _ F
2019 # International transaction – Address and postal code match _ _ _ D/M
2021 # ACCEPTABLE, BUT ISSUE A WARNING:
2022 # Ineligible transaction; or message contains a content error _ _ _ E
2023 # System unavailable; retry R U R R
2024 # Information unavailable U W U U
2025 # Issuer does not support AVS S U S S
2026 # AVS is not applicable _ _ _ S
2027 # Incompatible formats – Not verified _ _ _ C
2028 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2029 # International transaction – address not verified _ G _ G/I
2031 # UNACCEPTABLE AVS RESPONSES:
2032 # Only Address matches A Y A A
2033 # Only 5-digit postal code matches Z Z Z Z
2034 # Only 9-digit postal code matches Z Z W W
2035 # Neither address nor postal code matches N N N N
2037 if (my $avscode = uc($transaction->avs_code)) {
2039 # map codes to accept/warn/reject
2041 'American Express card' => {
2050 'Discover card' => {
2089 my $cardtype = cardtype($content{card_number});
2090 if ($avs->{$cardtype}) {
2091 my $avsact = $avs->{$cardtype}->{$avscode};
2093 if ($avsact eq 'r') {
2094 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2095 } elsif ($avsact eq 'w') {
2096 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2097 } elsif (!$avsact) {
2098 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2099 } # else $avsact eq 'a'
2101 $log->warning($warning);
2104 } # else $cardtype avs handling not implemented
2105 } # else !$transaction->avs_code
2107 } else { # is not success
2109 # status is 'done' not 'declined', as in _realtime_bop_result
2110 $cust_pay_pending->status('done');
2111 $error = $transaction->error_message || 'Unknown error';
2112 $cust_pay_pending->statustext($error);
2113 # could also record failure_status here,
2114 # but it's not supported by B::OP::vSecureProcessing...
2115 # need a B::OP module with (reverse) auth only to test it with
2116 my $cpp_declined_err = $cust_pay_pending->replace;
2117 return $cpp_declined_err if $cpp_declined_err;
2121 } # end of IMMEDIATE; we now have our $error and $transaction
2124 # Save the custnum (as part of the main transaction, so it can reference
2128 if (!$cust_pay_pending->custnum) {
2129 $cust_pay_pending->set('custnum', $self->custnum);
2130 my $set_custnum_err = $cust_pay_pending->replace;
2131 if ($set_custnum_err) {
2132 $log->error($set_custnum_err);
2133 $error ||= $set_custnum_err;
2134 # but if there was a real verification error also, return that one
2139 # remove paycvv here? need to find out if a reversed auth
2140 # counts as an initial transaction for paycvv retention requirements
2147 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2148 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2149 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2150 $cust_pay_pending->payinfo($card_token);
2151 my $cpp_token_err = $cust_pay_pending->replace;
2152 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2153 return $cpp_token_err if $cpp_token_err;
2154 #important that we not replace cust_payby here,
2155 #because cust_payby->replace uses realtime_verify_bop!
2162 # $error contains the transaction error_message, if is_success was false.
2168 =item realtime_tokenize [ OPTION => VALUE ... ]
2170 If possible and necessary, runs a tokenize transaction.
2171 In order to be possible, a credit card cust_payby record
2172 must be passed and a Business::OnlinePayment gateway capable
2173 of Tokenize transactions must be configured for this user.
2174 Is only necessary if payinfo is not yet tokenized.
2176 Returns the empty string if the authorization was sucessful
2177 or was not possible/necessary (thus allowing this to be safely called with
2178 non-tokenizable records/gateways, without having to perform separate tests),
2179 or an error message otherwise.
2181 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2182 Object will be tokenized if possible, but that change will not be
2183 updated in database (must be inserted/replaced afterwards.)
2185 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2186 may be passed. If options are passed as a hashref, I<payinfo>
2187 will be updated as appropriate in the passed hashref.
2189 Can be run as a class method if option I<payment_gateway> is passed,
2190 but default customer id/name/phone can't be set in that case. This
2191 is really only intended for tokenizing old records on upgrade.
2195 # careful--might be run as a class method
2196 sub realtime_tokenize {
2199 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2200 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2203 my $outoptions; #for returning cust_payby/payinfo
2204 if (ref($_[0]) eq 'HASH') {
2205 %options = %{$_[0]};
2206 $outoptions = $_[0];
2209 $outoptions = \%options;
2212 # set fields from passed cust_payby
2213 _bop_cust_payby_options(\%options);
2214 return '' unless $options{method} eq 'CC';
2215 return '' if $self->tokenized($options{payinfo}); #already tokenized
2221 $options{'nofatal'} = 1;
2222 my $payment_gateway = $self->_payment_gateway( \%options );
2223 return '' unless $payment_gateway;
2224 my $namespace = $payment_gateway->gateway_namespace;
2225 return '' unless $namespace eq 'Business::OnlinePayment';
2227 eval "use $namespace";
2231 # check for tokenize ability
2234 my $transaction = new $namespace( $payment_gateway->gateway_module,
2235 _bop_options(\%options),
2238 return '' unless $transaction->can('info');
2240 my %supported_actions = $transaction->info('supported_actions');
2241 return '' unless $supported_actions{'CC'} and grep(/^Tokenize$/,@{$supported_actions{'CC'}});
2244 # check for banned credit card/ACH
2247 my $ban = FS::banned_pay->ban_search(
2248 'payby' => $bop_method2payby{'CC'},
2249 'payinfo' => $options{payinfo},
2251 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2257 ### Currently, cardfortress only keys in on card number and exp date.
2258 ### We pass everything we'd pass to a normal transaction,
2259 ### for ease of current and future development,
2260 ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2262 my $bop_content = $self->_bop_content(\%options);
2263 return $bop_content unless ref($bop_content);
2268 $content{card_number} = $options{payinfo};
2269 $paydate = $options{'paydate'};
2270 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2271 $content{expiration} = "$2/$1";
2273 $content{cvv2} = $options{'paycvv'}
2274 if length($options{'paycvv'});
2276 my $paystart_month = $options{'paystart_month'};
2277 my $paystart_year = $options{'paystart_year'};
2279 $content{card_start} = "$paystart_month/$paystart_year"
2280 if $paystart_month && $paystart_year;
2282 my $payissue = $options{'payissue'};
2283 $content{issue_number} = $payissue if $payissue;
2285 $content{customer_id} = $self->custnum
2294 # no cust_pay_pending---this is not a financial transaction
2296 $transaction->content(
2298 _bop_auth(\%options),
2299 'action' => 'Tokenize',
2300 'description' => $options{'description'},
2305 # no $BOP_TESTING handling for this
2306 $transaction->test_transaction(1)
2307 if $conf->exists('business-onlinepayment-test_transaction');
2308 $transaction->submit();
2310 if ( $transaction->card_token() ) { # no is_success flag
2312 # realtime_tokenize should not clear paycvv at this time. it might be
2313 # needed for the first transaction, and a tokenize isn't actually a
2314 # transaction that hits the gateway. at some point in the future, card
2315 # fortress should take on the "store paycvv until first transaction"
2316 # functionality and we should fix this in freeside, but i that's a bigger
2317 # project for another time.
2319 #important that we not replace cust_payby here,
2320 #because cust_payby->replace uses realtime_tokenize!
2321 $self->_tokenize_card($transaction,$outoptions);
2325 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2334 =item tokenized PAYINFO
2336 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2338 PAYINFO is required.
2340 Can be run as class or object method, never loads from object.
2346 my $payinfo = shift;
2347 FS::cust_pay->tokenized($payinfo);
2350 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2352 NOT A METHOD. Acts on all customers. Placed here because it makes
2353 use of module-internal methods, and to keep everything that uses
2354 Billing::OnlinePayment all in one place.
2356 Tokenizes all tokenizable card numbers from payinfo in cust_payby and
2357 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2359 If the I<queue> flag is set, newly tokenized records will be immediately
2360 committed, regardless of AutoCommit, so as to release the mutex on the record.
2362 If all configured gateways have the ability to tokenize, detection of an
2363 untokenizable record will cause a fatal error. However, if the I<queue> flag
2364 is set, this will instead cause a critical error to be recorded in the log,
2365 and any other tokenizable records will still be committed.
2367 If the I<daily> flag is also set, detection of existing untokenized records will
2368 record a critical error in the system log (because they should have never appeared
2369 in the first place.) Tokenization will still be attempted.
2371 If any configured gateways do NOT have the ability to tokenize, or if a
2372 default gateway is not configured, then untokenized records are not considered
2373 a threat, and no critical errors will be generated in the log.
2378 #acts on all customers
2380 my $debug = !$opt{'quiet'} || $DEBUG;
2382 warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2384 # force some explicitness when invoking this method
2385 die "token_check must run with queue flag if run with daily flag"
2386 if $opt{'daily'} && !$opt{'queue'};
2388 my $conf = FS::Conf->new;
2390 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2392 my $cache = {}; #cache for module info
2394 # look for a gateway that can't tokenize
2395 my $require_tokenized = 1;
2396 foreach my $gateway (
2397 FS::payment_gateway->all_gateways(
2404 # no default gateway, no promise to tokenize
2405 # can just load other gateways as-needeed below
2406 $require_tokenized = 0;
2409 my $info = _token_check_gateway_info($cache,$gateway);
2410 die $info unless ref($info); # means it's an error message
2411 unless ($info->{'can_tokenize'}) {
2412 # a configured gateway can't tokenize, that's all we need to know right now
2413 # can just load other gateways as-needeed below
2414 $require_tokenized = 0;
2419 warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2421 # upgrade does not call this with autocommit turned on,
2422 # and autocommit will be ignored if opt queue is set,
2423 # but might as well be thorough...
2424 my $oldAutoCommit = $FS::UID::AutoCommit;
2425 local $FS::UID::AutoCommit = 0;
2428 # for retrieving data in chunks
2432 ### Tokenize cust_payby
2437 while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2438 my $cust_main = FS::cust_main->by_key($custnum);
2439 my $payment_gateway;
2440 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2442 # see if it's already tokenized
2443 if ($cust_payby->tokenized) {
2444 warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2448 if ($require_tokenized && $opt{'daily'}) {
2449 $log->critical("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum);
2450 $dbh->commit or die $dbh->errstr; # commit log message
2453 # only load gateway if we need to, and only need to load it once
2454 my $payment_gateway ||= $cust_main->_payment_gateway({
2457 'nofatal' => 1, # handle lack of gateway smoothly below
2459 unless ($payment_gateway) {
2460 # no reason to have untokenized card numbers saved if no gateway,
2461 # but only a problem if we expected everyone to tokenize card numbers
2462 unless ($require_tokenized) {
2463 warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2464 next CUSTLOOP; # can skip rest of customer
2466 my $error = "No gateway found for custnum ".$cust_main->custnum;
2467 if ($opt{'queue'}) {
2468 $log->critical($error);
2469 $dbh->commit or die $dbh->errstr; # commit error message
2470 next; # not next CUSTLOOP, want to record error for every cust_payby
2472 $dbh->rollback if $oldAutoCommit;
2476 my $info = _token_check_gateway_info($cache,$payment_gateway);
2477 unless (ref($info)) {
2478 # only throws error if Business::OnlinePayment won't load,
2479 # which is just cause to abort this whole process, even if queue
2480 $dbh->rollback if $oldAutoCommit;
2481 die $info; # error message
2483 # no fail here--a configured gateway can't tokenize, so be it
2484 unless ($info->{'can_tokenize'}) {
2485 warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2490 $cust_payby = $cust_payby->select_for_update;
2492 'payment_gateway' => $payment_gateway,
2493 'cust_payby' => $cust_payby,
2495 my $error = $cust_main->realtime_tokenize(\%tokenopts);
2496 if ($cust_payby->tokenized) { # implies no error
2497 $error = $cust_payby->replace;
2499 $error ||= 'Unknown error';
2502 $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2503 if ($opt{'queue'}) {
2504 $log->critical($error);
2505 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2506 next; # not next CUSTLOOP, want to record error for every cust_payby
2508 $dbh->rollback if $oldAutoCommit;
2511 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2512 warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2514 warn "cust_payby upgraded for custnum ".$cust_main->custnum if $debug;
2518 ### Tokenize/mask transaction tables
2520 # allow tokenization of closed cust_pay/cust_refund records
2521 local $FS::payinfo_Mixin::allow_closed_replace = 1;
2524 # $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2525 foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2526 warn "Checking $table" if $debug;
2528 # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2529 # loading only record ids, then loading individual records one at a time
2530 my $tclass = 'FS::'.$table;
2534 while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2535 my $record = $tclass->by_key($recnum);
2536 if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2537 warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2540 if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2541 warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2544 if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2545 warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2549 if ($require_tokenized && $opt{'daily'}) {
2550 $log->critical("Untokenized card number detected in $table ".$record->get($record->primary_key));
2551 $dbh->commit or die $dbh->errstr; # commit log message
2554 # don't use customer agent gateway here, use the gatewaynum specified by the record
2555 my $gateway = FS::payment_gateway->by_key_or_default(
2559 'gatewaynum' => $record->gatewaynum || '',
2562 # means no default gateway, no promise to tokenize, can skip
2563 warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2567 my $info = _token_check_gateway_info($cache,$gateway);
2568 unless (ref($info)) {
2569 # only throws error if Business::OnlinePayment won't load,
2570 # which is just cause to abort this whole process, even if queue
2571 $dbh->rollback if $oldAutoCommit;
2572 die $info; # error message
2575 # a configured gateway can't tokenize, move along
2576 unless ($info->{'can_tokenize'}) {
2577 warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
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' && $record->{'custnum_pending'}) {
2587 warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug;
2589 my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2590 if ($opt{'queue'}) {
2591 $log->critical($error);
2592 $dbh->commit or die $dbh->errstr; # commit log message
2595 $dbh->rollback if $oldAutoCommit;
2600 # if we got this far, time to mutex
2601 $record = $record->select_for_update;
2603 # no clear record of name/address/etc used for transaction,
2604 # but will load name/phone/id from customer if run as an object method,
2605 # so we try that if we can
2607 'payment_gateway' => $gateway,
2609 'payinfo' => $record->payinfo,
2610 'paydate' => $record->paydate,
2612 my $error = $cust_main
2613 ? $cust_main->realtime_tokenize(\%tokenopts)
2614 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2615 if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2616 $record->payinfo($tokenopts{'payinfo'});
2617 $error = $record->replace;
2619 $error ||= 'Unknown error';
2622 $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2623 if ($opt{'queue'}) {
2624 $log->critical($error);
2625 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2628 $dbh->rollback if $oldAutoCommit;
2631 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2632 warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2637 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2643 sub _token_check_next_recnum {
2644 my ($dbh,$table,$step,$offset,$recnums) = @_;
2645 my $recnum = shift @$recnums;
2646 return $recnum if $recnum;
2647 my $tclass = 'FS::'.$table;
2648 my $sth = $dbh->prepare('SELECT '.$tclass->primary_key.' FROM '.$table.' ORDER BY '.$tclass->primary_key.' LIMIT '.$step.' OFFSET '.$$offset) or die $dbh->errstr;
2649 $sth->execute() or die $sth->errstr;
2651 while (my $rec = $sth->fetchrow_hashref) {
2652 push @$recnums, $rec->{$tclass->primary_key};
2656 return shift @$recnums;
2660 sub _token_check_gateway_info {
2661 my ($cache,$payment_gateway) = @_;
2663 return $cache->{$payment_gateway->gateway_module}
2664 if $cache->{$payment_gateway->gateway_module};
2667 $cache->{$payment_gateway->gateway_module} = $info;
2669 my $namespace = $payment_gateway->gateway_namespace;
2670 return $info unless $namespace eq 'Business::OnlinePayment';
2671 $info->{'is_bop'} = 1;
2673 # only need to load this once,
2674 # don't want to load if nothing is_bop
2675 unless ($cache->{'Business::OnlinePayment'}) {
2676 eval "use $namespace";
2677 return "Error initializing Business:OnlinePayment: ".$@ if $@;
2678 $cache->{'Business::OnlinePayment'} = 1;
2681 my $transaction = new $namespace( $payment_gateway->gateway_module,
2682 _bop_options({ 'payment_gateway' => $payment_gateway }),
2685 return $info unless $transaction->can('info');
2686 $info->{'can_info'} = 1;
2688 my %supported_actions = $transaction->info('supported_actions');
2689 $info->{'can_tokenize'} = 1
2690 if $supported_actions{'CC'}
2691 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2693 # not using this any more, but for future reference...
2694 $info->{'void_requires_card'} = 1
2695 if $transaction->info('CC_void_requires_card');
2706 L<FS::cust_main>, L<FS::cust_main::Billing>