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 sub realtime_collect {
117 my( $self, %options ) = @_;
119 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
122 warn "$me realtime_collect:\n";
123 warn " $_ => $options{$_}\n" foreach keys %options;
126 $options{amount} = $self->balance unless exists( $options{amount} );
127 return '' unless $options{amount} > 0;
129 #huh, in v4, realtime_bop no longer will just process a card without passing
130 # payinfo or cust_payby...
131 if ( ! $options{'payinfo'} && ! $options{'cust_payby'} && $self->has_cust_payby_auto ) {
132 my @cust_payby = $self->cust_payby;
133 $options{'cust_payby'} = $cust_payby[0];
136 return $self->realtime_bop({%options});
140 =item realtime_bop { [ ARG => VALUE ... ] }
142 Runs a realtime credit card or ACH (electronic check) transaction
143 via a Business::OnlinePayment realtime gateway. See
144 L<http://420.am/business-onlinepayment> for supported gateways.
146 Required arguments in the hashref are I<amount> and either
147 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
148 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
150 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
152 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
154 I<description> is a free-text field passed to the gateway. It defaults to
155 the value defined by the business-onlinepayment-description configuration
156 option, or "Internet services" if that is unset.
158 If an I<invnum> is specified, this payment (if successful) is applied to the
159 specified invoice. If the customer has exactly one open invoice, that
160 invoice number will be assumed. If you don't specify an I<invnum> you might
161 want to call the B<apply_payments> method or set the I<apply> option.
163 I<no_invnum> can be set to true to prevent that default invnum from being set.
165 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
167 I<no_auto_apply> can be set to true to set that flag on the resulting payment
168 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
169 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
171 I<quiet> can be set true to surpress email decline notices.
173 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
174 resulting paynum, if any.
176 I<payunique> is a unique identifier for this payment.
178 I<session_id> is a session identifier associated with this payment.
180 I<depend_jobnum> allows payment capture to unlock export jobs
182 I<discount_term> attempts to take a discount by prepaying for discount_term.
183 The payment will fail if I<amount> is incorrect for this discount term.
185 A direct (Business::OnlinePayment) transaction will return nothing on success,
186 or an error message on failure.
188 A third-party transaction will return a hashref containing:
190 - popup_url: the URL to which a browser should be redirected to complete
192 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
193 - reference: a reference ID for the transaction, to show the customer.
195 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
199 # some helper routines
201 # _bop_recurring_billing: Checks whether this payment should have the
202 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
203 # vSecure, etc.). This works in two different modes:
204 # - actual_oncard (default): treat the payment as recurring if the customer
205 # has made a payment using this card before.
206 # - transaction_is_recur: treat the payment as recurring if the invoice
207 # being paid has any recurring package charges.
209 sub _bop_recurring_billing {
210 my( $self, %opt ) = @_;
212 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
214 if ( defined($method) && $method eq 'transaction_is_recur' ) {
216 return 1 if $opt{'trans_is_recur'};
220 # return 1 if the payinfo has been used for another payment
221 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
229 #can run safely as class method if opt payment_gateway already exists
230 sub _payment_gateway {
231 my ($self, $options) = @_;
233 if ( $options->{'fake_gatewaynum'} ) {
234 $options->{payment_gateway} =
235 qsearchs('payment_gateway',
236 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
240 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
241 unless exists($options->{payment_gateway});
243 $options->{payment_gateway};
251 'login' => $options->{payment_gateway}->gateway_username,
252 'password' => $options->{payment_gateway}->gateway_password,
260 $options->{payment_gateway}->gatewaynum
261 ? $options->{payment_gateway}->options
262 : @{ $options->{payment_gateway}->get('options') };
267 my ($self, $options) = @_;
269 unless ( $options->{'description'} ) {
270 if ( $conf->exists('business-onlinepayment-description') ) {
271 my $dtempl = $conf->config('business-onlinepayment-description');
273 my $agent = $self->agent->agent;
275 $options->{'description'} = eval qq("$dtempl");
277 $options->{'description'} = 'Internet services';
281 # Default invoice number if the customer has exactly one open invoice.
282 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
283 $options->{'invnum'} = '';
284 my @open = $self->open_cust_bill;
285 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
291 sub _bop_cust_payby_options {
293 my $cust_payby = $options->{'cust_payby'};
296 $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
298 if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
299 # false laziness with cust_payby->check
300 # which might not have been run yet
302 if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
303 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
304 } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
305 ( $m, $y ) = ( $2, "19$1" );
306 } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
307 ( $m, $y ) = ( $3, "20$2" );
309 return "Illegal expiration date: ". $cust_payby->paydate;
311 $m = sprintf('%02d',$m);
312 $options->{paydate} = "$y-$m-01";
314 $options->{paydate} = '';
317 $options->{$_} = $cust_payby->$_()
318 for qw( payinfo paycvv paymask paystart_month paystart_year
319 payissue payname paystate paytype payip );
321 if ( $cust_payby->locationnum ) {
322 my $cust_location = $cust_payby->cust_location;
323 $options->{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
328 # can be called as class method,
329 # but can't load default name/phone fields as class method
331 my ($self, $options) = @_;
334 my $payip = $options->{'payip'};
335 $content{customer_ip} = $payip if length($payip);
337 $content{invoice_number} = $options->{'invnum'}
338 if exists($options->{'invnum'}) && length($options->{'invnum'});
340 $content{email_customer} =
341 ( $conf->exists('business-onlinepayment-email_customer')
342 || $conf->exists('business-onlinepayment-email-override') );
344 my ($payname, $payfirst, $paylast);
345 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
346 ($payname = $options->{payname}) =~
347 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
348 or return "Illegal payname $payname";
349 ($payfirst, $paylast) = ($1, $2);
350 } elsif (ref($self)) { # can't set payname if called as class method
351 $payfirst = $self->getfield('first');
352 $paylast = $self->getfield('last');
353 $payname = "$payfirst $paylast";
356 $content{last_name} = $paylast if $paylast;
357 $content{first_name} = $payfirst if $payfirst;
359 $content{name} = $payname if $payname;
361 $content{address} = $options->{'address1'};
362 my $address2 = $options->{'address2'};
363 $content{address} .= ", ". $address2 if length($address2);
365 $content{city} = $options->{'city'};
366 $content{state} = $options->{'state'};
367 $content{zip} = $options->{'zip'};
368 $content{country} = $options->{'country'};
370 # can't set phone if called as class method
371 $content{phone} = $self->daytime || $self->night
374 my $currency = $conf->exists('business-onlinepayment-currency')
375 && $conf->config('business-onlinepayment-currency');
376 $content{currency} = $currency if $currency;
381 # updates payinfo and cust_payby options with token from transaction
382 # can be called as a class method
384 my ($self,$transaction,$options) = @_;
385 if ( $transaction->can('card_token')
386 and $transaction->card_token
387 and !$self->tokenized($options->{'payinfo'})
389 $options->{'payinfo'} = $transaction->card_token;
390 $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
391 return $transaction->card_token;
396 my %bop_method2payby = (
405 confess "Can't call realtime_bop within another transaction ".
406 '($FS::UID::AutoCommit is false)'
407 unless $FS::UID::AutoCommit;
409 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
411 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
414 if (ref($_[0]) eq 'HASH') {
417 my ( $method, $amount ) = ( shift, shift );
419 $options{method} = $method;
420 $options{amount} = $amount;
423 # set fields from passed cust_payby
424 _bop_cust_payby_options(\%options);
426 # check for banned credit card/ACH
427 my $ban = FS::banned_pay->ban_search(
428 'payby' => $bop_method2payby{$options{method}},
429 'payinfo' => $options{payinfo},
431 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
433 # possibly run a separate transaction to tokenize card number,
434 # so that we never store tokenized card info in cust_pay_pending
435 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
436 my $token_error = $self->realtime_tokenize(\%options);
437 return $token_error if $token_error;
438 # in theory, all cust_payby will be tokenized during original save,
439 # so we shouldn't get here with opt cust_payby...but just in case...
440 if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
441 $token_error = $options{'cust_payby'}->replace;
442 return $token_error if $token_error;
447 # optional credit card surcharge
450 my $cc_surcharge = 0;
451 my $cc_surcharge_pct = 0;
452 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum)
453 if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
454 && $options{method} eq 'CC';
456 # always add cc surcharge if called from event
457 if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
458 $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
459 $options{'amount'} += $cc_surcharge;
460 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
462 elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a
463 # payment screen), so consider the given
464 # amount as post-surcharge
465 $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
468 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
469 $options{'cc_surcharge'} = $cc_surcharge;
473 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
474 warn " cc_surcharge = $cc_surcharge\n";
477 warn " $_ => $options{$_}\n" foreach keys %options;
480 return $self->fake_bop(\%options) if $options{'fake'};
482 $self->_bop_defaults(\%options);
484 return "Missing payinfo"
485 unless $options{'payinfo'};
488 # set trans_is_recur based on invnum if there is one
491 my $trans_is_recur = 0;
492 if ( $options{'invnum'} ) {
494 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
495 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
501 $cust_bill->cust_bill_pkg;
504 if grep { $_->freq ne '0' } @part_pkg;
512 my $payment_gateway = $self->_payment_gateway( \%options );
513 my $namespace = $payment_gateway->gateway_namespace;
515 eval "use $namespace";
519 # check for term discount validity
522 my $discount_term = $options{discount_term};
523 if ( $discount_term ) {
524 my $bill = ($self->cust_bill)[-1]
525 or return "Can't apply a term discount to an unbilled customer";
526 my $plan = FS::discount_plan->new(
528 months => $discount_term
529 ) or return "No discount available for term '$discount_term'";
531 if ( $plan->discounted_total != $options{amount} ) {
532 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
540 my $bop_content = $self->_bop_content(\%options);
541 return $bop_content unless ref($bop_content);
543 my @invoicing_list = $self->invoicing_list_emailonly;
544 if ( $conf->exists('emailinvoiceautoalways')
545 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
546 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
547 push @invoicing_list, $self->all_emails;
550 my $email = ($conf->exists('business-onlinepayment-email-override'))
551 ? $conf->config('business-onlinepayment-email-override')
552 : $invoicing_list[0];
557 if ( $namespace eq 'Business::OnlinePayment' ) {
559 if ( $options{method} eq 'CC' ) {
561 $content{card_number} = $options{payinfo};
562 $paydate = $options{'paydate'};
563 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
564 $content{expiration} = "$2/$1";
566 $content{cvv2} = $options{'paycvv'}
567 if length($options{'paycvv'});
569 my $paystart_month = $options{'paystart_month'};
570 my $paystart_year = $options{'paystart_year'};
571 $content{card_start} = "$paystart_month/$paystart_year"
572 if $paystart_month && $paystart_year;
574 my $payissue = $options{'payissue'};
575 $content{issue_number} = $payissue if $payissue;
577 if ( $self->_bop_recurring_billing(
578 'payinfo' => $options{'payinfo'},
579 'trans_is_recur' => $trans_is_recur,
583 $content{recurring_billing} = 'YES';
584 $content{acct_code} = 'rebill'
585 if $conf->exists('credit_card-recurring_billing_acct_code');
588 } elsif ( $options{method} eq 'ECHECK' ){
590 ( $content{account_number}, $content{routing_code} ) =
591 split('@', $options{payinfo});
592 $content{bank_name} = $options{payname};
593 $content{bank_state} = $options{'paystate'};
594 $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
596 $content{company} = $self->company if $self->company;
598 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
599 $content{account_name} = $self->company;
601 $content{account_name} = $self->getfield('first'). ' '.
602 $self->getfield('last');
605 $content{customer_org} = $self->company ? 'B' : 'I';
606 $content{state_id} = exists($options{'stateid'})
607 ? $options{'stateid'}
608 : $self->getfield('stateid');
609 $content{state_id_state} = exists($options{'stateid_state'})
610 ? $options{'stateid_state'}
611 : $self->getfield('stateid_state');
612 $content{customer_ssn} = exists($options{'ss'})
617 die "unknown method ". $options{method};
620 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
623 die "unknown namespace $namespace";
630 my $balance = exists( $options{'balance'} )
631 ? $options{'balance'}
634 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
635 $self->select_for_update; #mutex ... just until we get our pending record in
636 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
638 #the checks here are intended to catch concurrent payments
639 #double-form-submission prevention is taken care of in cust_pay_pending::check
642 return "The customer's balance has changed; $options{method} transaction aborted."
643 if $self->balance < $balance;
645 #also check and make sure there aren't *other* pending payments for this cust
647 my @pending = qsearch('cust_pay_pending', {
648 'custnum' => $self->custnum,
649 'status' => { op=>'!=', value=>'done' }
652 #for third-party payments only, remove pending payments if they're in the
653 #'thirdparty' (waiting for customer action) state.
654 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
655 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
656 my $error = $_->delete;
657 warn "error deleting unfinished third-party payment ".
658 $_->paypendingnum . ": $error\n"
661 @pending = grep { $_->status ne 'thirdparty' } @pending;
664 return "A payment is already being processed for this customer (".
665 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
666 "); $options{method} transaction aborted."
669 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
671 my $cust_pay_pending = new FS::cust_pay_pending {
672 'custnum' => $self->custnum,
673 'paid' => $options{amount},
675 'payby' => $bop_method2payby{$options{method}},
676 'payinfo' => $options{payinfo},
677 'paymask' => $options{paymask},
678 'paydate' => $paydate,
679 'recurring_billing' => $content{recurring_billing},
680 'pkgnum' => $options{'pkgnum'},
682 'gatewaynum' => $payment_gateway->gatewaynum || '',
683 'session_id' => $options{session_id} || '',
684 'jobnum' => $options{depend_jobnum} || '',
686 $cust_pay_pending->payunique( $options{payunique} )
687 if defined($options{payunique}) && length($options{payunique});
689 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
691 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
692 return $cpp_new_err if $cpp_new_err;
694 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
696 warn Dumper($cust_pay_pending) if $DEBUG > 2;
698 my( $action1, $action2 ) =
699 split( /\s*\,\s*/, $payment_gateway->gateway_action );
701 my $transaction = new $namespace( $payment_gateway->gateway_module,
702 _bop_options(\%options),
705 $transaction->content(
706 'type' => $options{method},
707 _bop_auth(\%options),
708 'action' => $action1,
709 'description' => $options{'description'},
710 'amount' => $options{amount},
711 #'invoice_number' => $options{'invnum'},
712 'customer_id' => $self->custnum,
714 'reference' => $cust_pay_pending->paypendingnum, #for now
715 'callback_url' => $payment_gateway->gateway_callback_url,
716 'cancel_url' => $payment_gateway->gateway_cancel_url,
721 $cust_pay_pending->status('pending');
722 my $cpp_pending_err = $cust_pay_pending->replace;
723 return $cpp_pending_err if $cpp_pending_err;
725 warn Dumper($transaction) if $DEBUG > 2;
727 unless ( $BOP_TESTING ) {
728 $transaction->test_transaction(1)
729 if $conf->exists('business-onlinepayment-test_transaction');
730 $transaction->submit();
732 if ( $BOP_TESTING_SUCCESS ) {
733 $transaction->is_success(1);
734 $transaction->authorization('fake auth');
736 $transaction->is_success(0);
737 $transaction->error_message('fake failure');
741 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
743 $cust_pay_pending->status('thirdparty');
744 my $cpp_err = $cust_pay_pending->replace;
745 return { error => $cpp_err } if $cpp_err;
746 return { reference => $cust_pay_pending->paypendingnum,
747 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
749 } elsif ( $transaction->is_success() && $action2 ) {
751 $cust_pay_pending->status('authorized');
752 my $cpp_authorized_err = $cust_pay_pending->replace;
753 return $cpp_authorized_err if $cpp_authorized_err;
755 my $auth = $transaction->authorization;
756 my $ordernum = $transaction->can('order_number')
757 ? $transaction->order_number
761 new Business::OnlinePayment( $payment_gateway->gateway_module,
762 _bop_options(\%options),
767 type => $options{method},
769 _bop_auth(\%options),
770 order_number => $ordernum,
771 amount => $options{amount},
772 authorization => $auth,
773 description => $options{'description'},
776 foreach my $field (qw( authorization_source_code returned_ACI
777 transaction_identifier validation_code
778 transaction_sequence_num local_transaction_date
779 local_transaction_time AVS_result_code )) {
780 $capture{$field} = $transaction->$field() if $transaction->can($field);
783 $capture->content( %capture );
785 $capture->test_transaction(1)
786 if $conf->exists('business-onlinepayment-test_transaction');
789 unless ( $capture->is_success ) {
790 my $e = "Authorization successful but capture failed, custnum #".
791 $self->custnum. ': '. $capture->result_code.
792 ": ". $capture->error_message;
800 # remove paycvv after initial transaction
803 # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
804 if ( length($options{'paycvv'})
805 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
807 my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
809 $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
810 #not returning error, should at least attempt to handle results of an otherwise valid transaction
811 warn "WARNING: error removing cvv: $error\n";
819 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
820 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
821 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
822 # cpp will be replaced in _realtime_bop_result
823 $cust_pay_pending->payinfo($card_token);
824 if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
825 $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
826 #not returning error, should at least attempt to handle results of an otherwise valid transaction
827 #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
835 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
847 if (ref($_[0]) eq 'HASH') {
850 my ( $method, $amount ) = ( shift, shift );
852 $options{method} = $method;
853 $options{amount} = $amount;
856 if ( $options{'fake_failure'} ) {
857 return "Error: No error; test failure requested with fake_failure";
860 my $cust_pay = new FS::cust_pay ( {
861 'custnum' => $self->custnum,
862 'invnum' => $options{'invnum'},
863 'paid' => $options{amount},
865 'payby' => $bop_method2payby{$options{method}},
866 'payinfo' => '4111111111111111',
867 'paydate' => '2012-05-01',
868 'processor' => 'FakeProcessor',
870 'order_number' => '32',
872 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
875 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
876 warn " $_ => $options{$_}\n" foreach keys %options;
879 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
882 $cust_pay->invnum(''); #try again with no specific invnum
883 my $error2 = $cust_pay->insert( $options{'manual'} ?
884 ( 'manual' => 1 ) : ()
887 # gah, even with transactions.
888 my $e = 'WARNING: Card/ACH debited but database not updated - '.
889 "error inserting (fake!) payment: $error2".
890 " (previously tried insert with invnum #$options{'invnum'}" .
897 if ( $options{'paynum_ref'} ) {
898 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
906 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
908 # Wraps up processing of a realtime credit card or ACH (electronic check)
911 sub _realtime_bop_result {
912 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
914 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
917 warn "$me _realtime_bop_result: pending transaction ".
918 $cust_pay_pending->paypendingnum. "\n";
919 warn " $_ => $options{$_}\n" foreach keys %options;
922 my $payment_gateway = $options{payment_gateway}
923 or return "no payment gateway in arguments to _realtime_bop_result";
925 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
926 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
927 return $cpp_captured_err if $cpp_captured_err;
929 if ( $transaction->is_success() ) {
931 my $order_number = $transaction->order_number
932 if $transaction->can('order_number');
934 my $cust_pay = new FS::cust_pay ( {
935 'custnum' => $self->custnum,
936 'invnum' => $options{'invnum'},
937 'paid' => $cust_pay_pending->paid,
939 'payby' => $cust_pay_pending->payby,
940 'payinfo' => $options{'payinfo'},
941 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
942 'paydate' => $cust_pay_pending->paydate,
943 'pkgnum' => $cust_pay_pending->pkgnum,
944 'discount_term' => $options{'discount_term'},
945 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
946 'processor' => $payment_gateway->gateway_module,
947 'auth' => $transaction->authorization,
948 'order_number' => $order_number || '',
949 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
951 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
952 $cust_pay->payunique( $options{payunique} )
953 if defined($options{payunique}) && length($options{payunique});
955 my $oldAutoCommit = $FS::UID::AutoCommit;
956 local $FS::UID::AutoCommit = 0;
959 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
961 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
964 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
965 $cust_pay->invnum(''); #try again with no specific invnum
966 $cust_pay->paynum('');
967 my $error2 = $cust_pay->insert( $options{'manual'} ?
968 ( 'manual' => 1 ) : ()
971 # gah. but at least we have a record of the state we had to abort in
972 # from cust_pay_pending now.
973 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
974 my $e = "WARNING: $options{method} captured but payment not recorded -".
975 " error inserting payment (". $payment_gateway->gateway_module.
977 " (previously tried insert with invnum #$options{'invnum'}" .
978 ": $error ) - pending payment saved as paypendingnum ".
979 $cust_pay_pending->paypendingnum. "\n";
985 my $jobnum = $cust_pay_pending->jobnum;
987 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
989 unless ( $placeholder ) {
990 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
991 my $e = "WARNING: $options{method} captured but job $jobnum not ".
992 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
997 $error = $placeholder->delete;
1000 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1001 my $e = "WARNING: $options{method} captured but could not delete ".
1002 "job $jobnum for paypendingnum ".
1003 $cust_pay_pending->paypendingnum. ": $error\n";
1008 $cust_pay_pending->set('jobnum','');
1012 if ( $options{'paynum_ref'} ) {
1013 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1016 $cust_pay_pending->status('done');
1017 $cust_pay_pending->statustext('captured');
1018 $cust_pay_pending->paynum($cust_pay->paynum);
1019 my $cpp_done_err = $cust_pay_pending->replace;
1021 if ( $cpp_done_err ) {
1023 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1024 my $e = "WARNING: $options{method} captured but payment not recorded - ".
1025 "error updating status for paypendingnum ".
1026 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1032 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1034 if ( $options{'apply'} ) {
1035 my $apply_error = $self->apply_payments_and_credits;
1036 if ( $apply_error ) {
1037 warn "WARNING: error applying payment: $apply_error\n";
1038 #but we still should return no error cause the payment otherwise went
1043 # have a CC surcharge portion --> one-time charge
1044 if ( $options{'cc_surcharge'} > 0 ) {
1045 # XXX: this whole block needs to be in a transaction?
1048 $invnum = $options{'invnum'} if $options{'invnum'};
1049 unless ( $invnum ) { # probably from a payment screen
1050 # do we have any open invoices? pick earliest
1051 # uses the fact that cust_main->cust_bill sorts by date ascending
1052 my @open = $self->open_cust_bill;
1053 $invnum = $open[0]->invnum if scalar(@open);
1056 unless ( $invnum ) { # still nothing? pick last closed invoice
1057 # again uses fact that cust_main->cust_bill sorts by date ascending
1058 my @closed = $self->cust_bill;
1059 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1062 unless ( $invnum ) {
1063 # XXX: unlikely case - pre-paying before any invoices generated
1064 # what it should do is create a new invoice and pick it
1065 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1070 my $charge_error = $self->charge({
1071 'amount' => $options{'cc_surcharge'},
1072 'pkg' => 'Credit Card Surcharge',
1074 'cust_pkg_ref' => \$cust_pkg,
1077 warn 'Unable to add CC surcharge cust_pkg';
1081 $cust_pkg->setup(time);
1082 my $cp_error = $cust_pkg->replace;
1084 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1088 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1089 unless ( $cust_bill ) {
1090 warn "race condition + invoice deletion just happened";
1095 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1097 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1101 return ''; #no error
1107 my $perror = $transaction->error_message;
1108 #$payment_gateway->gateway_module. " error: ".
1109 # removed for conciseness
1111 my $jobnum = $cust_pay_pending->jobnum;
1113 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1115 if ( $placeholder ) {
1116 my $error = $placeholder->depended_delete;
1117 $error ||= $placeholder->delete;
1118 $cust_pay_pending->set('jobnum','');
1119 warn "error removing provisioning jobs after declined paypendingnum ".
1120 $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1122 my $e = "error finding job $jobnum for declined paypendingnum ".
1123 $cust_pay_pending->paypendingnum. "\n";
1129 unless ( $transaction->error_message ) {
1132 if ( $transaction->can('response_page') ) {
1134 'page' => ( $transaction->can('response_page')
1135 ? $transaction->response_page
1138 'code' => ( $transaction->can('response_code')
1139 ? $transaction->response_code
1142 'headers' => ( $transaction->can('response_headers')
1143 ? $transaction->response_headers
1149 "No additional debugging information available for ".
1150 $payment_gateway->gateway_module;
1153 $perror .= "No error_message returned from ".
1154 $payment_gateway->gateway_module. " -- ".
1155 ( ref($t_response) ? Dumper($t_response) : $t_response );
1159 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1160 && $conf->exists('emaildecline', $self->agentnum)
1161 && grep { $_ ne 'POST' } $self->invoicing_list
1162 && ! grep { $transaction->error_message =~ /$_/ }
1163 $conf->config('emaildecline-exclude', $self->agentnum)
1166 # Send a decline alert to the customer.
1167 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1170 # include the raw error message in the transaction state
1171 $cust_pay_pending->setfield('error', $transaction->error_message);
1172 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1173 $error = $msg_template->send( 'cust_main' => $self,
1174 'object' => $cust_pay_pending );
1178 $perror .= " (also received error sending decline notification: $error)"
1183 $cust_pay_pending->status('done');
1184 $cust_pay_pending->statustext($perror);
1185 #'declined:': no, that's failure_status
1186 if ( $transaction->can('failure_status') ) {
1187 $cust_pay_pending->failure_status( $transaction->failure_status );
1189 my $cpp_done_err = $cust_pay_pending->replace;
1190 if ( $cpp_done_err ) {
1191 my $e = "WARNING: $options{method} declined but pending payment not ".
1192 "resolved - error updating status for paypendingnum ".
1193 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1195 $perror = "$e ($perror)";
1203 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1205 Verifies successful third party processing of a realtime credit card or
1206 ACH (electronic check) transaction via a
1207 Business::OnlineThirdPartyPayment realtime gateway. See
1208 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1210 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1212 The additional options I<payname>, I<city>, I<state>,
1213 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1214 if set, will override the value from the customer record.
1216 I<description> is a free-text field passed to the gateway. It defaults to
1217 "Internet services".
1219 If an I<invnum> is specified, this payment (if successful) is applied to the
1220 specified invoice. If you don't specify an I<invnum> you might want to
1221 call the B<apply_payments> method.
1223 I<quiet> can be set true to surpress email decline notices.
1225 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1226 resulting paynum, if any.
1228 I<payunique> is a unique identifier for this payment.
1230 Returns a hashref containing elements bill_error (which will be undefined
1231 upon success) and session_id of any associated session.
1235 sub realtime_botpp_capture {
1236 my( $self, $cust_pay_pending, %options ) = @_;
1238 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1241 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1242 warn " $_ => $options{$_}\n" foreach keys %options;
1245 eval "use Business::OnlineThirdPartyPayment";
1249 # select the gateway
1252 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1254 my $payment_gateway;
1255 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1256 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1257 { gatewaynum => $gatewaynum }
1259 : $self->agent->payment_gateway( 'method' => $method,
1260 # 'invnum' => $cust_pay_pending->invnum,
1261 # 'payinfo' => $cust_pay_pending->payinfo,
1264 $options{payment_gateway} = $payment_gateway; # for the helper subs
1270 my @invoicing_list = $self->invoicing_list_emailonly;
1271 if ( $conf->exists('emailinvoiceautoalways')
1272 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1273 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1274 push @invoicing_list, $self->all_emails;
1277 my $email = ($conf->exists('business-onlinepayment-email-override'))
1278 ? $conf->config('business-onlinepayment-email-override')
1279 : $invoicing_list[0];
1283 $content{email_customer} =
1284 ( $conf->exists('business-onlinepayment-email_customer')
1285 || $conf->exists('business-onlinepayment-email-override') );
1288 # run transaction(s)
1292 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1293 _bop_options(\%options),
1296 $transaction->reference({ %options });
1298 $transaction->content(
1300 _bop_auth(\%options),
1301 'action' => 'Post Authorization',
1302 'description' => $options{'description'},
1303 'amount' => $cust_pay_pending->paid,
1304 #'invoice_number' => $options{'invnum'},
1305 'customer_id' => $self->custnum,
1306 'reference' => $cust_pay_pending->paypendingnum,
1308 'phone' => $self->daytime || $self->night,
1310 # plus whatever is required for bogus capture avoidance
1313 $transaction->submit();
1316 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1318 if ( $options{'apply'} ) {
1319 my $apply_error = $self->apply_payments_and_credits;
1320 if ( $apply_error ) {
1321 warn "WARNING: error applying payment: $apply_error\n";
1326 bill_error => $error,
1327 session_id => $cust_pay_pending->session_id,
1332 =item default_payment_gateway
1334 DEPRECATED -- use agent->payment_gateway
1338 sub default_payment_gateway {
1339 my( $self, $method ) = @_;
1341 die "Real-time processing not enabled\n"
1342 unless $conf->exists('business-onlinepayment');
1344 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1347 my $bop_config = 'business-onlinepayment';
1348 $bop_config .= '-ach'
1349 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1350 my ( $processor, $login, $password, $action, @bop_options ) =
1351 $conf->config($bop_config);
1352 $action ||= 'normal authorization';
1353 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1354 die "No real-time processor is enabled - ".
1355 "did you set the business-onlinepayment configuration value?\n"
1358 ( $processor, $login, $password, $action, @bop_options )
1361 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1363 Refunds a realtime credit card or ACH (electronic check) transaction
1364 via a Business::OnlinePayment realtime gateway. See
1365 L<http://420.am/business-onlinepayment> for supported gateways.
1367 Available methods are: I<CC> or I<ECHECK>
1369 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1371 Most gateways require a reference to an original payment transaction to refund,
1372 so you probably need to specify a I<paynum>.
1374 I<amount> defaults to the original amount of the payment if not specified.
1376 I<reasonnum> specified an existing refund reason for the refund
1378 I<paydate> specifies the expiration date for a credit card overriding the
1379 value from the customer record or the payment record. Specified as yyyy-mm-dd
1381 Implementation note: If I<amount> is unspecified or equal to the amount of the
1382 orignal payment, first an attempt is made to "void" the transaction via
1383 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1384 the normal attempt is made to "refund" ("credit") the transaction via the
1385 gateway is attempted. No attempt to "void" the transaction is made if the
1386 gateway has introspection data and doesn't support void.
1388 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1389 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1390 #if set, will override the value from the customer record.
1392 #If an I<invnum> is specified, this payment (if successful) is applied to the
1393 #specified invoice. If you don't specify an I<invnum> you might want to
1394 #call the B<apply_payments> method.
1398 #some false laziness w/realtime_bop, not enough to make it worth merging
1399 #but some useful small subs should be pulled out
1400 sub realtime_refund_bop {
1403 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1406 if (ref($_[0]) eq 'HASH') {
1407 %options = %{$_[0]};
1411 $options{method} = $method;
1415 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1416 warn " $_ => $options{$_}\n" foreach keys %options;
1419 return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1424 # look up the original payment and optionally a gateway for that payment
1428 my $amount = $options{'amount'};
1430 my( $processor, $login, $password, @bop_options, $namespace ) ;
1431 my( $auth, $order_number ) = ( '', '', '' );
1432 my $gatewaynum = '';
1434 if ( $options{'paynum'} ) {
1436 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1437 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1438 or return "Unknown paynum $options{'paynum'}";
1439 $amount ||= $cust_pay->paid;
1441 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1442 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1444 if ( $cust_pay->get('processor') ) {
1445 ($gatewaynum, $processor, $auth, $order_number) =
1447 $cust_pay->gatewaynum,
1448 $cust_pay->processor,
1450 $cust_pay->order_number,
1453 # this payment wasn't upgraded, which probably means this won't work,
1455 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1456 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1457 $cust_pay->paybatch;
1458 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1461 my $payment_gateway;
1462 if ( $gatewaynum ) { #gateway for the payment to be refunded
1465 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1466 die "payment gateway $gatewaynum not found"
1467 unless $payment_gateway;
1469 $processor = $payment_gateway->gateway_module;
1470 $login = $payment_gateway->gateway_username;
1471 $password = $payment_gateway->gateway_password;
1472 $namespace = $payment_gateway->gateway_namespace;
1473 @bop_options = $payment_gateway->options;
1475 } else { #try the default gateway
1479 $self->agent->payment_gateway('method' => $options{method});
1481 ( $conf_processor, $login, $password, $namespace ) =
1482 map { my $method = "gateway_$_"; $payment_gateway->$method }
1483 qw( module username password namespace );
1485 @bop_options = $payment_gateway->gatewaynum
1486 ? $payment_gateway->options
1487 : @{ $payment_gateway->get('options') };
1488 my %bop_options = @bop_options;
1490 return "processor of payment $options{'paynum'} $processor does not".
1491 " match default processor $conf_processor"
1492 unless ($processor eq $conf_processor)
1493 || (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}));
1495 $processor = $conf_processor;
1499 # if gateway has switched to CardFortress but token_check hasn't run yet,
1500 # tokenize just this record now, so that token gets passed/set appropriately
1501 if ($cust_pay->payby eq 'CARD' && !$cust_pay->tokenized) {
1503 'payment_gateway' => $payment_gateway,
1505 'payinfo' => $cust_pay->payinfo,
1506 'paydate' => $cust_pay->paydate,
1508 my $error = $self->realtime_tokenize(\%tokenopts); # no-op unless gateway can tokenize
1509 if ($self->tokenized($tokenopts{'payinfo'})) { # implies no error
1510 warn " tokenizing cust_pay\n" if $DEBUG > 1;
1511 $cust_pay->payinfo($tokenopts{'payinfo'});
1512 $error = $cust_pay->replace;
1514 return $error if $error;
1517 } else { # didn't specify a paynum, so look for agent gateway overrides
1518 # like a normal transaction
1520 my $payment_gateway =
1521 $self->agent->payment_gateway( 'method' => $options{method} );
1522 my( $processor, $login, $password, $namespace ) =
1523 map { my $method = "gateway_$_"; $payment_gateway->$method }
1524 qw( module username password namespace );
1526 my @bop_options = $payment_gateway->gatewaynum
1527 ? $payment_gateway->options
1528 : @{ $payment_gateway->get('options') };
1531 return "neither amount nor paynum specified" unless $amount;
1533 eval "use $namespace";
1538 'type' => $options{method},
1540 'password' => $password,
1541 'order_number' => $order_number,
1542 'amount' => $amount,
1544 $content{authorization} = $auth
1545 if length($auth); #echeck/ACH transactions have an order # but no auth
1546 #(at least with authorize.net)
1548 my $currency = $conf->exists('business-onlinepayment-currency')
1549 && $conf->config('business-onlinepayment-currency');
1550 $content{currency} = $currency if $currency;
1552 my $disable_void_after;
1553 if ($conf->exists('disable_void_after')
1554 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1555 $disable_void_after = $1;
1558 #first try void if applicable
1559 my $void = new Business::OnlinePayment( $processor, @bop_options );
1562 if ($void->can('info')) {
1564 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1565 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1566 my %supported_actions = $void->info('supported_actions');
1568 if ( %supported_actions && $paytype
1569 && defined($supported_actions{$paytype})
1570 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1573 if ( $cust_pay && $cust_pay->paid == $amount
1575 ( not defined($disable_void_after) )
1576 || ( time < ($cust_pay->_date + $disable_void_after ) )
1580 warn " attempting void\n" if $DEBUG > 1;
1581 if ( $void->can('info') ) {
1582 if ( $cust_pay->payby eq 'CARD'
1583 && $void->info('CC_void_requires_card') )
1585 $content{'card_number'} = $cust_pay->payinfo;
1586 } elsif ( $cust_pay->payby eq 'CHEK'
1587 && $void->info('ECHECK_void_requires_account') )
1589 ( $content{'account_number'}, $content{'routing_code'} ) =
1590 split('@', $cust_pay->payinfo);
1591 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1594 $void->content( 'action' => 'void', %content );
1595 $void->test_transaction(1)
1596 if $conf->exists('business-onlinepayment-test_transaction');
1598 if ( $void->is_success ) {
1599 # specified as a refund reason, but now we want a payment void reason
1600 # extract just the reason text, let cust_pay::void handle new_or_existing
1601 my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1603 $error = 'Reason could not be loaded' unless $reason;
1604 $error = $cust_pay->void($reason->reason) unless $error;
1606 # gah, even with transactions.
1607 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1608 "error voiding payment: $error";
1612 warn " void successful\n" if $DEBUG > 1;
1617 warn " void unsuccessful, trying refund\n"
1621 my $address = $self->address1;
1622 $address .= ", ". $self->address2 if $self->address2;
1624 my($payname, $payfirst, $paylast);
1625 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1626 $payname = $self->payname;
1627 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1628 or return "Illegal payname $payname";
1629 ($payfirst, $paylast) = ($1, $2);
1631 $payfirst = $self->getfield('first');
1632 $paylast = $self->getfield('last');
1633 $payname = "$payfirst $paylast";
1636 my @invoicing_list = $self->invoicing_list_emailonly;
1637 if ( $conf->exists('emailinvoiceautoalways')
1638 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1639 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1640 push @invoicing_list, $self->all_emails;
1643 my $email = ($conf->exists('business-onlinepayment-email-override'))
1644 ? $conf->config('business-onlinepayment-email-override')
1645 : $invoicing_list[0];
1647 my $payip = exists($options{'payip'})
1650 $content{customer_ip} = $payip
1654 my $paymask = ''; # for refund record
1655 if ( $options{method} eq 'CC' ) {
1658 $content{card_number} = $payinfo = $cust_pay->payinfo;
1659 $paymask = $cust_pay->paymask;
1660 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1661 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1662 ($content{expiration} = "$2/$1"); # where available
1664 # this really needs a better cleanup
1665 die "Refund without paynum not supported";
1666 # $content{card_number} = $payinfo = $self->payinfo;
1667 # (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1668 # =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1669 # $content{expiration} = "$2/$1";
1672 } elsif ( $options{method} eq 'ECHECK' ) {
1675 $payinfo = $cust_pay->payinfo;
1677 $payinfo = $self->payinfo;
1679 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1680 $content{bank_name} = $self->payname;
1681 $content{account_type} = 'CHECKING';
1682 $content{account_name} = $payname;
1683 $content{customer_org} = $self->company ? 'B' : 'I';
1684 $content{customer_ssn} = $self->ss;
1689 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1690 my %sub_content = $refund->content(
1691 'action' => 'credit',
1692 'customer_id' => $self->custnum,
1693 'last_name' => $paylast,
1694 'first_name' => $payfirst,
1696 'address' => $address,
1697 'city' => $self->city,
1698 'state' => $self->state,
1699 'zip' => $self->zip,
1700 'country' => $self->country,
1702 'phone' => $self->daytime || $self->night,
1705 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1707 $refund->test_transaction(1)
1708 if $conf->exists('business-onlinepayment-test_transaction');
1711 return "$processor error: ". $refund->error_message
1712 unless $refund->is_success();
1714 $order_number = $refund->order_number if $refund->can('order_number');
1716 # change this to just use $cust_pay->delete_cust_bill_pay?
1717 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1718 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1719 last unless @cust_bill_pay;
1720 my $cust_bill_pay = pop @cust_bill_pay;
1721 my $error = $cust_bill_pay->delete;
1725 my $cust_refund = new FS::cust_refund ( {
1726 'custnum' => $self->custnum,
1727 'paynum' => $options{'paynum'},
1728 'source_paynum' => $options{'paynum'},
1729 'refund' => $amount,
1731 'payby' => $bop_method2payby{$options{method}},
1732 'payinfo' => $payinfo,
1733 'paymask' => $paymask,
1734 'reasonnum' => $options{'reasonnum'},
1735 'gatewaynum' => $gatewaynum, # may be null
1736 'processor' => $processor,
1737 'auth' => $refund->authorization,
1738 'order_number' => $order_number,
1740 my $error = $cust_refund->insert;
1742 $cust_refund->paynum(''); #try again with no specific paynum
1743 $cust_refund->source_paynum('');
1744 my $error2 = $cust_refund->insert;
1746 # gah, even with transactions.
1747 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1748 "error inserting refund ($processor): $error2".
1749 " (previously tried insert with paynum #$options{'paynum'}" .
1760 =item realtime_verify_bop [ OPTION => VALUE ... ]
1762 Runs an authorization-only transaction for $1 against this credit card (if
1763 successful, immediatly reverses the authorization).
1765 Returns the empty string if the authorization was sucessful, or an error
1768 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1769 Object will be tokenized if possible, but that change will not be
1770 updated in database (must be inserted/replaced afterwards.)
1772 Currently only succeeds for Business::OnlinePayment CC transactions.
1776 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1777 #it worth merging but some useful small subs should be pulled out
1778 sub realtime_verify_bop {
1781 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1782 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1785 if (ref($_[0]) eq 'HASH') {
1786 %options = %{$_[0]};
1792 warn "$me realtime_verify_bop\n";
1793 warn " $_ => $options{$_}\n" foreach keys %options;
1796 # set fields from passed cust_payby
1797 return "No cust_payby" unless $options{'cust_payby'};
1798 _bop_cust_payby_options(\%options);
1800 # check for banned credit card/ACH
1801 my $ban = FS::banned_pay->ban_search(
1802 'payby' => $bop_method2payby{'CC'},
1803 'payinfo' => $options{payinfo},
1805 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1807 # possibly run a separate transaction to tokenize card number,
1808 # so that we never store tokenized card info in cust_pay_pending
1809 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1810 my $token_error = $self->realtime_tokenize(\%options);
1811 return $token_error if $token_error;
1812 #important that we not replace cust_payby here,
1813 #because cust_payby->replace uses realtime_verify_bop!
1820 my $payment_gateway = $self->_payment_gateway( \%options );
1821 my $namespace = $payment_gateway->gateway_namespace;
1823 eval "use $namespace";
1830 my $bop_content = $self->_bop_content(\%options);
1831 return $bop_content unless ref($bop_content);
1833 my @invoicing_list = $self->invoicing_list_emailonly;
1834 if ( $conf->exists('emailinvoiceautoalways')
1835 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1836 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1837 push @invoicing_list, $self->all_emails;
1840 my $email = ($conf->exists('business-onlinepayment-email-override'))
1841 ? $conf->config('business-onlinepayment-email-override')
1842 : $invoicing_list[0];
1847 if ( $namespace eq 'Business::OnlinePayment' ) {
1849 if ( $options{method} eq 'CC' ) {
1851 $content{card_number} = $options{payinfo};
1852 $paydate = $options{'paydate'};
1853 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1854 $content{expiration} = "$2/$1";
1856 $content{cvv2} = $options{'paycvv'}
1857 if length($options{'paycvv'});
1859 my $paystart_month = $options{'paystart_month'};
1860 my $paystart_year = $options{'paystart_year'};
1862 $content{card_start} = "$paystart_month/$paystart_year"
1863 if $paystart_month && $paystart_year;
1865 my $payissue = $options{'payissue'};
1866 $content{issue_number} = $payissue if $payissue;
1868 } elsif ( $options{method} eq 'ECHECK' ){
1869 #cannot verify, move along (though it shouldn't be called...)
1872 return "unknown method ". $options{method};
1874 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1875 #cannot verify, move along
1878 return "unknown namespace $namespace";
1882 # run transaction(s)
1886 my $transaction; #need this back so we can do _tokenize_card
1888 # don't mutex the customer here, because they might be uncommitted. and
1889 # this is only verification. it doesn't matter if they have other
1890 # unfinished verifications.
1892 my $cust_pay_pending = new FS::cust_pay_pending {
1893 'custnum_pending' => 1,
1896 'payby' => $bop_method2payby{'CC'},
1897 'payinfo' => $options{payinfo},
1898 'paymask' => $options{paymask},
1899 'paydate' => $paydate,
1900 'pkgnum' => $options{'pkgnum'},
1902 'gatewaynum' => $payment_gateway->gatewaynum || '',
1903 'session_id' => $options{session_id} || '',
1905 $cust_pay_pending->payunique( $options{payunique} )
1906 if defined($options{payunique}) && length($options{payunique});
1909 # open a separate handle for creating/updating the cust_pay_pending
1911 local $FS::UID::dbh = myconnect();
1912 local $FS::UID::AutoCommit = 1;
1914 # if this is an existing customer (and we can tell now because
1915 # this is a fresh transaction), it's safe to assign their custnum
1916 # to the cust_pay_pending record, and then the verification attempt
1917 # will remain linked to them even if it fails.
1918 if ( FS::cust_main->by_key($self->custnum) ) {
1919 $cust_pay_pending->set('custnum', $self->custnum);
1922 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1925 # if this fails, just return; everything else will still allow the
1926 # cust_pay_pending to have its custnum set later
1927 my $cpp_new_err = $cust_pay_pending->insert;
1928 return $cpp_new_err if $cpp_new_err;
1930 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1932 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1934 $transaction = new $namespace( $payment_gateway->gateway_module,
1935 _bop_options(\%options),
1938 $transaction->content(
1940 _bop_auth(\%options),
1941 'action' => 'Authorization Only',
1942 'description' => $options{'description'},
1944 'customer_id' => $self->custnum,
1946 'reference' => $cust_pay_pending->paypendingnum, #for now
1951 $cust_pay_pending->status('pending');
1952 my $cpp_pending_err = $cust_pay_pending->replace;
1953 return $cpp_pending_err if $cpp_pending_err;
1955 warn Dumper($transaction) if $DEBUG > 2;
1957 unless ( $BOP_TESTING ) {
1958 $transaction->test_transaction(1)
1959 if $conf->exists('business-onlinepayment-test_transaction');
1960 $transaction->submit();
1962 if ( $BOP_TESTING_SUCCESS ) {
1963 $transaction->is_success(1);
1964 $transaction->authorization('fake auth');
1966 $transaction->is_success(0);
1967 $transaction->error_message('fake failure');
1971 if ( $transaction->is_success() ) {
1973 $cust_pay_pending->status('authorized');
1974 my $cpp_authorized_err = $cust_pay_pending->replace;
1975 return $cpp_authorized_err if $cpp_authorized_err;
1977 my $auth = $transaction->authorization;
1978 my $ordernum = $transaction->can('order_number')
1979 ? $transaction->order_number
1982 my $reverse = new $namespace( $payment_gateway->gateway_module,
1983 _bop_options(\%options),
1986 $reverse->content( 'action' => 'Reverse Authorization',
1987 _bop_auth(\%options),
1991 'authorization' => $transaction->authorization,
1992 'order_number' => $ordernum,
1995 'result_code' => $transaction->result_code,
1996 'txn_date' => $transaction->txn_date,
2000 $reverse->test_transaction(1)
2001 if $conf->exists('business-onlinepayment-test_transaction');
2004 if ( $reverse->is_success ) {
2006 $cust_pay_pending->status('done');
2007 $cust_pay_pending->statustext('reversed');
2008 my $cpp_reversed_err = $cust_pay_pending->replace;
2009 return $cpp_reversed_err if $cpp_reversed_err;
2013 my $e = "Authorization successful but reversal failed, custnum #".
2014 $self->custnum. ': '. $reverse->result_code.
2015 ": ". $reverse->error_message;
2022 ### Address Verification ###
2024 # Single-letter codes vary by cardtype.
2026 # Erring on the side of accepting cards if avs is not available,
2027 # only rejecting if avs occurred and there's been an explicit mismatch
2029 # Charts below taken from vSecure documentation,
2030 # shows codes for Amex/Dscv/MC/Visa
2032 # ACCEPTABLE AVS RESPONSES:
2033 # Both Address and 5-digit postal code match Y A Y Y
2034 # Both address and 9-digit postal code match Y A X Y
2035 # United Kingdom – Address and postal code match _ _ _ F
2036 # International transaction – Address and postal code match _ _ _ D/M
2038 # ACCEPTABLE, BUT ISSUE A WARNING:
2039 # Ineligible transaction; or message contains a content error _ _ _ E
2040 # System unavailable; retry R U R R
2041 # Information unavailable U W U U
2042 # Issuer does not support AVS S U S S
2043 # AVS is not applicable _ _ _ S
2044 # Incompatible formats – Not verified _ _ _ C
2045 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2046 # International transaction – address not verified _ G _ G/I
2048 # UNACCEPTABLE AVS RESPONSES:
2049 # Only Address matches A Y A A
2050 # Only 5-digit postal code matches Z Z Z Z
2051 # Only 9-digit postal code matches Z Z W W
2052 # Neither address nor postal code matches N N N N
2054 if (my $avscode = uc($transaction->avs_code)) {
2056 # map codes to accept/warn/reject
2058 'American Express card' => {
2067 'Discover card' => {
2106 my $cardtype = cardtype($content{card_number});
2107 if ($avs->{$cardtype}) {
2108 my $avsact = $avs->{$cardtype}->{$avscode};
2110 if ($avsact eq 'r') {
2111 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2112 } elsif ($avsact eq 'w') {
2113 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2114 } elsif (!$avsact) {
2115 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2116 } # else $avsact eq 'a'
2118 $log->warning($warning);
2121 } # else $cardtype avs handling not implemented
2122 } # else !$transaction->avs_code
2124 } else { # is not success
2126 # status is 'done' not 'declined', as in _realtime_bop_result
2127 $cust_pay_pending->status('done');
2128 $error = $transaction->error_message || 'Unknown error';
2129 $cust_pay_pending->statustext($error);
2130 # could also record failure_status here,
2131 # but it's not supported by B::OP::vSecureProcessing...
2132 # need a B::OP module with (reverse) auth only to test it with
2133 my $cpp_declined_err = $cust_pay_pending->replace;
2134 return $cpp_declined_err if $cpp_declined_err;
2138 } # end of IMMEDIATE; we now have our $error and $transaction
2141 # Save the custnum (as part of the main transaction, so it can reference
2145 if (!$cust_pay_pending->custnum) {
2146 $cust_pay_pending->set('custnum', $self->custnum);
2147 my $set_custnum_err = $cust_pay_pending->replace;
2148 if ($set_custnum_err) {
2149 $log->error($set_custnum_err);
2150 $error ||= $set_custnum_err;
2151 # but if there was a real verification error also, return that one
2156 # remove paycvv here? need to find out if a reversed auth
2157 # counts as an initial transaction for paycvv retention requirements
2164 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2165 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2166 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2167 $cust_pay_pending->payinfo($card_token);
2168 my $cpp_token_err = $cust_pay_pending->replace;
2169 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2170 return $cpp_token_err if $cpp_token_err;
2171 #important that we not replace cust_payby here,
2172 #because cust_payby->replace uses realtime_verify_bop!
2179 # $error contains the transaction error_message, if is_success was false.
2185 =item realtime_tokenize [ OPTION => VALUE ... ]
2187 If possible and necessary, runs a tokenize transaction.
2188 In order to be possible, a credit card cust_payby record
2189 must be passed and a Business::OnlinePayment gateway capable
2190 of Tokenize transactions must be configured for this user.
2191 Is only necessary if payinfo is not yet tokenized.
2193 Returns the empty string if the authorization was sucessful
2194 or was not possible/necessary (thus allowing this to be safely called with
2195 non-tokenizable records/gateways, without having to perform separate tests),
2196 or an error message otherwise.
2198 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2199 Object will be tokenized if possible, but that change will not be
2200 updated in database (must be inserted/replaced afterwards.)
2202 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2203 may be passed. If options are passed as a hashref, I<payinfo>
2204 will be updated as appropriate in the passed hashref.
2206 Can be run as a class method if option I<payment_gateway> is passed,
2207 but default customer id/name/phone can't be set in that case. This
2208 is really only intended for tokenizing old records on upgrade.
2212 # careful--might be run as a class method
2213 sub realtime_tokenize {
2216 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2217 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2220 my $outoptions; #for returning cust_payby/payinfo
2221 if (ref($_[0]) eq 'HASH') {
2222 %options = %{$_[0]};
2223 $outoptions = $_[0];
2226 $outoptions = \%options;
2229 # set fields from passed cust_payby
2230 _bop_cust_payby_options(\%options);
2231 return '' unless $options{method} eq 'CC';
2232 return '' if $self->tokenized($options{payinfo}); #already tokenized
2234 # check for banned credit card/ACH
2235 my $ban = FS::banned_pay->ban_search(
2236 'payby' => $bop_method2payby{'CC'},
2237 'payinfo' => $options{payinfo},
2239 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2245 $options{'nofatal'} = 1;
2246 my $payment_gateway = $self->_payment_gateway( \%options );
2247 return '' unless $payment_gateway;
2248 my $namespace = $payment_gateway->gateway_namespace;
2249 return '' unless $namespace eq 'Business::OnlinePayment';
2251 eval "use $namespace";
2255 # check for tokenize ability
2258 my $transaction = new $namespace( $payment_gateway->gateway_module,
2259 _bop_options(\%options),
2262 return '' unless $transaction->can('info');
2264 my %supported_actions = $transaction->info('supported_actions');
2265 return '' unless $supported_actions{'CC'}
2266 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2272 ### Currently, cardfortress only keys in on card number and exp date.
2273 ### We pass everything we'd pass to a normal transaction,
2274 ### for ease of current and future development,
2275 ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2277 my $bop_content = $self->_bop_content(\%options);
2278 return $bop_content unless ref($bop_content);
2283 $content{card_number} = $options{payinfo};
2284 $paydate = $options{'paydate'};
2285 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2286 $content{expiration} = "$2/$1";
2288 $content{cvv2} = $options{'paycvv'}
2289 if length($options{'paycvv'});
2291 my $paystart_month = $options{'paystart_month'};
2292 my $paystart_year = $options{'paystart_year'};
2294 $content{card_start} = "$paystart_month/$paystart_year"
2295 if $paystart_month && $paystart_year;
2297 my $payissue = $options{'payissue'};
2298 $content{issue_number} = $payissue if $payissue;
2300 $content{customer_id} = $self->custnum
2309 # no cust_pay_pending---this is not a financial transaction
2311 $transaction->content(
2313 _bop_auth(\%options),
2314 'action' => 'Tokenize',
2315 'description' => $options{'description'},
2320 # no $BOP_TESTING handling for this
2321 $transaction->test_transaction(1)
2322 if $conf->exists('business-onlinepayment-test_transaction');
2323 $transaction->submit();
2325 if ( $transaction->card_token() ) { # no is_success flag
2327 # realtime_tokenize should not clear paycvv at this time. it might be
2328 # needed for the first transaction, and a tokenize isn't actually a
2329 # transaction that hits the gateway. at some point in the future, card
2330 # fortress should take on the "store paycvv until first transaction"
2331 # functionality and we should fix this in freeside, but i that's a bigger
2332 # project for another time.
2334 #important that we not replace cust_payby here,
2335 #because cust_payby->replace uses realtime_tokenize!
2336 $self->_tokenize_card($transaction,$outoptions);
2340 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2349 =item tokenized PAYINFO
2351 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2353 PAYINFO is required.
2355 Can be run as class or object method, never loads from object.
2361 my $payinfo = shift;
2362 FS::cust_pay->tokenized($payinfo);
2365 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2367 NOT A METHOD. Acts on all customers. Placed here because it makes
2368 use of module-internal methods, and to keep everything that uses
2369 Billing::OnlinePayment all in one place.
2371 Tokenizes all tokenizable card numbers from payinfo in cust_payby and
2372 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2374 If the I<queue> flag is set, newly tokenized records will be immediately
2375 committed, regardless of AutoCommit, so as to release the mutex on the record.
2377 If all configured gateways have the ability to tokenize, detection of an
2378 untokenizable record will cause a fatal error. However, if the I<queue> flag
2379 is set, this will instead cause a critical error to be recorded in the log,
2380 and any other tokenizable records will still be committed.
2382 If the I<daily> flag is also set, detection of existing untokenized records will
2383 record an info message in the system log (because they should have never appeared
2384 in the first place.) Tokenization will still be attempted.
2386 If any configured gateways do NOT have the ability to tokenize, or if a
2387 default gateway is not configured, then untokenized records are not considered
2388 a threat, and no critical errors will be generated in the log.
2393 #acts on all customers
2395 my $debug = !$opt{'quiet'} || $DEBUG;
2396 my $hascritical = 0;
2398 warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2400 # force some explicitness when invoking this method
2401 die "token_check must run with queue flag if run with daily flag"
2402 if $opt{'daily'} && !$opt{'queue'};
2404 my $conf = FS::Conf->new;
2406 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2408 my $cache = {}; #cache for module info
2410 # look for a gateway that can and can't tokenize
2411 my $require_tokenized = 1;
2412 my $someone_tokenizing = 0;
2413 foreach my $gateway (
2414 FS::payment_gateway->all_gateways(
2421 # no default gateway, no promise to tokenize
2422 # can just load other gateways as-needeed below
2423 $require_tokenized = 0;
2424 last if $someone_tokenizing;
2427 my $info = _token_check_gateway_info($cache,$gateway);
2428 die $info unless ref($info); # means it's an error message
2429 if ($info->{'can_tokenize'}) {
2430 $someone_tokenizing = 1;
2432 # a configured gateway can't tokenize, that's all we need to know right now
2433 # can just load other gateways as-needeed below
2434 $require_tokenized = 0;
2435 last if $someone_tokenizing;
2439 unless ($someone_tokenizing) { #no need to check, if no one can tokenize
2440 warn "no gateways tokenize\n" if $debug;
2444 warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2446 # upgrade does not call this with autocommit turned on,
2447 # and autocommit will be ignored if opt queue is set,
2448 # but might as well be thorough...
2449 my $oldAutoCommit = $FS::UID::AutoCommit;
2450 local $FS::UID::AutoCommit = 0;
2453 # for retrieving data in chunks
2457 ### Tokenize cust_payby
2462 while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2463 my $cust_main = FS::cust_main->by_key($custnum);
2464 my $payment_gateway;
2465 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2467 # see if it's already tokenized
2468 if ($cust_payby->tokenized) {
2469 warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2473 if ($require_tokenized && $opt{'daily'}) {
2474 $log->info("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum. '; tokenizing');
2475 $dbh->commit or die $dbh->errstr; # commit log message
2478 # only load gateway if we need to, and only need to load it once
2479 $payment_gateway ||= $cust_main->_payment_gateway({
2482 'nofatal' => 1, # handle lack of gateway smoothly below
2484 unless ($payment_gateway) {
2485 # no reason to have untokenized card numbers saved if no gateway,
2486 # but only a problem if we expected everyone to tokenize card numbers
2487 unless ($require_tokenized) {
2488 warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2489 next CUSTLOOP; # can skip rest of customer
2491 my $error = "No gateway found for custnum ".$cust_main->custnum;
2492 if ($opt{'queue'}) {
2494 $log->critical($error);
2495 $dbh->commit or die $dbh->errstr; # commit error message
2496 next; # not next CUSTLOOP, want to record error for every cust_payby
2498 $dbh->rollback if $oldAutoCommit;
2502 my $info = _token_check_gateway_info($cache,$payment_gateway);
2503 unless (ref($info)) {
2504 # only throws error if Business::OnlinePayment won't load,
2505 # which is just cause to abort this whole process, even if queue
2506 $dbh->rollback if $oldAutoCommit;
2507 die $info; # error message
2509 # no fail here--a configured gateway can't tokenize, so be it
2510 unless ($info->{'can_tokenize'}) {
2511 warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2516 $cust_payby = $cust_payby->select_for_update;
2518 'payment_gateway' => $payment_gateway,
2519 'cust_payby' => $cust_payby,
2521 my $error = $cust_main->realtime_tokenize(\%tokenopts);
2522 if ($cust_payby->tokenized) { # implies no error
2523 $error = $cust_payby->replace;
2525 $error ||= 'Unknown error';
2528 $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2529 if ($opt{'queue'}) {
2531 $log->critical($error);
2532 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2533 next; # not next CUSTLOOP, want to record error for every cust_payby
2535 $dbh->rollback if $oldAutoCommit;
2538 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2539 warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2541 warn "cust_payby upgraded for custnum ".$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 unless ($record->payby eq 'CARD') {
2564 warn "Skipping non-card record for $table ".$record->get($record->primary_key) if $debug;
2567 if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2568 warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2571 if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2572 warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2575 if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2576 warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2580 if ($require_tokenized && $opt{'daily'}) {
2581 $log->info("Untokenized card number detected in $table ".$record->get($record->primary_key). ';tokenizing');
2582 $dbh->commit or die $dbh->errstr; # commit log message
2585 my $cust_main = $record->cust_main;
2587 # might happen for cust_pay_pending from failed verify records,
2588 # in which case we attempt tokenization without cust_main
2589 # everything else should absolutely have a cust_main
2590 if ($table eq 'cust_pay_pending' and !$record->custnum ) {
2591 # override the usual safety check and allow the record to be
2592 # updated even without a custnum.
2593 $record->set('custnum_pending', 1);
2595 my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2596 if ($opt{'queue'}) {
2598 $log->critical($error);
2599 $dbh->commit or die $dbh->errstr; # commit log message
2602 $dbh->rollback if $oldAutoCommit;
2609 # use the gatewaynum specified by the record if possible
2610 $gateway = FS::payment_gateway->by_key_with_namespace(
2611 'gatewaynum' => $record->gatewaynum,
2612 ) if $record->gateway;
2614 # otherwise use the cust agent gateway if possible (which realtime_refund_bop would do)
2615 # otherwise just use default gateway
2618 $gateway = $cust_main
2619 ? $cust_main->agent->payment_gateway
2620 : FS::payment_gateway->default_gateway;
2622 # check for processor mismatch
2623 unless ($table eq 'cust_pay_pending') { # has no processor table
2624 if (my $processor = $record->processor) {
2626 my $conf_processor = $gateway->gateway_module;
2627 my %bop_options = $gateway->gatewaynum
2629 : @{ $gateway->get('options') };
2631 # this is the same standard used by realtime_refund_bop
2633 ($processor eq $conf_processor) ||
2634 (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}))
2637 # processors don't match, so refund already cannot be run on this object,
2638 # regardless of what we do now...
2639 # but unless we gotta tokenize everything, just leave well enough alone
2640 unless ($require_tokenized) {
2641 warn "Skipping mismatched processor for $table ".$record->get($record->primary_key) if $debug;
2644 ### no error--we'll tokenize using the new gateway, just to remove stored payinfo,
2645 ### because refunds are already impossible for this record, anyway
2647 } # end processor mismatch
2649 } # end record has processor
2650 } # end not cust_pay_pending
2654 # means no default gateway, no promise to tokenize, can skip
2656 warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2660 my $info = _token_check_gateway_info($cache,$gateway);
2661 unless (ref($info)) {
2662 # only throws error if Business::OnlinePayment won't load,
2663 # which is just cause to abort this whole process, even if queue
2664 $dbh->rollback if $oldAutoCommit;
2665 die $info; # error message
2668 # a configured gateway can't tokenize, move along
2669 unless ($info->{'can_tokenize'}) {
2670 warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2674 warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug && !$cust_main;
2676 # if we got this far, time to mutex
2677 $record->select_for_update;
2679 # no clear record of name/address/etc used for transaction,
2680 # but will load name/phone/id from customer if run as an object method,
2681 # so we try that if we can
2683 'payment_gateway' => $gateway,
2685 'payinfo' => $record->payinfo,
2686 'paydate' => $record->paydate,
2688 my $error = $cust_main
2689 ? $cust_main->realtime_tokenize(\%tokenopts)
2690 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2691 if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2692 $record->payinfo($tokenopts{'payinfo'});
2693 $error = $record->replace;
2695 $error ||= 'Unknown error';
2698 $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2699 if ($opt{'queue'}) {
2701 $log->critical($error);
2702 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2705 $dbh->rollback if $oldAutoCommit;
2708 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2709 warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2714 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2716 return $hascritical ? 'Critical errors occurred on some records, see system log' : '';
2720 sub _token_check_next_recnum {
2721 my ($dbh,$table,$step,$offset,$recnums) = @_;
2722 my $recnum = shift @$recnums;
2723 return $recnum if $recnum;
2724 my $tclass = 'FS::'.$table;
2725 my $sth = $dbh->prepare(
2726 'SELECT '.$tclass->primary_key.
2728 " WHERE ( is_tokenized IS NULL OR is_tokenized = '' ) ".
2729 ' ORDER BY '.$tclass->primary_key.
2732 ) or die $dbh->errstr;
2733 $sth->execute() or die $sth->errstr;
2735 while (my $rec = $sth->fetchrow_hashref) {
2736 push @$recnums, $rec->{$tclass->primary_key};
2740 return shift @$recnums;
2744 sub _token_check_gateway_info {
2745 my ($cache,$payment_gateway) = @_;
2747 return $cache->{$payment_gateway->gateway_module}
2748 if $cache->{$payment_gateway->gateway_module};
2751 $cache->{$payment_gateway->gateway_module} = $info;
2753 my $namespace = $payment_gateway->gateway_namespace;
2754 return $info unless $namespace eq 'Business::OnlinePayment';
2755 $info->{'is_bop'} = 1;
2757 # only need to load this once,
2758 # don't want to load if nothing is_bop
2759 unless ($cache->{'Business::OnlinePayment'}) {
2760 eval "use $namespace";
2761 return "Error initializing Business:OnlinePayment: ".$@ if $@;
2762 $cache->{'Business::OnlinePayment'} = 1;
2765 my $transaction = new $namespace( $payment_gateway->gateway_module,
2766 _bop_options({ 'payment_gateway' => $payment_gateway }),
2769 return $info unless $transaction->can('info');
2770 $info->{'can_info'} = 1;
2772 my %supported_actions = $transaction->info('supported_actions');
2773 $info->{'can_tokenize'} = 1
2774 if $supported_actions{'CC'}
2775 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2777 # not using this any more, but for future reference...
2778 $info->{'void_requires_card'} = 1
2779 if $transaction->info('CC_void_requires_card');
2790 L<FS::cust_main>, L<FS::cust_main::Billing>