1 package FS::cust_main::Billing_Realtime;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
8 use Business::CreditCard 0.35;
9 use FS::UID qw( dbh myconnect );
10 use FS::Record qw( qsearch qsearchs );
13 use FS::cust_pay_pending;
14 use FS::cust_bill_pay;
18 $realtime_bop_decline_quiet = 0;
20 # 1 is mostly method/subroutine entry and options
21 # 2 traces progress of some operations
22 # 3 is even more information including possibly sensitive data
24 $me = '[FS::cust_main::Billing_Realtime]';
27 our $BOP_TESTING_SUCCESS = 1;
29 install_callback FS::UID sub {
31 #yes, need it for stuff below (prolly should be cached)
36 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
42 These methods are available on FS::cust_main objects.
48 =item realtime_cust_payby
52 sub realtime_cust_payby {
53 my( $self, %options ) = @_;
55 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
57 $options{amount} = $self->balance unless exists( $options{amount} );
59 my @cust_payby = $self->cust_payby('CARD','CHEK');
62 foreach my $cust_payby (@cust_payby) {
63 $error = $cust_payby->realtime_bop( %options, );
67 #XXX what about the earlier errors?
73 =item realtime_collect [ OPTION => VALUE ... ]
75 Attempt to collect the customer's current balance with a realtime credit
76 card or electronic check transaction (see realtime_bop() below).
78 Returns the result of realtime_bop(): nothing, an error message, or a
79 hashref of state information for a third-party transaction.
81 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
83 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
84 then it is deduced from the customer record.
86 If no I<amount> is specified, then the customer balance is used.
88 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
89 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
90 if set, will override the value from the customer record.
92 I<description> is a free-text field passed to the gateway. It defaults to
93 the value defined by the business-onlinepayment-description configuration
94 option, or "Internet services" if that is unset.
96 If an I<invnum> is specified, this payment (if successful) is applied to the
99 I<apply> will automatically apply a resulting payment.
101 I<quiet> can be set true to suppress email decline notices.
103 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
104 resulting paynum, if any.
106 I<payunique> is a unique identifier for this payment.
108 I<session_id> is a session identifier associated with this payment.
110 I<depend_jobnum> allows payment capture to unlock export jobs
114 # Currently only used by ClientAPI
115 # NOT 4.x COMPATIBLE (see below)
116 sub realtime_collect {
117 my( $self, %options ) = @_;
119 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
122 warn "$me realtime_collect:\n";
123 warn " $_ => $options{$_}\n" foreach keys %options;
126 $options{amount} = $self->balance unless exists( $options{amount} );
127 return '' unless $options{amount} > 0;
129 #### NOT 4.x COMPATIBLE
130 $options{method} = FS::payby->payby2bop($self->payby)
131 unless exists( $options{method} );
133 return $self->realtime_bop({%options});
137 =item realtime_bop { [ ARG => VALUE ... ] }
139 Runs a realtime credit card or ACH (electronic check) transaction
140 via a Business::OnlinePayment realtime gateway. See
141 L<http://420.am/business-onlinepayment> for supported gateways.
143 Required arguments in the hashref are I<amount> and either
144 I<cust_payby> or I<method>, I<payinfo> and (as applicable for method)
145 I<payname>, I<address1>, I<address2>, I<city>, I<state>, I<zip> and I<paydate>.
147 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
149 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
151 I<description> is a free-text field passed to the gateway. It defaults to
152 the value defined by the business-onlinepayment-description configuration
153 option, or "Internet services" if that is unset.
155 If an I<invnum> is specified, this payment (if successful) is applied to the
156 specified invoice. If the customer has exactly one open invoice, that
157 invoice number will be assumed. If you don't specify an I<invnum> you might
158 want to call the B<apply_payments> method or set the I<apply> option.
160 I<no_invnum> can be set to true to prevent that default invnum from being set.
162 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
164 I<no_auto_apply> can be set to true to set that flag on the resulting payment
165 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
166 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
168 I<quiet> can be set true to surpress email decline notices.
170 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
171 resulting paynum, if any.
173 I<payunique> is a unique identifier for this payment.
175 I<session_id> is a session identifier associated with this payment.
177 I<depend_jobnum> allows payment capture to unlock export jobs
179 I<discount_term> attempts to take a discount by prepaying for discount_term.
180 The payment will fail if I<amount> is incorrect for this discount term.
182 A direct (Business::OnlinePayment) transaction will return nothing on success,
183 or an error message on failure.
185 A third-party transaction will return a hashref containing:
187 - popup_url: the URL to which a browser should be redirected to complete
189 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
190 - reference: a reference ID for the transaction, to show the customer.
192 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
196 # some helper routines
198 # _bop_recurring_billing: Checks whether this payment should have the
199 # recurring_billing flag used by some B:OP interfaces (IPPay, PlugnPay,
200 # vSecure, etc.). This works in two different modes:
201 # - actual_oncard (default): treat the payment as recurring if the customer
202 # has made a payment using this card before.
203 # - transaction_is_recur: treat the payment as recurring if the invoice
204 # being paid has any recurring package charges.
206 sub _bop_recurring_billing {
207 my( $self, %opt ) = @_;
209 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
211 if ( defined($method) && $method eq 'transaction_is_recur' ) {
213 return 1 if $opt{'trans_is_recur'};
217 # return 1 if the payinfo has been used for another payment
218 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
226 sub _payment_gateway {
227 my ($self, $options) = @_;
229 if ( $options->{'selfservice'} ) {
230 my $gatewaynum = FS::Conf->new->config('selfservice-payment_gateway');
232 return $options->{payment_gateway} ||=
233 qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
237 if ( $options->{'fake_gatewaynum'} ) {
238 $options->{payment_gateway} =
239 qsearchs('payment_gateway',
240 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
244 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
245 unless exists($options->{payment_gateway});
247 $options->{payment_gateway};
251 my ($self, $options) = @_;
254 'login' => $options->{payment_gateway}->gateway_username,
255 'password' => $options->{payment_gateway}->gateway_password,
260 my ($self, $options) = @_;
262 $options->{payment_gateway}->gatewaynum
263 ? $options->{payment_gateway}->options
264 : @{ $options->{payment_gateway}->get('options') };
269 my ($self, $options) = @_;
271 unless ( $options->{'description'} ) {
272 if ( $conf->exists('business-onlinepayment-description') ) {
273 my $dtempl = $conf->config('business-onlinepayment-description');
275 my $agent = $self->agent->agent;
277 $options->{'description'} = eval qq("$dtempl");
279 $options->{'description'} = 'Internet services';
283 # Default invoice number if the customer has exactly one open invoice.
284 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
285 $options->{'invnum'} = '';
286 my @open = $self->open_cust_bill;
287 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
292 sub _bop_cust_payby_options {
293 my ($self,$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 );
330 my ($self, $options) = @_;
333 my $payip = $options->{'payip'};
334 $content{customer_ip} = $payip if length($payip);
336 $content{invoice_number} = $options->{'invnum'}
337 if exists($options->{'invnum'}) && length($options->{'invnum'});
339 $content{email_customer} =
340 ( $conf->exists('business-onlinepayment-email_customer')
341 || $conf->exists('business-onlinepayment-email-override') );
343 my ($payname, $payfirst, $paylast);
344 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
345 ($payname = $options->{payname}) =~
346 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
347 or return "Illegal payname $payname";
348 ($payfirst, $paylast) = ($1, $2);
350 $payfirst = $self->getfield('first');
351 $paylast = $self->getfield('last');
352 $payname = "$payfirst $paylast";
355 $content{last_name} = $paylast;
356 $content{first_name} = $payfirst;
358 $content{name} = $payname;
360 $content{address} = $options->{'address1'};
361 my $address2 = $options->{'address2'};
362 $content{address} .= ", ". $address2 if length($address2);
364 $content{city} = $options->{'city'};
365 $content{state} = $options->{'state'};
366 $content{zip} = $options->{'zip'};
367 $content{country} = $options->{'country'};
369 $content{phone} = $self->daytime || $self->night;
371 my $currency = $conf->exists('business-onlinepayment-currency')
372 && $conf->config('business-onlinepayment-currency');
373 $content{currency} = $currency if $currency;
378 # updates payinfo and cust_payby options with token from transaction
380 my ($self,$transaction,$options) = @_;
381 if ( $transaction->can('card_token')
382 and $transaction->card_token
383 and !$self->tokenized($options->{'payinfo'})
385 $options->{'payinfo'} = $transaction->card_token;
386 $options->{'cust_payby'}->payinfo($transaction->card_token) if $options->{'cust_payby'};
387 return $transaction->card_token;
392 my %bop_method2payby = (
401 confess "Can't call realtime_bop within another transaction ".
402 '($FS::UID::AutoCommit is false)'
403 unless $FS::UID::AutoCommit;
405 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
407 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_bop');
410 if (ref($_[0]) eq 'HASH') {
413 my ( $method, $amount ) = ( shift, shift );
415 $options{method} = $method;
416 $options{amount} = $amount;
419 # set fields from passed cust_payby
420 $self->_bop_cust_payby_options(\%options);
422 # possibly run a separate transaction to tokenize card number,
423 # so that we never store tokenized card info in cust_pay_pending
424 if (!$self->tokenized($options{'payinfo'})) {
425 my $token_error = $self->realtime_tokenize(\%options);
426 return $token_error if $token_error;
427 # in theory, all cust_payby will be tokenized during original save,
428 # so we shouldn't get here with opt cust_payby...but just in case...
429 if ($options{'cust_payby'}) {
430 $token_error = $options{'cust_payby'}->replace;
431 return $token_error if $token_error;
436 # optional credit card surcharge
439 my $cc_surcharge = 0;
440 my $cc_surcharge_pct = 0;
441 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage', $self->agentnum)
442 if $conf->config('credit-card-surcharge-percentage', $self->agentnum)
443 && $options{method} eq 'CC';
445 # always add cc surcharge if called from event
446 if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
447 $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
448 $options{'amount'} += $cc_surcharge;
449 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
451 elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a
452 # payment screen), so consider the given
453 # amount as post-surcharge
454 $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
457 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
458 $options{'cc_surcharge'} = $cc_surcharge;
462 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
463 warn " cc_surcharge = $cc_surcharge\n";
466 warn " $_ => $options{$_}\n" foreach keys %options;
469 return $self->fake_bop(\%options) if $options{'fake'};
471 $self->_bop_defaults(\%options);
473 return "Missing payinfo"
474 unless $options{'payinfo'};
477 # set trans_is_recur based on invnum if there is one
480 my $trans_is_recur = 0;
481 if ( $options{'invnum'} ) {
483 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
484 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
490 $cust_bill->cust_bill_pkg;
493 if grep { $_->freq ne '0' } @part_pkg;
501 my $payment_gateway = $self->_payment_gateway( \%options );
502 my $namespace = $payment_gateway->gateway_namespace;
504 eval "use $namespace";
508 # check for banned credit card/ACH
511 my $ban = FS::banned_pay->ban_search(
512 'payby' => $bop_method2payby{$options{method}},
513 'payinfo' => $options{payinfo},
515 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
518 # check for term discount validity
521 my $discount_term = $options{discount_term};
522 if ( $discount_term ) {
523 my $bill = ($self->cust_bill)[-1]
524 or return "Can't apply a term discount to an unbilled customer";
525 my $plan = FS::discount_plan->new(
527 months => $discount_term
528 ) or return "No discount available for term '$discount_term'";
530 if ( $plan->discounted_total != $options{amount} ) {
531 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
539 my $bop_content = $self->_bop_content(\%options);
540 return $bop_content unless ref($bop_content);
542 my @invoicing_list = $self->invoicing_list_emailonly;
543 if ( $conf->exists('emailinvoiceautoalways')
544 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
545 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
546 push @invoicing_list, $self->all_emails;
549 my $email = ($conf->exists('business-onlinepayment-email-override'))
550 ? $conf->config('business-onlinepayment-email-override')
551 : $invoicing_list[0];
556 if ( $namespace eq 'Business::OnlinePayment' ) {
558 if ( $options{method} eq 'CC' ) {
560 $content{card_number} = $options{payinfo};
561 $paydate = $options{'paydate'};
562 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
563 $content{expiration} = "$2/$1";
565 $content{cvv2} = $options{'paycvv'}
566 if length($options{'paycvv'});
568 my $paystart_month = $options{'paystart_month'};
569 my $paystart_year = $options{'paystart_year'};
570 $content{card_start} = "$paystart_month/$paystart_year"
571 if $paystart_month && $paystart_year;
573 my $payissue = $options{'payissue'};
574 $content{issue_number} = $payissue if $payissue;
576 if ( $self->_bop_recurring_billing(
577 'payinfo' => $options{'payinfo'},
578 'trans_is_recur' => $trans_is_recur,
582 $content{recurring_billing} = 'YES';
583 $content{acct_code} = 'rebill'
584 if $conf->exists('credit_card-recurring_billing_acct_code');
587 } elsif ( $options{method} eq 'ECHECK' ){
589 ( $content{account_number}, $content{routing_code} ) =
590 split('@', $options{payinfo});
591 $content{bank_name} = $options{payname};
592 $content{bank_state} = $options{'paystate'};
593 $content{account_type}= uc($options{'paytype'}) || 'PERSONAL CHECKING';
595 $content{company} = $self->company if $self->company;
597 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
598 $content{account_name} = $self->company;
600 $content{account_name} = $self->getfield('first'). ' '.
601 $self->getfield('last');
604 $content{customer_org} = $self->company ? 'B' : 'I';
605 $content{state_id} = exists($options{'stateid'})
606 ? $options{'stateid'}
607 : $self->getfield('stateid');
608 $content{state_id_state} = exists($options{'stateid_state'})
609 ? $options{'stateid_state'}
610 : $self->getfield('stateid_state');
611 $content{customer_ssn} = exists($options{'ss'})
616 die "unknown method ". $options{method};
619 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
622 die "unknown namespace $namespace";
629 my $balance = exists( $options{'balance'} )
630 ? $options{'balance'}
633 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
634 $self->select_for_update; #mutex ... just until we get our pending record in
635 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
637 #the checks here are intended to catch concurrent payments
638 #double-form-submission prevention is taken care of in cust_pay_pending::check
641 return "The customer's balance has changed; $options{method} transaction aborted."
642 if $self->balance < $balance;
644 #also check and make sure there aren't *other* pending payments for this cust
646 my @pending = qsearch('cust_pay_pending', {
647 'custnum' => $self->custnum,
648 'status' => { op=>'!=', value=>'done' }
651 #for third-party payments only, remove pending payments if they're in the
652 #'thirdparty' (waiting for customer action) state.
653 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
654 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
655 my $error = $_->delete;
656 warn "error deleting unfinished third-party payment ".
657 $_->paypendingnum . ": $error\n"
660 @pending = grep { $_->status ne 'thirdparty' } @pending;
663 return "A payment is already being processed for this customer (".
664 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
665 "); $options{method} transaction aborted."
668 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
670 my $cust_pay_pending = new FS::cust_pay_pending {
671 'custnum' => $self->custnum,
672 'paid' => $options{amount},
674 'payby' => $bop_method2payby{$options{method}},
675 'payinfo' => $options{payinfo},
676 'paymask' => $options{paymask},
677 'paydate' => $paydate,
678 'recurring_billing' => $content{recurring_billing},
679 'pkgnum' => $options{'pkgnum'},
681 'gatewaynum' => $payment_gateway->gatewaynum || '',
682 'session_id' => $options{session_id} || '',
683 'jobnum' => $options{depend_jobnum} || '',
685 $cust_pay_pending->payunique( $options{payunique} )
686 if defined($options{payunique}) && length($options{payunique});
688 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
690 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
691 return $cpp_new_err if $cpp_new_err;
693 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
695 warn Dumper($cust_pay_pending) if $DEBUG > 2;
697 my( $action1, $action2 ) =
698 split( /\s*\,\s*/, $payment_gateway->gateway_action );
700 my $transaction = new $namespace( $payment_gateway->gateway_module,
701 $self->_bop_options(\%options),
704 $transaction->content(
705 'type' => $options{method},
706 $self->_bop_auth(\%options),
707 'action' => $action1,
708 'description' => $options{'description'},
709 'amount' => $options{amount},
710 #'invoice_number' => $options{'invnum'},
711 'customer_id' => $self->custnum,
713 'reference' => $cust_pay_pending->paypendingnum, #for now
714 'callback_url' => $payment_gateway->gateway_callback_url,
715 'cancel_url' => $payment_gateway->gateway_cancel_url,
720 $cust_pay_pending->status('pending');
721 my $cpp_pending_err = $cust_pay_pending->replace;
722 return $cpp_pending_err if $cpp_pending_err;
724 warn Dumper($transaction) if $DEBUG > 2;
726 unless ( $BOP_TESTING ) {
727 $transaction->test_transaction(1)
728 if $conf->exists('business-onlinepayment-test_transaction');
729 $transaction->submit();
731 if ( $BOP_TESTING_SUCCESS ) {
732 $transaction->is_success(1);
733 $transaction->authorization('fake auth');
735 $transaction->is_success(0);
736 $transaction->error_message('fake failure');
740 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
742 $cust_pay_pending->status('thirdparty');
743 my $cpp_err = $cust_pay_pending->replace;
744 return { error => $cpp_err } if $cpp_err;
745 return { reference => $cust_pay_pending->paypendingnum,
746 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
748 } elsif ( $transaction->is_success() && $action2 ) {
750 $cust_pay_pending->status('authorized');
751 my $cpp_authorized_err = $cust_pay_pending->replace;
752 return $cpp_authorized_err if $cpp_authorized_err;
754 my $auth = $transaction->authorization;
755 my $ordernum = $transaction->can('order_number')
756 ? $transaction->order_number
760 new Business::OnlinePayment( $payment_gateway->gateway_module,
761 $self->_bop_options(\%options),
766 type => $options{method},
768 $self->_bop_auth(\%options),
769 order_number => $ordernum,
770 amount => $options{amount},
771 authorization => $auth,
772 description => $options{'description'},
775 foreach my $field (qw( authorization_source_code returned_ACI
776 transaction_identifier validation_code
777 transaction_sequence_num local_transaction_date
778 local_transaction_time AVS_result_code )) {
779 $capture{$field} = $transaction->$field() if $transaction->can($field);
782 $capture->content( %capture );
784 $capture->test_transaction(1)
785 if $conf->exists('business-onlinepayment-test_transaction');
788 unless ( $capture->is_success ) {
789 my $e = "Authorization successful but capture failed, custnum #".
790 $self->custnum. ': '. $capture->result_code.
791 ": ". $capture->error_message;
799 # remove paycvv after initial transaction
802 # compare to FS::cust_main::save_cust_payby - check both to make sure working correctly
803 if ( length($options{'paycvv'})
804 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
806 my $error = $self->remove_cvv_from_cust_payby($options{payinfo});
808 $log->critical('Error removing cvv for cust '.$self->custnum.': '.$error);
809 #not returning error, should at least attempt to handle results of an otherwise valid transaction
810 warn "WARNING: error removing cvv: $error\n";
818 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
819 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
820 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
821 # cpp will be replaced in _realtime_bop_result
822 $cust_pay_pending->payinfo($card_token);
823 if ($options{'cust_payby'} and my $error = $options{'cust_payby'}->replace) {
824 $log->critical('Error storing token for cust '.$self->custnum.', cust_payby '.$options{'cust_payby'}->custpaybynum.': '.$error);
825 #not returning error, should at least attempt to handle results of an otherwise valid transaction
826 #this leaves real card number in cust_payby, but can't do much else if cust_payby won't replace
834 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
846 if (ref($_[0]) eq 'HASH') {
849 my ( $method, $amount ) = ( shift, shift );
851 $options{method} = $method;
852 $options{amount} = $amount;
855 if ( $options{'fake_failure'} ) {
856 return "Error: No error; test failure requested with fake_failure";
859 my $cust_pay = new FS::cust_pay ( {
860 'custnum' => $self->custnum,
861 'invnum' => $options{'invnum'},
862 'paid' => $options{amount},
864 'payby' => $bop_method2payby{$options{method}},
865 'payinfo' => '4111111111111111',
866 'paydate' => '2012-05-01',
867 'processor' => 'FakeProcessor',
869 'order_number' => '32',
871 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
874 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
875 warn " $_ => $options{$_}\n" foreach keys %options;
878 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
881 $cust_pay->invnum(''); #try again with no specific invnum
882 my $error2 = $cust_pay->insert( $options{'manual'} ?
883 ( 'manual' => 1 ) : ()
886 # gah, even with transactions.
887 my $e = 'WARNING: Card/ACH debited but database not updated - '.
888 "error inserting (fake!) payment: $error2".
889 " (previously tried insert with invnum #$options{'invnum'}" .
896 if ( $options{'paynum_ref'} ) {
897 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
905 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
907 # Wraps up processing of a realtime credit card or ACH (electronic check)
910 sub _realtime_bop_result {
911 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
913 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
916 warn "$me _realtime_bop_result: pending transaction ".
917 $cust_pay_pending->paypendingnum. "\n";
918 warn " $_ => $options{$_}\n" foreach keys %options;
921 my $payment_gateway = $options{payment_gateway}
922 or return "no payment gateway in arguments to _realtime_bop_result";
924 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
925 my $cpp_captured_err = $cust_pay_pending->replace; #also saves post-transaction tokenization, if that happens
926 return $cpp_captured_err if $cpp_captured_err;
928 if ( $transaction->is_success() ) {
930 my $order_number = $transaction->order_number
931 if $transaction->can('order_number');
933 my $cust_pay = new FS::cust_pay ( {
934 'custnum' => $self->custnum,
935 'invnum' => $options{'invnum'},
936 'paid' => $cust_pay_pending->paid,
938 'payby' => $cust_pay_pending->payby,
939 'payinfo' => $options{'payinfo'},
940 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
941 'paydate' => $cust_pay_pending->paydate,
942 'pkgnum' => $cust_pay_pending->pkgnum,
943 'discount_term' => $options{'discount_term'},
944 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
945 'processor' => $payment_gateway->gateway_module,
946 'auth' => $transaction->authorization,
947 'order_number' => $order_number || '',
948 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
950 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
951 $cust_pay->payunique( $options{payunique} )
952 if defined($options{payunique}) && length($options{payunique});
954 my $oldAutoCommit = $FS::UID::AutoCommit;
955 local $FS::UID::AutoCommit = 0;
958 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
960 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
963 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
964 $cust_pay->invnum(''); #try again with no specific invnum
965 $cust_pay->paynum('');
966 my $error2 = $cust_pay->insert( $options{'manual'} ?
967 ( 'manual' => 1 ) : ()
970 # gah. but at least we have a record of the state we had to abort in
971 # from cust_pay_pending now.
972 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
973 my $e = "WARNING: $options{method} captured but payment not recorded -".
974 " error inserting payment (". $payment_gateway->gateway_module.
976 " (previously tried insert with invnum #$options{'invnum'}" .
977 ": $error ) - pending payment saved as paypendingnum ".
978 $cust_pay_pending->paypendingnum. "\n";
984 my $jobnum = $cust_pay_pending->jobnum;
986 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
988 unless ( $placeholder ) {
989 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
990 my $e = "WARNING: $options{method} captured but job $jobnum not ".
991 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
996 $error = $placeholder->delete;
999 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1000 my $e = "WARNING: $options{method} captured but could not delete ".
1001 "job $jobnum for paypendingnum ".
1002 $cust_pay_pending->paypendingnum. ": $error\n";
1007 $cust_pay_pending->set('jobnum','');
1011 if ( $options{'paynum_ref'} ) {
1012 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
1015 $cust_pay_pending->status('done');
1016 $cust_pay_pending->statustext('captured');
1017 $cust_pay_pending->paynum($cust_pay->paynum);
1018 my $cpp_done_err = $cust_pay_pending->replace;
1020 if ( $cpp_done_err ) {
1022 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
1023 my $e = "WARNING: $options{method} captured but payment not recorded - ".
1024 "error updating status for paypendingnum ".
1025 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1031 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
1033 if ( $options{'apply'} ) {
1034 my $apply_error = $self->apply_payments_and_credits;
1035 if ( $apply_error ) {
1036 warn "WARNING: error applying payment: $apply_error\n";
1037 #but we still should return no error cause the payment otherwise went
1042 # have a CC surcharge portion --> one-time charge
1043 if ( $options{'cc_surcharge'} > 0 ) {
1044 # XXX: this whole block needs to be in a transaction?
1047 $invnum = $options{'invnum'} if $options{'invnum'};
1048 unless ( $invnum ) { # probably from a payment screen
1049 # do we have any open invoices? pick earliest
1050 # uses the fact that cust_main->cust_bill sorts by date ascending
1051 my @open = $self->open_cust_bill;
1052 $invnum = $open[0]->invnum if scalar(@open);
1055 unless ( $invnum ) { # still nothing? pick last closed invoice
1056 # again uses fact that cust_main->cust_bill sorts by date ascending
1057 my @closed = $self->cust_bill;
1058 $invnum = $closed[$#closed]->invnum if scalar(@closed);
1061 unless ( $invnum ) {
1062 # XXX: unlikely case - pre-paying before any invoices generated
1063 # what it should do is create a new invoice and pick it
1064 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
1069 my $charge_error = $self->charge({
1070 'amount' => $options{'cc_surcharge'},
1071 'pkg' => 'Credit Card Surcharge',
1073 'cust_pkg_ref' => \$cust_pkg,
1076 warn 'Unable to add CC surcharge cust_pkg';
1080 $cust_pkg->setup(time);
1081 my $cp_error = $cust_pkg->replace;
1083 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1087 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1088 unless ( $cust_bill ) {
1089 warn "race condition + invoice deletion just happened";
1094 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1096 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1100 return ''; #no error
1106 my $perror = $transaction->error_message;
1107 #$payment_gateway->gateway_module. " error: ".
1108 # removed for conciseness
1110 my $jobnum = $cust_pay_pending->jobnum;
1112 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1114 if ( $placeholder ) {
1115 my $error = $placeholder->depended_delete;
1116 $error ||= $placeholder->delete;
1117 $cust_pay_pending->set('jobnum','');
1118 warn "error removing provisioning jobs after declined paypendingnum ".
1119 $cust_pay_pending->paypendingnum. ": $error\n" if $error;
1121 my $e = "error finding job $jobnum for declined paypendingnum ".
1122 $cust_pay_pending->paypendingnum. "\n";
1128 unless ( $transaction->error_message ) {
1131 if ( $transaction->can('response_page') ) {
1133 'page' => ( $transaction->can('response_page')
1134 ? $transaction->response_page
1137 'code' => ( $transaction->can('response_code')
1138 ? $transaction->response_code
1141 'headers' => ( $transaction->can('response_headers')
1142 ? $transaction->response_headers
1148 "No additional debugging information available for ".
1149 $payment_gateway->gateway_module;
1152 $perror .= "No error_message returned from ".
1153 $payment_gateway->gateway_module. " -- ".
1154 ( ref($t_response) ? Dumper($t_response) : $t_response );
1158 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1159 && $conf->exists('emaildecline', $self->agentnum)
1160 && grep { $_ ne 'POST' } $self->invoicing_list
1161 && ! grep { $transaction->error_message =~ /$_/ }
1162 $conf->config('emaildecline-exclude', $self->agentnum)
1165 # Send a decline alert to the customer.
1166 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1169 # include the raw error message in the transaction state
1170 $cust_pay_pending->setfield('error', $transaction->error_message);
1171 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1172 $error = $msg_template->send( 'cust_main' => $self,
1173 'object' => $cust_pay_pending );
1177 $perror .= " (also received error sending decline notification: $error)"
1182 $cust_pay_pending->status('done');
1183 $cust_pay_pending->statustext($perror);
1184 #'declined:': no, that's failure_status
1185 if ( $transaction->can('failure_status') ) {
1186 $cust_pay_pending->failure_status( $transaction->failure_status );
1188 my $cpp_done_err = $cust_pay_pending->replace;
1189 if ( $cpp_done_err ) {
1190 my $e = "WARNING: $options{method} declined but pending payment not ".
1191 "resolved - error updating status for paypendingnum ".
1192 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1194 $perror = "$e ($perror)";
1202 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1204 Verifies successful third party processing of a realtime credit card or
1205 ACH (electronic check) transaction via a
1206 Business::OnlineThirdPartyPayment realtime gateway. See
1207 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1209 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1211 The additional options I<payname>, I<city>, I<state>,
1212 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1213 if set, will override the value from the customer record.
1215 I<description> is a free-text field passed to the gateway. It defaults to
1216 "Internet services".
1218 If an I<invnum> is specified, this payment (if successful) is applied to the
1219 specified invoice. If you don't specify an I<invnum> you might want to
1220 call the B<apply_payments> method.
1222 I<quiet> can be set true to surpress email decline notices.
1224 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1225 resulting paynum, if any.
1227 I<payunique> is a unique identifier for this payment.
1229 Returns a hashref containing elements bill_error (which will be undefined
1230 upon success) and session_id of any associated session.
1234 sub realtime_botpp_capture {
1235 my( $self, $cust_pay_pending, %options ) = @_;
1237 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1240 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1241 warn " $_ => $options{$_}\n" foreach keys %options;
1244 eval "use Business::OnlineThirdPartyPayment";
1248 # select the gateway
1251 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1253 my $payment_gateway;
1254 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1255 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1256 { gatewaynum => $gatewaynum }
1258 : $self->agent->payment_gateway( 'method' => $method,
1259 # 'invnum' => $cust_pay_pending->invnum,
1260 # 'payinfo' => $cust_pay_pending->payinfo,
1263 $options{payment_gateway} = $payment_gateway; # for the helper subs
1269 my @invoicing_list = $self->invoicing_list_emailonly;
1270 if ( $conf->exists('emailinvoiceautoalways')
1271 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1272 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1273 push @invoicing_list, $self->all_emails;
1276 my $email = ($conf->exists('business-onlinepayment-email-override'))
1277 ? $conf->config('business-onlinepayment-email-override')
1278 : $invoicing_list[0];
1282 $content{email_customer} =
1283 ( $conf->exists('business-onlinepayment-email_customer')
1284 || $conf->exists('business-onlinepayment-email-override') );
1287 # run transaction(s)
1291 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1292 $self->_bop_options(\%options),
1295 $transaction->reference({ %options });
1297 $transaction->content(
1299 $self->_bop_auth(\%options),
1300 'action' => 'Post Authorization',
1301 'description' => $options{'description'},
1302 'amount' => $cust_pay_pending->paid,
1303 #'invoice_number' => $options{'invnum'},
1304 'customer_id' => $self->custnum,
1305 'reference' => $cust_pay_pending->paypendingnum,
1307 'phone' => $self->daytime || $self->night,
1309 # plus whatever is required for bogus capture avoidance
1312 $transaction->submit();
1315 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1317 if ( $options{'apply'} ) {
1318 my $apply_error = $self->apply_payments_and_credits;
1319 if ( $apply_error ) {
1320 warn "WARNING: error applying payment: $apply_error\n";
1325 bill_error => $error,
1326 session_id => $cust_pay_pending->session_id,
1331 =item default_payment_gateway
1333 DEPRECATED -- use agent->payment_gateway
1337 sub default_payment_gateway {
1338 my( $self, $method ) = @_;
1340 die "Real-time processing not enabled\n"
1341 unless $conf->exists('business-onlinepayment');
1343 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1346 my $bop_config = 'business-onlinepayment';
1347 $bop_config .= '-ach'
1348 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1349 my ( $processor, $login, $password, $action, @bop_options ) =
1350 $conf->config($bop_config);
1351 $action ||= 'normal authorization';
1352 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1353 die "No real-time processor is enabled - ".
1354 "did you set the business-onlinepayment configuration value?\n"
1357 ( $processor, $login, $password, $action, @bop_options )
1360 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1362 Refunds a realtime credit card or ACH (electronic check) transaction
1363 via a Business::OnlinePayment realtime gateway. See
1364 L<http://420.am/business-onlinepayment> for supported gateways.
1366 Available methods are: I<CC> or I<ECHECK>
1368 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1370 Most gateways require a reference to an original payment transaction to refund,
1371 so you probably need to specify a I<paynum>.
1373 I<amount> defaults to the original amount of the payment if not specified.
1375 I<reasonnum> specified an existing refund reason for the refund
1377 I<paydate> specifies the expiration date for a credit card overriding the
1378 value from the customer record or the payment record. Specified as yyyy-mm-dd
1380 Implementation note: If I<amount> is unspecified or equal to the amount of the
1381 orignal payment, first an attempt is made to "void" the transaction via
1382 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1383 the normal attempt is made to "refund" ("credit") the transaction via the
1384 gateway is attempted. No attempt to "void" the transaction is made if the
1385 gateway has introspection data and doesn't support void.
1387 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1388 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1389 #if set, will override the value from the customer record.
1391 #If an I<invnum> is specified, this payment (if successful) is applied to the
1392 #specified invoice. If you don't specify an I<invnum> you might want to
1393 #call the B<apply_payments> method.
1397 #some false laziness w/realtime_bop, not enough to make it worth merging
1398 #but some useful small subs should be pulled out
1399 sub realtime_refund_bop {
1402 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1405 if (ref($_[0]) eq 'HASH') {
1406 %options = %{$_[0]};
1410 $options{method} = $method;
1414 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1415 warn " $_ => $options{$_}\n" foreach keys %options;
1418 return "No reason specified" unless $options{'reasonnum'} =~ /^\d+$/;
1423 # look up the original payment and optionally a gateway for that payment
1427 my $amount = $options{'amount'};
1429 my( $processor, $login, $password, @bop_options, $namespace ) ;
1430 my( $auth, $order_number ) = ( '', '', '' );
1431 my $gatewaynum = '';
1433 if ( $options{'paynum'} ) {
1435 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1436 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1437 or return "Unknown paynum $options{'paynum'}";
1438 $amount ||= $cust_pay->paid;
1440 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1441 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1443 if ( $cust_pay->get('processor') ) {
1444 ($gatewaynum, $processor, $auth, $order_number) =
1446 $cust_pay->gatewaynum,
1447 $cust_pay->processor,
1449 $cust_pay->order_number,
1452 # this payment wasn't upgraded, which probably means this won't work,
1454 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1455 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1456 $cust_pay->paybatch;
1457 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1460 if ( $gatewaynum ) { #gateway for the payment to be refunded
1462 my $payment_gateway =
1463 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1464 die "payment gateway $gatewaynum not found"
1465 unless $payment_gateway;
1467 $processor = $payment_gateway->gateway_module;
1468 $login = $payment_gateway->gateway_username;
1469 $password = $payment_gateway->gateway_password;
1470 $namespace = $payment_gateway->gateway_namespace;
1471 @bop_options = $payment_gateway->options;
1473 } else { #try the default gateway
1476 my $payment_gateway =
1477 $self->agent->payment_gateway('method' => $options{method});
1479 ( $conf_processor, $login, $password, $namespace ) =
1480 map { my $method = "gateway_$_"; $payment_gateway->$method }
1481 qw( module username password namespace );
1483 @bop_options = $payment_gateway->gatewaynum
1484 ? $payment_gateway->options
1485 : @{ $payment_gateway->get('options') };
1487 return "processor of payment $options{'paynum'} $processor does not".
1488 " match default processor $conf_processor"
1489 unless $processor eq $conf_processor;
1494 } else { # didn't specify a paynum, so look for agent gateway overrides
1495 # like a normal transaction
1497 my $payment_gateway =
1498 $self->agent->payment_gateway( 'method' => $options{method},
1499 #'payinfo' => $payinfo,
1501 my( $processor, $login, $password, $namespace ) =
1502 map { my $method = "gateway_$_"; $payment_gateway->$method }
1503 qw( module username password namespace );
1505 my @bop_options = $payment_gateway->gatewaynum
1506 ? $payment_gateway->options
1507 : @{ $payment_gateway->get('options') };
1510 return "neither amount nor paynum specified" unless $amount;
1512 eval "use $namespace";
1517 'type' => $options{method},
1519 'password' => $password,
1520 'order_number' => $order_number,
1521 'amount' => $amount,
1523 $content{authorization} = $auth
1524 if length($auth); #echeck/ACH transactions have an order # but no auth
1525 #(at least with authorize.net)
1527 my $currency = $conf->exists('business-onlinepayment-currency')
1528 && $conf->config('business-onlinepayment-currency');
1529 $content{currency} = $currency if $currency;
1531 my $disable_void_after;
1532 if ($conf->exists('disable_void_after')
1533 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1534 $disable_void_after = $1;
1537 #first try void if applicable
1538 my $void = new Business::OnlinePayment( $processor, @bop_options );
1541 if ($void->can('info')) {
1543 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1544 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1545 my %supported_actions = $void->info('supported_actions');
1547 if ( %supported_actions && $paytype
1548 && defined($supported_actions{$paytype})
1549 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1552 if ( $cust_pay && $cust_pay->paid == $amount
1554 ( not defined($disable_void_after) )
1555 || ( time < ($cust_pay->_date + $disable_void_after ) )
1559 warn " attempting void\n" if $DEBUG > 1;
1560 if ( $void->can('info') ) {
1561 if ( $cust_pay->payby eq 'CARD'
1562 && $void->info('CC_void_requires_card') )
1564 $content{'card_number'} = $cust_pay->payinfo;
1565 } elsif ( $cust_pay->payby eq 'CHEK'
1566 && $void->info('ECHECK_void_requires_account') )
1568 ( $content{'account_number'}, $content{'routing_code'} ) =
1569 split('@', $cust_pay->payinfo);
1570 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1573 $void->content( 'action' => 'void', %content );
1574 $void->test_transaction(1)
1575 if $conf->exists('business-onlinepayment-test_transaction');
1577 if ( $void->is_success ) {
1578 # specified as a refund reason, but now we want a payment void reason
1579 # extract just the reason text, let cust_pay::void handle new_or_existing
1580 my $reason = qsearchs('reason',{ 'reasonnum' => $options{'reasonnum'} });
1582 $error = 'Reason could not be loaded' unless $reason;
1583 $error = $cust_pay->void($reason->reason) unless $error;
1585 # gah, even with transactions.
1586 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1587 "error voiding payment: $error";
1591 warn " void successful\n" if $DEBUG > 1;
1596 warn " void unsuccessful, trying refund\n"
1600 my $address = $self->address1;
1601 $address .= ", ". $self->address2 if $self->address2;
1603 my($payname, $payfirst, $paylast);
1604 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1605 $payname = $self->payname;
1606 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1607 or return "Illegal payname $payname";
1608 ($payfirst, $paylast) = ($1, $2);
1610 $payfirst = $self->getfield('first');
1611 $paylast = $self->getfield('last');
1612 $payname = "$payfirst $paylast";
1615 my @invoicing_list = $self->invoicing_list_emailonly;
1616 if ( $conf->exists('emailinvoiceautoalways')
1617 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1618 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1619 push @invoicing_list, $self->all_emails;
1622 my $email = ($conf->exists('business-onlinepayment-email-override'))
1623 ? $conf->config('business-onlinepayment-email-override')
1624 : $invoicing_list[0];
1626 my $payip = exists($options{'payip'})
1629 $content{customer_ip} = $payip
1633 if ( $options{method} eq 'CC' ) {
1636 $content{card_number} = $payinfo = $cust_pay->payinfo;
1637 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1638 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1639 ($content{expiration} = "$2/$1"); # where available
1641 $content{card_number} = $payinfo = $self->payinfo;
1642 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1643 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1644 $content{expiration} = "$2/$1";
1647 } elsif ( $options{method} eq 'ECHECK' ) {
1650 $payinfo = $cust_pay->payinfo;
1652 $payinfo = $self->payinfo;
1654 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1655 $content{bank_name} = $self->payname;
1656 $content{account_type} = 'CHECKING';
1657 $content{account_name} = $payname;
1658 $content{customer_org} = $self->company ? 'B' : 'I';
1659 $content{customer_ssn} = $self->ss;
1664 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1665 my %sub_content = $refund->content(
1666 'action' => 'credit',
1667 'customer_id' => $self->custnum,
1668 'last_name' => $paylast,
1669 'first_name' => $payfirst,
1671 'address' => $address,
1672 'city' => $self->city,
1673 'state' => $self->state,
1674 'zip' => $self->zip,
1675 'country' => $self->country,
1677 'phone' => $self->daytime || $self->night,
1680 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1682 $refund->test_transaction(1)
1683 if $conf->exists('business-onlinepayment-test_transaction');
1686 return "$processor error: ". $refund->error_message
1687 unless $refund->is_success();
1689 $order_number = $refund->order_number if $refund->can('order_number');
1691 # change this to just use $cust_pay->delete_cust_bill_pay?
1692 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1693 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1694 last unless @cust_bill_pay;
1695 my $cust_bill_pay = pop @cust_bill_pay;
1696 my $error = $cust_bill_pay->delete;
1700 my $cust_refund = new FS::cust_refund ( {
1701 'custnum' => $self->custnum,
1702 'paynum' => $options{'paynum'},
1703 'source_paynum' => $options{'paynum'},
1704 'refund' => $amount,
1706 'payby' => $bop_method2payby{$options{method}},
1707 'payinfo' => $payinfo,
1708 'reasonnum' => $options{'reasonnum'},
1709 'gatewaynum' => $gatewaynum, # may be null
1710 'processor' => $processor,
1711 'auth' => $refund->authorization,
1712 'order_number' => $order_number,
1714 my $error = $cust_refund->insert;
1716 $cust_refund->paynum(''); #try again with no specific paynum
1717 $cust_refund->source_paynum('');
1718 my $error2 = $cust_refund->insert;
1720 # gah, even with transactions.
1721 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1722 "error inserting refund ($processor): $error2".
1723 " (previously tried insert with paynum #$options{'paynum'}" .
1734 =item realtime_verify_bop [ OPTION => VALUE ... ]
1736 Runs an authorization-only transaction for $1 against this credit card (if
1737 successful, immediatly reverses the authorization).
1739 Returns the empty string if the authorization was sucessful, or an error
1742 Option I<cust_payby> should be passed, even if it's not yet been inserted.
1743 Object will be tokenized if possible, but that change will not be
1744 updated in database (must be inserted/replaced afterwards.)
1746 Currently only succeeds for Business::OnlinePayment CC transactions.
1750 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1751 #it worth merging but some useful small subs should be pulled out
1752 sub realtime_verify_bop {
1755 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1756 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_verify_bop');
1759 if (ref($_[0]) eq 'HASH') {
1760 %options = %{$_[0]};
1766 warn "$me realtime_verify_bop\n";
1767 warn " $_ => $options{$_}\n" foreach keys %options;
1770 # set fields from passed cust_payby
1771 return "No cust_payby" unless $options{'cust_payby'};
1772 $self->_bop_cust_payby_options(\%options);
1774 # possibly run a separate transaction to tokenize card number,
1775 # so that we never store tokenized card info in cust_pay_pending
1776 if (!$self->tokenized($options{'payinfo'})) {
1777 my $token_error = $self->realtime_tokenize(\%options);
1778 return $token_error if $token_error;
1779 #important that we not replace cust_payby here,
1780 #because cust_payby->replace uses realtime_verify_bop!
1787 my $payment_gateway = $self->_payment_gateway( \%options );
1788 my $namespace = $payment_gateway->gateway_namespace;
1790 eval "use $namespace";
1794 # check for banned credit card/ACH
1797 my $ban = FS::banned_pay->ban_search(
1798 'payby' => $bop_method2payby{'CC'},
1799 'payinfo' => $options{payinfo},
1801 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1807 my $bop_content = $self->_bop_content(\%options);
1808 return $bop_content unless ref($bop_content);
1810 my @invoicing_list = $self->invoicing_list_emailonly;
1811 if ( $conf->exists('emailinvoiceautoalways')
1812 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1813 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1814 push @invoicing_list, $self->all_emails;
1817 my $email = ($conf->exists('business-onlinepayment-email-override'))
1818 ? $conf->config('business-onlinepayment-email-override')
1819 : $invoicing_list[0];
1824 if ( $namespace eq 'Business::OnlinePayment' ) {
1826 if ( $options{method} eq 'CC' ) {
1828 $content{card_number} = $options{payinfo};
1829 $paydate = $options{'paydate'};
1830 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1831 $content{expiration} = "$2/$1";
1833 $content{cvv2} = $options{'paycvv'}
1834 if length($options{'paycvv'});
1836 my $paystart_month = $options{'paystart_month'};
1837 my $paystart_year = $options{'paystart_year'};
1839 $content{card_start} = "$paystart_month/$paystart_year"
1840 if $paystart_month && $paystart_year;
1842 my $payissue = $options{'payissue'};
1843 $content{issue_number} = $payissue if $payissue;
1845 } elsif ( $options{method} eq 'ECHECK' ){
1846 #cannot verify, move along (though it shouldn't be called...)
1849 return "unknown method ". $options{method};
1851 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1852 #cannot verify, move along
1855 return "unknown namespace $namespace";
1859 # run transaction(s)
1863 my $transaction; #need this back so we can do _tokenize_card
1865 # don't mutex the customer here, because they might be uncommitted. and
1866 # this is only verification. it doesn't matter if they have other
1867 # unfinished verifications.
1869 my $cust_pay_pending = new FS::cust_pay_pending {
1870 'custnum_pending' => 1,
1873 'payby' => $bop_method2payby{'CC'},
1874 'payinfo' => $options{payinfo},
1875 'paymask' => $options{paymask},
1876 'paydate' => $paydate,
1877 'pkgnum' => $options{'pkgnum'},
1879 'gatewaynum' => $payment_gateway->gatewaynum || '',
1880 'session_id' => $options{session_id} || '',
1882 $cust_pay_pending->payunique( $options{payunique} )
1883 if defined($options{payunique}) && length($options{payunique});
1886 # open a separate handle for creating/updating the cust_pay_pending
1888 local $FS::UID::dbh = myconnect();
1889 local $FS::UID::AutoCommit = 1;
1891 # if this is an existing customer (and we can tell now because
1892 # this is a fresh transaction), it's safe to assign their custnum
1893 # to the cust_pay_pending record, and then the verification attempt
1894 # will remain linked to them even if it fails.
1895 if ( FS::cust_main->by_key($self->custnum) ) {
1896 $cust_pay_pending->set('custnum', $self->custnum);
1899 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1902 # if this fails, just return; everything else will still allow the
1903 # cust_pay_pending to have its custnum set later
1904 my $cpp_new_err = $cust_pay_pending->insert;
1905 return $cpp_new_err if $cpp_new_err;
1907 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1909 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1911 $transaction = new $namespace( $payment_gateway->gateway_module,
1912 $self->_bop_options(\%options),
1915 $transaction->content(
1917 $self->_bop_auth(\%options),
1918 'action' => 'Authorization Only',
1919 'description' => $options{'description'},
1921 'customer_id' => $self->custnum,
1923 'reference' => $cust_pay_pending->paypendingnum, #for now
1928 $cust_pay_pending->status('pending');
1929 my $cpp_pending_err = $cust_pay_pending->replace;
1930 return $cpp_pending_err if $cpp_pending_err;
1932 warn Dumper($transaction) if $DEBUG > 2;
1934 unless ( $BOP_TESTING ) {
1935 $transaction->test_transaction(1)
1936 if $conf->exists('business-onlinepayment-test_transaction');
1937 $transaction->submit();
1939 if ( $BOP_TESTING_SUCCESS ) {
1940 $transaction->is_success(1);
1941 $transaction->authorization('fake auth');
1943 $transaction->is_success(0);
1944 $transaction->error_message('fake failure');
1948 if ( $transaction->is_success() ) {
1950 $cust_pay_pending->status('authorized');
1951 my $cpp_authorized_err = $cust_pay_pending->replace;
1952 return $cpp_authorized_err if $cpp_authorized_err;
1954 my $auth = $transaction->authorization;
1955 my $ordernum = $transaction->can('order_number')
1956 ? $transaction->order_number
1959 my $reverse = new $namespace( $payment_gateway->gateway_module,
1960 $self->_bop_options(\%options),
1963 $reverse->content( 'action' => 'Reverse Authorization',
1964 $self->_bop_auth(\%options),
1968 'authorization' => $transaction->authorization,
1969 'order_number' => $ordernum,
1972 'result_code' => $transaction->result_code,
1973 'txn_date' => $transaction->txn_date,
1977 $reverse->test_transaction(1)
1978 if $conf->exists('business-onlinepayment-test_transaction');
1981 if ( $reverse->is_success ) {
1983 $cust_pay_pending->status('done');
1984 $cust_pay_pending->statustext('reversed');
1985 my $cpp_reversed_err = $cust_pay_pending->replace;
1986 return $cpp_reversed_err if $cpp_reversed_err;
1990 my $e = "Authorization successful but reversal failed, custnum #".
1991 $self->custnum. ': '. $reverse->result_code.
1992 ": ". $reverse->error_message;
1999 ### Address Verification ###
2001 # Single-letter codes vary by cardtype.
2003 # Erring on the side of accepting cards if avs is not available,
2004 # only rejecting if avs occurred and there's been an explicit mismatch
2006 # Charts below taken from vSecure documentation,
2007 # shows codes for Amex/Dscv/MC/Visa
2009 # ACCEPTABLE AVS RESPONSES:
2010 # Both Address and 5-digit postal code match Y A Y Y
2011 # Both address and 9-digit postal code match Y A X Y
2012 # United Kingdom – Address and postal code match _ _ _ F
2013 # International transaction – Address and postal code match _ _ _ D/M
2015 # ACCEPTABLE, BUT ISSUE A WARNING:
2016 # Ineligible transaction; or message contains a content error _ _ _ E
2017 # System unavailable; retry R U R R
2018 # Information unavailable U W U U
2019 # Issuer does not support AVS S U S S
2020 # AVS is not applicable _ _ _ S
2021 # Incompatible formats – Not verified _ _ _ C
2022 # Incompatible formats – Address not verified; postal code matches _ _ _ P
2023 # International transaction – address not verified _ G _ G/I
2025 # UNACCEPTABLE AVS RESPONSES:
2026 # Only Address matches A Y A A
2027 # Only 5-digit postal code matches Z Z Z Z
2028 # Only 9-digit postal code matches Z Z W W
2029 # Neither address nor postal code matches N N N N
2031 if (my $avscode = uc($transaction->avs_code)) {
2033 # map codes to accept/warn/reject
2035 'American Express card' => {
2044 'Discover card' => {
2083 my $cardtype = cardtype($content{card_number});
2084 if ($avs->{$cardtype}) {
2085 my $avsact = $avs->{$cardtype}->{$avscode};
2087 if ($avsact eq 'r') {
2088 return "AVS code verification failed, cardtype $cardtype, code $avscode";
2089 } elsif ($avsact eq 'w') {
2090 $warning = "AVS did not occur, cardtype $cardtype, code $avscode";
2091 } elsif (!$avsact) {
2092 $warning = "AVS code unknown, cardtype $cardtype, code $avscode";
2093 } # else $avsact eq 'a'
2095 $log->warning($warning);
2098 } # else $cardtype avs handling not implemented
2099 } # else !$transaction->avs_code
2101 } else { # is not success
2103 # status is 'done' not 'declined', as in _realtime_bop_result
2104 $cust_pay_pending->status('done');
2105 $error = $transaction->error_message || 'Unknown error';
2106 $cust_pay_pending->statustext($error);
2107 # could also record failure_status here,
2108 # but it's not supported by B::OP::vSecureProcessing...
2109 # need a B::OP module with (reverse) auth only to test it with
2110 my $cpp_declined_err = $cust_pay_pending->replace;
2111 return $cpp_declined_err if $cpp_declined_err;
2115 } # end of IMMEDIATE; we now have our $error and $transaction
2118 # Save the custnum (as part of the main transaction, so it can reference
2122 if (!$cust_pay_pending->custnum) {
2123 $cust_pay_pending->set('custnum', $self->custnum);
2124 my $set_custnum_err = $cust_pay_pending->replace;
2125 if ($set_custnum_err) {
2126 $log->error($set_custnum_err);
2127 $error ||= $set_custnum_err;
2128 # but if there was a real verification error also, return that one
2133 # remove paycvv here? need to find out if a reversed auth
2134 # counts as an initial transaction for paycvv retention requirements
2141 # This block will only run if the B::OP module supports card_token but not the Tokenize transaction;
2142 # if that never happens, we should get rid of it (as it has the potential to store real card numbers on error)
2143 if (my $card_token = $self->_tokenize_card($transaction,\%options)) {
2144 $cust_pay_pending->payinfo($card_token);
2145 my $cpp_token_err = $cust_pay_pending->replace;
2146 #this leaves real card number in cust_pay_pending, but can't do much else if cpp won't replace
2147 return $cpp_token_err if $cpp_token_err;
2148 #important that we not replace cust_payby here,
2149 #because cust_payby->replace uses realtime_verify_bop!
2156 # $error contains the transaction error_message, if is_success was false.
2162 =item realtime_tokenize [ OPTION => VALUE ... ]
2164 If possible and necessary, runs a tokenize transaction.
2165 In order to be possible, a credit card cust_payby record
2166 must be passed and a Business::OnlinePayment gateway capable
2167 of Tokenize transactions must be configured for this user.
2168 Is only necessary if payinfo is not yet tokenized.
2170 Returns the empty string if the authorization was sucessful
2171 or was not possible/necessary (thus allowing this to be safely called with
2172 non-tokenizable records/gateways, without having to perform separate tests),
2173 or an error message otherwise.
2175 Option I<cust_payby> may be passed, even if it's not yet been inserted.
2176 Object will be tokenized if possible, but that change will not be
2177 updated in database (must be inserted/replaced afterwards.)
2179 Otherwise, options I<method>, I<payinfo> and other cust_payby fields
2180 may be passed. If options are passed as a hashref, I<payinfo>
2181 will be updated as appropriate in the passed hashref.
2185 sub realtime_tokenize {
2188 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
2189 my $log = FS::Log->new('FS::cust_main::Billing_Realtime::realtime_tokenize');
2192 my $outoptions; #for returning cust_payby/payinfo
2193 if (ref($_[0]) eq 'HASH') {
2194 %options = %{$_[0]};
2195 $outoptions = $_[0];
2198 $outoptions = \%options;
2201 # set fields from passed cust_payby
2202 $self->_bop_cust_payby_options(\%options);
2203 return '' unless $options{method} eq 'CC';
2204 return '' if $self->tokenized($options{payinfo}); #already tokenized
2210 $options{'nofatal'} = 1;
2211 my $payment_gateway = $self->_payment_gateway( \%options );
2212 return '' unless $payment_gateway;
2213 my $namespace = $payment_gateway->gateway_namespace;
2214 return '' unless $namespace eq 'Business::OnlinePayment';
2216 eval "use $namespace";
2220 # check for tokenize ability
2223 my $transaction = new $namespace( $payment_gateway->gateway_module,
2224 $self->_bop_options(\%options),
2227 my %supported_actions = $transaction->info('supported_actions');
2228 return '' unless $supported_actions{'CC'} and grep(/^Tokenize$/,@{$supported_actions{'CC'}});
2231 # check for banned credit card/ACH
2234 my $ban = FS::banned_pay->ban_search(
2235 'payby' => $bop_method2payby{'CC'},
2236 'payinfo' => $options{payinfo},
2238 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
2244 my $bop_content = $self->_bop_content(\%options);
2245 return $bop_content unless ref($bop_content);
2250 $content{card_number} = $options{payinfo};
2251 $paydate = $options{'paydate'};
2252 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
2253 $content{expiration} = "$2/$1";
2255 $content{cvv2} = $options{'paycvv'}
2256 if length($options{'paycvv'});
2258 my $paystart_month = $options{'paystart_month'};
2259 my $paystart_year = $options{'paystart_year'};
2261 $content{card_start} = "$paystart_month/$paystart_year"
2262 if $paystart_month && $paystart_year;
2264 my $payissue = $options{'payissue'};
2265 $content{issue_number} = $payissue if $payissue;
2273 # no cust_pay_pending---this is not a financial transaction
2275 $transaction->content(
2277 $self->_bop_auth(\%options),
2278 'action' => 'Tokenize',
2279 'description' => $options{'description'},
2280 'customer_id' => $self->custnum,
2285 # no $BOP_TESTING handling for this
2286 $transaction->test_transaction(1)
2287 if $conf->exists('business-onlinepayment-test_transaction');
2288 $transaction->submit();
2290 if ( $transaction->card_token() ) { # no is_success flag
2292 # realtime_tokenize should not clear paycvv at this time. it might be
2293 # needed for the first transaction, and a tokenize isn't actually a
2294 # transaction that hits the gateway. at some point in the future, card
2295 # fortress should take on the "store paycvv until first transaction"
2296 # functionality and we should fix this in freeside, but i that's a bigger
2297 # project for another time.
2299 #important that we not replace cust_payby here,
2300 #because cust_payby->replace uses realtime_tokenize!
2301 $self->_tokenize_card($transaction,$outoptions);
2305 $error = $transaction->error_message || 'Unknown error when tokenizing card';
2314 =item tokenized PAYINFO
2316 Convenience wrapper for L<FS::payinfo_Mixin/tokenized>
2324 my $payinfo = shift;
2325 FS::cust_pay->tokenized($payinfo);
2336 L<FS::cust_main>, L<FS::cust_main::Billing>