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;
19 use FS::Misc::Savepoint;
21 $realtime_bop_decline_quiet = 0;
23 # 1 is mostly method/subroutine entry and options
24 # 2 traces progress of some operations
25 # 3 is even more information including possibly sensitive data
27 $me = '[FS::cust_main::Billing_Realtime]';
30 our $BOP_TESTING_SUCCESS = 1;
31 our $BOP_TESTING_TIMESTAMP = '';
33 install_callback FS::UID sub {
35 #yes, need it for stuff below (prolly should be cached)
40 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
46 These methods are available on FS::cust_main objects.
52 =item realtime_cust_payby
56 sub realtime_cust_payby {
57 my( $self, %options ) = @_;
59 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
61 $options{amount} = $self->balance unless exists( $options{amount} );
63 my @cust_payby = $self->cust_payby('CARD','CHEK');
66 foreach my $cust_payby (@cust_payby) {
67 $error = $cust_payby->realtime_bop( %options, );
71 #XXX what about the earlier errors?
77 =item realtime_collect [ OPTION => VALUE ... ]
79 Attempt to collect the customer's current balance with a realtime credit
80 card or electronic check transaction (see realtime_bop() below).
82 Returns the result of realtime_bop(): nothing, an error message, or a
83 hashref of state information for a third-party transaction.
85 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
87 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
88 then it is deduced from the customer record.
90 If no I<amount> is specified, then the customer balance is used.
92 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
93 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
94 if set, will override the value from the customer record.
96 I<description> is a free-text field passed to the gateway. It defaults to
97 the value defined by the business-onlinepayment-description configuration
98 option, or "Internet services" if that is unset.
100 If an I<invnum> is specified, this payment (if successful) is applied to the
103 I<apply> will automatically apply a resulting payment.
105 I<quiet> can be set true to suppress email decline notices.
107 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
108 resulting paynum, if any.
110 I<payunique> is a unique identifier for this payment.
112 I<session_id> is a session identifier associated with this payment.
114 I<depend_jobnum> allows payment capture to unlock export jobs
118 # Currently only used by ClientAPI
119 sub realtime_collect {
120 my( $self, %options ) = @_;
122 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
125 warn "$me realtime_collect:\n";
126 warn " $_ => $options{$_}\n" foreach keys %options;
129 $options{amount} = $self->balance unless exists( $options{amount} );
130 return '' unless $options{amount} > 0;
132 #huh, in v4, realtime_bop no longer will just process a card without passing
133 # payinfo or cust_payby...
134 if ( ! $options{'payinfo'} && ! $options{'cust_payby'} && $self->has_cust_payby_auto ) {
135 my @cust_payby = $self->cust_payby;
136 $options{'cust_payby'} = $cust_payby[0];
139 return $self->realtime_bop({%options});
143 =item realtime_bop { [ ARG => VALUE ... ] }
145 Runs a realtime credit card or ACH (electronic check) transaction
146 via a Business::OnlinePayment realtime gateway. See
147 L<http://420.am/business-onlinepayment> for supported gateways.
149 Required arguments in the hashref are I<amount> and either
150 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
151 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
153 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
155 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
157 I<description> is a free-text field passed to the gateway. It defaults to
158 the value defined by the business-onlinepayment-description configuration
159 option, or "Internet services" if that is unset.
161 If an I<invnum> is specified, this payment (if successful) is applied to the
162 specified invoice. If the customer has exactly one open invoice, that
163 invoice number will be assumed. If you don't specify an I<invnum> you might
164 want to call the B<apply_payments> method or set the I<apply> option.
166 I<no_invnum> can be set to true to prevent that default invnum from being set.
168 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
170 I<no_auto_apply> can be set to true to set that flag on the resulting payment
171 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
172 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
174 I<quiet> can be set true to surpress email decline notices.
176 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
177 resulting paynum, if any.
179 I<payunique> is a unique identifier for this payment.
181 I<session_id> is a session identifier associated with this payment.
183 I<depend_jobnum> allows payment capture to unlock export jobs
185 I<discount_term> attempts to take a discount by prepaying for discount_term.
186 The payment will fail if I<amount> is incorrect for this discount term.
188 A direct (Business::OnlinePayment) transaction will return nothing on success,
189 or an error message on failure.
191 A third-party transaction will return a hashref containing:
193 - popup_url: the URL to which a browser should be redirected to complete
195 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
196 - reference: a reference ID for the transaction, to show the customer.
198 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
202 # some helper routines
204 # _bop_recurring_billing: Checks whether this payment should have the
205 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
206 # vSecure, etc.). This works in two different modes:
207 # - actual_oncard (default): treat the payment as recurring if the customer
208 # has made a payment using this card before.
209 # - transaction_is_recur: treat the payment as recurring if the invoice
210 # being paid has any recurring package charges.
212 sub _bop_recurring_billing {
213 my( $self, %opt ) = @_;
215 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
217 if ( defined($method) && $method eq 'transaction_is_recur' ) {
219 return 1 if $opt{'trans_is_recur'};
223 # return 1 if the payinfo has been used for another payment
224 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
232 #can run safely as class method if opt payment_gateway already exists
233 sub _payment_gateway {
234 my ($self, $options) = @_;
236 if ( $options->{'fake_gatewaynum'} ) {
237 $options->{payment_gateway} =
238 qsearchs('payment_gateway',
239 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
243 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
244 unless exists($options->{payment_gateway});
246 $options->{payment_gateway};
254 'login' => $options->{payment_gateway}->gateway_username,
255 'password' => $options->{payment_gateway}->gateway_password,
263 $options->{payment_gateway}->gatewaynum
264 ? $options->{payment_gateway}->options
265 : @{ $options->{payment_gateway}->get('options') };
270 my ($self, $options) = @_;
272 unless ( $options->{'description'} ) {
273 if ( $conf->exists('business-onlinepayment-description') ) {
274 my $dtempl = $conf->config('business-onlinepayment-description');
276 my $agent = $self->agent->agent;
278 $options->{'description'} = eval qq("$dtempl");
280 $options->{'description'} = 'Internet services';
284 # Default invoice number if the customer has exactly one open invoice.
285 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
286 $options->{'invnum'} = '';
287 my @open = $self->open_cust_bill;
288 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
294 sub _bop_cust_payby_options {
296 my $cust_payby = $options->{'cust_payby'};
299 $options->{'method'} = FS::payby->payby2bop( $cust_payby->payby );
301 if ($cust_payby->payby =~ /^(CARD|DCRD)$/) {
302 # false laziness with cust_payby->check
303 # which might not have been run yet
305 if ( $cust_payby->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
306 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
307 } elsif ( $cust_payby->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
308 ( $m, $y ) = ( $2, "19$1" );
309 } elsif ( $cust_payby->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
310 ( $m, $y ) = ( $3, "20$2" );
312 return "Illegal expiration date: ". $cust_payby->paydate;
314 $m = sprintf('%02d',$m);
315 $options->{paydate} = "$y-$m-01";
317 $options->{paydate} = '';
320 $options->{$_} = $cust_payby->$_()
321 for qw( payinfo paycvv paymask paystart_month paystart_year
322 payissue payname paystate paytype payip );
324 if ( $cust_payby->locationnum ) {
325 my $cust_location = $cust_payby->cust_location;
326 $options->{$_} = $cust_location->$_()
327 for qw( address1 address2 city state zip country );
332 # can be called as class method,
333 # but can't load default name/phone fields as class method
334 # (why was this added? ah, it might get called from realtime_tokenize in this
335 # fashion "to tokenize old records on upgrade")
337 my ($self, $options) = @_;
340 my $payip = $options->{'payip'};
341 $content{customer_ip} = $payip if length($payip);
343 $content{invoice_number} = $options->{'invnum'}
344 if exists($options->{'invnum'}) && length($options->{'invnum'});
346 $content{email_customer} =
347 ( $conf->exists('business-onlinepayment-email_customer')
348 || $conf->exists('business-onlinepayment-email-override') );
350 my ($payname, $payfirst, $paylast);
351 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
352 ($payname = $options->{payname}) =~
353 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
354 or return "Illegal payname $payname";
355 ($payfirst, $paylast) = ($1, $2);
356 } elsif (ref($self)) { # can't set payname if called as class method
357 $payfirst = $self->getfield('first');
358 $paylast = $self->getfield('last');
359 $payname = "$payfirst $paylast";
362 $content{last_name} = $paylast if $paylast;
363 $content{first_name} = $payfirst if $payfirst;
365 $content{name} = $payname if $payname;
367 if ( exists($options->{'address1'}) && length($options->{'address1'}) ) {
369 $content{address} = $options->{'address1'};
370 my $address2 = $options->{'address2'};
371 $content{address} .= ", ". $address2 if length($address2);
373 $content{$_} = $options->{$_} foreach qw( city state zip country );
375 } elsif ( ref($self) ) {
377 $content{address} = $self->address1;
378 my $address2 = $self->address2;
379 $content{address} .= ", ". $address2 if length($address2);
381 $content{$_} = $self->$_() foreach qw( city state zip country );
385 # can't set phone if called as class method
386 $content{phone} = $self->daytime || $self->night
389 my $currency = $conf->exists('business-onlinepayment-currency')
390 && $conf->config('business-onlinepayment-currency');
391 $content{currency} = $currency if $currency;
396 # updates payinfo and cust_payby options with token from transaction
397 # can be called as a class method
399 my ($self,$transaction,$options) = @_;
400 if ( $transaction->can('card_token')
401 and $transaction->card_token
402 and !$self->tokenized($options->{'payinfo'})
404 $options->{'payinfo'} = $transaction->card_token;
405 $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
406 return $transaction->card_token;
411 my %bop_method2payby = (
420 confess "Can't call realtime_bop within another transaction ".
421 '($FS::UID::AutoCommit is false)'
422 unless $FS::UID::AutoCommit || $BOP_TESTING;
424 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
426 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
429 if (ref($_[0]) eq 'HASH') {
432 my ( $method, $amount ) = ( shift, shift );
434 $options{method} = $method;
435 $options{amount} = $amount;
438 return '' unless $options{amount} > 0;
440 # set fields from passed cust_payby
441 _bop_cust_payby_options(\%options);
443 # check for banned credit card/ACH
444 my $ban = FS::banned_pay->ban_search(
445 'payby' => $bop_method2payby{$options{method}},
446 'payinfo' => $options{payinfo},
448 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
450 # possibly run a separate transaction to tokenize card number,
451 # so that we never store tokenized card info in cust_pay_pending
452 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
453 my $token_error = $self->realtime_tokenize(\%options);
454 return $token_error if $token_error;
455 # in theory, all cust_payby will be tokenized during original save,
456 # so we shouldn't get here with opt cust_payby...but just in case...
457 if ($options{'cust_payby'} && $self->tokenized($options{'payinfo'})) {
458 $token_error = $options{'cust_payby'}->replace;
459 return $token_error if $token_error;
464 # optional credit card surcharge
467 my $cc_surcharge = 0;
468 my $cc_surcharge_pct = 0;
469 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum)
470 if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
471 && $options{method} eq 'CC';
473 my $cc_surcharge_flat = 0;
474 $cc_surcharge_flat = $conf->config('credit-card-surcharge-flatfee', $self->agentnum)
475 if $conf->config('credit-card-surcharge-flatfee', $self->agentnum)
476 && $options{method} eq 'CC';
478 # always add cc surcharge if called from event
479 if($options{'cc_surcharge_from_event'} && ($cc_surcharge_pct > 0 || $cc_surcharge_flat > 0)) {
480 if ($options{'amount'} > 0) {
481 $cc_surcharge = ($options{'amount'} * ($cc_surcharge_pct / 100)) + $cc_surcharge_flat;
482 $options{'amount'} += $cc_surcharge;
483 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
486 elsif($cc_surcharge_pct > 0 || $cc_surcharge_flat > 0) {
487 # we're called not from event (i.e. from a
488 # payment screen), so consider the given
489 # amount as post-surcharge-processing_fee
490 $cc_surcharge = $options{'amount'} - $options{'processing-fee'} - (($options{'amount'} - ($cc_surcharge_flat + $options{'processing-fee'})) / ( 1 + $cc_surcharge_pct/100 )) if $options{'amount'} > 0;
493 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
494 $options{'cc_surcharge'} = $cc_surcharge;
498 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
499 warn " cc_surcharge = $cc_surcharge\n";
502 warn " $_ => $options{$_}\n" foreach keys %options;
505 return $self->fake_bop(\%options) if $options{'fake'};
507 $self->_bop_defaults(\%options);
509 return "Missing payinfo"
510 unless $options{'payinfo'};
513 # set trans_is_recur based on invnum if there is one
516 my $trans_is_recur = 0;
517 if ( $options{'invnum'} ) {
519 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
520 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
526 $cust_bill->cust_bill_pkg;
529 if grep { $_->freq ne '0' } @part_pkg;
537 my $payment_gateway = $self->_payment_gateway( \%options );
538 my $namespace = $payment_gateway->gateway_namespace;
540 eval "use $namespace";
544 # check for term discount validity
547 my $discount_term = $options{discount_term};
548 if ( $discount_term ) {
549 my $bill = ($self->cust_bill)[-1]
550 or return "Can't apply a term discount to an unbilled customer";
551 my $plan = FS::discount_plan->new(
553 months => $discount_term
554 ) or return "No discount available for term '$discount_term'";
556 if ( $plan->discounted_total != $options{amount} ) {
557 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
565 my $bop_content = $self->_bop_content(\%options);
566 return $bop_content unless ref($bop_content);
568 my @invoicing_list = $self->invoicing_list_emailonly;
569 if ( $conf->exists('emailinvoiceautoalways')
570 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
571 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
572 push @invoicing_list, $self->all_emails;
575 my $email = ($conf->exists('business-onlinepayment-email-override'))
576 ? $conf->config('business-onlinepayment-email-override')
577 : $invoicing_list[0];
582 if ( $namespace eq 'Business::OnlinePayment' ) {
584 if ( $options{method} eq 'CC' ) {
586 $content{card_number} = $options{payinfo};
587 $paydate = $options{'paydate'};
588 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
589 $content{expiration} = "$2/$1";
591 $content{cvv2} = $options{'paycvv'}
592 if length($options{'paycvv'});
594 my $paystart_month = $options{'paystart_month'};
595 my $paystart_year = $options{'paystart_year'};
596 $content{card_start} = "$paystart_month/$paystart_year"
597 if $paystart_month && $paystart_year;
599 my $payissue = $options{'payissue'};
600 $content{issue_number} = $payissue if $payissue;
602 if ( $self->_bop_recurring_billing(
603 'payinfo' => $options{'payinfo'},
604 'trans_is_recur' => $trans_is_recur,
608 $content{recurring_billing} = 'YES';
609 $content{acct_code} = 'rebill'
610 if $conf->exists('credit_card-recurring_billing_acct_code');
613 } elsif ( $options{method} eq 'ECHECK' ){
615 ( $content{account_number}, $content{routing_code} ) =
616 split('@', $options{payinfo});
617 $content{bank_name} = $options{payname};
618 $content{bank_state} = $options{'paystate'};
619 $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
621 $content{company} = $self->company if $self->company;
623 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
624 $content{account_name} = $self->company;
626 $content{account_name} = $self->getfield('first'). ' '.
627 $self->getfield('last');
630 $content{customer_org} = $self->company ? 'B' : 'I';
631 $content{state_id} = exists($options{'stateid'})
632 ? $options{'stateid'}
633 : $self->getfield('stateid');
634 $content{state_id_state} = exists($options{'stateid_state'})
635 ? $options{'stateid_state'}
636 : $self->getfield('stateid_state');
637 $content{customer_ssn} = exists($options{'ss'})
642 die "unknown method ". $options{method};
645 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
648 die "unknown namespace $namespace";
655 my $balance = exists( $options{'balance'} )
656 ? $options{'balance'}
659 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
660 $self->select_for_update; #mutex ... just until we get our pending record in
661 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
663 #the checks here are intended to catch concurrent payments
664 #double-form-submission prevention is taken care of in cust_pay_pending::check
667 return "The customer's balance has changed; $options{method} transaction aborted."
668 if $self->balance < $balance;
670 #also check and make sure there aren't *other* pending payments for this cust
672 my @pending = qsearch('cust_pay_pending', {
673 'custnum' => $self->custnum,
674 'status' => { op=>'!=', value=>'done' }
677 #for third-party payments only, remove pending payments if they're in the
678 #'thirdparty' (waiting for customer action) state.
679 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
680 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
681 my $error = $_->delete;
682 warn "error deleting unfinished third-party payment ".
683 $_->paypendingnum . ": $error\n"
686 @pending = grep { $_->status ne 'thirdparty' } @pending;
689 return "A payment is already being processed for this customer (".
690 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
691 "); $options{method} transaction aborted."
694 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
696 my $cust_pay_pending = new FS::cust_pay_pending {
697 'custnum' => $self->custnum,
698 'paid' => $options{amount},
699 '_date' => $BOP_TESTING ? $BOP_TESTING_TIMESTAMP : '',
700 'payby' => $bop_method2payby{$options{method}},
701 'payinfo' => $options{payinfo},
702 'paymask' => $options{paymask},
703 'paydate' => $paydate,
704 'recurring_billing' => $content{recurring_billing},
705 'pkgnum' => $options{'pkgnum'},
707 'gatewaynum' => $payment_gateway->gatewaynum || '',
708 'session_id' => $options{session_id} || '',
709 'jobnum' => $options{depend_jobnum} || '',
711 $cust_pay_pending->payunique( $options{payunique} )
712 if defined($options{payunique}) && length($options{payunique});
714 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
716 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
717 return $cpp_new_err if $cpp_new_err;
719 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
721 warn Dumper($cust_pay_pending) if $DEBUG > 2;
723 my( $action1, $action2 ) =
724 split( /\s*\,\s*/, $payment_gateway->gateway_action );
726 my $transaction = new $namespace( $payment_gateway->gateway_module,
727 _bop_options(\%options),
730 $transaction->content(
731 'type' => $options{method},
732 _bop_auth(\%options),
733 'action' => $action1,
734 'description' => $options{'description'},
735 'amount' => $options{amount},
736 #'invoice_number' => $options{'invnum'},
737 'customer_id' => $self->custnum,
739 'reference' => $cust_pay_pending->paypendingnum, #for now
740 'callback_url' => $payment_gateway->gateway_callback_url,
741 'cancel_url' => $payment_gateway->gateway_cancel_url,
746 $cust_pay_pending->status('pending');
747 my $cpp_pending_err = $cust_pay_pending->replace;
748 return $cpp_pending_err if $cpp_pending_err;
750 warn Dumper($transaction) if $DEBUG > 2;
752 unless ( $BOP_TESTING ) {
753 $transaction->test_transaction(1)
754 if $conf->exists('business-onlinepayment-test_transaction');
755 $transaction->submit();
757 if ( $BOP_TESTING_SUCCESS ) {
758 $transaction->is_success(1);
759 $transaction->authorization('fake auth');
761 $transaction->is_success(0);
762 $transaction->error_message('fake failure');
766 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
768 $cust_pay_pending->status('thirdparty');
769 my $cpp_err = $cust_pay_pending->replace;
770 return { error => $cpp_err } if $cpp_err;
771 return { reference => $cust_pay_pending->paypendingnum,
772 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
774 } elsif ( !$BOP_TESTING && $transaction->is_success() && $action2 ) {
776 $cust_pay_pending->status('authorized');
777 my $cpp_authorized_err = $cust_pay_pending->replace;
778 return $cpp_authorized_err if $cpp_authorized_err;
780 my $auth = $transaction->authorization;
781 my $ordernum = $transaction->can('order_number')
782 ? $transaction->order_number
786 new Business::OnlinePayment( $payment_gateway->gateway_module,
787 _bop_options(\%options),
792 type => $options{method},
794 _bop_auth(\%options),
795 order_number => $ordernum,
796 amount => $options{amount},
797 authorization => $auth,
798 description => $options{'description'},
801 foreach my $field (qw( authorization_source_code returned_ACI
802 transaction_identifier validation_code
803 transaction_sequence_num local_transaction_date
804 local_transaction_time AVS_result_code )) {
805 $capture{$field} = $transaction->$field() if $transaction->can($field);
808 $capture->content( %capture );
810 $capture->test_transaction(1)
811 if $conf->exists('business-onlinepayment-test_transaction');
814 unless ( $capture->is_success ) {
815 my $e = "Authorization successful but capture failed, custnum #".
816 $self->custnum. ': '. $capture->result_code.
817 ": ". $capture->error_message;
825 # remove paycvv after initial transaction
828 # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
829 if ( length($options{'paycvv'})
830 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
832 my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
834 $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
835 #not returning error, should at least attempt to handle results of an otherwise valid transaction
836 warn "WARNING: error removing cvv: $error\n";
844 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
845 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
846 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
847 # cpp will be replaced in _realtime_bop_result
848 $cust_pay_pending->payinfo($card_token);
849 if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
850 $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
851 #not returning error, should at least attempt to handle results of an otherwise valid transaction
852 #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
860 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
872 if (ref($_[0]) eq 'HASH') {
875 my ( $method, $amount ) = ( shift, shift );
877 $options{method} = $method;
878 $options{amount} = $amount;
881 if ( $options{'fake_failure'} ) {
882 return "Error: No error; test failure requested with fake_failure";
885 my $cust_pay = new FS::cust_pay ( {
886 'custnum' => $self->custnum,
887 'invnum' => $options{'invnum'},
888 'paid' => $options{amount},
890 'payby' => $bop_method2payby{$options{method}},
891 'payinfo' => '4111111111111111',
892 'paydate' => '2012-05-01',
893 'processor' => 'FakeProcessor',
895 'order_number' => '32',
897 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
900 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
901 warn " $_ => $options{$_}\n" foreach keys %options;
904 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
907 $cust_pay->invnum(''); #try again with no specific invnum
908 my $error2 = $cust_pay->insert( $options{'manual'} ?
909 ( 'manual' => 1 ) : ()
912 # gah, even with transactions.
913 my $e = 'WARNING: Card/ACH debited but database not updated - '.
914 "error inserting (fake!) payment: $error2".
915 " (previously tried insert with invnum #$options{'invnum'}" .
922 if ( $options{'paynum_ref'} ) {
923 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
931 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
933 # Wraps up processing of a realtime credit card or ACH (electronic check)
936 sub _realtime_bop_result {
937 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
939 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
942 warn "$me _realtime_bop_result: pending transaction ".
943 $cust_pay_pending->paypendingnum. "\n";
944 warn " $_ => $options{$_}\n" foreach keys %options;
947 my $payment_gateway = $options{payment_gateway}
948 or return "no payment gateway in arguments to _realtime_bop_result";
950 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
951 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
952 return $cpp_captured_err if $cpp_captured_err;
954 if ( $transaction->is_success() ) {
956 my $order_number = $transaction->order_number
957 if $transaction->can('order_number');
959 my $cust_pay = new FS::cust_pay ( {
960 'custnum' => $self->custnum,
961 'invnum' => $options{'invnum'},
962 'paid' => $cust_pay_pending->paid,
963 '_date' => $BOP_TESTING ? $BOP_TESTING_TIMESTAMP : '',
964 'payby' => $cust_pay_pending->payby,
965 'payinfo' => $options{'payinfo'},
966 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
967 'paydate' => $cust_pay_pending->paydate,
968 'pkgnum' => $cust_pay_pending->pkgnum,
969 'discount_term' => $options{'discount_term'},
970 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
971 'processor' => $payment_gateway->gateway_module,
972 'auth' => $transaction->authorization,
973 'order_number' => $order_number || '',
974 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
976 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
977 $cust_pay->payunique( $options{payunique} )
978 if defined($options{payunique}) && length($options{payunique});
980 my $oldAutoCommit = $FS::UID::AutoCommit;
981 local $FS::UID::AutoCommit = 0;
984 my $savepoint_label = '_realtime_bop_result';
985 savepoint_create( $savepoint_label );
987 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
989 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
992 savepoint_rollback( $savepoint_label );
994 $cust_pay->invnum(''); #try again with no specific invnum
995 $cust_pay->paynum('');
996 my $error2 = $cust_pay->insert( $options{'manual'} ?
997 ( 'manual' => 1 ) : ()
1000 # gah. but at least we have a record of the state we had to abort in
1001 # from cust_pay_pending now.
1002 savepoint_rollback_and_release( $savepoint_label );
1004 my $e = "WARNING: $options{method} captured but payment not recorded -".
1005 " error inserting payment (". $payment_gateway->gateway_module.
1007 " (previously tried insert with invnum #$options{'invnum'}" .
1008 ": $error ) - pending payment saved as paypendingnum ".
1009 $cust_pay_pending->paypendingnum. "\n";
1015 my $jobnum = $cust_pay_pending->jobnum;
1017 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1019 unless ( $placeholder ) {
1020 savepoint_rollback_and_release( $savepoint_label );
1022 my $e = "WARNING: $options{method} captured but job $jobnum not ".
1023 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
1028 $error = $placeholder->delete;
1031 savepoint_rollback_and_release( $savepoint_label );
1033 my $e = "WARNING: $options{method} captured but could not delete ".
1034 "job $jobnum for paypendingnum ".
1035 $cust_pay_pending->paypendingnum. ": $error\n";
1040 $cust_pay_pending->set('jobnum','');
1044 if ( $options{'paynum_ref'} ) {
1045 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1048 $cust_pay_pending->status('done');
1049 $cust_pay_pending->statustext('captured');
1050 $cust_pay_pending->paynum($cust_pay->paynum);
1051 my $cpp_done_err = $cust_pay_pending->replace;
1053 if ( $cpp_done_err ) {
1054 savepoint_rollback_and_release( $savepoint_label );
1056 my $e = "WARNING: $options{method} captured but payment not recorded - ".
1057 "error updating status for paypendingnum ".
1058 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1063 savepoint_release( $savepoint_label );
1064 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1066 if ( $options{'apply'} ) {
1067 my $apply_error = $self->apply_payments_and_credits;
1068 if ( $apply_error ) {
1069 warn "WARNING: error applying payment: $apply_error\n";
1070 #but we still should return no error cause the payment otherwise went
1075 # have a CC surcharge portion --> one-time charge
1076 if ( $options{'cc_surcharge'} > 0 || $options{'processing-fee'} > 0) {
1077 # XXX: this whole block needs to be in a transaction?
1080 $invnum = $options{'invnum'} if $options{'invnum'};
1081 unless ( $invnum ) { # probably from a payment screen
1082 # do we have any open invoices? pick earliest
1083 # uses the fact that cust_main->cust_bill sorts by date ascending
1084 my @open = $self->open_cust_bill;
1085 $invnum = $open[0]->invnum if scalar(@open);
1088 unless ( $invnum ) { # still nothing? pick last closed invoice
1089 # again uses fact that cust_main->cust_bill sorts by date ascending
1090 my @closed = $self->cust_bill;
1091 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1094 unless ( $invnum ) {
1095 # XXX: unlikely case - pre-paying before any invoices generated
1096 # what it should do is create a new invoice and pick it
1097 warn 'CC SURCHARGE OR PROCESS FEE AND NO INVOICES PICKED TO APPLY IT!';
1101 if ($options{'cc_surcharge'} > 0) {
1103 my $cc_surcharge_text = 'Credit Card Surcharge';
1104 $cc_surcharge_text = $conf->config('credit-card-surcharge-text', $self->agentnum) if $conf->exists('credit-card-surcharge-text', $self->agentnum);
1105 my $charge_error = $self->charge({
1106 'amount' => $options{'cc_surcharge'},
1107 'pkg' => $cc_surcharge_text,
1109 'cust_pkg_ref' => \$cust_pkg,
1113 warn 'Unable to add CC surcharge cust_pkg';
1117 $cust_pkg->setup(time);
1118 my $cp_error = $cust_pkg->replace;
1120 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1124 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1125 unless ( $cust_bill ) {
1126 warn "race condition + invoice deletion just happened";
1131 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1133 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1135 } # end if $options{'cc_surcharge'}
1137 if ($options{'processing-fee'} > 0) {
1139 my $processing_fee_text = 'Payment Processing Fee';
1140 my $pf_change_error = $self->charge({
1141 'amount' => $options{'processing-fee'},
1142 'pkg' => $processing_fee_text,
1144 'cust_pkg_ref' => \$pf_cust_pkg,
1147 if($pf_change_error) {
1148 warn 'Unable to add payment processing fee';
1152 $pf_cust_pkg->setup(time);
1153 my $pf_error = $pf_cust_pkg->replace;
1155 warn 'Unable to set setup time on cust_pkg for processing fee';
1159 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1160 unless ( $cust_bill ) {
1161 warn "race condition + invoice deletion just happened";
1165 my $grand_pf_error =
1166 $cust_bill->add_cc_surcharge($pf_cust_pkg->pkgnum,$options{'processing-fee'});
1168 warn "cannot add Processing fee to invoice #$invnum: $grand_pf_error"
1170 } #end if $options{'processing-fee'}
1172 } #end if ( $options{'cc_surcharge'} > 0 || $options{'processing-fee'} > 0)
1174 return ''; #no error
1180 my $perror = $transaction->error_message;
1181 #$payment_gateway->gateway_module. " error: ".
1182 # removed for conciseness
1184 my $jobnum = $cust_pay_pending->jobnum;
1186 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1188 if ( $placeholder ) {
1189 my $error = $placeholder->depended_delete;
1190 $error ||= $placeholder->delete;
1191 $cust_pay_pending->set('jobnum','');
1192 warn "error removing provisioning jobs after declined paypendingnum ".
1193 $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1195 my $e = "error finding job $jobnum for declined paypendingnum ".
1196 $cust_pay_pending->paypendingnum. "\n";
1202 unless ( $transaction->error_message ) {
1205 if ( $transaction->can('response_page') ) {
1207 'page' => ( $transaction->can('response_page')
1208 ? $transaction->response_page
1211 'code' => ( $transaction->can('response_code')
1212 ? $transaction->response_code
1215 'headers' => ( $transaction->can('response_headers')
1216 ? $transaction->response_headers
1222 "No additional debugging information available for ".
1223 $payment_gateway->gateway_module;
1226 $perror .= "No error_message returned from ".
1227 $payment_gateway->gateway_module. " -- ".
1228 ( ref($t_response) ? Dumper($t_response) : $t_response );
1232 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1233 && $conf->exists('emaildecline', $self->agentnum)
1234 && grep { $_ ne 'POST' } $self->invoicing_list
1235 && ! grep { $transaction->error_message =~ /$_/ }
1236 $conf->config('emaildecline-exclude', $self->agentnum)
1239 # Send a decline alert to the customer.
1240 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1243 # include the raw error message in the transaction state
1244 $cust_pay_pending->setfield('error', $transaction->error_message);
1245 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1246 $error = $msg_template->send( 'cust_main' => $self,
1247 'object' => $cust_pay_pending );
1251 $perror .= " (also received error sending decline notification: $error)"
1256 $cust_pay_pending->status('done');
1257 $cust_pay_pending->statustext($perror);
1258 #'declined:': no, that's failure_status
1259 if ( $transaction->can('failure_status') ) {
1260 $cust_pay_pending->failure_status( $transaction->failure_status );
1262 my $cpp_done_err = $cust_pay_pending->replace;
1263 if ( $cpp_done_err ) {
1264 my $e = "WARNING: $options{method} declined but pending payment not ".
1265 "resolved - error updating status for paypendingnum ".
1266 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1268 #XXX internal system log $e (what's going on?)
1269 $perror = "$e ($perror)";
1277 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1279 Verifies successful third party processing of a realtime credit card or
1280 ACH (electronic check) transaction via a
1281 Business::OnlineThirdPartyPayment realtime gateway. See
1282 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1284 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1286 The additional options I<payname>, I<city>, I<state>,
1287 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1288 if set, will override the value from the customer record.
1290 I<description> is a free-text field passed to the gateway. It defaults to
1291 "Internet services".
1293 If an I<invnum> is specified, this payment (if successful) is applied to the
1294 specified invoice. If you don't specify an I<invnum> you might want to
1295 call the B<apply_payments> method.
1297 I<quiet> can be set true to surpress email decline notices.
1299 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1300 resulting paynum, if any.
1302 I<payunique> is a unique identifier for this payment.
1304 Returns a hashref containing elements bill_error (which will be undefined
1305 upon success) and session_id of any associated session.
1309 sub realtime_botpp_capture {
1310 my( $self, $cust_pay_pending, %options ) = @_;
1312 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1315 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1316 warn " $_ => $options{$_}\n" foreach keys %options;
1319 eval "use Business::OnlineThirdPartyPayment";
1323 # select the gateway
1326 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1328 my $payment_gateway;
1329 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1330 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1331 { gatewaynum => $gatewaynum }
1333 : $self->agent->payment_gateway( 'method' => $method,
1334 # 'invnum' => $cust_pay_pending->invnum,
1335 # 'payinfo' => $cust_pay_pending->payinfo,
1338 $options{payment_gateway} = $payment_gateway; # for the helper subs
1344 my @invoicing_list = $self->invoicing_list_emailonly;
1345 if ( $conf->exists('emailinvoiceautoalways')
1346 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1347 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1348 push @invoicing_list, $self->all_emails;
1351 my $email = ($conf->exists('business-onlinepayment-email-override'))
1352 ? $conf->config('business-onlinepayment-email-override')
1353 : $invoicing_list[0];
1357 $content{email_customer} =
1358 ( $conf->exists('business-onlinepayment-email_customer')
1359 || $conf->exists('business-onlinepayment-email-override') );
1362 # run transaction(s)
1366 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1367 _bop_options(\%options),
1370 $transaction->reference({ %options });
1372 $transaction->content(
1374 _bop_auth(\%options),
1375 'action' => 'Post Authorization',
1376 'description' => $options{'description'},
1377 'amount' => $cust_pay_pending->paid,
1378 #'invoice_number' => $options{'invnum'},
1379 'customer_id' => $self->custnum,
1380 'reference' => $cust_pay_pending->paypendingnum,
1382 'phone' => $self->daytime || $self->night,
1384 # plus whatever is required for bogus capture avoidance
1387 $transaction->submit();
1390 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1392 if ( $options{'apply'} ) {
1393 my $apply_error = $self->apply_payments_and_credits;
1394 if ( $apply_error ) {
1395 warn "WARNING: error applying payment: $apply_error\n";
1400 bill_error => $error,
1401 session_id => $cust_pay_pending->session_id,
1406 =item default_payment_gateway
1408 DEPRECATED -- use agent->payment_gateway
1412 sub default_payment_gateway {
1413 my( $self, $method ) = @_;
1415 die "Real-time processing not enabled\n"
1416 unless $conf->exists('business-onlinepayment');
1418 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1421 my $bop_config = 'business-onlinepayment';
1422 $bop_config .= '-ach'
1423 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1424 my ( $processor, $login, $password, $action, @bop_options ) =
1425 $conf->config($bop_config);
1426 $action ||= 'normal authorization';
1427 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1428 die "No real-time processor is enabled - ".
1429 "did you set the business-onlinepayment configuration value?\n"
1432 ( $processor, $login, $password, $action, @bop_options )
1435 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1437 Refunds a realtime credit card or ACH (electronic check) transaction
1438 via a Business::OnlinePayment realtime gateway. See
1439 L<http://420.am/business-onlinepayment> for supported gateways.
1441 Available methods are: I<CC> or I<ECHECK>
1443 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1445 Most gateways require a reference to an original payment transaction to refund,
1446 so you probably need to specify a I<paynum>.
1448 I<amount> defaults to the original amount of the payment if not specified.
1450 I<reasonnum> specified an existing refund reason for the refund
1452 I<paydate> specifies the expiration date for a credit card overriding the
1453 value from the customer record or the payment record. Specified as yyyy-mm-dd
1455 Implementation note: If I<amount> is unspecified or equal to the amount of the
1456 orignal payment, first an attempt is made to "void" the transaction via
1457 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1458 the normal attempt is made to "refund" ("credit") the transaction via the
1459 gateway is attempted. No attempt to "void" the transaction is made if the
1460 gateway has introspection data and doesn't support void.
1462 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1463 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1464 #if set, will override the value from the customer record.
1466 #If an I<invnum> is specified, this payment (if successful) is applied to the
1467 #specified invoice. If you don't specify an I<invnum> you might want to
1468 #call the B<apply_payments> method.
1472 #some false laziness w/realtime_bop, not enough to make it worth merging
1473 #but some useful small subs should be pulled out
1474 sub realtime_refund_bop {
1477 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1480 if (ref($_[0]) eq 'HASH') {
1481 %options = %{$_[0]};
1485 $options{method} = $method;
1489 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1490 warn " $_ => $options{$_}\n" foreach keys %options;
1493 return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1498 # look up the original payment and optionally a gateway for that payment
1502 my $amount = $options{'amount'};
1504 my( $processor, $login, $password, @bop_options, $namespace ) ;
1505 my( $auth, $order_number ) = ( '', '', '' );
1506 my $gatewaynum = '';
1508 if ( $options{'paynum'} ) {
1510 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1511 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1512 or return "Unknown paynum $options{'paynum'}";
1513 $amount ||= $cust_pay->paid;
1515 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1516 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1518 if ( $cust_pay->get('processor') ) {
1519 ($gatewaynum, $processor, $auth, $order_number) =
1521 $cust_pay->gatewaynum,
1522 $cust_pay->processor,
1524 $cust_pay->order_number,
1527 # this payment wasn't upgraded, which probably means this won't work,
1529 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1530 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1531 $cust_pay->paybatch;
1532 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1535 my $payment_gateway;
1536 if ( $gatewaynum ) { #gateway for the payment to be refunded
1539 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1540 die "payment gateway $gatewaynum not found"
1541 unless $payment_gateway;
1543 $processor = $payment_gateway->gateway_module;
1544 $login = $payment_gateway->gateway_username;
1545 $password = $payment_gateway->gateway_password;
1546 $namespace = $payment_gateway->gateway_namespace;
1547 @bop_options = $payment_gateway->options;
1549 } else { #try the default gateway
1553 $self->agent->payment_gateway('method' => $options{method});
1555 ( $conf_processor, $login, $password, $namespace ) =
1556 map { my $method = "gateway_$_"; $payment_gateway->$method }
1557 qw( module username password namespace );
1559 @bop_options = $payment_gateway->gatewaynum
1560 ? $payment_gateway->options
1561 : @{ $payment_gateway->get('options') };
1562 my %bop_options = @bop_options;
1564 return "processor of payment $options{'paynum'} $processor does not".
1565 " match default processor $conf_processor"
1566 unless ($processor eq $conf_processor)
1567 || (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}));
1569 $processor = $conf_processor;
1573 # if gateway has switched to CardFortress but token_check hasn't run yet,
1574 # tokenize just this record now, so that token gets passed/set appropriately
1575 if ($cust_pay->payby eq 'CARD' && !$cust_pay->tokenized) {
1577 'payment_gateway' => $payment_gateway,
1579 'payinfo' => $cust_pay->payinfo,
1580 'paydate' => $cust_pay->paydate,
1582 my $error = $self->realtime_tokenize(\%tokenopts); # no-op unless gateway can tokenize
1583 if ($self->tokenized($tokenopts{'payinfo'})) { # implies no error
1584 warn " tokenizing cust_pay\n" if $DEBUG > 1;
1585 $cust_pay->payinfo($tokenopts{'payinfo'});
1586 $error = $cust_pay->replace;
1588 return $error if $error;
1591 } else { # didn't specify a paynum, so look for agent gateway overrides
1592 # like a normal transaction
1594 my $payment_gateway =
1595 $self->agent->payment_gateway( 'method' => $options{method} );
1596 ( $processor, $login, $password, $namespace ) =
1597 map { my $method = "gateway_$_"; $payment_gateway->$method }
1598 qw( module username password namespace );
1600 my @bop_options = $payment_gateway->gatewaynum
1601 ? $payment_gateway->options
1602 : @{ $payment_gateway->get('options') };
1605 return "neither amount nor paynum specified" unless $amount;
1607 eval "use $namespace";
1612 'type' => $options{method},
1614 'password' => $password,
1615 'order_number' => $order_number,
1616 'amount' => $amount,
1618 $content{authorization} = $auth
1619 if length($auth); #echeck/ACH transactions have an order # but no auth
1620 #(at least with authorize.net)
1622 my $currency = $conf->exists('business-onlinepayment-currency')
1623 && $conf->config('business-onlinepayment-currency');
1624 $content{currency} = $currency if $currency;
1626 my $disable_void_after;
1627 if ($conf->exists('disable_void_after')
1628 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1629 $disable_void_after = $1;
1632 #first try void if applicable
1633 my $void = new Business::OnlinePayment( $processor, @bop_options );
1636 if ($void->can('info')) {
1638 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1639 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1640 my %supported_actions = $void->info('supported_actions');
1642 if ( %supported_actions && $paytype
1643 && defined($supported_actions{$paytype})
1644 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1647 if ( $cust_pay && $cust_pay->paid == $amount
1649 ( not defined($disable_void_after) )
1650 || ( time < ($cust_pay->_date + $disable_void_after ) )
1654 warn " attempting void\n" if $DEBUG > 1;
1655 if ( $void->can('info') ) {
1656 if ( $cust_pay->payby eq 'CARD'
1657 && $void->info('CC_void_requires_card') )
1659 $content{'card_number'} = $cust_pay->payinfo;
1660 } elsif ( $cust_pay->payby eq 'CHEK'
1661 && $void->info('ECHECK_void_requires_account') )
1663 ( $content{'account_number'}, $content{'routing_code'} ) =
1664 split('@', $cust_pay->payinfo);
1665 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1668 $void->content( 'action' => 'void', %content );
1669 $void->test_transaction(1)
1670 if $conf->exists('business-onlinepayment-test_transaction');
1672 if ( $void->is_success ) {
1673 # specified as a refund reason, but now we want a payment void reason
1674 # extract just the reason text, let cust_pay::void handle new_or_existing
1675 my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1677 $error = 'Reason could not be loaded' unless $reason;
1678 $error = $cust_pay->void($reason->reason) unless $error;
1680 # gah, even with transactions.
1681 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1682 "error voiding payment: $error";
1686 warn " void successful\n" if $DEBUG > 1;
1691 warn " void unsuccessful, trying refund\n"
1695 my $address = $self->address1;
1696 $address .= ", ". $self->address2 if $self->address2;
1698 my($payname, $payfirst, $paylast);
1699 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1700 $payname = $self->payname;
1701 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1702 or return "Illegal payname $payname";
1703 ($payfirst, $paylast) = ($1, $2);
1705 $payfirst = $self->getfield('first');
1706 $paylast = $self->getfield('last');
1707 $payname = "$payfirst $paylast";
1710 my @invoicing_list = $self->invoicing_list_emailonly;
1711 if ( $conf->exists('emailinvoiceautoalways')
1712 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1713 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1714 push @invoicing_list, $self->all_emails;
1717 my $email = ($conf->exists('business-onlinepayment-email-override'))
1718 ? $conf->config('business-onlinepayment-email-override')
1719 : $invoicing_list[0];
1721 my $payip = exists($options{'payip'})
1724 $content{customer_ip} = $payip
1728 my $paymask = ''; # for refund record
1729 if ( $options{method} eq 'CC' ) {
1732 $content{card_number} = $payinfo = $cust_pay->payinfo;
1733 $paymask = $cust_pay->paymask;
1734 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1735 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1736 ($content{expiration} = "$2/$1"); # where available
1738 # this really needs a better cleanup
1739 die "Refund without paynum not supported";
1740 # $content{card_number} = $payinfo = $self->payinfo;
1741 # (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1742 # =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1743 # $content{expiration} = "$2/$1";
1746 } elsif ( $options{method} eq 'ECHECK' ) {
1749 $payinfo = $cust_pay->payinfo;
1751 $payinfo = $self->payinfo;
1753 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1754 $content{bank_name} = $self->payname;
1755 $content{account_type} = 'CHECKING';
1756 $content{account_name} = $payname;
1757 $content{customer_org} = $self->company ? 'B' : 'I';
1758 $content{customer_ssn} = $self->ss;
1763 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1764 my %sub_content = $refund->content(
1765 'action' => 'credit',
1766 'customer_id' => $self->custnum,
1767 'last_name' => $paylast,
1768 'first_name' => $payfirst,
1770 'address' => $address,
1771 'city' => $self->city,
1772 'state' => $self->state,
1773 'zip' => $self->zip,
1774 'country' => $self->country,
1776 'phone' => $self->daytime || $self->night,
1779 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1781 $refund->test_transaction(1)
1782 if $conf->exists('business-onlinepayment-test_transaction');
1785 return "$processor error: ". $refund->error_message
1786 unless $refund->is_success();
1788 $order_number = $refund->order_number if $refund->can('order_number');
1790 # change this to just use $cust_pay->delete_cust_bill_pay?
1791 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1792 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1793 last unless @cust_bill_pay;
1794 my $cust_bill_pay = pop @cust_bill_pay;
1795 my $error = $cust_bill_pay->delete;
1799 my $cust_refund = new FS::cust_refund ( {
1800 'custnum' => $self->custnum,
1801 'paynum' => $options{'paynum'},
1802 'source_paynum' => $options{'paynum'},
1803 'refund' => $amount,
1805 'payby' => $bop_method2payby{$options{method}},
1806 'payinfo' => $payinfo,
1807 'paymask' => $paymask,
1808 'reasonnum' => $options{'reasonnum'},
1809 'gatewaynum' => $gatewaynum, # may be null
1810 'processor' => $processor,
1811 'auth' => $refund->authorization,
1812 'order_number' => $order_number,
1814 my $error = $cust_refund->insert;
1816 $cust_refund->paynum(''); #try again with no specific paynum
1817 $cust_refund->source_paynum('');
1818 my $error2 = $cust_refund->insert;
1820 # gah, even with transactions.
1821 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1822 "error inserting refund ($processor): $error2".
1823 " (previously tried insert with paynum #$options{'paynum'}" .
1834 =item realtime_verify_bop [ OPTION => VALUE ... ]
1836 Runs an authorization-only transaction for $1 against this credit card (if
1837 successful, immediatly reverses the authorization).
1839 Returns the empty string if the authorization was sucessful, or an error
1842 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1843 Object will be tokenized if possible, but that change will not be
1844 updated in database (must be inserted/replaced afterwards.)
1846 Currently only succeeds for Business::OnlinePayment CC transactions.
1850 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1851 #it worth merging but some useful small subs should be pulled out
1852 sub realtime_verify_bop {
1855 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1856 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1859 if (ref($_[0]) eq 'HASH') {
1860 %options = %{$_[0]};
1866 warn "$me realtime_verify_bop\n";
1867 warn " $_ => $options{$_}\n" foreach keys %options;
1870 # set fields from passed cust_payby
1871 return "No cust_payby" unless $options{'cust_payby'};
1872 _bop_cust_payby_options(\%options);
1874 # check for banned credit card/ACH
1875 my $ban = FS::banned_pay->ban_search(
1876 'payby' => $bop_method2payby{'CC'},
1877 'payinfo' => $options{payinfo},
1879 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1881 # possibly run a separate transaction to tokenize card number,
1882 # so that we never store tokenized card info in cust_pay_pending
1883 if (($options{method} eq 'CC') && !$self->tokenized($options{'payinfo'})) {
1884 my $token_error = $self->realtime_tokenize(\%options);
1885 return $token_error if $token_error;
1886 #important that we not replace cust_payby here,
1887 #because cust_payby->replace uses realtime_verify_bop!
1894 my $payment_gateway = $self->_payment_gateway( \%options );
1895 my $namespace = $payment_gateway->gateway_namespace;
1897 eval "use $namespace";
1904 my $bop_content = $self->_bop_content(\%options);
1905 return $bop_content unless ref($bop_content);
1907 my @invoicing_list = $self->invoicing_list_emailonly;
1908 if ( $conf->exists('emailinvoiceautoalways')
1909 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1910 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1911 push @invoicing_list, $self->all_emails;
1914 my $email = ($conf->exists('business-onlinepayment-email-override'))
1915 ? $conf->config('business-onlinepayment-email-override')
1916 : $invoicing_list[0];
1921 if ( $namespace eq 'Business::OnlinePayment' ) {
1923 if ( $options{method} eq 'CC' ) {
1925 $content{card_number} = $options{payinfo};
1926 $paydate = $options{'paydate'};
1927 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1928 $content{expiration} = "$2/$1";
1930 $content{cvv2} = $options{'paycvv'}
1931 if length($options{'paycvv'});
1933 my $paystart_month = $options{'paystart_month'};
1934 my $paystart_year = $options{'paystart_year'};
1936 $content{card_start} = "$paystart_month/$paystart_year"
1937 if $paystart_month && $paystart_year;
1939 my $payissue = $options{'payissue'};
1940 $content{issue_number} = $payissue if $payissue;
1942 } elsif ( $options{method} eq 'ECHECK' ){
1943 #cannot verify, move along (though it shouldn't be called...)
1946 return "unknown method ". $options{method};
1948 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1949 #cannot verify, move along
1952 return "unknown namespace $namespace";
1956 # run transaction(s)
1960 my $transaction; #need this back so we can do _tokenize_card
1962 # don't mutex the customer here, because they might be uncommitted. and
1963 # this is only verification. it doesn't matter if they have other
1964 # unfinished verifications.
1966 my $cust_pay_pending = new FS::cust_pay_pending {
1967 'custnum_pending' => 1,
1970 'payby' => $bop_method2payby{'CC'},
1971 'payinfo' => $options{payinfo},
1972 'paymask' => $options{paymask},
1973 'paydate' => $paydate,
1974 'pkgnum' => $options{'pkgnum'},
1976 'gatewaynum' => $payment_gateway->gatewaynum || '',
1977 'session_id' => $options{session_id} || '',
1979 $cust_pay_pending->payunique( $options{payunique} )
1980 if defined($options{payunique}) && length($options{payunique});
1983 # open a separate handle for creating/updating the cust_pay_pending
1985 local $FS::UID::dbh = myconnect();
1986 local $FS::UID::AutoCommit = 1;
1988 # if this is an existing customer (and we can tell now because
1989 # this is a fresh transaction), it's safe to assign their custnum
1990 # to the cust_pay_pending record, and then the verification attempt
1991 # will remain linked to them even if it fails.
1992 if ( FS::cust_main->by_key($self->custnum) ) {
1993 $cust_pay_pending->set('custnum', $self->custnum);
1996 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1999 # if this fails, just return; everything else will still allow the
2000 # cust_pay_pending to have its custnum set later
2001 my $cpp_new_err = $cust_pay_pending->insert;
2002 return $cpp_new_err if $cpp_new_err;
2004 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
2006 warn Dumper($cust_pay_pending) if $DEBUG > 2;
2008 $transaction = new $namespace( $payment_gateway->gateway_module,
2009 _bop_options(\%options),
2012 $transaction->content(
2014 _bop_auth(\%options),
2015 'action' => 'Authorization Only',
2016 'description' => $options{'description'},
2018 'customer_id' => $self->custnum,
2020 'reference' => $cust_pay_pending->paypendingnum, #for now
2025 $cust_pay_pending->status('pending');
2026 my $cpp_pending_err = $cust_pay_pending->replace;
2027 return $cpp_pending_err if $cpp_pending_err;
2029 warn Dumper($transaction) if $DEBUG > 2;
2031 unless ( $BOP_TESTING ) {
2032 $transaction->test_transaction(1)
2033 if $conf->exists('business-onlinepayment-test_transaction');
2034 $transaction->submit();
2036 if ( $BOP_TESTING_SUCCESS ) {
2037 $transaction->is_success(1);
2038 $transaction->authorization('fake auth');
2040 $transaction->is_success(0);
2041 $transaction->error_message('fake failure');
2045 if ( $transaction->is_success() ) {
2047 $cust_pay_pending->status('authorized');
2048 my $cpp_authorized_err = $cust_pay_pending->replace;
2049 return $cpp_authorized_err if $cpp_authorized_err;
2051 my $auth = $transaction->authorization;
2052 my $ordernum = $transaction->can('order_number')
2053 ? $transaction->order_number
2056 my $reverse = new $namespace( $payment_gateway->gateway_module,
2057 _bop_options(\%options),
2060 $reverse->content( 'action' => 'Reverse Authorization',
2061 _bop_auth(\%options),
2065 'authorization' => $transaction->authorization,
2066 'order_number' => $ordernum,
2069 'result_code' => $transaction->result_code,
2070 'txn_date' => $transaction->txn_date,
2074 $reverse->test_transaction(1)
2075 if $conf->exists('business-onlinepayment-test_transaction');
2078 if ( $reverse->is_success ) {
2080 $cust_pay_pending->status('done');
2081 $cust_pay_pending->statustext('reversed');
2082 my $cpp_reversed_err = $cust_pay_pending->replace;
2083 return $cpp_reversed_err if $cpp_reversed_err;
2087 my $e = "Authorization successful but reversal failed, custnum #".
2088 $self->custnum. ': '. $reverse->result_code.
2089 ": ". $reverse->error_message;
2096 ### Address Verification ###
2098 # Single-letter codes vary by cardtype.
2100 # Erring on the side of accepting cards if avs is not available,
2101 # only rejecting if avs occurred and there's been an explicit mismatch
2103 # Charts below taken from vSecure documentation,
2104 # shows codes for Amex/Dscv/MC/Visa
2106 # ACCEPTABLE AVS RESPONSES:
2107 # Both Address and 5-digit postal code match Y A Y Y
2108 # Both address and 9-digit postal code match Y A X Y
2109 # United Kingdom – Address and postal code match _ _ _ F
2110 # International transaction – Address and postal code match _ _ _ D/M
2112 # ACCEPTABLE, BUT ISSUE A WARNING:
2113 # Ineligible transaction; or message contains a content error _ _ _ E
2114 # System unavailable; retry R U R R
2115 # Information unavailable U W U U
2116 # Issuer does not support AVS S U S S
2117 # AVS is not applicable _ _ _ S
2118 # Incompatible formats – Not verified _ _ _ C
2119 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2120 # International transaction – address not verified _ G _ G/I
2122 # UNACCEPTABLE AVS RESPONSES:
2123 # Only Address matches A Y A A
2124 # Only 5-digit postal code matches Z Z Z Z
2125 # Only 9-digit postal code matches Z Z W W
2126 # Neither address nor postal code matches N N N N
2128 if (my $avscode = uc($transaction->avs_code)) {
2130 # map codes to accept/warn/reject
2132 'American Express card' => {
2141 'Discover card' => {
2180 my $cardtype = cardtype($content{card_number});
2181 if ($avs->{$cardtype}) {
2182 my $avsact = $avs->{$cardtype}->{$avscode};
2184 if ($avsact eq 'r') {
2185 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2186 } elsif ($avsact eq 'w') {
2187 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2188 } elsif (!$avsact) {
2189 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2190 } # else $avsact eq 'a'
2192 $log->warning($warning);
2195 } # else $cardtype avs handling not implemented
2196 } # else !$transaction->avs_code
2198 } else { # is not success
2200 # status is 'done' not 'declined', as in _realtime_bop_result
2201 $cust_pay_pending->status('done');
2202 $error = $transaction->error_message || 'Unknown error';
2203 $cust_pay_pending->statustext($error);
2204 # could also record failure_status here,
2205 # but it's not supported by B::OP::vSecureProcessing...
2206 # need a B::OP module with (reverse) auth only to test it with
2207 my $cpp_declined_err = $cust_pay_pending->replace;
2208 return $cpp_declined_err if $cpp_declined_err;
2212 } # end of IMMEDIATE; we now have our $error and $transaction
2215 # Save the custnum (as part of the main transaction, so it can reference
2219 if (!$cust_pay_pending->custnum) {
2220 $cust_pay_pending->set('custnum', $self->custnum);
2221 my $set_custnum_err = $cust_pay_pending->replace;
2222 if ($set_custnum_err) {
2223 $log->error($set_custnum_err);
2224 $error ||= $set_custnum_err;
2225 # but if there was a real verification error also, return that one
2230 # remove paycvv here? need to find out if a reversed auth
2231 # counts as an initial transaction for paycvv retention requirements
2238 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2239 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2240 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2241 $cust_pay_pending->payinfo($card_token);
2242 my $cpp_token_err = $cust_pay_pending->replace;
2243 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2244 return $cpp_token_err if $cpp_token_err;
2245 #important that we not replace cust_payby here,
2246 #because cust_payby->replace uses realtime_verify_bop!
2253 # $error contains the transaction error_message, if is_success was false.
2259 =item realtime_tokenize [ OPTION => VALUE ... ]
2261 If possible and necessary, runs a tokenize transaction.
2262 In order to be possible, a credit card cust_payby record
2263 must be passed and a Business::OnlinePayment gateway capable
2264 of Tokenize transactions must be configured for this user.
2265 Is only necessary if payinfo is not yet tokenized.
2267 Returns the empty string if the authorization was sucessful
2268 or was not possible/necessary (thus allowing this to be safely called with
2269 non-tokenizable records/gateways, without having to perform separate tests),
2270 or an error message otherwise.
2272 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2273 Object will be tokenized if possible, but that change will not be
2274 updated in database (must be inserted/replaced afterwards.)
2276 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2277 may be passed. If options are passed as a hashref, I<payinfo>
2278 will be updated as appropriate in the passed hashref.
2280 Can be run as a class method if option I<payment_gateway> is passed,
2281 but default customer id/name/phone can't be set in that case. This
2282 is really only intended for tokenizing old records on upgrade.
2286 # careful--might be run as a class method
2287 sub realtime_tokenize {
2290 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2291 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2294 my $outoptions; #for returning cust_payby/payinfo
2295 if (ref($_[0]) eq 'HASH') {
2296 %options = %{$_[0]};
2297 $outoptions = $_[0];
2300 $outoptions = \%options;
2303 # set fields from passed cust_payby
2304 _bop_cust_payby_options(\%options);
2305 return '' unless $options{method} eq 'CC';
2306 return '' if $self->tokenized($options{payinfo}); #already tokenized
2308 # check for banned credit card/ACH
2309 my $ban = FS::banned_pay->ban_search(
2310 'payby' => $bop_method2payby{'CC'},
2311 'payinfo' => $options{payinfo},
2313 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2319 $options{'nofatal'} = 1;
2320 my $payment_gateway = $self->_payment_gateway( \%options );
2321 return '' unless $payment_gateway;
2322 my $namespace = $payment_gateway->gateway_namespace;
2323 return '' unless $namespace eq 'Business::OnlinePayment';
2325 eval "use $namespace";
2329 # check for tokenize ability
2332 my $transaction = new $namespace( $payment_gateway->gateway_module,
2333 _bop_options(\%options),
2336 return '' unless $transaction->can('info');
2338 my %supported_actions = $transaction->info('supported_actions');
2339 return '' unless $supported_actions{'CC'}
2340 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2346 ### Currently, cardfortress only keys in on card number and exp date.
2347 ### We pass everything we'd pass to a normal transaction,
2348 ### for ease of current and future development,
2349 ### but note, when tokenizing old records, we may only have access to payinfo/paydate
2351 my $bop_content = $self->_bop_content(\%options);
2352 return $bop_content unless ref($bop_content);
2357 $content{card_number} = $options{payinfo};
2358 $paydate = $options{'paydate'};
2359 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2360 $content{expiration} = "$2/$1";
2362 $content{cvv2} = $options{'paycvv'}
2363 if length($options{'paycvv'});
2365 my $paystart_month = $options{'paystart_month'};
2366 my $paystart_year = $options{'paystart_year'};
2368 $content{card_start} = "$paystart_month/$paystart_year"
2369 if $paystart_month && $paystart_year;
2371 my $payissue = $options{'payissue'};
2372 $content{issue_number} = $payissue if $payissue;
2374 $content{customer_id} = $self->custnum
2383 # no cust_pay_pending---this is not a financial transaction
2385 $transaction->content(
2387 _bop_auth(\%options),
2388 'action' => 'Tokenize',
2389 'description' => $options{'description'},
2394 # no $BOP_TESTING handling for this
2395 $transaction->test_transaction(1)
2396 if $conf->exists('business-onlinepayment-test_transaction');
2397 $transaction->submit();
2399 if ( $transaction->card_token() ) { # no is_success flag
2401 # realtime_tokenize should not clear paycvv at this time. it might be
2402 # needed for the first transaction, and a tokenize isn't actually a
2403 # transaction that hits the gateway. at some point in the future, card
2404 # fortress should take on the "store paycvv until first transaction"
2405 # functionality and we should fix this in freeside, but i that's a bigger
2406 # project for another time.
2408 #important that we not replace cust_payby here,
2409 #because cust_payby->replace uses realtime_tokenize!
2410 $self->_tokenize_card($transaction,$outoptions);
2414 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2423 =item tokenized PAYINFO
2425 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2427 PAYINFO is required.
2429 Can be run as class or object method, never loads from object.
2435 my $payinfo = shift;
2436 FS::cust_pay->tokenized($payinfo);
2439 =item token_check [ quiet => 1, queue => 1, daily => 1 ]
2441 NOT A METHOD. Acts on all customers. Placed here because it makes
2442 use of module-internal methods, and to keep everything that uses
2443 Billing::OnlinePayment all in one place.
2445 Tokenizes all tokenizable card numbers from payinfo in cust_payby and
2446 CARD transactions in cust_pay_pending, cust_pay, cust_pay_void and cust_refund.
2448 If the I<queue> flag is set, newly tokenized records will be immediately
2449 committed, regardless of AutoCommit, so as to release the mutex on the record.
2451 If all configured gateways have the ability to tokenize, detection of an
2452 untokenizable record will cause a fatal error. However, if the I<queue> flag
2453 is set, this will instead cause a critical error to be recorded in the log,
2454 and any other tokenizable records will still be committed.
2456 If the I<daily> flag is also set, detection of existing untokenized records will
2457 record an info message in the system log (because they should have never appeared
2458 in the first place.) Tokenization will still be attempted.
2460 If any configured gateways do NOT have the ability to tokenize, or if a
2461 default gateway is not configured, then untokenized records are not considered
2462 a threat, and no critical errors will be generated in the log.
2467 #acts on all customers
2469 my $debug = !$opt{'quiet'} || $DEBUG;
2470 my $hascritical = 0;
2472 warn "token_check called with opts\n".Dumper(\%opt) if $debug;
2474 # force some explicitness when invoking this method
2475 die "token_check must run with queue flag if run with daily flag"
2476 if $opt{'daily'} && !$opt{'queue'};
2478 my $conf = FS::Conf->new;
2480 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::token_check');
2482 my $cache = {}; #cache for module info
2484 # look for a gateway that can and can't tokenize
2485 my $require_tokenized = 1;
2486 my $someone_tokenizing = 0;
2487 foreach my $gateway (
2488 FS::payment_gateway->all_gateways(
2495 # no default gateway, no promise to tokenize
2496 # can just load other gateways as-needeed below
2497 $require_tokenized = 0;
2498 last if $someone_tokenizing;
2501 my $info = _token_check_gateway_info($cache,$gateway);
2502 die $info unless ref($info); # means it's an error message
2503 if ($info->{'can_tokenize'}) {
2504 $someone_tokenizing = 1;
2506 # a configured gateway can't tokenize, that's all we need to know right now
2507 # can just load other gateways as-needeed below
2508 $require_tokenized = 0;
2509 last if $someone_tokenizing;
2513 unless ($someone_tokenizing) { #no need to check, if no one can tokenize
2514 warn "no gateways tokenize\n" if $debug;
2518 warn "REQUIRE TOKENIZED" if $require_tokenized && $debug;
2520 # upgrade does not call this with autocommit turned on,
2521 # and autocommit will be ignored if opt queue is set,
2522 # but might as well be thorough...
2523 my $oldAutoCommit = $FS::UID::AutoCommit;
2524 local $FS::UID::AutoCommit = 0;
2527 # for retrieving data in chunks
2531 ### Tokenize cust_payby
2536 while (my $custnum = _token_check_next_recnum($dbh,'cust_main',$step,\$offset,\@recnums)) {
2537 my $cust_main = FS::cust_main->by_key($custnum);
2538 my $payment_gateway;
2539 foreach my $cust_payby ($cust_main->cust_payby('CARD','DCRD')) {
2541 # see if it's already tokenized
2542 if ($cust_payby->tokenized) {
2543 warn "cust_payby ".$cust_payby->get($cust_payby->primary_key)." already tokenized" if $debug;
2547 if ($require_tokenized && $opt{'daily'}) {
2548 $log->info("Untokenized card number detected in cust_payby ".$cust_payby->custpaybynum. '; tokenizing');
2549 $dbh->commit or die $dbh->errstr; # commit log message
2552 # only load gateway if we need to, and only need to load it once
2553 $payment_gateway ||= $cust_main->_payment_gateway({
2556 'nofatal' => 1, # handle lack of gateway smoothly below
2558 unless ($payment_gateway) {
2559 # no reason to have untokenized card numbers saved if no gateway,
2560 # but only a problem if we expected everyone to tokenize card numbers
2561 unless ($require_tokenized) {
2562 warn "Skipping cust_payby for cust_main ".$cust_main->custnum.", no payment gateway" if $debug;
2563 next CUSTLOOP; # can skip rest of customer
2565 my $error = "No gateway found for custnum ".$cust_main->custnum;
2566 if ($opt{'queue'}) {
2568 $log->critical($error);
2569 $dbh->commit or die $dbh->errstr; # commit error message
2570 next; # not next CUSTLOOP, want to record error for every cust_payby
2572 $dbh->rollback if $oldAutoCommit;
2576 my $info = _token_check_gateway_info($cache,$payment_gateway);
2577 unless (ref($info)) {
2578 # only throws error if Business::OnlinePayment won't load,
2579 # which is just cause to abort this whole process, even if queue
2580 $dbh->rollback if $oldAutoCommit;
2581 die $info; # error message
2583 # no fail here--a configured gateway can't tokenize, so be it
2584 unless ($info->{'can_tokenize'}) {
2585 warn "Skipping ".$cust_main->custnum." cannot tokenize" if $debug;
2590 $cust_payby = $cust_payby->select_for_update;
2592 'payment_gateway' => $payment_gateway,
2593 'cust_payby' => $cust_payby,
2595 my $error = $cust_main->realtime_tokenize(\%tokenopts);
2596 if ($cust_payby->tokenized) { # implies no error
2597 $error = $cust_payby->replace;
2599 $error ||= 'Unknown error';
2602 $error = "Error tokenizing cust_payby ".$cust_payby->custpaybynum.": ".$error;
2603 if ($opt{'queue'}) {
2605 $log->critical($error);
2606 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2607 next; # not next CUSTLOOP, want to record error for every cust_payby
2609 $dbh->rollback if $oldAutoCommit;
2612 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2613 warn "TOKENIZED cust_payby ".$cust_payby->get($cust_payby->primary_key) if $debug;
2615 warn "cust_payby upgraded for custnum ".$cust_main->custnum if $debug;
2619 ### Tokenize/mask transaction tables
2621 # allow tokenization of closed cust_pay/cust_refund records
2622 local $FS::payinfo_Mixin::allow_closed_replace = 1;
2625 # $cust_pay_pending->replace, $cust_pay->replace, $cust_pay_void->replace, $cust_refund->replace all run here
2626 foreach my $table ( qw(cust_pay_pending cust_pay cust_pay_void cust_refund) ) {
2627 warn "Checking $table" if $debug;
2629 # FS::Cursor does not seem to work over multiple commits (gives cursor not found errors)
2630 # loading only record ids, then loading individual records one at a time
2631 my $tclass = 'FS::'.$table;
2635 while (my $recnum = _token_check_next_recnum($dbh,$table,$step,\$offset,\@recnums)) {
2636 my $record = $tclass->by_key($recnum);
2637 unless ($record->payby eq 'CARD') {
2638 warn "Skipping non-card record for $table ".$record->get($record->primary_key) if $debug;
2641 if (FS::cust_main::Billing_Realtime->tokenized($record->payinfo)) {
2642 warn "Skipping tokenized record for $table ".$record->get($record->primary_key) if $debug;
2645 if (!$record->payinfo) { #shouldn't happen, but at least it's not a card number
2646 warn "Skipping blank payinfo for $table ".$record->get($record->primary_key) if $debug;
2649 if ($record->payinfo =~ /N\/A/) { # ??? Not sure why we do this, but it's not a card number
2650 warn "Skipping NA payinfo for $table ".$record->get($record->primary_key) if $debug;
2654 if ($require_tokenized && $opt{'daily'}) {
2655 $log->info("Untokenized card number detected in $table ".$record->get($record->primary_key). ';tokenizing');
2656 $dbh->commit or die $dbh->errstr; # commit log message
2659 my $cust_main = $record->cust_main;
2661 # might happen for cust_pay_pending from failed verify records,
2662 # in which case we attempt tokenization without cust_main
2663 # everything else should absolutely have a cust_main
2664 if ($table eq 'cust_pay_pending' and !$record->custnum ) {
2665 # override the usual safety check and allow the record to be
2666 # updated even without a custnum.
2667 $record->set('custnum_pending', 1);
2669 my $error = "Could not load cust_main for $table ".$record->get($record->primary_key);
2670 if ($opt{'queue'}) {
2672 $log->critical($error);
2673 $dbh->commit or die $dbh->errstr; # commit log message
2676 $dbh->rollback if $oldAutoCommit;
2683 # use the gatewaynum specified by the record if possible
2684 $gateway = FS::payment_gateway->by_key_with_namespace(
2685 'gatewaynum' => $record->gatewaynum,
2686 ) if $record->gateway;
2688 # otherwise use the cust agent gateway if possible (which realtime_refund_bop would do)
2689 # otherwise just use default gateway
2692 $gateway = $cust_main
2693 ? $cust_main->agent->payment_gateway
2694 : FS::payment_gateway->default_gateway;
2696 # check for processor mismatch
2697 unless ($table eq 'cust_pay_pending') { # has no processor table
2698 if (my $processor = $record->processor) {
2700 my $conf_processor = $gateway->gateway_module;
2701 my %bop_options = $gateway->gatewaynum
2703 : @{ $gateway->get('options') };
2705 # this is the same standard used by realtime_refund_bop
2707 ($processor eq $conf_processor) ||
2708 (($conf_processor eq 'CardFortress') && ($processor eq $bop_options{'gateway'}))
2711 # processors don't match, so refund already cannot be run on this object,
2712 # regardless of what we do now...
2713 # but unless we gotta tokenize everything, just leave well enough alone
2714 unless ($require_tokenized) {
2715 warn "Skipping mismatched processor for $table ".$record->get($record->primary_key) if $debug;
2718 ### no error--we'll tokenize using the new gateway, just to remove stored payinfo,
2719 ### because refunds are already impossible for this record, anyway
2721 } # end processor mismatch
2723 } # end record has processor
2724 } # end not cust_pay_pending
2728 # means no default gateway, no promise to tokenize, can skip
2730 warn "Skipping missing gateway for $table ".$record->get($record->primary_key) if $debug;
2734 my $info = _token_check_gateway_info($cache,$gateway);
2735 unless (ref($info)) {
2736 # only throws error if Business::OnlinePayment won't load,
2737 # which is just cause to abort this whole process, even if queue
2738 $dbh->rollback if $oldAutoCommit;
2739 die $info; # error message
2742 # a configured gateway can't tokenize, move along
2743 unless ($info->{'can_tokenize'}) {
2744 warn "Skipping, cannot tokenize $table ".$record->get($record->primary_key) if $debug;
2748 warn "ATTEMPTING GATEWAY-ONLY TOKENIZE" if $debug && !$cust_main;
2750 # if we got this far, time to mutex
2751 $record->select_for_update;
2753 # no clear record of name/address/etc used for transaction,
2754 # but will load name/phone/id from customer if run as an object method,
2755 # so we try that if we can
2757 'payment_gateway' => $gateway,
2759 'payinfo' => $record->payinfo,
2760 'paydate' => $record->paydate,
2762 my $error = $cust_main
2763 ? $cust_main->realtime_tokenize(\%tokenopts)
2764 : FS::cust_main::Billing_Realtime->realtime_tokenize(\%tokenopts);
2765 if (FS::cust_main::Billing_Realtime->tokenized($tokenopts{'payinfo'})) { # implies no error
2766 $record->payinfo($tokenopts{'payinfo'});
2767 $error = $record->replace;
2769 $error ||= 'Unknown error';
2772 $error = "Error tokenizing $table ".$record->get($record->primary_key).": ".$error;
2773 if ($opt{'queue'}) {
2775 $log->critical($error);
2776 $dbh->commit or die $dbh->errstr; # commit log message, release mutex
2779 $dbh->rollback if $oldAutoCommit;
2782 $dbh->commit or die $dbh->errstr if $opt{'queue'}; # release mutex
2783 warn "TOKENIZED $table ".$record->get($record->primary_key) if $debug;
2788 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
2790 return $hascritical ? 'Critical errors occurred on some records, see system log' : '';
2794 sub _token_check_next_recnum {
2795 my ($dbh,$table,$step,$offset,$recnums) = @_;
2796 my $recnum = shift @$recnums;
2797 return $recnum if $recnum;
2798 my $tclass = 'FS::'.$table;
2799 my $sth = $dbh->prepare(
2800 'SELECT '.$tclass->primary_key.
2802 " WHERE ( is_tokenized IS NULL OR is_tokenized = '' ) ".
2803 ' ORDER BY '.$tclass->primary_key.
2806 ) or die $dbh->errstr;
2807 $sth->execute() or die $sth->errstr;
2809 while (my $rec = $sth->fetchrow_hashref) {
2810 push @$recnums, $rec->{$tclass->primary_key};
2814 return shift @$recnums;
2818 sub _token_check_gateway_info {
2819 my ($cache,$payment_gateway) = @_;
2821 return $cache->{$payment_gateway->gateway_module}
2822 if $cache->{$payment_gateway->gateway_module};
2825 $cache->{$payment_gateway->gateway_module} = $info;
2827 my $namespace = $payment_gateway->gateway_namespace;
2828 return $info unless $namespace eq 'Business::OnlinePayment';
2829 $info->{'is_bop'} = 1;
2831 # only need to load this once,
2832 # don't want to load if nothing is_bop
2833 unless ($cache->{'Business::OnlinePayment'}) {
2834 eval "use $namespace";
2835 return "Error initializing Business:OnlinePayment: ".$@ if $@;
2836 $cache->{'Business::OnlinePayment'} = 1;
2839 my $transaction = new $namespace( $payment_gateway->gateway_module,
2840 _bop_options({ 'payment_gateway' => $payment_gateway }),
2843 return $info unless $transaction->can('info');
2844 $info->{'can_info'} = 1;
2846 my %supported_actions = $transaction->info('supported_actions');
2847 $info->{'can_tokenize'} = 1
2848 if $supported_actions{'CC'}
2849 && grep /^Tokenize$/, @{$supported_actions{'CC'}};
2851 # not using this any more, but for future reference...
2852 $info->{'void_requires_card'} = 1
2853 if $transaction->info('CC_void_requires_card');
2864 L<FS::cust_main>, L<FS::cust_main::Billing>