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 Business::OnlinePayment;
10 use FS::UID qw( dbh myconnect );
11 use FS::Record qw( qsearch qsearchs );
14 use FS::cust_pay_pending;
15 use FS::cust_bill_pay;
18 use FS::payment_gateway;
20 $realtime_bop_decline_quiet = 0;
22 # 1 is mostly method/subroutine entry and options
23 # 2 traces progress of some operations
24 # 3 is even more information including possibly sensitive data
26 $me = '[FS::cust_main::Billing_Realtime]';
29 our $BOP_TESTING_SUCCESS = 1;
31 install_callback FS::UID sub {
33 #yes, need it for stuff below (prolly should be cached)
38 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
44 These methods are available on FS::cust_main objects.
50 =item realtime_cust_payby
54 sub realtime_cust_payby {
55 my( $self, %options ) = @_;
57 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
59 $options{amount} = $self->balance unless exists( $options{amount} );
61 my @cust_payby = $self->cust_payby('CARD','CHEK');
64 foreach my $cust_payby (@cust_payby) {
65 $error = $cust_payby->realtime_bop( %options, );
69 #XXX what about the earlier errors?
75 =item realtime_collect [ OPTION => VALUE ... ]
77 Attempt to collect the customer's current balance with a realtime credit
78 card or electronic check transaction (see realtime_bop() below).
80 Returns the result of realtime_bop(): nothing, an error message, or a
81 hashref of state information for a third-party transaction.
83 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
85 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
86 then it is deduced from the customer record.
88 If no I<amount> is specified, then the customer balance is used.
90 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
91 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
92 if set, will override the value from the customer record.
94 I<description> is a free-text field passed to the gateway. It defaults to
95 the value defined by the business-onlinepayment-description configuration
96 option, or "Internet services" if that is unset.
98 If an I<invnum> is specified, this payment (if successful) is applied to the
101 I<apply> will automatically apply a resulting payment.
103 I<quiet> can be set true to suppress email decline notices.
105 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
106 resulting paynum, if any.
108 I<payunique> is a unique identifier for this payment.
110 I<session_id> is a session identifier associated with this payment.
112 I<depend_jobnum> allows payment capture to unlock export jobs
116 # Currently only used by ClientAPI
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 #huh, in v4, realtime_bop no longer will just process a card without passing
131 # payinfo or cust_payby...
132 if ( ! $options{'payinfo'} && ! $options{'cust_payby'} && $self->has_cust_payby_auto ) {
133 my @cust_payby = $self->cust_payby;
134 $options{'cust_payby'} = $cust_payby[0];
137 return $self->realtime_bop({%options});
141 =item realtime_bop { [ ARG => VALUE ... ] }
143 Runs a realtime credit card or ACH (electronic check) transaction
144 via a Business::OnlinePayment realtime gateway. See
145 L<http://420.am/business-onlinepayment> for supported gateways.
147 Required arguments in the hashref are I<amount> and either
148 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
149 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
151 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
153 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
155 I<description> is a free-text field passed to the gateway. It defaults to
156 the value defined by the business-onlinepayment-description configuration
157 option, or "Internet services" if that is unset.
159 If an I<invnum> is specified, this payment (if successful) is applied to the
160 specified invoice. If the customer has exactly one open invoice, that
161 invoice number will be assumed. If you don't specify an I<invnum> you might
162 want to call the B<apply_payments> method or set the I<apply> option.
164 I<no_invnum> can be set to true to prevent that default invnum from being set.
166 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
168 I<no_auto_apply> can be set to true to set that flag on the resulting payment
169 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
170 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
172 I<quiet> can be set true to surpress email decline notices.
174 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
175 resulting paynum, if any.
177 I<payunique> is a unique identifier for this payment.
179 I<session_id> is a session identifier associated with this payment.
181 I<depend_jobnum> allows payment capture to unlock export jobs
183 I<discount_term> attempts to take a discount by prepaying for discount_term.
184 The payment will fail if I<amount> is incorrect for this discount term.
186 A direct (Business::OnlinePayment) transaction will return nothing on success,
187 or an error message on failure.
189 A third-party transaction will return a hashref containing:
191 - popup_url: the URL to which a browser should be redirected to complete
193 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
194 - reference: a reference ID for the transaction, to show the customer.
196 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
200 # some helper routines
202 # _bop_recurring_billing: Checks whether this payment should have the
203 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
204 # vSecure, etc.). This works in two different modes:
205 # - actual_oncard (default): treat the payment as recurring if the customer
206 # has made a payment using this card before.
207 # - transaction_is_recur: treat the payment as recurring if the invoice
208 # being paid has any recurring package charges.
210 sub _bop_recurring_billing {
211 my( $self, %opt ) = @_;
213 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
215 if ( defined($method) && $method eq 'transaction_is_recur' ) {
217 return 1 if $opt{'trans_is_recur'};
221 # return 1 if the payinfo has been used for another payment
222 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
230 #can run safely as class method if opt payment_gateway already exists
231 sub _payment_gateway {
232 my ($self, $options) = @_;
234 if ( $options->{'fake_gatewaynum'} ) {
235 $options->{payment_gateway} =
236 qsearchs('payment_gateway',
237 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
241 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
242 unless exists($options->{payment_gateway});
244 $options->{payment_gateway};
252 'login' => $options->{payment_gateway}->gateway_username,
253 'password' => $options->{payment_gateway}->gateway_password,
261 $options->{payment_gateway}->gatewaynum
262 ? $options->{payment_gateway}->options
263 : @{ $options->{payment_gateway}->get('options') };
268 my ($self, $options) = @_;
270 unless ( $options->{'description'} ) {
271 if ( $conf->exists('business-onlinepayment-description') ) {
272 my $dtempl = $conf->config('business-onlinepayment-description');
274 my $agent = $self->agent->agent;
276 $options->{'description'} = eval qq("$dtempl");
278 $options->{'description'} = 'Internet services';
282 # Default invoice number if the customer has exactly one open invoice.
283 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
284 $options->{'invnum'} = '';
285 my @open = $self->open_cust_bill;
286 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
292 sub _bop_cust_payby_options {
294 my $cust_payby = $options->{'cust_payby'};
297 $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
299 if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
300 # false laziness with cust_payby->check
301 # which might not have been run yet
303 if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
304 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
305 } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
306 ( $m, $y ) = ( $2, "19$1" );
307 } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
308 ( $m, $y ) = ( $3, "20$2" );
310 return "Illegal expiration date: ". $cust_payby->paydate;
312 $m = sprintf('%02d',$m);
313 $options->{paydate} = "$y-$m-01";
315 $options->{paydate} = '';
318 $options->{$_} = $cust_payby->$_()
319 for qw( payinfo paycvv paymask paystart_month paystart_year
320 payissue payname paystate paytype payip );
322 if ( $cust_payby->locationnum ) {
323 my $cust_location = $cust_payby->cust_location;
324 $options->{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
329 # can be called as class method,
330 # but can't load default name/phone fields as class method
332 my ($self, $options) = @_;
335 my $payip = $options->{'payip'};
336 $content{customer_ip} = $payip if length($payip);
338 $content{invoice_number} = $options->{'invnum'}
339 if exists($options->{'invnum'}) && length($options->{'invnum'});
341 $content{email_customer} =
342 ( $conf->exists('business-onlinepayment-email_customer')
343 || $conf->exists('business-onlinepayment-email-override') );
345 my ($payname, $payfirst, $paylast);
346 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
347 ($payname = $options->{payname}) =~
348 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
349 or return "Illegal payname $payname";
350 ($payfirst, $paylast) = ($1, $2);
351 } elsif (ref($self)) { # can't set payname if called as class method
352 $payfirst = $self->getfield('first');
353 $paylast = $self->getfield('last');
354 $payname = "$payfirst $paylast";
357 $content{last_name} = $paylast if $paylast;
358 $content{first_name} = $payfirst if $payfirst;
360 $content{name} = $payname if $payname;
362 $content{address} = $options->{'address1'};
363 my $address2 = $options->{'address2'};
364 $content{address} .= ", ". $address2 if length($address2);
366 $content{city} = $options->{'city'};
367 $content{state} = $options->{'state'};
368 $content{zip} = $options->{'zip'};
369 $content{country} = $options->{'country'};
371 # can't set phone if called as class method
372 $content{phone} = $self->daytime || $self->night
375 my $currency = $conf->exists('business-onlinepayment-currency')
376 && $conf->config('business-onlinepayment-currency');
377 $content{currency} = $currency if $currency;
382 # updates payinfo and cust_payby options with token from transaction
383 # can be called as a class method
385 my ($self,$transaction,$options) = @_;
386 if ( $transaction->can('card_token')
387 and $transaction->card_token
388 and !$self->tokenized($options->{'payinfo'})
390 $options->{'payinfo'} = $transaction->card_token;
391 $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
392 return $transaction->card_token;
397 my %bop_method2payby = (
406 confess "Can't call realtime_bop within another transaction ".
407 '($FS::UID::AutoCommit is false)'
408 unless $FS::UID::AutoCommit;
410 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
412 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
415 if (ref($_[0]) eq 'HASH') {
418 my ( $method, $amount ) = ( shift, shift );
420 $options{method} = $method;
421 $options{amount} = $amount;
424 return '' unless $options{amount} > 0;
426 # set fields from passed cust_payby
427 _bop_cust_payby_options(\%options);
429 # check for banned credit card/ACH
430 my $ban = FS::banned_pay->ban_search(
431 'payby' => $bop_method2payby{$options{method}},
432 'payinfo' => $options{payinfo},
434 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
436 # possibly run a separate transaction to tokenize card number,
437 # so that we never store tokenized card info in cust_pay_pending
438 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
439 my $token_error = $self->realtime_tokenize(\%options);
440 return $token_error if $token_error;
441 # in theory, all cust_payby will be tokenized during original save,
442 # so we shouldn't get here with opt cust_payby...but just in case...
443 if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
444 $token_error = $options{'cust_payby'}->replace;
445 return $token_error if $token_error;
450 # optional credit card surcharge
453 my $cc_surcharge = 0;
454 my $cc_surcharge_pct = 0;
455 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum)
456 if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
457 && $options{method} eq 'CC';
459 my $cc_surcharge_flat = 0;
460 $cc_surcharge_flat = $conf->config('credit-card-surcharge-flatfee', $self->agentnum)
461 if $conf->config('credit-card-surcharge-flatfee', $self->agentnum)
462 && $options{method} eq 'CC';
464 # always add cc surcharge if called from event
465 if($options{'cc_surcharge_from_event'} && ($cc_surcharge_pct > 0 || $cc_surcharge_flat > 0)) {
466 if ($options{'amount'} > 0) {
467 $cc_surcharge = ($options{'amount'} * ($cc_surcharge_pct / 100)) + $cc_surcharge_flat;
468 $options{'amount'} += $cc_surcharge;
469 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
472 elsif($cc_surcharge_pct > 0 || $cc_surcharge_flat > 0) {
473 # we're called not from event (i.e. from a
474 # payment screen), so consider the given
475 # amount as post-surcharge
476 $cc_surcharge = $options{'amount'} - (($options{'amount'} - $cc_surcharge_flat) / ( 1 + $cc_surcharge_pct/100 )) if $options{'amount'} > 0;
479 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
480 $options{'cc_surcharge'} = $cc_surcharge;
484 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
485 warn " cc_surcharge = $cc_surcharge\n";
488 warn " $_ => $options{$_}\n" foreach keys %options;
491 return $self->fake_bop(\%options) if $options{'fake'};
493 $self->_bop_defaults(\%options);
495 return "Missing payinfo"
496 unless $options{'payinfo'};
499 # set trans_is_recur based on invnum if there is one
502 my $trans_is_recur = 0;
503 if ( $options{'invnum'} ) {
505 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
506 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
512 $cust_bill->cust_bill_pkg;
515 if grep { $_->freq ne '0' } @part_pkg;
523 my $payment_gateway = $self->_payment_gateway( \%options );
524 my $namespace = $payment_gateway->gateway_namespace;
526 eval "use $namespace";
530 # check for term discount validity
533 my $discount_term = $options{discount_term};
534 if ( $discount_term ) {
535 my $bill = ($self->cust_bill)[-1]
536 or return "Can't apply a term discount to an unbilled customer";
537 my $plan = FS::discount_plan->new(
539 months => $discount_term
540 ) or return "No discount available for term '$discount_term'";
542 if ( $plan->discounted_total != $options{amount} ) {
543 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
551 my $bop_content = $self->_bop_content(\%options);
552 return $bop_content unless ref($bop_content);
554 my @invoicing_list = $self->invoicing_list_emailonly;
555 if ( $conf->exists('emailinvoiceautoalways')
556 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
557 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
558 push @invoicing_list, $self->all_emails;
561 my $email = ($conf->exists('business-onlinepayment-email-override'))
562 ? $conf->config('business-onlinepayment-email-override')
563 : $invoicing_list[0];
568 if ( $namespace eq 'Business::OnlinePayment' ) {
570 if ( $options{method} eq 'CC' ) {
572 $content{card_number} = $options{payinfo};
573 $paydate = $options{'paydate'};
574 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
575 $content{expiration} = "$2/$1";
577 $content{cvv2} = $options{'paycvv'}
578 if length($options{'paycvv'});
580 my $paystart_month = $options{'paystart_month'};
581 my $paystart_year = $options{'paystart_year'};
582 $content{card_start} = "$paystart_month/$paystart_year"
583 if $paystart_month && $paystart_year;
585 my $payissue = $options{'payissue'};
586 $content{issue_number} = $payissue if $payissue;
588 if ( $self->_bop_recurring_billing(
589 'payinfo' => $options{'payinfo'},
590 'trans_is_recur' => $trans_is_recur,
594 $content{recurring_billing} = 'YES';
595 $content{acct_code} = 'rebill'
596 if $conf->exists('credit_card-recurring_billing_acct_code');
599 } elsif ( $options{method} eq 'ECHECK' ){
601 ( $content{account_number}, $content{routing_code} ) =
602 split('@', $options{payinfo});
603 $content{bank_name} = $options{payname};
604 $content{bank_state} = $options{'paystate'};
605 $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
607 $content{company} = $self->company if $self->company;
609 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
610 $content{account_name} = $self->company;
612 $content{account_name} = $self->getfield('first'). ' '.
613 $self->getfield('last');
616 $content{customer_org} = $self->company ? 'B' : 'I';
617 $content{state_id} = exists($options{'stateid'})
618 ? $options{'stateid'}
619 : $self->getfield('stateid');
620 $content{state_id_state} = exists($options{'stateid_state'})
621 ? $options{'stateid_state'}
622 : $self->getfield('stateid_state');
623 $content{customer_ssn} = exists($options{'ss'})
628 die "unknown method ". $options{method};
631 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
634 die "unknown namespace $namespace";
641 my $balance = exists( $options{'balance'} )
642 ? $options{'balance'}
645 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
646 $self->select_for_update; #mutex ... just until we get our pending record in
647 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
649 #the checks here are intended to catch concurrent payments
650 #double-form-submission prevention is taken care of in cust_pay_pending::check
653 return "The customer's balance has changed; $options{method} transaction aborted."
654 if $self->balance < $balance;
656 #also check and make sure there aren't *other* pending payments for this cust
658 my @pending = qsearch('cust_pay_pending', {
659 'custnum' => $self->custnum,
660 'status' => { op=>'!=', value=>'done' }
663 #for third-party payments only, remove pending payments if they're in the
664 #'thirdparty' (waiting for customer action) state.
665 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
666 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
667 my $error = $_->delete;
668 warn "error deleting unfinished third-party payment ".
669 $_->paypendingnum . ": $error\n"
672 @pending = grep { $_->status ne 'thirdparty' } @pending;
675 return "A payment is already being processed for this customer (".
676 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
677 "); $options{method} transaction aborted."
680 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
682 my $cust_pay_pending = new FS::cust_pay_pending {
683 'custnum' => $self->custnum,
684 'paid' => $options{amount},
686 'payby' => $bop_method2payby{$options{method}},
687 'payinfo' => $options{payinfo},
688 'paymask' => $options{paymask},
689 'paydate' => $paydate,
690 'recurring_billing' => $content{recurring_billing},
691 'pkgnum' => $options{'pkgnum'},
693 'gatewaynum' => $payment_gateway->gatewaynum || '',
694 'session_id' => $options{session_id} || '',
695 'jobnum' => $options{depend_jobnum} || '',
697 $cust_pay_pending->payunique( $options{payunique} )
698 if defined($options{payunique}) && length($options{payunique});
700 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
702 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
703 return $cpp_new_err if $cpp_new_err;
705 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
707 warn Dumper($cust_pay_pending) if $DEBUG > 2;
709 my( $action1, $action2 ) =
710 split( /\s*\,\s*/, $payment_gateway->gateway_action );
712 my $transaction = new $namespace( $payment_gateway->gateway_module,
713 _bop_options(\%options),
716 $transaction->content(
717 'type' => $options{method},
718 _bop_auth(\%options),
719 'action' => $action1,
720 'description' => $options{'description'},
721 'amount' => $options{amount},
722 #'invoice_number' => $options{'invnum'},
723 'customer_id' => $self->custnum,
725 'reference' => $cust_pay_pending->paypendingnum, #for now
726 'callback_url' => $payment_gateway->gateway_callback_url,
727 'cancel_url' => $payment_gateway->gateway_cancel_url,
732 $cust_pay_pending->status('pending');
733 my $cpp_pending_err = $cust_pay_pending->replace;
734 return $cpp_pending_err if $cpp_pending_err;
736 warn Dumper($transaction) if $DEBUG > 2;
738 unless ( $BOP_TESTING ) {
739 $transaction->test_transaction(1)
740 if $conf->exists('business-onlinepayment-test_transaction');
741 $transaction->submit();
743 if ( $BOP_TESTING_SUCCESS ) {
744 $transaction->is_success(1);
745 $transaction->authorization('fake auth');
747 $transaction->is_success(0);
748 $transaction->error_message('fake failure');
752 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
754 $cust_pay_pending->status('thirdparty');
755 my $cpp_err = $cust_pay_pending->replace;
756 return { error => $cpp_err } if $cpp_err;
757 return { reference => $cust_pay_pending->paypendingnum,
758 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
760 } elsif ( $transaction->is_success() && $action2 ) {
762 $cust_pay_pending->status('authorized');
763 my $cpp_authorized_err = $cust_pay_pending->replace;
764 return $cpp_authorized_err if $cpp_authorized_err;
766 my $auth = $transaction->authorization;
767 my $ordernum = $transaction->can('order_number')
768 ? $transaction->order_number
772 new Business::OnlinePayment( $payment_gateway->gateway_module,
773 _bop_options(\%options),
778 type => $options{method},
780 _bop_auth(\%options),
781 order_number => $ordernum,
782 amount => $options{amount},
783 authorization => $auth,
784 description => $options{'description'},
787 foreach my $field (qw( authorization_source_code returned_ACI
788 transaction_identifier validation_code
789 transaction_sequence_num local_transaction_date
790 local_transaction_time AVS_result_code )) {
791 $capture{$field} = $transaction->$field() if $transaction->can($field);
794 $capture->content( %capture );
796 $capture->test_transaction(1)
797 if $conf->exists('business-onlinepayment-test_transaction');
800 unless ( $capture->is_success ) {
801 my $e = "Authorization successful but capture failed, custnum #".
802 $self->custnum. ': '. $capture->result_code.
803 ": ". $capture->error_message;
811 # remove paycvv after initial transaction
814 # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
815 if ( length($options{'paycvv'})
816 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
818 my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
820 $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
821 #not returning error, should at least attempt to handle results of an otherwise valid transaction
822 warn "WARNING: error removing cvv: $error\n";
830 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
831 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
832 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
833 # cpp will be replaced in _realtime_bop_result
834 $cust_pay_pending->payinfo($card_token);
835 if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
836 $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
837 #not returning error, should at least attempt to handle results of an otherwise valid transaction
838 #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
846 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
858 if (ref($_[0]) eq 'HASH') {
861 my ( $method, $amount ) = ( shift, shift );
863 $options{method} = $method;
864 $options{amount} = $amount;
867 if ( $options{'fake_failure'} ) {
868 return "Error: No error; test failure requested with fake_failure";
871 my $cust_pay = new FS::cust_pay ( {
872 'custnum' => $self->custnum,
873 'invnum' => $options{'invnum'},
874 'paid' => $options{amount},
876 'payby' => $bop_method2payby{$options{method}},
877 'payinfo' => '4111111111111111',
878 'paydate' => '2012-05-01',
879 'processor' => 'FakeProcessor',
881 'order_number' => '32',
883 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
886 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
887 warn " $_ => $options{$_}\n" foreach keys %options;
890 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
893 $cust_pay->invnum(''); #try again with no specific invnum
894 my $error2 = $cust_pay->insert( $options{'manual'} ?
895 ( 'manual' => 1 ) : ()
898 # gah, even with transactions.
899 my $e = 'WARNING: Card/ACH debited but database not updated - '.
900 "error inserting (fake!) payment: $error2".
901 " (previously tried insert with invnum #$options{'invnum'}" .
908 if ( $options{'paynum_ref'} ) {
909 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
917 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
919 # Wraps up processing of a realtime credit card or ACH (electronic check)
922 sub _realtime_bop_result {
923 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
925 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
928 warn "$me _realtime_bop_result: pending transaction ".
929 $cust_pay_pending->paypendingnum. "\n";
930 warn " $_ => $options{$_}\n" foreach keys %options;
933 my $payment_gateway = $options{payment_gateway}
934 or return "no payment gateway in arguments to _realtime_bop_result";
936 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
937 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
938 return $cpp_captured_err if $cpp_captured_err;
940 if ( $transaction->is_success() ) {
942 my $order_number = $transaction->order_number
943 if $transaction->can('order_number');
945 my $cust_pay = new FS::cust_pay ( {
946 'custnum' => $self->custnum,
947 'invnum' => $options{'invnum'},
948 'paid' => $cust_pay_pending->paid,
950 'payby' => $cust_pay_pending->payby,
951 'payinfo' => $options{'payinfo'},
952 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
953 'paydate' => $cust_pay_pending->paydate,
954 'pkgnum' => $cust_pay_pending->pkgnum,
955 'discount_term' => $options{'discount_term'},
956 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
957 'processor' => $payment_gateway->gateway_module,
958 'auth' => $transaction->authorization,
959 'order_number' => $order_number || '',
960 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
962 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
963 $cust_pay->payunique( $options{payunique} )
964 if defined($options{payunique}) && length($options{payunique});
966 my $oldAutoCommit = $FS::UID::AutoCommit;
967 local $FS::UID::AutoCommit = 0;
970 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
972 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
975 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
976 $cust_pay->invnum(''); #try again with no specific invnum
977 $cust_pay->paynum('');
978 my $error2 = $cust_pay->insert( $options{'manual'} ?
979 ( 'manual' => 1 ) : ()
982 # gah. but at least we have a record of the state we had to abort in
983 # from cust_pay_pending now.
984 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
985 my $e = "WARNING: $options{method} captured but payment not recorded -".
986 " error inserting payment (". $payment_gateway->gateway_module.
988 " (previously tried insert with invnum #$options{'invnum'}" .
989 ": $error ) - pending payment saved as paypendingnum ".
990 $cust_pay_pending->paypendingnum. "\n";
996 my $jobnum = $cust_pay_pending->jobnum;
998 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1000 unless ( $placeholder ) {
1001 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1002 my $e = "WARNING: $options{method} captured but job $jobnum not ".
1003 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
1008 $error = $placeholder->delete;
1011 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1012 my $e = "WARNING: $options{method} captured but could not delete ".
1013 "job $jobnum for paypendingnum ".
1014 $cust_pay_pending->paypendingnum. ": $error\n";
1019 $cust_pay_pending->set('jobnum','');
1023 if ( $options{'paynum_ref'} ) {
1024 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1027 $cust_pay_pending->status('done');
1028 $cust_pay_pending->statustext('captured');
1029 $cust_pay_pending->paynum($cust_pay->paynum);
1030 my $cpp_done_err = $cust_pay_pending->replace;
1032 if ( $cpp_done_err ) {
1034 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1035 my $e = "WARNING: $options{method} captured but payment not recorded - ".
1036 "error updating status for paypendingnum ".
1037 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1043 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1045 if ( $options{'apply'} ) {
1046 my $apply_error = $self->apply_payments_and_credits;
1047 if ( $apply_error ) {
1048 warn "WARNING: error applying payment: $apply_error\n";
1049 #but we still should return no error cause the payment otherwise went
1054 # have a CC surcharge portion --> one-time charge
1055 if ( $options{'cc_surcharge'} > 0 ) {
1056 # XXX: this whole block needs to be in a transaction?
1059 $invnum = $options{'invnum'} if $options{'invnum'};
1060 unless ( $invnum ) { # probably from a payment screen
1061 # do we have any open invoices? pick earliest
1062 # uses the fact that cust_main->cust_bill sorts by date ascending
1063 my @open = $self->open_cust_bill;
1064 $invnum = $open[0]->invnum if scalar(@open);
1067 unless ( $invnum ) { # still nothing? pick last closed invoice
1068 # again uses fact that cust_main->cust_bill sorts by date ascending
1069 my @closed = $self->cust_bill;
1070 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1073 unless ( $invnum ) {
1074 # XXX: unlikely case - pre-paying before any invoices generated
1075 # what it should do is create a new invoice and pick it
1076 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1081 my $cc_surcharge_text = 'Credit Card Surcharge';
1082 $cc_surcharge_text = $conf->config('credit-card-surcharge-text', $self->agentnum) if $conf->exists('credit-card-surcharge-text', $self->agentnum);
1083 my $charge_error = $self->charge({
1084 'amount' => $options{'cc_surcharge'},
1085 'pkg' => $cc_surcharge_text,
1087 'cust_pkg_ref' => \$cust_pkg,
1090 warn 'Unable to add CC surcharge cust_pkg';
1094 $cust_pkg->setup(time);
1095 my $cp_error = $cust_pkg->replace;
1097 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1101 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1102 unless ( $cust_bill ) {
1103 warn "race condition + invoice deletion just happened";
1108 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1110 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1114 return ''; #no error
1120 my $perror = $transaction->error_message;
1121 #$payment_gateway->gateway_module. " error: ".
1122 # removed for conciseness
1124 my $jobnum = $cust_pay_pending->jobnum;
1126 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1128 if ( $placeholder ) {
1129 my $error = $placeholder->depended_delete;
1130 $error ||= $placeholder->delete;
1131 $cust_pay_pending->set('jobnum','');
1132 warn "error removing provisioning jobs after declined paypendingnum ".
1133 $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1135 my $e = "error finding job $jobnum for declined paypendingnum ".
1136 $cust_pay_pending->paypendingnum. "\n";
1142 unless ( $transaction->error_message ) {
1145 if ( $transaction->can('response_page') ) {
1147 'page' => ( $transaction->can('response_page')
1148 ? $transaction->response_page
1151 'code' => ( $transaction->can('response_code')
1152 ? $transaction->response_code
1155 'headers' => ( $transaction->can('response_headers')
1156 ? $transaction->response_headers
1162 "No additional debugging information available for ".
1163 $payment_gateway->gateway_module;
1166 $perror .= "No error_message returned from ".
1167 $payment_gateway->gateway_module. " -- ".
1168 ( ref($t_response) ? Dumper($t_response) : $t_response );
1172 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1173 && $conf->exists('emaildecline', $self->agentnum)
1174 && grep { $_ ne 'POST' } $self->invoicing_list
1175 && ! grep { $transaction->error_message =~ /$_/ }
1176 $conf->config('emaildecline-exclude', $self->agentnum)
1179 # Send a decline alert to the customer.
1180 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1183 # include the raw error message in the transaction state
1184 $cust_pay_pending->setfield('error', $transaction->error_message);
1185 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1186 $error = $msg_template->send( 'cust_main' => $self,
1187 'object' => $cust_pay_pending );
1191 $perror .= " (also received error sending decline notification: $error)"
1196 $cust_pay_pending->status('done');
1197 $cust_pay_pending->statustext($perror);
1198 #'declined:': no, that's failure_status
1199 if ( $transaction->can('failure_status') ) {
1200 $cust_pay_pending->failure_status( $transaction->failure_status );
1202 my $cpp_done_err = $cust_pay_pending->replace;
1203 if ( $cpp_done_err ) {
1204 my $e = "WARNING: $options{method} declined but pending payment not ".
1205 "resolved - error updating status for paypendingnum ".
1206 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1208 #XXX internal system log $e (what's going on?)
1209 $perror = "$e ($perror)";
1217 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1219 Verifies successful third party processing of a realtime credit card or
1220 ACH (electronic check) transaction via a
1221 Business::OnlineThirdPartyPayment realtime gateway. See
1222 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1224 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1226 The additional options I<payname>, I<city>, I<state>,
1227 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1228 if set, will override the value from the customer record.
1230 I<description> is a free-text field passed to the gateway. It defaults to
1231 "Internet services".
1233 If an I<invnum> is specified, this payment (if successful) is applied to the
1234 specified invoice. If you don't specify an I<invnum> you might want to
1235 call the B<apply_payments> method.
1237 I<quiet> can be set true to surpress email decline notices.
1239 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1240 resulting paynum, if any.
1242 I<payunique> is a unique identifier for this payment.
1244 Returns a hashref containing elements bill_error (which will be undefined
1245 upon success) and session_id of any associated session.
1249 sub realtime_botpp_capture {
1250 my( $self, $cust_pay_pending, %options ) = @_;
1252 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1255 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1256 warn " $_ => $options{$_}\n" foreach keys %options;
1259 eval "use Business::OnlineThirdPartyPayment";
1263 # select the gateway
1266 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1268 my $payment_gateway;
1269 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1270 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1271 { gatewaynum => $gatewaynum }
1273 : $self->agent->payment_gateway( 'method' => $method,
1274 # 'invnum' => $cust_pay_pending->invnum,
1275 # 'payinfo' => $cust_pay_pending->payinfo,
1278 $options{payment_gateway} = $payment_gateway; # for the helper subs
1284 my @invoicing_list = $self->invoicing_list_emailonly;
1285 if ( $conf->exists('emailinvoiceautoalways')
1286 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1287 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1288 push @invoicing_list, $self->all_emails;
1291 my $email = ($conf->exists('business-onlinepayment-email-override'))
1292 ? $conf->config('business-onlinepayment-email-override')
1293 : $invoicing_list[0];
1297 $content{email_customer} =
1298 ( $conf->exists('business-onlinepayment-email_customer')
1299 || $conf->exists('business-onlinepayment-email-override') );
1302 # run transaction(s)
1306 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1307 _bop_options(\%options),
1310 $transaction->reference({ %options });
1312 $transaction->content(
1314 _bop_auth(\%options),
1315 'action' => 'Post Authorization',
1316 'description' => $options{'description'},
1317 'amount' => $cust_pay_pending->paid,
1318 #'invoice_number' => $options{'invnum'},
1319 'customer_id' => $self->custnum,
1320 'reference' => $cust_pay_pending->paypendingnum,
1322 'phone' => $self->daytime || $self->night,
1324 # plus whatever is required for bogus capture avoidance
1327 $transaction->submit();
1330 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1332 if ( $options{'apply'} ) {
1333 my $apply_error = $self->apply_payments_and_credits;
1334 if ( $apply_error ) {
1335 warn "WARNING: error applying payment: $apply_error\n";
1340 bill_error => $error,
1341 session_id => $cust_pay_pending->session_id,
1346 =item default_payment_gateway
1348 DEPRECATED -- use agent->payment_gateway
1352 sub default_payment_gateway {
1353 my( $self, $method ) = @_;
1355 die "Real-time processing not enabled\n"
1356 unless $conf->exists('business-onlinepayment');
1358 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1361 my $bop_config = 'business-onlinepayment';
1362 $bop_config .= '-ach'
1363 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1364 my ( $processor, $login, $password, $action, @bop_options ) =
1365 $conf->config($bop_config);
1366 $action ||= 'normal authorization';
1367 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1368 die "No real-time processor is enabled - ".
1369 "did you set the business-onlinepayment configuration value?\n"
1372 ( $processor, $login, $password, $action, @bop_options )
1375 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1377 Refunds a realtime credit card or ACH (electronic check) transaction
1378 via a Business::OnlinePayment realtime gateway. See
1379 L<http://420.am/business-onlinepayment> for supported gateways.
1381 Available methods are: I<CC> or I<ECHECK>
1383 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1385 Most gateways require a reference to an original payment transaction to refund,
1386 so you probably need to specify a I<paynum>.
1388 I<amount> defaults to the original amount of the payment if not specified.
1390 I<reasonnum> specified an existing refund reason for the refund
1392 I<paydate> specifies the expiration date for a credit card overriding the
1393 value from the customer record or the payment record. Specified as yyyy-mm-dd
1395 Implementation note: If I<amount> is unspecified or equal to the amount of the
1396 orignal payment, first an attempt is made to "void" the transaction via
1397 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1398 the normal attempt is made to "refund" ("credit") the transaction via the
1399 gateway is attempted. No attempt to "void" the transaction is made if the
1400 gateway has introspection data and doesn't support void.
1402 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1403 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1404 #if set, will override the value from the customer record.
1406 #If an I<invnum> is specified, this payment (if successful) is applied to the
1407 #specified invoice. If you don't specify an I<invnum> you might want to
1408 #call the B<apply_payments> method.
1412 #some false laziness w/realtime_bop, not enough to make it worth merging
1413 #but some useful small subs should be pulled out
1414 sub realtime_refund_bop {
1417 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1420 if (ref($_[0]) eq 'HASH') {
1421 %options = %{$_[0]};
1425 $options{method} = $method;
1429 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1430 warn " $_ => $options{$_}\n" foreach keys %options;
1433 return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1438 # look up the original payment and optionally a gateway for that payment
1442 my $amount = $options{'amount'};
1444 my( $processor, $login, $password, @bop_options, $namespace ) ;
1445 my( $auth, $order_number ) = ( '', '', '' );
1446 my $gatewaynum = '';
1448 if ( $options{'paynum'} ) {
1450 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1451 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1452 or return "Unknown paynum $options{'paynum'}";
1453 $amount ||= $cust_pay->paid;
1455 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1456 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1458 if ( $cust_pay->get('processor') ) {
1459 ($gatewaynum, $processor, $auth, $order_number) =
1461 $cust_pay->gatewaynum,
1462 $cust_pay->processor,
1464 $cust_pay->order_number,
1467 # this payment wasn't upgraded, which probably means this won't work,
1469 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1470 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1471 $cust_pay->paybatch;
1472 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1475 my $payment_gateway;
1476 if ( $gatewaynum ) { #gateway for the payment to be refunded
1479 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1480 die "payment gateway $gatewaynum not found"
1481 unless $payment_gateway;
1483 $processor = $payment_gateway->gateway_module;
1484 $login = $payment_gateway->gateway_username;
1485 $password = $payment_gateway->gateway_password;
1486 $namespace = $payment_gateway->gateway_namespace;
1487 @bop_options = $payment_gateway->options;
1489 } else { #try the default gateway
1493 $self->agent->payment_gateway('method' => $options{method});
1495 ( $conf_processor, $login, $password, $namespace ) =
1496 map { my $method = "gateway_$_"; $payment_gateway->$method }
1497 qw( module username password namespace );
1499 @bop_options = $payment_gateway->gatewaynum
1500 ? $payment_gateway->options
1501 : @{ $payment_gateway->get('options') };
1502 my %bop_options = @bop_options;
1504 return "processor of payment $options{'paynum'} $processor does not".
1505 " match default processor $conf_processor"
1506 unless ($processor eq $conf_processor)
1507 || (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}));
1509 $processor = $conf_processor;
1513 # if gateway has switched to CardFortress but token_check hasn't run yet,
1514 # tokenize just this record now, so that token gets passed/set appropriately
1515 if ($cust_pay->payby eq 'CARD' && !$cust_pay->tokenized) {
1517 'payment_gateway' => $payment_gateway,
1519 'payinfo' => $cust_pay->payinfo,
1520 'paydate' => $cust_pay->paydate,
1522 my $error = $self->realtime_tokenize(\%tokenopts); # no-op unless gateway can tokenize
1523 if ($self->tokenized($tokenopts{'payinfo'})) { # implies no error
1524 warn " tokenizing cust_pay\n" if $DEBUG > 1;
1525 $cust_pay->payinfo($tokenopts{'payinfo'});
1526 $error = $cust_pay->replace;
1528 return $error if $error;
1531 } else { # didn't specify a paynum, so look for agent gateway overrides
1532 # like a normal transaction
1534 my $payment_gateway =
1535 $self->agent->payment_gateway( 'method' => $options{method} );
1536 ( $processor, $login, $password, $namespace ) =
1537 map { my $method = "gateway_$_"; $payment_gateway->$method }
1538 qw( module username password namespace );
1540 my @bop_options = $payment_gateway->gatewaynum
1541 ? $payment_gateway->options
1542 : @{ $payment_gateway->get('options') };
1545 return "neither amount nor paynum specified" unless $amount;
1547 eval "use $namespace";
1552 'type' => $options{method},
1554 'password' => $password,
1555 'order_number' => $order_number,
1556 'amount' => $amount,
1558 $content{authorization} = $auth
1559 if length($auth); #echeck/ACH transactions have an order # but no auth
1560 #(at least with authorize.net)
1562 my $currency = $conf->exists('business-onlinepayment-currency')
1563 && $conf->config('business-onlinepayment-currency');
1564 $content{currency} = $currency if $currency;
1566 my $disable_void_after;
1567 if ($conf->exists('disable_void_after')
1568 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1569 $disable_void_after = $1;
1572 #first try void if applicable
1573 my $void = new Business::OnlinePayment( $processor, @bop_options );
1576 if ($void->can('info')) {
1578 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1579 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1580 my %supported_actions = $void->info('supported_actions');
1582 if ( %supported_actions && $paytype
1583 && defined($supported_actions{$paytype})
1584 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1587 if ( $cust_pay && $cust_pay->paid == $amount
1589 ( not defined($disable_void_after) )
1590 || ( time < ($cust_pay->_date + $disable_void_after ) )
1594 warn " attempting void\n" if $DEBUG > 1;
1595 if ( $void->can('info') ) {
1596 if ( $cust_pay->payby eq 'CARD'
1597 && $void->info('CC_void_requires_card') )
1599 $content{'card_number'} = $cust_pay->payinfo;
1600 } elsif ( $cust_pay->payby eq 'CHEK'
1601 && $void->info('ECHECK_void_requires_account') )
1603 ( $content{'account_number'}, $content{'routing_code'} ) =
1604 split('@', $cust_pay->payinfo);
1605 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1608 $void->content( 'action' => 'void', %content );
1609 $void->test_transaction(1)
1610 if $conf->exists('business-onlinepayment-test_transaction');
1612 if ( $void->is_success ) {
1613 # specified as a refund reason, but now we want a payment void reason
1614 # extract just the reason text, let cust_pay::void handle new_or_existing
1615 my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1617 $error = 'Reason could not be loaded' unless $reason;
1618 $error = $cust_pay->void($reason->reason) unless $error;
1620 # gah, even with transactions.
1621 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1622 "error voiding payment: $error";
1626 warn " void successful\n" if $DEBUG > 1;
1631 warn " void unsuccessful, trying refund\n"
1635 my $address = $self->address1;
1636 $address .= ", ". $self->address2 if $self->address2;
1638 my($payname, $payfirst, $paylast);
1639 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1640 $payname = $self->payname;
1641 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1642 or return "Illegal payname $payname";
1643 ($payfirst, $paylast) = ($1, $2);
1645 $payfirst = $self->getfield('first');
1646 $paylast = $self->getfield('last');
1647 $payname = "$payfirst $paylast";
1650 my @invoicing_list = $self->invoicing_list_emailonly;
1651 if ( $conf->exists('emailinvoiceautoalways')
1652 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1653 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1654 push @invoicing_list, $self->all_emails;
1657 my $email = ($conf->exists('business-onlinepayment-email-override'))
1658 ? $conf->config('business-onlinepayment-email-override')
1659 : $invoicing_list[0];
1661 my $payip = exists($options{'payip'})
1664 $content{customer_ip} = $payip
1668 my $paymask = ''; # for refund record
1669 if ( $options{method} eq 'CC' ) {
1672 $content{card_number} = $payinfo = $cust_pay->payinfo;
1673 $paymask = $cust_pay->paymask;
1674 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1675 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1676 ($content{expiration} = "$2/$1"); # where available
1678 # this really needs a better cleanup
1679 die "Refund without paynum not supported";
1680 # $content{card_number} = $payinfo = $self->payinfo;
1681 # (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1682 # =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1683 # $content{expiration} = "$2/$1";
1686 } elsif ( $options{method} eq 'ECHECK' ) {
1689 $payinfo = $cust_pay->payinfo;
1691 $payinfo = $self->payinfo;
1693 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1694 $content{bank_name} = $self->payname;
1695 $content{account_type} = 'CHECKING';
1696 $content{account_name} = $payname;
1697 $content{customer_org} = $self->company ? 'B' : 'I';
1698 $content{customer_ssn} = $self->ss;
1703 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1704 my %sub_content = $refund->content(
1705 'action' => 'credit',
1706 'customer_id' => $self->custnum,
1707 'last_name' => $paylast,
1708 'first_name' => $payfirst,
1710 'address' => $address,
1711 'city' => $self->city,
1712 'state' => $self->state,
1713 'zip' => $self->zip,
1714 'country' => $self->country,
1716 'phone' => $self->daytime || $self->night,
1719 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1721 $refund->test_transaction(1)
1722 if $conf->exists('business-onlinepayment-test_transaction');
1725 return "$processor error: ". $refund->error_message
1726 unless $refund->is_success();
1728 $order_number = $refund->order_number if $refund->can('order_number');
1730 # change this to just use $cust_pay->delete_cust_bill_pay?
1731 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1732 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1733 last unless @cust_bill_pay;
1734 my $cust_bill_pay = pop @cust_bill_pay;
1735 my $error = $cust_bill_pay->delete;
1739 my $cust_refund = new FS::cust_refund ( {
1740 'custnum' => $self->custnum,
1741 'paynum' => $options{'paynum'},
1742 'source_paynum' => $options{'paynum'},
1743 'refund' => $amount,
1745 'payby' => $bop_method2payby{$options{method}},
1746 'payinfo' => $payinfo,
1747 'paymask' => $paymask,
1748 'reasonnum' => $options{'reasonnum'},
1749 'gatewaynum' => $gatewaynum, # may be null
1750 'processor' => $processor,
1751 'auth' => $refund->authorization,
1752 'order_number' => $order_number,
1754 my $error = $cust_refund->insert;
1756 $cust_refund->paynum(''); #try again with no specific paynum
1757 $cust_refund->source_paynum('');
1758 my $error2 = $cust_refund->insert;
1760 # gah, even with transactions.
1761 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1762 "error inserting refund ($processor): $error2".
1763 " (previously tried insert with paynum #$options{'paynum'}" .
1774 =item realtime_verify_bop [ OPTION => VALUE ... ]
1776 Runs an authorization-only transaction for $1 against this credit card (if
1777 successful, immediatly reverses the authorization).
1779 Returns the empty string if the authorization was sucessful, or an error
1782 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1783 Object will be tokenized if possible, but that change will not be
1784 updated in database (must be inserted/replaced afterwards.)
1786 Currently only succeeds for Business::OnlinePayment CC transactions.
1790 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1791 #it worth merging but some useful small subs should be pulled out
1792 sub realtime_verify_bop {
1795 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1796 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1799 if (ref($_[0]) eq 'HASH') {
1800 %options = %{$_[0]};
1806 warn "$me realtime_verify_bop\n";
1807 warn " $_ => $options{$_}\n" foreach keys %options;
1810 # set fields from passed cust_payby
1811 return "No cust_payby" unless $options{'cust_payby'};
1812 _bop_cust_payby_options(\%options);
1814 # check for banned credit card/ACH
1815 my $ban = FS::banned_pay->ban_search(
1816 'payby' => $bop_method2payby{'CC'},
1817 'payinfo' => $options{payinfo},
1819 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1821 # possibly run a separate transaction to tokenize card number,
1822 # so that we never store tokenized card info in cust_pay_pending
1823 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1824 my $token_error = $self->realtime_tokenize(\%options);
1825 return $token_error if $token_error;
1826 #important that we not replace cust_payby here,
1827 #because cust_payby->replace uses realtime_verify_bop!
1834 my $payment_gateway = $self->_payment_gateway( \%options );
1835 my $namespace = $payment_gateway->gateway_namespace;
1837 eval "use $namespace";
1844 my $bop_content = $self->_bop_content(\%options);
1845 return $bop_content unless ref($bop_content);
1847 my @invoicing_list = $self->invoicing_list_emailonly;
1848 if ( $conf->exists('emailinvoiceautoalways')
1849 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1850 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1851 push @invoicing_list, $self->all_emails;
1854 my $email = ($conf->exists('business-onlinepayment-email-override'))
1855 ? $conf->config('business-onlinepayment-email-override')
1856 : $invoicing_list[0];
1861 if ( $namespace eq 'Business::OnlinePayment' ) {
1863 if ( $options{method} eq 'CC' ) {
1865 $content{card_number} = $options{payinfo};
1866 $paydate = $options{'paydate'};
1867 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1868 $content{expiration} = "$2/$1";
1870 $content{cvv2} = $options{'paycvv'}
1871 if length($options{'paycvv'});
1873 my $paystart_month = $options{'paystart_month'};
1874 my $paystart_year = $options{'paystart_year'};
1876 $content{card_start} = "$paystart_month/$paystart_year"
1877 if $paystart_month && $paystart_year;
1879 my $payissue = $options{'payissue'};
1880 $content{issue_number} = $payissue if $payissue;
1882 } elsif ( $options{method} eq 'ECHECK' ){
1883 #cannot verify, move along (though it shouldn't be called...)
1886 return "unknown method ". $options{method};
1888 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1889 #cannot verify, move along
1892 return "unknown namespace $namespace";
1896 # run transaction(s)
1900 my $transaction; #need this back so we can do _tokenize_card
1902 # don't mutex the customer here, because they might be uncommitted. and
1903 # this is only verification. it doesn't matter if they have other
1904 # unfinished verifications.
1906 my $cust_pay_pending = new FS::cust_pay_pending {
1907 'custnum_pending' => 1,
1910 'payby' => $bop_method2payby{'CC'},
1911 'payinfo' => $options{payinfo},
1912 'paymask' => $options{paymask},
1913 'paydate' => $paydate,
1914 'pkgnum' => $options{'pkgnum'},
1916 'gatewaynum' => $payment_gateway->gatewaynum || '',
1917 'session_id' => $options{session_id} || '',
1919 $cust_pay_pending->payunique( $options{payunique} )
1920 if defined($options{payunique}) && length($options{payunique});
1923 # open a separate handle for creating/updating the cust_pay_pending
1925 local $FS::UID::dbh = myconnect();
1926 local $FS::UID::AutoCommit = 1;
1928 # if this is an existing customer (and we can tell now because
1929 # this is a fresh transaction), it's safe to assign their custnum
1930 # to the cust_pay_pending record, and then the verification attempt
1931 # will remain linked to them even if it fails.
1932 if ( FS::cust_main->by_key($self->custnum) ) {
1933 $cust_pay_pending->set('custnum', $self->custnum);
1936 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1939 # if this fails, just return; everything else will still allow the
1940 # cust_pay_pending to have its custnum set later
1941 my $cpp_new_err = $cust_pay_pending->insert;
1942 return $cpp_new_err if $cpp_new_err;
1944 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1946 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1948 $transaction = new $namespace( $payment_gateway->gateway_module,
1949 _bop_options(\%options),
1952 $transaction->content(
1954 _bop_auth(\%options),
1955 'action' => 'Authorization Only',
1956 'description' => $options{'description'},
1958 'customer_id' => $self->custnum,
1960 'reference' => $cust_pay_pending->paypendingnum, #for now
1965 $cust_pay_pending->status('pending');
1966 my $cpp_pending_err = $cust_pay_pending->replace;
1967 return $cpp_pending_err if $cpp_pending_err;
1969 warn Dumper($transaction) if $DEBUG > 2;
1971 unless ( $BOP_TESTING ) {
1972 $transaction->test_transaction(1)
1973 if $conf->exists('business-onlinepayment-test_transaction');
1974 $transaction->submit();
1976 if ( $BOP_TESTING_SUCCESS ) {
1977 $transaction->is_success(1);
1978 $transaction->authorization('fake auth');
1980 $transaction->is_success(0);
1981 $transaction->error_message('fake failure');
1985 if ( $transaction->is_success() ) {
1987 $cust_pay_pending->status('authorized');
1988 my $cpp_authorized_err = $cust_pay_pending->replace;
1989 return $cpp_authorized_err if $cpp_authorized_err;
1991 my $auth = $transaction->authorization;
1992 my $ordernum = $transaction->can('order_number')
1993 ? $transaction->order_number
1996 my $reverse = new $namespace( $payment_gateway->gateway_module,
1997 _bop_options(\%options),
2000 $reverse->content( 'action' => 'Reverse Authorization',
2001 _bop_auth(\%options),
2005 'authorization' => $transaction->authorization,
2006 'order_number' => $ordernum,
2009 'result_code' => $transaction->result_code,
2010 'txn_date' => $transaction->txn_date,
2014 $reverse->test_transaction(1)
2015 if $conf->exists('business-onlinepayment-test_transaction');
2018 if ( $reverse->is_success ) {
2020 $cust_pay_pending->status('done');
2021 $cust_pay_pending->statustext('reversed');
2022 my $cpp_reversed_err = $cust_pay_pending->replace;
2023 return $cpp_reversed_err if $cpp_reversed_err;
2027 my $e = "Authorization successful but reversal failed, custnum #".
2028 $self->custnum. ': '. $reverse->result_code.
2029 ": ". $reverse->error_message;
2036 ### Address Verification ###
2038 # Single-letter codes vary by cardtype.
2040 # Erring on the side of accepting cards if avs is not available,
2041 # only rejecting if avs occurred and there's been an explicit mismatch
2043 # Charts below taken from vSecure documentation,
2044 # shows codes for Amex/Dscv/MC/Visa
2046 # ACCEPTABLE AVS RESPONSES:
2047 # Both Address and 5-digit postal code match Y A Y Y
2048 # Both address and 9-digit postal code match Y A X Y
2049 # United Kingdom – Address and postal code match _ _ _ F
2050 # International transaction – Address and postal code match _ _ _ D/M
2052 # ACCEPTABLE, BUT ISSUE A WARNING:
2053 # Ineligible transaction; or message contains a content error _ _ _ E
2054 # System unavailable; retry R U R R
2055 # Information unavailable U W U U
2056 # Issuer does not support AVS S U S S
2057 # AVS is not applicable _ _ _ S
2058 # Incompatible formats – Not verified _ _ _ C
2059 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2060 # International transaction – address not verified _ G _ G/I
2062 # UNACCEPTABLE AVS RESPONSES:
2063 # Only Address matches A Y A A
2064 # Only 5-digit postal code matches Z Z Z Z
2065 # Only 9-digit postal code matches Z Z W W
2066 # Neither address nor postal code matches N N N N
2068 if (my $avscode = uc($transaction->avs_code)) {
2070 # map codes to accept/warn/reject
2072 'American Express card' => {
2081 'Discover card' => {
2120 my $cardtype = cardtype($content{card_number});
2121 if ($avs->{$cardtype}) {
2122 my $avsact = $avs->{$cardtype}->{$avscode};
2124 if ($avsact eq 'r') {
2125 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2126 } elsif ($avsact eq 'w') {
2127 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2128 } elsif (!$avsact) {
2129 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2130 } # else $avsact eq 'a'
2132 $log->warning($warning);
2135 } # else $cardtype avs handling not implemented
2136 } # else !$transaction->avs_code
2138 } else { # is not success
2140 # status is 'done' not 'declined', as in _realtime_bop_result
2141 $cust_pay_pending->status('done');
2142 $error = $transaction->error_message || 'Unknown error';
2143 $cust_pay_pending->statustext($error);
2144 # could also record failure_status here,
2145 # but it's not supported by B::OP::vSecureProcessing...
2146 # need a B::OP module with (reverse) auth only to test it with
2147 my $cpp_declined_err = $cust_pay_pending->replace;
2148 return $cpp_declined_err if $cpp_declined_err;
2152 } # end of IMMEDIATE; we now have our $error and $transaction
2155 # Save the custnum (as part of the main transaction, so it can reference
2159 if (!$cust_pay_pending->custnum) {
2160 $cust_pay_pending->set('custnum', $self->custnum);
2161 my $set_custnum_err = $cust_pay_pending->replace;
2162 if ($set_custnum_err) {
2163 $log->error($set_custnum_err);
2164 $error ||= $set_custnum_err;
2165 # but if there was a real verification error also, return that one
2170 # remove paycvv here? need to find out if a reversed auth
2171 # counts as an initial transaction for paycvv retention requirements
2178 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2179 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2180 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2181 $cust_pay_pending->payinfo($card_token);
2182 my $cpp_token_err = $cust_pay_pending->replace;
2183 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2184 return $cpp_token_err if $cpp_token_err;
2185 #important that we not replace cust_payby here,
2186 #because cust_payby->replace uses realtime_verify_bop!
2193 # $error contains the transaction error_message, if is_success was false.
2199 =item realtime_tokenize [ OPTION => VALUE ... ]
2201 If possible and necessary, runs a tokenize transaction.
2202 In order to be possible, a credit card cust_payby record
2203 must be passed and a Business::OnlinePayment gateway capable
2204 of Tokenize transactions must be configured for this user.
2205 Is only necessary if payinfo is not yet tokenized.
2207 Returns the empty string if the authorization was sucessful
2208 or was not possible/necessary (thus allowing this to be safely called with
2209 non-tokenizable records/gateways, without having to perform separate tests),
2210 or an error message otherwise.
2212 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2213 Object will be tokenized if possible, but that change will not be
2214 updated in database (must be inserted/replaced afterwards.)
2216 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2217 may be passed. If options are passed as a hashref, I<payinfo>
2218 will be updated as appropriate in the passed hashref.
2220 Can be run as a class method if option I<payment_gateway> is passed,
2221 but default customer id/name/phone can't be set in that case. This
2222 is really only intended for tokenizing old records on upgrade.
2226 # careful--might be run as a class method
2227 sub realtime_tokenize {
2230 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2231 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2234 my $outoptions; #for returning cust_payby/payinfo
2235 if (ref($_[0]) eq 'HASH') {
2236 %options = %{$_[0]};
2237 $outoptions = $_[0];
2240 $outoptions = \%options;
2243 # set fields from passed cust_payby
2244 _bop_cust_payby_options(\%options);
2245 return '' unless $options{method} eq 'CC';
2246 return '' if $self->tokenized($options{payinfo}); #already tokenized
2248 # check for banned credit card/ACH
2249 my $ban = FS::banned_pay->ban_search(
2250 'payby' => $bop_method2payby{'CC'},
2251 'payinfo' => $options{payinfo},
2253 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2259 $options{'nofatal'} = 1;
2260 my $payment_gateway = $self->_payment_gateway( \%options );
2261 return '' unless $payment_gateway;
2262 my $namespace = $payment_gateway->gateway_namespace;
2263 return '' unless $namespace eq 'Business::OnlinePayment';
2265 eval "use $namespace";
2269 # check for tokenize ability
2272 my $transaction = new $namespace( $payment_gateway->gateway_module,
2273 _bop_options(\%options),
2276 return '' unless $transaction->can('info');
2278 my %supported_actions = $transaction->info('supported_actions');
2279 return '' unless $supported_actions{'CC'}
2280 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2286 ### Currently, cardfortress only keys in on card number and exp date.
2287 ### We pass everything we'd pass to a normal transaction,
2288 ### for ease of current and future development,
2289 ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2291 my $bop_content = $self->_bop_content(\%options);
2292 return $bop_content unless ref($bop_content);
2297 $content{card_number} = $options{payinfo};
2298 $paydate = $options{'paydate'};
2299 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2300 $content{expiration} = "$2/$1";
2302 $content{cvv2} = $options{'paycvv'}
2303 if length($options{'paycvv'});
2305 my $paystart_month = $options{'paystart_month'};
2306 my $paystart_year = $options{'paystart_year'};
2308 $content{card_start} = "$paystart_month/$paystart_year"
2309 if $paystart_month && $paystart_year;
2311 my $payissue = $options{'payissue'};
2312 $content{issue_number} = $payissue if $payissue;
2314 $content{customer_id} = $self->custnum
2323 # no cust_pay_pending---this is not a financial transaction
2325 $transaction->content(
2327 _bop_auth(\%options),
2328 'action' => 'Tokenize',
2329 'description' => $options{'description'},
2334 # no $BOP_TESTING handling for this
2335 $transaction->test_transaction(1)
2336 if $conf->exists('business-onlinepayment-test_transaction');
2337 $transaction->submit();
2339 if ( $transaction->card_token() ) { # no is_success flag
2341 # realtime_tokenize should not clear paycvv at this time. it might be
2342 # needed for the first transaction, and a tokenize isn't actually a
2343 # transaction that hits the gateway. at some point in the future, card
2344 # fortress should take on the "store paycvv until first transaction"
2345 # functionality and we should fix this in freeside, but i that's a bigger
2346 # project for another time.
2348 #important that we not replace cust_payby here,
2349 #because cust_payby->replace uses realtime_tokenize!
2350 $self->_tokenize_card($transaction,$outoptions);
2354 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2363 =item tokenized PAYINFO
2365 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2367 PAYINFO is required.
2369 Can be run as class or object method, never loads from object.
2375 my $payinfo = shift;
2376 FS::cust_pay->tokenized($payinfo);
2379 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2381 NOT A METHOD. Acts on all customers. Placed here because it makes
2382 use of module-internal methods, and to keep everything that uses
2383 Billing::OnlinePayment all in one place.
2385 Tokenizes all tokenizable card numbers from payinfo in cust_payby and
2386 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2388 If the I<queue> flag is set, newly tokenized records will be immediately
2389 committed, regardless of AutoCommit, so as to release the mutex on the record.
2391 If all configured gateways have the ability to tokenize, detection of an
2392 untokenizable record will cause a fatal error. However, if the I<queue> flag
2393 is set, this will instead cause a critical error to be recorded in the log,
2394 and any other tokenizable records will still be committed.
2396 If the I<daily> flag is also set, detection of existing untokenized records will
2397 record an info message in the system log (because they should have never appeared
2398 in the first place.) Tokenization will still be attempted.
2400 If any configured gateways do NOT have the ability to tokenize, or if a
2401 default gateway is not configured, then untokenized records are not considered
2402 a threat, and no critical errors will be generated in the log.
2407 #acts on all customers
2409 my $debug = !$opt{'quiet'} || $DEBUG;
2410 my $hascritical = 0;
2412 warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2414 # force some explicitness when invoking this method
2415 die "token_check must run with queue flag if run with daily flag"
2416 if $opt{'daily'} && !$opt{'queue'};
2418 my $conf = FS::Conf->new;
2420 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2422 my $cache = {}; #cache for module info
2424 # look for a gateway that can and can't tokenize
2425 my $require_tokenized = 1;
2426 my $someone_tokenizing = 0;
2427 foreach my $gateway (
2428 FS::payment_gateway->all_gateways(
2435 # no default gateway, no promise to tokenize
2436 # can just load other gateways as-needeed below
2437 $require_tokenized = 0;
2438 last if $someone_tokenizing;
2441 my $info = _token_check_gateway_info($cache,$gateway);
2442 die $info unless ref($info); # means it's an error message
2443 if ($info->{'can_tokenize'}) {
2444 $someone_tokenizing = 1;
2446 # a configured gateway can't tokenize, that's all we need to know right now
2447 # can just load other gateways as-needeed below
2448 $require_tokenized = 0;
2449 last if $someone_tokenizing;
2453 unless ($someone_tokenizing) { #no need to check, if no one can tokenize
2454 warn "no gateways tokenize\n" if $debug;
2458 warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2460 # upgrade does not call this with autocommit turned on,
2461 # and autocommit will be ignored if opt queue is set,
2462 # but might as well be thorough...
2463 my $oldAutoCommit = $FS::UID::AutoCommit;
2464 local $FS::UID::AutoCommit = 0;
2467 # for retrieving data in chunks
2471 ### Tokenize cust_payby
2476 while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2477 my $cust_main = FS::cust_main->by_key($custnum);
2478 my $payment_gateway;
2479 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2481 # see if it's already tokenized
2482 if ($cust_payby->tokenized) {
2483 warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2487 if ($require_tokenized && $opt{'daily'}) {
2488 $log->info("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum. '; tokenizing');
2489 $dbh->commit or die $dbh->errstr; # commit log message
2492 # only load gateway if we need to, and only need to load it once
2493 $payment_gateway ||= $cust_main->_payment_gateway({
2496 'nofatal' => 1, # handle lack of gateway smoothly below
2498 unless ($payment_gateway) {
2499 # no reason to have untokenized card numbers saved if no gateway,
2500 # but only a problem if we expected everyone to tokenize card numbers
2501 unless ($require_tokenized) {
2502 warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2503 next CUSTLOOP; # can skip rest of customer
2505 my $error = "No gateway found for custnum ".$cust_main->custnum;
2506 if ($opt{'queue'}) {
2508 $log->critical($error);
2509 $dbh->commit or die $dbh->errstr; # commit error message
2510 next; # not next CUSTLOOP, want to record error for every cust_payby
2512 $dbh->rollback if $oldAutoCommit;
2516 my $info = _token_check_gateway_info($cache,$payment_gateway);
2517 unless (ref($info)) {
2518 # only throws error if Business::OnlinePayment won't load,
2519 # which is just cause to abort this whole process, even if queue
2520 $dbh->rollback if $oldAutoCommit;
2521 die $info; # error message
2523 # no fail here--a configured gateway can't tokenize, so be it
2524 unless ($info->{'can_tokenize'}) {
2525 warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2530 $cust_payby = $cust_payby->select_for_update;
2532 'payment_gateway' => $payment_gateway,
2533 'cust_payby' => $cust_payby,
2535 my $error = $cust_main->realtime_tokenize(\%tokenopts);
2536 if ($cust_payby->tokenized) { # implies no error
2537 $error = $cust_payby->replace;
2539 $error ||= 'Unknown error';
2542 $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2543 if ($opt{'queue'}) {
2545 $log->critical($error);
2546 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2547 next; # not next CUSTLOOP, want to record error for every cust_payby
2549 $dbh->rollback if $oldAutoCommit;
2552 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2553 warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2555 warn "cust_payby upgraded for custnum ".$cust_main->custnum if $debug;
2559 ### Tokenize/mask transaction tables
2561 # allow tokenization of closed cust_pay/cust_refund records
2562 local $FS::payinfo_Mixin::allow_closed_replace = 1;
2565 # $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2566 foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2567 warn "Checking $table" if $debug;
2569 # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2570 # loading only record ids, then loading individual records one at a time
2571 my $tclass = 'FS::'.$table;
2575 while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2576 my $record = $tclass->by_key($recnum);
2577 unless ($record->payby eq 'CARD') {
2578 warn "Skipping non-card record for $table ".$record->get($record->primary_key) if $debug;
2581 if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2582 warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2585 if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2586 warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2589 if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2590 warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2594 if ($require_tokenized && $opt{'daily'}) {
2595 $log->info("Untokenized card number detected in $table ".$record->get($record->primary_key). ';tokenizing');
2596 $dbh->commit or die $dbh->errstr; # commit log message
2599 my $cust_main = $record->cust_main;
2601 # might happen for cust_pay_pending from failed verify records,
2602 # in which case we attempt tokenization without cust_main
2603 # everything else should absolutely have a cust_main
2604 if ($table eq 'cust_pay_pending' and !$record->custnum ) {
2605 # override the usual safety check and allow the record to be
2606 # updated even without a custnum.
2607 $record->set('custnum_pending', 1);
2609 my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2610 if ($opt{'queue'}) {
2612 $log->critical($error);
2613 $dbh->commit or die $dbh->errstr; # commit log message
2616 $dbh->rollback if $oldAutoCommit;
2623 # use the gatewaynum specified by the record if possible
2624 $gateway = FS::payment_gateway->by_key_with_namespace(
2625 'gatewaynum' => $record->gatewaynum,
2626 ) if $record->gateway;
2628 # otherwise use the cust agent gateway if possible (which realtime_refund_bop would do)
2629 # otherwise just use default gateway
2632 $gateway = $cust_main
2633 ? $cust_main->agent->payment_gateway
2634 : FS::payment_gateway->default_gateway;
2636 # check for processor mismatch
2637 unless ($table eq 'cust_pay_pending') { # has no processor table
2638 if (my $processor = $record->processor) {
2640 my $conf_processor = $gateway->gateway_module;
2641 my %bop_options = $gateway->gatewaynum
2643 : @{ $gateway->get('options') };
2645 # this is the same standard used by realtime_refund_bop
2647 ($processor eq $conf_processor) ||
2648 (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}))
2651 # processors don't match, so refund already cannot be run on this object,
2652 # regardless of what we do now...
2653 # but unless we gotta tokenize everything, just leave well enough alone
2654 unless ($require_tokenized) {
2655 warn "Skipping mismatched processor for $table ".$record->get($record->primary_key) if $debug;
2658 ### no error--we'll tokenize using the new gateway, just to remove stored payinfo,
2659 ### because refunds are already impossible for this record, anyway
2661 } # end processor mismatch
2663 } # end record has processor
2664 } # end not cust_pay_pending
2668 # means no default gateway, no promise to tokenize, can skip
2670 warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2674 my $info = _token_check_gateway_info($cache,$gateway);
2675 unless (ref($info)) {
2676 # only throws error if Business::OnlinePayment won't load,
2677 # which is just cause to abort this whole process, even if queue
2678 $dbh->rollback if $oldAutoCommit;
2679 die $info; # error message
2682 # a configured gateway can't tokenize, move along
2683 unless ($info->{'can_tokenize'}) {
2684 warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2688 warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug && !$cust_main;
2690 # if we got this far, time to mutex
2691 $record->select_for_update;
2693 # no clear record of name/address/etc used for transaction,
2694 # but will load name/phone/id from customer if run as an object method,
2695 # so we try that if we can
2697 'payment_gateway' => $gateway,
2699 'payinfo' => $record->payinfo,
2700 'paydate' => $record->paydate,
2702 my $error = $cust_main
2703 ? $cust_main->realtime_tokenize(\%tokenopts)
2704 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2705 if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2706 $record->payinfo($tokenopts{'payinfo'});
2707 $error = $record->replace;
2709 $error ||= 'Unknown error';
2712 $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2713 if ($opt{'queue'}) {
2715 $log->critical($error);
2716 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2719 $dbh->rollback if $oldAutoCommit;
2722 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2723 warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2728 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2730 return $hascritical ? 'Critical errors occurred on some records, see system log' : '';
2734 sub _token_check_next_recnum {
2735 my ($dbh,$table,$step,$offset,$recnums) = @_;
2736 my $recnum = shift @$recnums;
2737 return $recnum if $recnum;
2738 my $tclass = 'FS::'.$table;
2739 my $sth = $dbh->prepare(
2740 'SELECT '.$tclass->primary_key.
2742 " WHERE ( is_tokenized IS NULL OR is_tokenized = '' ) ".
2743 ' ORDER BY '.$tclass->primary_key.
2746 ) or die $dbh->errstr;
2747 $sth->execute() or die $sth->errstr;
2749 while (my $rec = $sth->fetchrow_hashref) {
2750 push @$recnums, $rec->{$tclass->primary_key};
2754 return shift @$recnums;
2758 sub _token_check_gateway_info {
2759 my ($cache,$payment_gateway) = @_;
2761 return $cache->{$payment_gateway->gateway_module}
2762 if $cache->{$payment_gateway->gateway_module};
2765 $cache->{$payment_gateway->gateway_module} = $info;
2767 my $namespace = $payment_gateway->gateway_namespace;
2768 return $info unless $namespace eq 'Business::OnlinePayment';
2769 $info->{'is_bop'} = 1;
2771 # only need to load this once,
2772 # don't want to load if nothing is_bop
2773 unless ($cache->{'Business::OnlinePayment'}) {
2774 eval "use $namespace";
2775 return "Error initializing Business:OnlinePayment: ".$@ if $@;
2776 $cache->{'Business::OnlinePayment'} = 1;
2779 my $transaction = new $namespace( $payment_gateway->gateway_module,
2780 _bop_options({ 'payment_gateway' => $payment_gateway }),
2783 return $info unless $transaction->can('info');
2784 $info->{'can_info'} = 1;
2786 my %supported_actions = $transaction->info('supported_actions');
2787 $info->{'can_tokenize'} = 1
2788 if $supported_actions{'CC'}
2789 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2791 # not using this any more, but for future reference...
2792 $info->{'void_requires_card'} = 1
2793 if $transaction->info('CC_void_requires_card');
2804 L<FS::cust_main>, L<FS::cust_main::Billing>