1 package FS::cust_main::Billing_Realtime;
4 use vars qw( $conf $DEBUG $me );
5 use vars qw( $realtime_bop_decline_quiet ); #ugh
7 use Business::CreditCard 0.28;
9 use FS::Record qw( qsearch qsearchs );
10 use FS::Misc qw( send_email );
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_collect [ OPTION => VALUE ... ]
50 Attempt to collect the customer's current balance with a realtime credit
51 card or electronic check transaction (see realtime_bop() below).
53 Returns the result of realtime_bop(): nothing, an error message, or a
54 hashref of state information for a third-party transaction.
56 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
58 I<method> is one of: I<CC> or I<ECHECK>. If none is specified
59 then it is deduced from the customer record.
61 If no I<amount> is specified, then the customer balance is used.
63 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
64 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
65 if set, will override the value from the customer record.
67 I<description> is a free-text field passed to the gateway. It defaults to
68 the value defined by the business-onlinepayment-description configuration
69 option, or "Internet services" if that is unset.
71 If an I<invnum> is specified, this payment (if successful) is applied to the
74 I<apply> will automatically apply a resulting payment.
76 I<quiet> can be set true to suppress email decline notices.
78 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
79 resulting paynum, if any.
81 I<payunique> is a unique identifier for this payment.
83 I<session_id> is a session identifier associated with this payment.
85 I<depend_jobnum> allows payment capture to unlock export jobs
89 sub realtime_collect {
90 my( $self, %options ) = @_;
92 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
95 warn "$me realtime_collect:\n";
96 warn " $_ => $options{$_}\n" foreach keys %options;
99 $options{amount} = $self->balance unless exists( $options{amount} );
100 return '' unless $options{amount} > 0;
102 $options{method} = FS::payby->payby2bop($self->payby)
103 unless exists( $options{method} );
105 return $self->realtime_bop({%options});
109 =item realtime_bop { [ ARG => VALUE ... ] }
111 Runs a realtime credit card or ACH (electronic check) transaction
112 via a Business::OnlinePayment realtime gateway. See
113 L<http://420.am/business-onlinepayment> for supported gateways.
115 Required arguments in the hashref are I<method>, and I<amount>
117 Available methods are: I<CC>, I<ECHECK>, or I<PAYPAL>
119 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
121 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
122 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
123 if set, will override the value from the customer record.
125 I<description> is a free-text field passed to the gateway. It defaults to
126 the value defined by the business-onlinepayment-description configuration
127 option, or "Internet services" if that is unset.
129 If an I<invnum> is specified, this payment (if successful) is applied to the
130 specified invoice. If the customer has exactly one open invoice, that
131 invoice number will be assumed. If you don't specify an I<invnum> you might
132 want to call the B<apply_payments> method or set the I<apply> option.
134 I<no_invnum> can be set to true to prevent that default invnum from being set.
136 I<apply> can be set to true to run B<apply_payments_and_credits> on success.
138 I<no_auto_apply> can be set to true to set that flag on the resulting payment
139 (prevents payment from being applied by B<apply_payments> or B<apply_payments_and_credits>,
140 but will still be applied if I<invnum> exists...use with I<no_invnum> for intended effect.)
142 I<quiet> can be set true to surpress email decline notices.
144 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
145 resulting paynum, if any.
147 I<payunique> is a unique identifier for this payment.
149 I<session_id> is a session identifier associated with this payment.
151 I<depend_jobnum> allows payment capture to unlock export jobs
153 I<discount_term> attempts to take a discount by prepaying for discount_term.
154 The payment will fail if I<amount> is incorrect for this discount term.
156 A direct (Business::OnlinePayment) transaction will return nothing on success,
157 or an error message on failure.
159 A third-party transaction will return a hashref containing:
161 - popup_url: the URL to which a browser should be redirected to complete
163 - collectitems: an arrayref of name-value pairs to be posted to popup_url.
164 - reference: a reference ID for the transaction, to show the customer.
166 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
170 # some helper routines
171 sub _bop_recurring_billing {
172 my( $self, %opt ) = @_;
174 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
176 if ( defined($method) && $method eq 'transaction_is_recur' ) {
178 return 1 if $opt{'trans_is_recur'};
182 # return 1 if the payinfo has been used for another payment
183 return $self->payinfo_used($opt{'payinfo'}); # in payinfo_Mixin
191 sub _payment_gateway {
192 my ($self, $options) = @_;
194 if ( $options->{'selfservice'} ) {
195 my $gatewaynum = FS::Conf->new->config('selfservice-payment_gateway');
197 return $options->{payment_gateway} ||=
198 qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
202 if ( $options->{'fake_gatewaynum'} ) {
203 $options->{payment_gateway} =
204 qsearchs('payment_gateway',
205 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
209 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
210 unless exists($options->{payment_gateway});
212 $options->{payment_gateway};
216 my ($self, $options) = @_;
219 'login' => $options->{payment_gateway}->gateway_username,
220 'password' => $options->{payment_gateway}->gateway_password,
225 my ($self, $options) = @_;
227 $options->{payment_gateway}->gatewaynum
228 ? $options->{payment_gateway}->options
229 : @{ $options->{payment_gateway}->get('options') };
234 my ($self, $options) = @_;
236 unless ( $options->{'description'} ) {
237 if ( $conf->exists('business-onlinepayment-description') ) {
238 my $dtempl = $conf->config('business-onlinepayment-description');
240 my $agent = $self->agent->agent;
242 $options->{'description'} = eval qq("$dtempl");
244 $options->{'description'} = 'Internet services';
248 unless ( exists( $options->{'payinfo'} ) ) {
249 $options->{'payinfo'} = $self->payinfo;
250 $options->{'paymask'} = $self->paymask;
253 # Default invoice number if the customer has exactly one open invoice.
254 unless ( $options->{'invnum'} || $options->{'no_invnum'} ) {
255 $options->{'invnum'} = '';
256 my @open = $self->open_cust_bill;
257 $options->{'invnum'} = $open[0]->invnum if scalar(@open) == 1;
260 $options->{payname} = $self->payname unless exists( $options->{payname} );
264 my ($self, $options) = @_;
267 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
268 $content{customer_ip} = $payip if length($payip);
270 $content{invoice_number} = $options->{'invnum'}
271 if exists($options->{'invnum'}) && length($options->{'invnum'});
273 $content{email_customer} =
274 ( $conf->exists('business-onlinepayment-email_customer')
275 || $conf->exists('business-onlinepayment-email-override') );
277 my ($payname, $payfirst, $paylast);
278 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
279 ($payname = $options->{payname}) =~
280 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
281 or return "Illegal payname $payname";
282 ($payfirst, $paylast) = ($1, $2);
284 $payfirst = $self->getfield('first');
285 $paylast = $self->getfield('last');
286 $payname = "$payfirst $paylast";
289 $content{last_name} = $paylast;
290 $content{first_name} = $payfirst;
292 $content{name} = $payname;
294 $content{address} = exists($options->{'address1'})
295 ? $options->{'address1'}
297 my $address2 = exists($options->{'address2'})
298 ? $options->{'address2'}
300 $content{address} .= ", ". $address2 if length($address2);
302 $content{city} = exists($options->{city})
305 $content{state} = exists($options->{state})
308 $content{zip} = exists($options->{zip})
311 $content{country} = exists($options->{country})
312 ? $options->{country}
315 #3.0 is a good a time as any to get rid of this... add a config to pass it
316 # if anyone still needs it
317 #$content{referer} = 'http://cleanwhisker.420.am/';
319 $content{phone} = $self->daytime || $self->night;
321 my $currency = $conf->exists('business-onlinepayment-currency')
322 && $conf->config('business-onlinepayment-currency');
323 $content{currency} = $currency if $currency;
328 my %bop_method2payby = (
337 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
340 if (ref($_[0]) eq 'HASH') {
343 my ( $method, $amount ) = ( shift, shift );
345 $options{method} = $method;
346 $options{amount} = $amount;
351 # optional credit card surcharge
354 my $cc_surcharge = 0;
355 my $cc_surcharge_pct = 0;
356 $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage')
357 if $conf->config('credit-card-surcharge-percentage')
358 && $options{method} eq 'CC';
360 # always add cc surcharge if called from event
361 if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
362 $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
363 $options{'amount'} += $cc_surcharge;
364 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
366 elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a
367 # payment screen), so consider the given
368 # amount as post-surcharge
369 $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
372 $cc_surcharge = sprintf("%.2f",$cc_surcharge) if $cc_surcharge > 0;
373 $options{'cc_surcharge'} = $cc_surcharge;
377 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
378 warn " cc_surcharge = $cc_surcharge\n";
381 warn " $_ => $options{$_}\n" foreach keys %options;
384 return $self->fake_bop(\%options) if $options{'fake'};
386 $self->_bop_defaults(\%options);
389 # set trans_is_recur based on invnum if there is one
392 my $trans_is_recur = 0;
393 if ( $options{'invnum'} ) {
395 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
396 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
402 $cust_bill->cust_bill_pkg;
405 if grep { $_->freq ne '0' } @part_pkg;
413 my $payment_gateway = $self->_payment_gateway( \%options );
414 my $namespace = $payment_gateway->gateway_namespace;
416 eval "use $namespace";
420 # check for banned credit card/ACH
423 my $ban = FS::banned_pay->ban_search(
424 'payby' => $bop_method2payby{$options{method}},
425 'payinfo' => $options{payinfo},
427 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
430 # check for term discount validity
433 my $discount_term = $options{discount_term};
434 if ( $discount_term ) {
435 my $bill = ($self->cust_bill)[-1]
436 or return "Can't apply a term discount to an unbilled customer";
437 my $plan = FS::discount_plan->new(
439 months => $discount_term
440 ) or return "No discount available for term '$discount_term'";
442 if ( $plan->discounted_total != $options{amount} ) {
443 return "Incorrect term prepayment amount (term $discount_term, amount $options{amount}, requires ".$plan->discounted_total.")";
451 my $bop_content = $self->_bop_content(\%options);
452 return $bop_content unless ref($bop_content);
454 my @invoicing_list = $self->invoicing_list_emailonly;
455 if ( $conf->exists('emailinvoiceautoalways')
456 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
457 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
458 push @invoicing_list, $self->all_emails;
461 my $email = ($conf->exists('business-onlinepayment-email-override'))
462 ? $conf->config('business-onlinepayment-email-override')
463 : $invoicing_list[0];
468 if ( $namespace eq 'Business::OnlinePayment' ) {
470 if ( $options{method} eq 'CC' ) {
472 $content{card_number} = $options{payinfo};
473 $paydate = exists($options{'paydate'})
474 ? $options{'paydate'}
476 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
477 $content{expiration} = "$2/$1";
479 my $paycvv = exists($options{'paycvv'})
482 $content{cvv2} = $paycvv
485 my $paystart_month = exists($options{'paystart_month'})
486 ? $options{'paystart_month'}
487 : $self->paystart_month;
489 my $paystart_year = exists($options{'paystart_year'})
490 ? $options{'paystart_year'}
491 : $self->paystart_year;
493 $content{card_start} = "$paystart_month/$paystart_year"
494 if $paystart_month && $paystart_year;
496 my $payissue = exists($options{'payissue'})
497 ? $options{'payissue'}
499 $content{issue_number} = $payissue if $payissue;
501 if ( $self->_bop_recurring_billing(
502 'payinfo' => $options{'payinfo'},
503 'trans_is_recur' => $trans_is_recur,
507 $content{recurring_billing} = 'YES';
508 $content{acct_code} = 'rebill'
509 if $conf->exists('credit_card-recurring_billing_acct_code');
512 } elsif ( $options{method} eq 'ECHECK' ){
514 ( $content{account_number}, $content{routing_code} ) =
515 split('@', $options{payinfo});
516 $content{bank_name} = $options{payname};
517 $content{bank_state} = exists($options{'paystate'})
518 ? $options{'paystate'}
519 : $self->getfield('paystate');
520 $content{account_type}=
521 (exists($options{'paytype'}) && $options{'paytype'})
522 ? uc($options{'paytype'})
523 : uc($self->getfield('paytype')) || 'PERSONAL CHECKING';
525 if ( $content{account_type} =~ /BUSINESS/i && $self->company ) {
526 $content{account_name} = $self->company;
528 $content{account_name} = $self->getfield('first'). ' '.
529 $self->getfield('last');
532 $content{customer_org} = $self->company ? 'B' : 'I';
533 $content{state_id} = exists($options{'stateid'})
534 ? $options{'stateid'}
535 : $self->getfield('stateid');
536 $content{state_id_state} = exists($options{'stateid_state'})
537 ? $options{'stateid_state'}
538 : $self->getfield('stateid_state');
539 $content{customer_ssn} = exists($options{'ss'})
544 die "unknown method ". $options{method};
547 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
550 die "unknown namespace $namespace";
557 my $balance = exists( $options{'balance'} )
558 ? $options{'balance'}
561 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
562 $self->select_for_update; #mutex ... just until we get our pending record in
563 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
565 #the checks here are intended to catch concurrent payments
566 #double-form-submission prevention is taken care of in cust_pay_pending::check
569 return "The customer's balance has changed; $options{method} transaction aborted."
570 if $self->balance < $balance;
572 #also check and make sure there aren't *other* pending payments for this cust
574 my @pending = qsearch('cust_pay_pending', {
575 'custnum' => $self->custnum,
576 'status' => { op=>'!=', value=>'done' }
579 #for third-party payments only, remove pending payments if they're in the
580 #'thirdparty' (waiting for customer action) state.
581 if ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
582 foreach ( grep { $_->status eq 'thirdparty' } @pending ) {
583 my $error = $_->delete;
584 warn "error deleting unfinished third-party payment ".
585 $_->paypendingnum . ": $error\n"
588 @pending = grep { $_->status ne 'thirdparty' } @pending;
591 return "A payment is already being processed for this customer (".
592 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
593 "); $options{method} transaction aborted."
596 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
598 my $cust_pay_pending = new FS::cust_pay_pending {
599 'custnum' => $self->custnum,
600 'paid' => $options{amount},
602 'payby' => $bop_method2payby{$options{method}},
603 'payinfo' => $options{payinfo},
604 'paymask' => $options{paymask},
605 'paydate' => $paydate,
606 'recurring_billing' => $content{recurring_billing},
607 'pkgnum' => $options{'pkgnum'},
609 'gatewaynum' => $payment_gateway->gatewaynum || '',
610 'session_id' => $options{session_id} || '',
611 'jobnum' => $options{depend_jobnum} || '',
613 $cust_pay_pending->payunique( $options{payunique} )
614 if defined($options{payunique}) && length($options{payunique});
616 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
618 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
619 return $cpp_new_err if $cpp_new_err;
621 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
623 warn Dumper($cust_pay_pending) if $DEBUG > 2;
625 my( $action1, $action2 ) =
626 split( /\s*\,\s*/, $payment_gateway->gateway_action );
628 my $transaction = new $namespace( $payment_gateway->gateway_module,
629 $self->_bop_options(\%options),
632 $transaction->content(
633 'type' => $options{method},
634 $self->_bop_auth(\%options),
635 'action' => $action1,
636 'description' => $options{'description'},
637 'amount' => $options{amount},
638 #'invoice_number' => $options{'invnum'},
639 'customer_id' => $self->custnum,
641 'reference' => $cust_pay_pending->paypendingnum, #for now
642 'callback_url' => $payment_gateway->gateway_callback_url,
643 'cancel_url' => $payment_gateway->gateway_cancel_url,
648 $cust_pay_pending->status('pending');
649 my $cpp_pending_err = $cust_pay_pending->replace;
650 return $cpp_pending_err if $cpp_pending_err;
652 warn Dumper($transaction) if $DEBUG > 2;
654 unless ( $BOP_TESTING ) {
655 $transaction->test_transaction(1)
656 if $conf->exists('business-onlinepayment-test_transaction');
657 $transaction->submit();
659 if ( $BOP_TESTING_SUCCESS ) {
660 $transaction->is_success(1);
661 $transaction->authorization('fake auth');
663 $transaction->is_success(0);
664 $transaction->error_message('fake failure');
668 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
670 $cust_pay_pending->status('thirdparty');
671 my $cpp_err = $cust_pay_pending->replace;
672 return { error => $cpp_err } if $cpp_err;
673 return { reference => $cust_pay_pending->paypendingnum,
674 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
676 } elsif ( $transaction->is_success() && $action2 ) {
678 $cust_pay_pending->status('authorized');
679 my $cpp_authorized_err = $cust_pay_pending->replace;
680 return $cpp_authorized_err if $cpp_authorized_err;
682 my $auth = $transaction->authorization;
683 my $ordernum = $transaction->can('order_number')
684 ? $transaction->order_number
688 new Business::OnlinePayment( $payment_gateway->gateway_module,
689 $self->_bop_options(\%options),
694 type => $options{method},
696 $self->_bop_auth(\%options),
697 order_number => $ordernum,
698 amount => $options{amount},
699 authorization => $auth,
700 description => $options{'description'},
703 foreach my $field (qw( authorization_source_code returned_ACI
704 transaction_identifier validation_code
705 transaction_sequence_num local_transaction_date
706 local_transaction_time AVS_result_code )) {
707 $capture{$field} = $transaction->$field() if $transaction->can($field);
710 $capture->content( %capture );
712 $capture->test_transaction(1)
713 if $conf->exists('business-onlinepayment-test_transaction');
716 unless ( $capture->is_success ) {
717 my $e = "Authorization successful but capture failed, custnum #".
718 $self->custnum. ': '. $capture->result_code.
719 ": ". $capture->error_message;
727 # remove paycvv after initial transaction
730 #false laziness w/misc/process/payment.cgi - check both to make sure working
732 if ( length($self->paycvv)
733 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
735 my $error = $self->remove_cvv;
737 warn "WARNING: error removing cvv: $error\n";
746 if ( $transaction->can('card_token') && $transaction->card_token ) {
748 if ( $options{'payinfo'} eq $self->payinfo ) {
749 $self->payinfo($transaction->card_token);
750 my $error = $self->replace;
752 warn "WARNING: error storing token: $error, but proceeding anyway\n";
762 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
774 if (ref($_[0]) eq 'HASH') {
777 my ( $method, $amount ) = ( shift, shift );
779 $options{method} = $method;
780 $options{amount} = $amount;
783 if ( $options{'fake_failure'} ) {
784 return "Error: No error; test failure requested with fake_failure";
787 my $cust_pay = new FS::cust_pay ( {
788 'custnum' => $self->custnum,
789 'invnum' => $options{'invnum'},
790 'paid' => $options{amount},
792 'payby' => $bop_method2payby{$options{method}},
793 #'payinfo' => $payinfo,
794 'payinfo' => '4111111111111111',
795 #'paydate' => $paydate,
796 'paydate' => '2012-05-01',
797 'processor' => 'FakeProcessor',
799 'order_number' => '32',
801 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
804 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
805 warn " $_ => $options{$_}\n" foreach keys %options;
808 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
811 $cust_pay->invnum(''); #try again with no specific invnum
812 my $error2 = $cust_pay->insert( $options{'manual'} ?
813 ( 'manual' => 1 ) : ()
816 # gah, even with transactions.
817 my $e = 'WARNING: Card/ACH debited but database not updated - '.
818 "error inserting (fake!) payment: $error2".
819 " (previously tried insert with invnum #$options{'invnum'}" .
826 if ( $options{'paynum_ref'} ) {
827 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
835 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
837 # Wraps up processing of a realtime credit card or ACH (electronic check)
840 sub _realtime_bop_result {
841 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
843 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
846 warn "$me _realtime_bop_result: pending transaction ".
847 $cust_pay_pending->paypendingnum. "\n";
848 warn " $_ => $options{$_}\n" foreach keys %options;
851 my $payment_gateway = $options{payment_gateway}
852 or return "no payment gateway in arguments to _realtime_bop_result";
854 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
855 my $cpp_captured_err = $cust_pay_pending->replace;
856 return $cpp_captured_err if $cpp_captured_err;
858 if ( $transaction->is_success() ) {
860 my $order_number = $transaction->order_number
861 if $transaction->can('order_number');
863 my $cust_pay = new FS::cust_pay ( {
864 'custnum' => $self->custnum,
865 'invnum' => $options{'invnum'},
866 'paid' => $cust_pay_pending->paid,
868 'payby' => $cust_pay_pending->payby,
869 'payinfo' => $options{'payinfo'},
870 'paymask' => $options{'paymask'} || $cust_pay_pending->paymask,
871 'paydate' => $cust_pay_pending->paydate,
872 'pkgnum' => $cust_pay_pending->pkgnum,
873 'discount_term' => $options{'discount_term'},
874 'gatewaynum' => ($payment_gateway->gatewaynum || ''),
875 'processor' => $payment_gateway->gateway_module,
876 'auth' => $transaction->authorization,
877 'order_number' => $order_number || '',
878 'no_auto_apply' => $options{'no_auto_apply'} ? 'Y' : '',
880 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
881 $cust_pay->payunique( $options{payunique} )
882 if defined($options{payunique}) && length($options{payunique});
884 my $oldAutoCommit = $FS::UID::AutoCommit;
885 local $FS::UID::AutoCommit = 0;
888 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
890 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
893 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
894 $cust_pay->invnum(''); #try again with no specific invnum
895 $cust_pay->paynum('');
896 my $error2 = $cust_pay->insert( $options{'manual'} ?
897 ( 'manual' => 1 ) : ()
900 # gah. but at least we have a record of the state we had to abort in
901 # from cust_pay_pending now.
902 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
903 my $e = "WARNING: $options{method} captured but payment not recorded -".
904 " error inserting payment (". $payment_gateway->gateway_module.
906 " (previously tried insert with invnum #$options{'invnum'}" .
907 ": $error ) - pending payment saved as paypendingnum ".
908 $cust_pay_pending->paypendingnum. "\n";
914 my $jobnum = $cust_pay_pending->jobnum;
916 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
918 unless ( $placeholder ) {
919 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
920 my $e = "WARNING: $options{method} captured but job $jobnum not ".
921 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
926 $error = $placeholder->delete;
929 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
930 my $e = "WARNING: $options{method} captured but could not delete ".
931 "job $jobnum for paypendingnum ".
932 $cust_pay_pending->paypendingnum. ": $error\n";
939 if ( $options{'paynum_ref'} ) {
940 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
943 $cust_pay_pending->status('done');
944 $cust_pay_pending->statustext('captured');
945 $cust_pay_pending->paynum($cust_pay->paynum);
946 my $cpp_done_err = $cust_pay_pending->replace;
948 if ( $cpp_done_err ) {
950 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
951 my $e = "WARNING: $options{method} captured but payment not recorded - ".
952 "error updating status for paypendingnum ".
953 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
959 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
961 if ( $options{'apply'} ) {
962 my $apply_error = $self->apply_payments_and_credits;
963 if ( $apply_error ) {
964 warn "WARNING: error applying payment: $apply_error\n";
965 #but we still should return no error cause the payment otherwise went
970 # have a CC surcharge portion --> one-time charge
971 if ( $options{'cc_surcharge'} > 0 ) {
972 # XXX: this whole block needs to be in a transaction?
975 $invnum = $options{'invnum'} if $options{'invnum'};
976 unless ( $invnum ) { # probably from a payment screen
977 # do we have any open invoices? pick earliest
978 # uses the fact that cust_main->cust_bill sorts by date ascending
979 my @open = $self->open_cust_bill;
980 $invnum = $open[0]->invnum if scalar(@open);
983 unless ( $invnum ) { # still nothing? pick last closed invoice
984 # again uses fact that cust_main->cust_bill sorts by date ascending
985 my @closed = $self->cust_bill;
986 $invnum = $closed[$#closed]->invnum if scalar(@closed);
990 # XXX: unlikely case - pre-paying before any invoices generated
991 # what it should do is create a new invoice and pick it
992 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
997 my $charge_error = $self->charge({
998 'amount' => $options{'cc_surcharge'},
999 'pkg' => 'Credit Card Surcharge',
1001 'cust_pkg_ref' => \$cust_pkg,
1004 warn 'Unable to add CC surcharge cust_pkg';
1008 $cust_pkg->setup(time);
1009 my $cp_error = $cust_pkg->replace;
1011 warn 'Unable to set setup time on cust_pkg for cc surcharge';
1015 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
1016 unless ( $cust_bill ) {
1017 warn "race condition + invoice deletion just happened";
1022 $cust_bill->add_cc_surcharge($cust_pkg->pkgnum,$options{'cc_surcharge'});
1024 warn "cannot add CC surcharge to invoice #$invnum: $grand_error"
1028 return ''; #no error
1034 my $perror = $payment_gateway->gateway_module. " error: ".
1035 $transaction->error_message;
1037 my $jobnum = $cust_pay_pending->jobnum;
1039 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
1041 if ( $placeholder ) {
1042 my $error = $placeholder->depended_delete;
1043 $error ||= $placeholder->delete;
1044 warn "error removing provisioning jobs after declined paypendingnum ".
1045 $cust_pay_pending->paypendingnum. ": $error\n";
1047 my $e = "error finding job $jobnum for declined paypendingnum ".
1048 $cust_pay_pending->paypendingnum. "\n";
1054 unless ( $transaction->error_message ) {
1057 if ( $transaction->can('response_page') ) {
1059 'page' => ( $transaction->can('response_page')
1060 ? $transaction->response_page
1063 'code' => ( $transaction->can('response_code')
1064 ? $transaction->response_code
1067 'headers' => ( $transaction->can('response_headers')
1068 ? $transaction->response_headers
1074 "No additional debugging information available for ".
1075 $payment_gateway->gateway_module;
1078 $perror .= "No error_message returned from ".
1079 $payment_gateway->gateway_module. " -- ".
1080 ( ref($t_response) ? Dumper($t_response) : $t_response );
1084 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1085 && $conf->exists('emaildecline', $self->agentnum)
1086 && grep { $_ ne 'POST' } $self->invoicing_list
1087 && ! grep { $transaction->error_message =~ /$_/ }
1088 $conf->config('emaildecline-exclude', $self->agentnum)
1091 # Send a decline alert to the customer.
1092 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1095 # include the raw error message in the transaction state
1096 $cust_pay_pending->setfield('error', $transaction->error_message);
1097 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1098 $error = $msg_template->send( 'cust_main' => $self,
1099 'object' => $cust_pay_pending );
1103 my @templ = $conf->config('declinetemplate');
1104 my $template = new Text::Template (
1106 SOURCE => [ map "$_\n", @templ ],
1107 ) or return "($perror) can't create template: $Text::Template::ERROR";
1108 $template->compile()
1109 or return "($perror) can't compile template: $Text::Template::ERROR";
1113 scalar( $conf->config('company_name', $self->agentnum ) ),
1114 'company_address' =>
1115 join("\n", $conf->config('company_address', $self->agentnum ) ),
1116 'error' => $transaction->error_message,
1119 my $error = send_email(
1120 'from' => $conf->invoice_from_full( $self->agentnum ),
1121 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
1122 'subject' => 'Your payment could not be processed',
1123 'body' => [ $template->fill_in(HASH => $templ_hash) ],
1127 $perror .= " (also received error sending decline notification: $error)"
1132 $cust_pay_pending->status('done');
1133 $cust_pay_pending->statustext("declined: $perror");
1134 my $cpp_done_err = $cust_pay_pending->replace;
1135 if ( $cpp_done_err ) {
1136 my $e = "WARNING: $options{method} declined but pending payment not ".
1137 "resolved - error updating status for paypendingnum ".
1138 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1140 $perror = "$e ($perror)";
1148 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1150 Verifies successful third party processing of a realtime credit card or
1151 ACH (electronic check) transaction via a
1152 Business::OnlineThirdPartyPayment realtime gateway. See
1153 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1155 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1157 The additional options I<payname>, I<city>, I<state>,
1158 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1159 if set, will override the value from the customer record.
1161 I<description> is a free-text field passed to the gateway. It defaults to
1162 "Internet services".
1164 If an I<invnum> is specified, this payment (if successful) is applied to the
1165 specified invoice. If you don't specify an I<invnum> you might want to
1166 call the B<apply_payments> method.
1168 I<quiet> can be set true to surpress email decline notices.
1170 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1171 resulting paynum, if any.
1173 I<payunique> is a unique identifier for this payment.
1175 Returns a hashref containing elements bill_error (which will be undefined
1176 upon success) and session_id of any associated session.
1180 sub realtime_botpp_capture {
1181 my( $self, $cust_pay_pending, %options ) = @_;
1183 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1186 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1187 warn " $_ => $options{$_}\n" foreach keys %options;
1190 eval "use Business::OnlineThirdPartyPayment";
1194 # select the gateway
1197 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1199 my $payment_gateway;
1200 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1201 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1202 { gatewaynum => $gatewaynum }
1204 : $self->agent->payment_gateway( 'method' => $method,
1205 # 'invnum' => $cust_pay_pending->invnum,
1206 # 'payinfo' => $cust_pay_pending->payinfo,
1209 $options{payment_gateway} = $payment_gateway; # for the helper subs
1215 my @invoicing_list = $self->invoicing_list_emailonly;
1216 if ( $conf->exists('emailinvoiceautoalways')
1217 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1218 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1219 push @invoicing_list, $self->all_emails;
1222 my $email = ($conf->exists('business-onlinepayment-email-override'))
1223 ? $conf->config('business-onlinepayment-email-override')
1224 : $invoicing_list[0];
1228 $content{email_customer} =
1229 ( $conf->exists('business-onlinepayment-email_customer')
1230 || $conf->exists('business-onlinepayment-email-override') );
1233 # run transaction(s)
1237 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1238 $self->_bop_options(\%options),
1241 $transaction->reference({ %options });
1243 $transaction->content(
1245 $self->_bop_auth(\%options),
1246 'action' => 'Post Authorization',
1247 'description' => $options{'description'},
1248 'amount' => $cust_pay_pending->paid,
1249 #'invoice_number' => $options{'invnum'},
1250 'customer_id' => $self->custnum,
1252 #3.0 is a good a time as any to get rid of this... add a config to pass it
1253 # if anyone still needs it
1254 #'referer' => 'http://cleanwhisker.420.am/',
1256 'reference' => $cust_pay_pending->paypendingnum,
1258 'phone' => $self->daytime || $self->night,
1260 # plus whatever is required for bogus capture avoidance
1263 $transaction->submit();
1266 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1268 if ( $options{'apply'} ) {
1269 my $apply_error = $self->apply_payments_and_credits;
1270 if ( $apply_error ) {
1271 warn "WARNING: error applying payment: $apply_error\n";
1276 bill_error => $error,
1277 session_id => $cust_pay_pending->session_id,
1282 =item default_payment_gateway
1284 DEPRECATED -- use agent->payment_gateway
1288 sub default_payment_gateway {
1289 my( $self, $method ) = @_;
1291 die "Real-time processing not enabled\n"
1292 unless $conf->exists('business-onlinepayment');
1294 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1297 my $bop_config = 'business-onlinepayment';
1298 $bop_config .= '-ach'
1299 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1300 my ( $processor, $login, $password, $action, @bop_options ) =
1301 $conf->config($bop_config);
1302 $action ||= 'normal authorization';
1303 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1304 die "No real-time processor is enabled - ".
1305 "did you set the business-onlinepayment configuration value?\n"
1308 ( $processor, $login, $password, $action, @bop_options )
1311 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1313 Refunds a realtime credit card or ACH (electronic check) transaction
1314 via a Business::OnlinePayment realtime gateway. See
1315 L<http://420.am/business-onlinepayment> for supported gateways.
1317 Available methods are: I<CC> or I<ECHECK>
1319 Available options are: I<amount>, I<reasonnum>, I<paynum>, I<paydate>
1321 Most gateways require a reference to an original payment transaction to refund,
1322 so you probably need to specify a I<paynum>.
1324 I<amount> defaults to the original amount of the payment if not specified.
1326 I<reasonnum> specifies a reason for the refund.
1328 I<paydate> specifies the expiration date for a credit card overriding the
1329 value from the customer record or the payment record. Specified as yyyy-mm-dd
1331 Implementation note: If I<amount> is unspecified or equal to the amount of the
1332 orignal payment, first an attempt is made to "void" the transaction via
1333 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1334 the normal attempt is made to "refund" ("credit") the transaction via the
1335 gateway is attempted. No attempt to "void" the transaction is made if the
1336 gateway has introspection data and doesn't support void.
1338 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1339 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1340 #if set, will override the value from the customer record.
1342 #If an I<invnum> is specified, this payment (if successful) is applied to the
1343 #specified invoice. If you don't specify an I<invnum> you might want to
1344 #call the B<apply_payments> method.
1348 #some false laziness w/realtime_bop, not enough to make it worth merging
1349 #but some useful small subs should be pulled out
1350 sub realtime_refund_bop {
1353 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1356 if (ref($_[0]) eq 'HASH') {
1357 %options = %{$_[0]};
1361 $options{method} = $method;
1364 my ($reason, $reason_text);
1365 if ( $options{'reasonnum'} ) {
1366 # do this here, because we need the plain text reason string in case we
1368 $reason = FS::reason->by_key($options{'reasonnum'});
1369 $reason_text = $reason->reason;
1371 # support old 'reason' string parameter in case it's still used,
1372 # or else set a default
1373 $reason_text = $options{'reason'} || 'card or ACH refund';
1375 $reason = FS::reason->new_or_existing(
1376 reason => $reason_text,
1377 type => 'Refund reason',
1381 return "failed to add refund reason: $@";
1386 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1387 warn " $_ => $options{$_}\n" foreach keys %options;
1393 # look up the original payment and optionally a gateway for that payment
1397 my $amount = $options{'amount'};
1399 my( $processor, $login, $password, @bop_options, $namespace ) ;
1400 my( $auth, $order_number ) = ( '', '', '' );
1401 my $gatewaynum = '';
1403 if ( $options{'paynum'} ) {
1405 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1406 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1407 or return "Unknown paynum $options{'paynum'}";
1408 $amount ||= $cust_pay->paid;
1410 my @cust_bill_pay = qsearch('cust_bill_pay', { paynum=>$cust_pay->paynum });
1411 $content{'invoice_number'} = $cust_bill_pay[0]->invnum if @cust_bill_pay;
1413 if ( $cust_pay->get('processor') ) {
1414 ($gatewaynum, $processor, $auth, $order_number) =
1416 $cust_pay->gatewaynum,
1417 $cust_pay->processor,
1419 $cust_pay->order_number,
1422 # this payment wasn't upgraded, which probably means this won't work,
1424 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1425 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1426 $cust_pay->paybatch;
1427 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1430 if ( $gatewaynum ) { #gateway for the payment to be refunded
1432 my $payment_gateway =
1433 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1434 die "payment gateway $gatewaynum not found"
1435 unless $payment_gateway;
1437 $processor = $payment_gateway->gateway_module;
1438 $login = $payment_gateway->gateway_username;
1439 $password = $payment_gateway->gateway_password;
1440 $namespace = $payment_gateway->gateway_namespace;
1441 @bop_options = $payment_gateway->options;
1443 } else { #try the default gateway
1446 my $payment_gateway =
1447 $self->agent->payment_gateway('method' => $options{method});
1449 ( $conf_processor, $login, $password, $namespace ) =
1450 map { my $method = "gateway_$_"; $payment_gateway->$method }
1451 qw( module username password namespace );
1453 @bop_options = $payment_gateway->gatewaynum
1454 ? $payment_gateway->options
1455 : @{ $payment_gateway->get('options') };
1457 return "processor of payment $options{'paynum'} $processor does not".
1458 " match default processor $conf_processor"
1459 unless $processor eq $conf_processor;
1464 } else { # didn't specify a paynum, so look for agent gateway overrides
1465 # like a normal transaction
1467 my $payment_gateway =
1468 $self->agent->payment_gateway( 'method' => $options{method},
1469 #'payinfo' => $payinfo,
1471 my( $processor, $login, $password, $namespace ) =
1472 map { my $method = "gateway_$_"; $payment_gateway->$method }
1473 qw( module username password namespace );
1475 my @bop_options = $payment_gateway->gatewaynum
1476 ? $payment_gateway->options
1477 : @{ $payment_gateway->get('options') };
1480 return "neither amount nor paynum specified" unless $amount;
1482 eval "use $namespace";
1487 'type' => $options{method},
1489 'password' => $password,
1490 'order_number' => $order_number,
1491 'amount' => $amount,
1493 #3.0 is a good a time as any to get rid of this... add a config to pass it
1494 # if anyone still needs it
1495 #'referer' => 'http://cleanwhisker.420.am/',
1497 $content{authorization} = $auth
1498 if length($auth); #echeck/ACH transactions have an order # but no auth
1499 #(at least with authorize.net)
1501 my $currency = $conf->exists('business-onlinepayment-currency')
1502 && $conf->config('business-onlinepayment-currency');
1503 $content{currency} = $currency if $currency;
1505 my $disable_void_after;
1506 if ($conf->exists('disable_void_after')
1507 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1508 $disable_void_after = $1;
1511 #first try void if applicable
1512 my $void = new Business::OnlinePayment( $processor, @bop_options );
1515 if ($void->can('info')) {
1517 $paytype = 'ECHECK' if $cust_pay && $cust_pay->payby eq 'CHEK';
1518 $paytype = 'CC' if $cust_pay && $cust_pay->payby eq 'CARD';
1519 my %supported_actions = $void->info('supported_actions');
1521 if ( %supported_actions && $paytype
1522 && defined($supported_actions{$paytype})
1523 && !grep{ $_ eq 'Void' } @{$supported_actions{$paytype}} );
1526 if ( $cust_pay && $cust_pay->paid == $amount
1528 ( not defined($disable_void_after) )
1529 || ( time < ($cust_pay->_date + $disable_void_after ) )
1533 warn " attempting void\n" if $DEBUG > 1;
1534 if ( $void->can('info') ) {
1535 if ( $cust_pay->payby eq 'CARD'
1536 && $void->info('CC_void_requires_card') )
1538 $content{'card_number'} = $cust_pay->payinfo;
1539 } elsif ( $cust_pay->payby eq 'CHEK'
1540 && $void->info('ECHECK_void_requires_account') )
1542 ( $content{'account_number'}, $content{'routing_code'} ) =
1543 split('@', $cust_pay->payinfo);
1544 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1547 $void->content( 'action' => 'void', %content );
1548 $void->test_transaction(1)
1549 if $conf->exists('business-onlinepayment-test_transaction');
1551 if ( $void->is_success ) {
1552 my $error = $cust_pay->void($reason_text);
1554 # gah, even with transactions.
1555 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1556 "error voiding payment: $error";
1560 warn " void successful\n" if $DEBUG > 1;
1565 warn " void unsuccessful, trying refund\n"
1569 my $address = $self->address1;
1570 $address .= ", ". $self->address2 if $self->address2;
1572 my($payname, $payfirst, $paylast);
1573 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1574 $payname = $self->payname;
1575 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1576 or return "Illegal payname $payname";
1577 ($payfirst, $paylast) = ($1, $2);
1579 $payfirst = $self->getfield('first');
1580 $paylast = $self->getfield('last');
1581 $payname = "$payfirst $paylast";
1584 my @invoicing_list = $self->invoicing_list_emailonly;
1585 if ( $conf->exists('emailinvoiceautoalways')
1586 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1587 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1588 push @invoicing_list, $self->all_emails;
1591 my $email = ($conf->exists('business-onlinepayment-email-override'))
1592 ? $conf->config('business-onlinepayment-email-override')
1593 : $invoicing_list[0];
1595 my $payip = exists($options{'payip'})
1598 $content{customer_ip} = $payip
1602 if ( $options{method} eq 'CC' ) {
1605 $content{card_number} = $payinfo = $cust_pay->payinfo;
1606 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1607 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1608 ($content{expiration} = "$2/$1"); # where available
1610 $content{card_number} = $payinfo = $self->payinfo;
1611 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1612 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1613 $content{expiration} = "$2/$1";
1616 } elsif ( $options{method} eq 'ECHECK' ) {
1619 $payinfo = $cust_pay->payinfo;
1621 $payinfo = $self->payinfo;
1623 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1624 $content{bank_name} = $self->payname;
1625 $content{account_type} = 'CHECKING';
1626 $content{account_name} = $payname;
1627 $content{customer_org} = $self->company ? 'B' : 'I';
1628 $content{customer_ssn} = $self->ss;
1633 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1634 my %sub_content = $refund->content(
1635 'action' => 'credit',
1636 'customer_id' => $self->custnum,
1637 'last_name' => $paylast,
1638 'first_name' => $payfirst,
1640 'address' => $address,
1641 'city' => $self->city,
1642 'state' => $self->state,
1643 'zip' => $self->zip,
1644 'country' => $self->country,
1646 'phone' => $self->daytime || $self->night,
1649 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1651 $refund->test_transaction(1)
1652 if $conf->exists('business-onlinepayment-test_transaction');
1655 return "$processor error: ". $refund->error_message
1656 unless $refund->is_success();
1658 $order_number = $refund->order_number if $refund->can('order_number');
1660 # change this to just use $cust_pay->delete_cust_bill_pay?
1661 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1662 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1663 last unless @cust_bill_pay;
1664 my $cust_bill_pay = pop @cust_bill_pay;
1665 my $error = $cust_bill_pay->delete;
1669 my $cust_refund = new FS::cust_refund ( {
1670 'custnum' => $self->custnum,
1671 'paynum' => $options{'paynum'},
1672 'source_paynum' => $options{'paynum'},
1673 'refund' => $amount,
1675 'payby' => $bop_method2payby{$options{method}},
1676 'payinfo' => $payinfo,
1677 'reasonnum' => $reason->reasonnum,
1678 'gatewaynum' => $gatewaynum, # may be null
1679 'processor' => $processor,
1680 'auth' => $refund->authorization,
1681 'order_number' => $order_number,
1683 my $error = $cust_refund->insert;
1685 $cust_refund->paynum(''); #try again with no specific paynum
1686 $cust_refund->source_paynum('');
1687 my $error2 = $cust_refund->insert;
1689 # gah, even with transactions.
1690 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1691 "error inserting refund ($processor): $error2".
1692 " (previously tried insert with paynum #$options{'paynum'}" .
1703 =item realtime_verify_bop [ OPTION => VALUE ... ]
1705 Runs an authorization-only transaction for $1 against this credit card (if
1706 successful, immediatly reverses the authorization).
1708 Returns the empty string if the authorization was sucessful, or an error
1715 I<paydate> specifies the expiration date for a credit card overriding the
1716 value from the customer record or the payment record. Specified as yyyy-mm-dd
1718 #The additional options I<address1>, I<address2>, I<city>, I<state>,
1719 #I<zip> are also available. Any of these options,
1720 #if set, will override the value from the customer record.
1724 #Available methods are: I<CC> or I<ECHECK>
1726 #some false laziness w/realtime_bop and realtime_refund_bop, not enough to make
1727 #it worth merging but some useful small subs should be pulled out
1728 sub realtime_verify_bop {
1731 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1734 if (ref($_[0]) eq 'HASH') {
1735 %options = %{$_[0]};
1741 warn "$me realtime_verify_bop\n";
1742 warn " $_ => $options{$_}\n" foreach keys %options;
1749 my $payment_gateway = $self->_payment_gateway( \%options );
1750 my $namespace = $payment_gateway->gateway_namespace;
1752 eval "use $namespace";
1756 # check for banned credit card/ACH
1759 my $ban = FS::banned_pay->ban_search(
1760 'payby' => $bop_method2payby{'CC'},
1761 'payinfo' => $options{payinfo} || $self->payinfo,
1763 return "Banned credit card" if $ban && $ban->bantype ne 'warn';
1769 my $bop_content = $self->_bop_content(\%options);
1770 return $bop_content unless ref($bop_content);
1772 my @invoicing_list = $self->invoicing_list_emailonly;
1773 if ( $conf->exists('emailinvoiceautoalways')
1774 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1775 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1776 push @invoicing_list, $self->all_emails;
1779 my $email = ($conf->exists('business-onlinepayment-email-override'))
1780 ? $conf->config('business-onlinepayment-email-override')
1781 : $invoicing_list[0];
1786 if ( $namespace eq 'Business::OnlinePayment' ) {
1788 if ( $options{method} eq 'CC' ) {
1790 $content{card_number} = $options{payinfo} || $self->payinfo;
1791 $paydate = exists($options{'paydate'})
1792 ? $options{'paydate'}
1794 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1795 $content{expiration} = "$2/$1";
1797 my $paycvv = exists($options{'paycvv'})
1798 ? $options{'paycvv'}
1800 $content{cvv2} = $paycvv
1803 my $paystart_month = exists($options{'paystart_month'})
1804 ? $options{'paystart_month'}
1805 : $self->paystart_month;
1807 my $paystart_year = exists($options{'paystart_year'})
1808 ? $options{'paystart_year'}
1809 : $self->paystart_year;
1811 $content{card_start} = "$paystart_month/$paystart_year"
1812 if $paystart_month && $paystart_year;
1814 my $payissue = exists($options{'payissue'})
1815 ? $options{'payissue'}
1817 $content{issue_number} = $payissue if $payissue;
1819 } elsif ( $options{method} eq 'ECHECK' ){
1821 #nop for checks (though it shouldn't be called...)
1824 die "unknown method ". $options{method};
1827 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
1830 die "unknown namespace $namespace";
1834 # run transaction(s)
1837 warn "claiming mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
1838 $self->select_for_update; #mutex ... just until we get our pending record in
1839 warn "obtained mutex on customer ". $self->custnum. "\n" if $DEBUG > 1;
1841 #the checks here are intended to catch concurrent payments
1842 #double-form-submission prevention is taken care of in cust_pay_pending::check
1844 #also check and make sure there aren't *other* pending payments for this cust
1846 my @pending = qsearch('cust_pay_pending', {
1847 'custnum' => $self->custnum,
1848 'status' => { op=>'!=', value=>'done' }
1851 return "A payment is already being processed for this customer (".
1852 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
1853 "); verification transaction aborted."
1854 if scalar(@pending);
1856 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
1858 my $cust_pay_pending = new FS::cust_pay_pending {
1859 'custnum' => $self->custnum,
1862 'payby' => $bop_method2payby{'CC'},
1863 'payinfo' => $options{payinfo} || $self->payinfo,
1864 'paymask' => $options{paymask} || $self->paymask,
1865 'paydate' => $paydate,
1866 #'recurring_billing' => $content{recurring_billing},
1867 'pkgnum' => $options{'pkgnum'},
1869 'gatewaynum' => $payment_gateway->gatewaynum || '',
1870 'session_id' => $options{session_id} || '',
1871 #'jobnum' => $options{depend_jobnum} || '',
1873 $cust_pay_pending->payunique( $options{payunique} )
1874 if defined($options{payunique}) && length($options{payunique});
1876 warn "inserting cust_pay_pending record for customer ". $self->custnum. "\n"
1878 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
1879 return $cpp_new_err if $cpp_new_err;
1881 warn "inserted cust_pay_pending record for customer ". $self->custnum. "\n"
1883 warn Dumper($cust_pay_pending) if $DEBUG > 2;
1885 my $transaction = new $namespace( $payment_gateway->gateway_module,
1886 $self->_bop_options(\%options),
1889 $transaction->content(
1891 $self->_bop_auth(\%options),
1892 'action' => 'Authorization Only',
1893 'description' => $options{'description'},
1895 #'invoice_number' => $options{'invnum'},
1896 'customer_id' => $self->custnum,
1898 'reference' => $cust_pay_pending->paypendingnum, #for now
1899 'callback_url' => $payment_gateway->gateway_callback_url,
1900 'cancel_url' => $payment_gateway->gateway_cancel_url,
1905 $cust_pay_pending->status('pending');
1906 my $cpp_pending_err = $cust_pay_pending->replace;
1907 return $cpp_pending_err if $cpp_pending_err;
1909 warn Dumper($transaction) if $DEBUG > 2;
1911 unless ( $BOP_TESTING ) {
1912 $transaction->test_transaction(1)
1913 if $conf->exists('business-onlinepayment-test_transaction');
1914 $transaction->submit();
1916 if ( $BOP_TESTING_SUCCESS ) {
1917 $transaction->is_success(1);
1918 $transaction->authorization('fake auth');
1920 $transaction->is_success(0);
1921 $transaction->error_message('fake failure');
1925 if ( $transaction->is_success() ) {
1927 $cust_pay_pending->status('authorized');
1928 my $cpp_authorized_err = $cust_pay_pending->replace;
1929 return $cpp_authorized_err if $cpp_authorized_err;
1931 my $auth = $transaction->authorization;
1932 my $ordernum = $transaction->can('order_number')
1933 ? $transaction->order_number
1936 my $reverse = new $namespace( $payment_gateway->gateway_module,
1937 $self->_bop_options(\%options),
1940 $reverse->content( 'action' => 'Reverse Authorization',
1941 $self->_bop_auth(\%options),
1945 'authorization' => $transaction->authorization,
1946 'order_number' => $ordernum,
1949 'result_code' => $transaction->result_code,
1950 'txn_date' => $transaction->txn_date,
1954 $reverse->test_transaction(1)
1955 if $conf->exists('business-onlinepayment-test_transaction');
1958 if ( $reverse->is_success ) {
1960 $cust_pay_pending->status('done');
1961 my $cpp_authorized_err = $cust_pay_pending->replace;
1962 return $cpp_authorized_err if $cpp_authorized_err;
1966 my $e = "Authorization successful but reversal failed, custnum #".
1967 $self->custnum. ': '. $reverse->result_code.
1968 ": ". $reverse->error_message;
1980 if ( $transaction->can('card_token') && $transaction->card_token ) {
1982 if ( $options{'payinfo'} eq $self->payinfo ) {
1983 $self->payinfo($transaction->card_token);
1984 my $error = $self->replace;
1986 warn "WARNING: error storing token: $error, but proceeding anyway\n";
1996 $transaction->is_success() ? '' : $transaction->error_message();
2008 L<FS::cust_main>, L<FS::cust_main::Billing>