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 Digest::MD5 qw(md5_base64);
8 use Business::CreditCard 0.28;
10 use FS::Record qw( qsearch qsearchs );
11 use FS::Misc qw( send_email );
14 use FS::cust_pay_pending;
17 $realtime_bop_decline_quiet = 0;
19 # 1 is mostly method/subroutine entry and options
20 # 2 traces progress of some operations
21 # 3 is even more information including possibly sensitive data
23 $me = '[FS::cust_main::Billing_Realtime]';
25 install_callback FS::UID sub {
27 #yes, need it for stuff below (prolly should be cached)
32 FS::cust_main::Billing_Realtime - Realtime billing mixin for cust_main
38 These methods are available on FS::cust_main objects.
44 =item realtime_collect [ OPTION => VALUE ... ]
46 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
47 via a Business::OnlinePayment or Business::OnlineThirdPartyPayment realtime
48 gateway. See L<http://420.am/business-onlinepayment> and
49 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
51 On failure returns an error message.
53 Returns false or a hashref upon success. The hashref contains keys popup_url reference, and collectitems. The first is a URL to which a browser should be redirected for completion of collection. The second is a reference id for the transaction suitable for the end user. The collectitems is a reference to a list of name value pairs suitable for assigning to a html form and posted to popup_url.
55 Available options are: I<method>, I<amount>, I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>, I<pkgnum>
57 I<method> is one of: I<CC>, I<ECHECK> and I<LEC>. If none is specified
58 then it is deduced from the customer record.
60 If no I<amount> is specified, then the customer balance is used.
62 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
63 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
64 if set, will override the value from the customer record.
66 I<description> is a free-text field passed to the gateway. It defaults to
67 the value defined by the business-onlinepayment-description configuration
68 option, or "Internet services" if that is unset.
70 If an I<invnum> is specified, this payment (if successful) is applied to the
71 specified invoice. If you don't specify an I<invnum> you might want to
72 call the B<apply_payments> method or set the I<apply> option.
74 I<apply> can be set to true to apply a resulting payment.
76 I<quiet> can be set true to surpress 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 $options{method} = FS::payby->payby2bop($self->payby)
101 unless exists( $options{method} );
103 return $self->realtime_bop({%options});
107 =item realtime_bop { [ ARG => VALUE ... ] }
109 Runs a realtime credit card, ACH (electronic check) or phone bill transaction
110 via a Business::OnlinePayment realtime gateway. See
111 L<http://420.am/business-onlinepayment> for supported gateways.
113 Required arguments in the hashref are I<method>, and I<amount>
115 Available methods are: I<CC>, I<ECHECK> and I<LEC>
117 Available optional arguments are: I<description>, I<invnum>, I<apply>, I<quiet>, I<paynum_ref>, I<payunique>, I<session_id>
119 The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
120 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
121 if set, will override the value from the customer record.
123 I<description> is a free-text field passed to the gateway. It defaults to
124 the value defined by the business-onlinepayment-description configuration
125 option, or "Internet services" if that is unset.
127 If an I<invnum> is specified, this payment (if successful) is applied to the
128 specified invoice. If you don't specify an I<invnum> you might want to
129 call the B<apply_payments> method or set the I<apply> option.
131 I<apply> can be set to true to apply a resulting payment.
133 I<quiet> can be set true to surpress email decline notices.
135 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
136 resulting paynum, if any.
138 I<payunique> is a unique identifier for this payment.
140 I<session_id> is a session identifier associated with this payment.
142 I<depend_jobnum> allows payment capture to unlock export jobs
144 I<discount_term> attempts to take a discount by prepaying for discount_term
146 (moved from cust_bill) (probably should get realtime_{card,ach,lec} here too)
150 # some helper routines
151 sub _bop_recurring_billing {
152 my( $self, %opt ) = @_;
154 my $method = scalar($conf->config('credit_card-recurring_billing_flag'));
156 if ( defined($method) && $method eq 'transaction_is_recur' ) {
158 return 1 if $opt{'trans_is_recur'};
162 my %hash = ( 'custnum' => $self->custnum,
167 if qsearch('cust_pay', { %hash, 'payinfo' => $opt{'payinfo'} } )
168 || qsearch('cust_pay', { %hash, 'paymask' => $self->mask_payinfo('CARD',
178 sub _payment_gateway {
179 my ($self, $options) = @_;
181 if ( $options->{'selfservice'} ) {
182 my $gatewaynum = FS::Conf->new->config('selfservice-payment_gateway');
184 return $options->{payment_gateway} ||=
185 qsearchs('payment_gateway', { gatewaynum => $gatewaynum });
189 if ( $options->{'fake_gatewaynum'} ) {
190 $options->{payment_gateway} =
191 qsearchs('payment_gateway',
192 { 'gatewaynum' => $options->{'fake_gatewaynum'}, }
196 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
197 unless exists($options->{payment_gateway});
199 $options->{payment_gateway};
203 my ($self, $options) = @_;
206 'login' => $options->{payment_gateway}->gateway_username,
207 'password' => $options->{payment_gateway}->gateway_password,
212 my ($self, $options) = @_;
214 $options->{payment_gateway}->gatewaynum
215 ? $options->{payment_gateway}->options
216 : @{ $options->{payment_gateway}->get('options') };
221 my ($self, $options) = @_;
223 unless ( $options->{'description'} ) {
224 if ( $conf->exists('business-onlinepayment-description') ) {
225 my $dtempl = $conf->config('business-onlinepayment-description');
227 my $agent = $self->agent->agent;
229 $options->{'description'} = eval qq("$dtempl");
231 $options->{'description'} = 'Internet services';
235 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
236 $options->{invnum} ||= '';
237 $options->{payname} = $self->payname unless exists( $options->{payname} );
241 my ($self, $options) = @_;
244 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
245 $content{customer_ip} = $payip if length($payip);
247 $content{invoice_number} = $options->{'invnum'}
248 if exists($options->{'invnum'}) && length($options->{'invnum'});
250 $content{email_customer} =
251 ( $conf->exists('business-onlinepayment-email_customer')
252 || $conf->exists('business-onlinepayment-email-override') );
254 my ($payname, $payfirst, $paylast);
255 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
256 ($payname = $options->{payname}) =~
257 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
258 or return "Illegal payname $payname";
259 ($payfirst, $paylast) = ($1, $2);
261 $payfirst = $self->getfield('first');
262 $paylast = $self->getfield('last');
263 $payname = "$payfirst $paylast";
266 $content{last_name} = $paylast;
267 $content{first_name} = $payfirst;
269 $content{name} = $payname;
271 $content{address} = exists($options->{'address1'})
272 ? $options->{'address1'}
274 my $address2 = exists($options->{'address2'})
275 ? $options->{'address2'}
277 $content{address} .= ", ". $address2 if length($address2);
279 $content{city} = exists($options->{city})
282 $content{state} = exists($options->{state})
285 $content{zip} = exists($options->{zip})
288 $content{country} = exists($options->{country})
289 ? $options->{country}
292 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
293 $content{phone} = $self->daytime || $self->night;
298 my %bop_method2payby = (
307 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
310 if (ref($_[0]) eq 'HASH') {
313 my ( $method, $amount ) = ( shift, shift );
315 $options{method} = $method;
316 $options{amount} = $amount;
321 # optional credit card surcharge
324 my $cc_surcharge = 0;
325 my $cc_surcharge_pct = $conf->config('credit-card-surcharge-percentage');
327 # always add cc surcharge if called from event
328 if($options{'cc_surcharge_from_event'} && $cc_surcharge_pct > 0) {
329 $cc_surcharge = $options{'amount'} * $cc_surcharge_pct / 100;
330 $options{'amount'} += $cc_surcharge;
331 $options{'amount'} = sprintf("%.2f", $options{'amount'}); # round (again)?
333 elsif($cc_surcharge_pct > 0) { # we're called not from event (i.e. from a
334 # payment screen), so consider the given
335 # amount as post-surcharge
336 $cc_surcharge = $options{'amount'} - ($options{'amount'} / ( 1 + $cc_surcharge_pct/100 ));
338 if ( $cc_surcharge > 0) {
339 $cc_surcharge = sprintf("%.2f",$cc_surcharge);
340 $options{'cc_surcharge'} = $cc_surcharge;
345 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
346 warn " cc_surcharge = $cc_surcharge\n";
347 warn " $_ => $options{$_}\n" foreach keys %options;
350 return $self->fake_bop(\%options) if $options{'fake'};
352 $self->_bop_defaults(\%options);
355 # set trans_is_recur based on invnum if there is one
358 my $trans_is_recur = 0;
359 if ( $options{'invnum'} ) {
361 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
362 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
368 $cust_bill->cust_bill_pkg;
371 if grep { $_->freq ne '0' } @part_pkg;
379 my $payment_gateway = $self->_payment_gateway( \%options );
380 my $namespace = $payment_gateway->gateway_namespace;
382 eval "use $namespace";
386 # check for banned credit card/ACH
389 my $ban = qsearchs('banned_pay', {
390 'payby' => $bop_method2payby{$options{method}},
391 'payinfo' => md5_base64($options{payinfo}),
393 return "Banned credit card" if $ban;
399 my $bop_content = $self->_bop_content(\%options);
400 return $bop_content unless ref($bop_content);
402 my @invoicing_list = $self->invoicing_list_emailonly;
403 if ( $conf->exists('emailinvoiceautoalways')
404 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
405 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
406 push @invoicing_list, $self->all_emails;
409 my $email = ($conf->exists('business-onlinepayment-email-override'))
410 ? $conf->config('business-onlinepayment-email-override')
411 : $invoicing_list[0];
415 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
417 $content{card_number} = $options{payinfo};
418 $paydate = exists($options{'paydate'})
419 ? $options{'paydate'}
421 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
422 $content{expiration} = "$2/$1";
424 my $paycvv = exists($options{'paycvv'})
427 $content{cvv2} = $paycvv
430 my $paystart_month = exists($options{'paystart_month'})
431 ? $options{'paystart_month'}
432 : $self->paystart_month;
434 my $paystart_year = exists($options{'paystart_year'})
435 ? $options{'paystart_year'}
436 : $self->paystart_year;
438 $content{card_start} = "$paystart_month/$paystart_year"
439 if $paystart_month && $paystart_year;
441 my $payissue = exists($options{'payissue'})
442 ? $options{'payissue'}
444 $content{issue_number} = $payissue if $payissue;
446 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
447 'trans_is_recur' => $trans_is_recur,
451 $content{recurring_billing} = 'YES';
452 $content{acct_code} = 'rebill'
453 if $conf->exists('credit_card-recurring_billing_acct_code');
456 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
457 ( $content{account_number}, $content{routing_code} ) =
458 split('@', $options{payinfo});
459 $content{bank_name} = $options{payname};
460 $content{bank_state} = exists($options{'paystate'})
461 ? $options{'paystate'}
462 : $self->getfield('paystate');
463 $content{account_type} = exists($options{'paytype'})
464 ? uc($options{'paytype'}) || 'CHECKING'
465 : uc($self->getfield('paytype')) || 'CHECKING';
466 $content{account_name} = $self->getfield('first'). ' '.
467 $self->getfield('last');
469 $content{customer_org} = $self->company ? 'B' : 'I';
470 $content{state_id} = exists($options{'stateid'})
471 ? $options{'stateid'}
472 : $self->getfield('stateid');
473 $content{state_id_state} = exists($options{'stateid_state'})
474 ? $options{'stateid_state'}
475 : $self->getfield('stateid_state');
476 $content{customer_ssn} = exists($options{'ss'})
479 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
480 $content{phone} = $options{payinfo};
481 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
491 my $balance = exists( $options{'balance'} )
492 ? $options{'balance'}
495 $self->select_for_update; #mutex ... just until we get our pending record in
497 #the checks here are intended to catch concurrent payments
498 #double-form-submission prevention is taken care of in cust_pay_pending::check
501 return "The customer's balance has changed; $options{method} transaction aborted."
502 if $self->balance < $balance;
503 #&& $self->balance < $options{amount}; #might as well anyway?
505 #also check and make sure there aren't *other* pending payments for this cust
507 my @pending = qsearch('cust_pay_pending', {
508 'custnum' => $self->custnum,
509 'status' => { op=>'!=', value=>'done' }
511 # This is a problem. A self-service third party payment that fails somehow
512 # can't be retried, EVER, until someone manually clears it. Totally
513 # arbitrary fix: if the existing payment is more than two minutes old,
514 # kill it. This doesn't limit how long it can take the pending payment
515 # to complete, only how long it will obstruct new payments.
518 if ( time - $_->_date > 120 ) {
519 my $error = $_->delete;
520 warn "error deleting stale pending payment ".$_->paypendingnum.": $error"
521 if $error; # not fatal, it will fail anyway
524 push @still_pending, $_;
527 @pending = @still_pending;
529 return "A payment is already being processed for this customer (".
530 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
531 "); $options{method} transaction aborted."
534 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
536 my $cust_pay_pending = new FS::cust_pay_pending {
537 'custnum' => $self->custnum,
538 #'invnum' => $options{'invnum'},
539 'paid' => $options{amount},
541 'payby' => $bop_method2payby{$options{method}},
542 'payinfo' => $options{payinfo},
543 'paydate' => $paydate,
544 'recurring_billing' => $content{recurring_billing},
545 'pkgnum' => $options{'pkgnum'},
547 'gatewaynum' => $payment_gateway->gatewaynum || '',
548 'session_id' => $options{session_id} || '',
549 'jobnum' => $options{depend_jobnum} || '',
551 $cust_pay_pending->payunique( $options{payunique} )
552 if defined($options{payunique}) && length($options{payunique});
553 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
554 return $cpp_new_err if $cpp_new_err;
556 my( $action1, $action2 ) =
557 split( /\s*\,\s*/, $payment_gateway->gateway_action );
559 my $transaction = new $namespace( $payment_gateway->gateway_module,
560 $self->_bop_options(\%options),
563 $transaction->content(
564 'type' => $options{method},
565 $self->_bop_auth(\%options),
566 'action' => $action1,
567 'description' => $options{'description'},
568 'amount' => $options{amount},
569 #'invoice_number' => $options{'invnum'},
570 'customer_id' => $self->custnum,
572 'reference' => $cust_pay_pending->paypendingnum, #for now
573 'callback_url' => $payment_gateway->gateway_callback_url,
578 $cust_pay_pending->status('pending');
579 my $cpp_pending_err = $cust_pay_pending->replace;
580 return $cpp_pending_err if $cpp_pending_err;
584 my $BOP_TESTING_SUCCESS = 1;
586 unless ( $BOP_TESTING ) {
587 $transaction->test_transaction(1)
588 if $conf->exists('business-onlinepayment-test_transaction');
589 $transaction->submit();
591 if ( $BOP_TESTING_SUCCESS ) {
592 $transaction->is_success(1);
593 $transaction->authorization('fake auth');
595 $transaction->is_success(0);
596 $transaction->error_message('fake failure');
600 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
602 return { reference => $cust_pay_pending->paypendingnum,
603 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
605 } elsif ( $transaction->is_success() && $action2 ) {
607 $cust_pay_pending->status('authorized');
608 my $cpp_authorized_err = $cust_pay_pending->replace;
609 return $cpp_authorized_err if $cpp_authorized_err;
611 my $auth = $transaction->authorization;
612 my $ordernum = $transaction->can('order_number')
613 ? $transaction->order_number
617 new Business::OnlinePayment( $payment_gateway->gateway_module,
618 $self->_bop_options(\%options),
623 type => $options{method},
625 $self->_bop_auth(\%options),
626 order_number => $ordernum,
627 amount => $options{amount},
628 authorization => $auth,
629 description => $options{'description'},
632 foreach my $field (qw( authorization_source_code returned_ACI
633 transaction_identifier validation_code
634 transaction_sequence_num local_transaction_date
635 local_transaction_time AVS_result_code )) {
636 $capture{$field} = $transaction->$field() if $transaction->can($field);
639 $capture->content( %capture );
641 $capture->test_transaction(1)
642 if $conf->exists('business-onlinepayment-test_transaction');
645 unless ( $capture->is_success ) {
646 my $e = "Authorization successful but capture failed, custnum #".
647 $self->custnum. ': '. $capture->result_code.
648 ": ". $capture->error_message;
656 # remove paycvv after initial transaction
659 #false laziness w/misc/process/payment.cgi - check both to make sure working
661 if ( length($self->paycvv)
662 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
664 my $error = $self->remove_cvv;
666 warn "WARNING: error removing cvv: $error\n";
675 if ( $transaction->can('card_token') && $transaction->card_token ) {
677 $self->card_token($transaction->card_token);
679 if ( $options{'payinfo'} eq $self->payinfo ) {
680 $self->payinfo($transaction->card_token);
681 my $error = $self->replace;
683 warn "WARNING: error storing token: $error, but proceeding anyway\n";
693 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
705 if (ref($_[0]) eq 'HASH') {
708 my ( $method, $amount ) = ( shift, shift );
710 $options{method} = $method;
711 $options{amount} = $amount;
714 if ( $options{'fake_failure'} ) {
715 return "Error: No error; test failure requested with fake_failure";
719 #if ( $payment_gateway->gatewaynum ) { # agent override
720 # $paybatch = $payment_gateway->gatewaynum. '-';
723 #$paybatch .= "$processor:". $transaction->authorization;
725 #$paybatch .= ':'. $transaction->order_number
726 # if $transaction->can('order_number')
727 # && length($transaction->order_number);
729 my $paybatch = 'FakeProcessor:54:32';
731 my $cust_pay = new FS::cust_pay ( {
732 'custnum' => $self->custnum,
733 'invnum' => $options{'invnum'},
734 'paid' => $options{amount},
736 'payby' => $bop_method2payby{$options{method}},
737 #'payinfo' => $payinfo,
738 'payinfo' => '4111111111111111',
739 'paybatch' => $paybatch,
740 #'paydate' => $paydate,
741 'paydate' => '2012-05-01',
743 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
746 warn "fake_bop\n cust_pay: ". Dumper($cust_pay) . "\n options: ";
747 warn " $_ => $options{$_}\n" foreach keys %options;
750 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
753 $cust_pay->invnum(''); #try again with no specific invnum
754 my $error2 = $cust_pay->insert( $options{'manual'} ?
755 ( 'manual' => 1 ) : ()
758 # gah, even with transactions.
759 my $e = 'WARNING: Card/ACH debited but database not updated - '.
760 "error inserting (fake!) payment: $error2".
761 " (previously tried insert with invnum #$options{'invnum'}" .
768 if ( $options{'paynum_ref'} ) {
769 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
777 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
779 # Wraps up processing of a realtime credit card, ACH (electronic check) or
780 # phone bill transaction.
782 sub _realtime_bop_result {
783 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
785 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
788 warn "$me _realtime_bop_result: pending transaction ".
789 $cust_pay_pending->paypendingnum. "\n";
790 warn " $_ => $options{$_}\n" foreach keys %options;
793 my $payment_gateway = $options{payment_gateway}
794 or return "no payment gateway in arguments to _realtime_bop_result";
796 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
797 my $cpp_captured_err = $cust_pay_pending->replace;
798 return $cpp_captured_err if $cpp_captured_err;
800 if ( $transaction->is_success() ) {
803 if ( $payment_gateway->gatewaynum ) { # agent override
804 $paybatch = $payment_gateway->gatewaynum. '-';
807 $paybatch .= $payment_gateway->gateway_module. ":".
808 $transaction->authorization;
810 $paybatch .= ':'. $transaction->order_number
811 if $transaction->can('order_number')
812 && length($transaction->order_number);
814 my $cust_pay = new FS::cust_pay ( {
815 'custnum' => $self->custnum,
816 'invnum' => $options{'invnum'},
817 'paid' => $cust_pay_pending->paid,
819 'payby' => $cust_pay_pending->payby,
820 'payinfo' => $options{'payinfo'},
821 'paybatch' => $paybatch,
822 'paydate' => $cust_pay_pending->paydate,
823 'pkgnum' => $cust_pay_pending->pkgnum,
824 'discount_term' => $options{'discount_term'},
826 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
827 $cust_pay->payunique( $options{payunique} )
828 if defined($options{payunique}) && length($options{payunique});
830 my $oldAutoCommit = $FS::UID::AutoCommit;
831 local $FS::UID::AutoCommit = 0;
834 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
836 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
839 $cust_pay->invnum(''); #try again with no specific invnum
840 my $error2 = $cust_pay->insert( $options{'manual'} ?
841 ( 'manual' => 1 ) : ()
844 # gah. but at least we have a record of the state we had to abort in
845 # from cust_pay_pending now.
846 my $e = "WARNING: $options{method} captured but payment not recorded -".
847 " error inserting payment (". $payment_gateway->gateway_module.
849 " (previously tried insert with invnum #$options{'invnum'}" .
850 ": $error ) - pending payment saved as paypendingnum ".
851 $cust_pay_pending->paypendingnum. "\n";
857 my $jobnum = $cust_pay_pending->jobnum;
859 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
861 unless ( $placeholder ) {
862 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
863 my $e = "WARNING: $options{method} captured but job $jobnum not ".
864 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
869 $error = $placeholder->delete;
872 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
873 my $e = "WARNING: $options{method} captured but could not delete ".
874 "job $jobnum for paypendingnum ".
875 $cust_pay_pending->paypendingnum. ": $error\n";
882 if ( $options{'paynum_ref'} ) {
883 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
886 $cust_pay_pending->status('done');
887 $cust_pay_pending->statustext('captured');
888 $cust_pay_pending->paynum($cust_pay->paynum);
889 my $cpp_done_err = $cust_pay_pending->replace;
891 if ( $cpp_done_err ) {
893 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
894 my $e = "WARNING: $options{method} captured but payment not recorded - ".
895 "error updating status for paypendingnum ".
896 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
902 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
904 if ( $options{'apply'} ) {
905 my $apply_error = $self->apply_payments_and_credits;
906 if ( $apply_error ) {
907 warn "WARNING: error applying payment: $apply_error\n";
908 #but we still should return no error cause the payment otherwise went
913 # have a CC surcharge portion --> one-time charge
914 if ( $options{'cc_surcharge'} > 0 ) {
916 $invnum = $options{'invnum'} if $options{'invnum'};
917 unless ( $invnum ) { # probably from a payment screen
918 # do we have any open invoices? pick earliest
919 # uses the fact that cust_main->cust_bill sorts by date ascending
920 my @open = $self->open_cust_bill;
921 $invnum = $open[0]->invnum if scalar(@open);
924 unless ( $invnum ) { # still nothing? pick last closed invoice
925 # again uses fact that cust_main->cust_bill sorts by date ascending
926 my @closed = $self->cust_bill;
927 $invnum = $closed[$#closed]->invnum if scalar(@closed);
931 # XXX: unlikely case - pre-paying before any invoices generated
932 # what it should do is create a new invoice and pick it
933 warn 'CC SURCHARGE AND NO INVOICES PICKED TO APPLY IT!';
938 my $charge_error = $self->charge({
939 'amount' => $options{'cc_surcharge'},
940 'pkg' => 'Credit Card Surcharge',
942 'cust_pkg_ref' => \$cust_pkg,
945 warn 'Unable to add CC surcharge';
949 my $cust_bill_pkg = new FS::cust_bill_pkg({
951 'pkgnum' => $cust_pkg->pkgnum,
952 'setup' => $options{'cc_surcharge'},
954 my $cbp_error = $cust_bill_pkg->insert;
957 warn 'Cannot add CC surcharge line item to invoice #'.$invnum;
960 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $invnum });
961 warn 'invoice for cc surcharge: ' . Dumper($cust_bill) if $DEBUG;
962 $cust_bill->apply_payments_and_credits;
973 my $perror = $payment_gateway->gateway_module. " error: ".
974 $transaction->error_message;
976 my $jobnum = $cust_pay_pending->jobnum;
978 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
980 if ( $placeholder ) {
981 my $error = $placeholder->depended_delete;
982 $error ||= $placeholder->delete;
983 warn "error removing provisioning jobs after declined paypendingnum ".
984 $cust_pay_pending->paypendingnum. "\n";
986 my $e = "error finding job $jobnum for declined paypendingnum ".
987 $cust_pay_pending->paypendingnum. "\n";
993 unless ( $transaction->error_message ) {
996 if ( $transaction->can('response_page') ) {
998 'page' => ( $transaction->can('response_page')
999 ? $transaction->response_page
1002 'code' => ( $transaction->can('response_code')
1003 ? $transaction->response_code
1006 'headers' => ( $transaction->can('response_headers')
1007 ? $transaction->response_headers
1013 "No additional debugging information available for ".
1014 $payment_gateway->gateway_module;
1017 $perror .= "No error_message returned from ".
1018 $payment_gateway->gateway_module. " -- ".
1019 ( ref($t_response) ? Dumper($t_response) : $t_response );
1023 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
1024 && $conf->exists('emaildecline', $self->agentnum)
1025 && grep { $_ ne 'POST' } $self->invoicing_list
1026 && ! grep { $transaction->error_message =~ /$_/ }
1027 $conf->config('emaildecline-exclude', $self->agentnum)
1030 # Send a decline alert to the customer.
1031 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
1034 # include the raw error message in the transaction state
1035 $cust_pay_pending->setfield('error', $transaction->error_message);
1036 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
1037 $error = $msg_template->send( 'cust_main' => $self,
1038 'object' => $cust_pay_pending );
1042 my @templ = $conf->config('declinetemplate');
1043 my $template = new Text::Template (
1045 SOURCE => [ map "$_\n", @templ ],
1046 ) or return "($perror) can't create template: $Text::Template::ERROR";
1047 $template->compile()
1048 or return "($perror) can't compile template: $Text::Template::ERROR";
1052 scalar( $conf->config('company_name', $self->agentnum ) ),
1053 'company_address' =>
1054 join("\n", $conf->config('company_address', $self->agentnum ) ),
1055 'error' => $transaction->error_message,
1058 my $error = send_email(
1059 'from' => $conf->config('invoice_from', $self->agentnum ),
1060 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
1061 'subject' => 'Your payment could not be processed',
1062 'body' => [ $template->fill_in(HASH => $templ_hash) ],
1066 $perror .= " (also received error sending decline notification: $error)"
1071 $cust_pay_pending->status('done');
1072 $cust_pay_pending->statustext("declined: $perror");
1073 my $cpp_done_err = $cust_pay_pending->replace;
1074 if ( $cpp_done_err ) {
1075 my $e = "WARNING: $options{method} declined but pending payment not ".
1076 "resolved - error updating status for paypendingnum ".
1077 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
1079 $perror = "$e ($perror)";
1087 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
1089 Verifies successful third party processing of a realtime credit card,
1090 ACH (electronic check) or phone bill transaction via a
1091 Business::OnlineThirdPartyPayment realtime gateway. See
1092 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1094 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1096 The additional options I<payname>, I<city>, I<state>,
1097 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1098 if set, will override the value from the customer record.
1100 I<description> is a free-text field passed to the gateway. It defaults to
1101 "Internet services".
1103 If an I<invnum> is specified, this payment (if successful) is applied to the
1104 specified invoice. If you don't specify an I<invnum> you might want to
1105 call the B<apply_payments> method.
1107 I<quiet> can be set true to surpress email decline notices.
1109 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1110 resulting paynum, if any.
1112 I<payunique> is a unique identifier for this payment.
1114 Returns a hashref containing elements bill_error (which will be undefined
1115 upon success) and session_id of any associated session.
1119 sub realtime_botpp_capture {
1120 my( $self, $cust_pay_pending, %options ) = @_;
1122 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1125 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1126 warn " $_ => $options{$_}\n" foreach keys %options;
1129 eval "use Business::OnlineThirdPartyPayment";
1133 # select the gateway
1136 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1138 my $payment_gateway;
1139 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1140 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1141 { gatewaynum => $gatewaynum }
1143 : $self->agent->payment_gateway( 'method' => $method,
1144 # 'invnum' => $cust_pay_pending->invnum,
1145 # 'payinfo' => $cust_pay_pending->payinfo,
1148 $options{payment_gateway} = $payment_gateway; # for the helper subs
1154 my @invoicing_list = $self->invoicing_list_emailonly;
1155 if ( $conf->exists('emailinvoiceautoalways')
1156 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1157 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1158 push @invoicing_list, $self->all_emails;
1161 my $email = ($conf->exists('business-onlinepayment-email-override'))
1162 ? $conf->config('business-onlinepayment-email-override')
1163 : $invoicing_list[0];
1167 $content{email_customer} =
1168 ( $conf->exists('business-onlinepayment-email_customer')
1169 || $conf->exists('business-onlinepayment-email-override') );
1172 # run transaction(s)
1176 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1177 $self->_bop_options(\%options),
1180 $transaction->reference({ %options });
1182 $transaction->content(
1184 $self->_bop_auth(\%options),
1185 'action' => 'Post Authorization',
1186 'description' => $options{'description'},
1187 'amount' => $cust_pay_pending->paid,
1188 #'invoice_number' => $options{'invnum'},
1189 'customer_id' => $self->custnum,
1190 'referer' => 'http://cleanwhisker.420.am/',
1191 'reference' => $cust_pay_pending->paypendingnum,
1193 'phone' => $self->daytime || $self->night,
1195 # plus whatever is required for bogus capture avoidance
1198 $transaction->submit();
1201 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1203 if ( $options{'apply'} ) {
1204 my $apply_error = $self->apply_payments_and_credits;
1205 if ( $apply_error ) {
1206 warn "WARNING: error applying payment: $apply_error\n";
1211 bill_error => $error,
1212 session_id => $cust_pay_pending->session_id,
1217 =item default_payment_gateway
1219 DEPRECATED -- use agent->payment_gateway
1223 sub default_payment_gateway {
1224 my( $self, $method ) = @_;
1226 die "Real-time processing not enabled\n"
1227 unless $conf->exists('business-onlinepayment');
1229 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1232 my $bop_config = 'business-onlinepayment';
1233 $bop_config .= '-ach'
1234 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1235 my ( $processor, $login, $password, $action, @bop_options ) =
1236 $conf->config($bop_config);
1237 $action ||= 'normal authorization';
1238 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1239 die "No real-time processor is enabled - ".
1240 "did you set the business-onlinepayment configuration value?\n"
1243 ( $processor, $login, $password, $action, @bop_options )
1246 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1248 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
1249 via a Business::OnlinePayment realtime gateway. See
1250 L<http://420.am/business-onlinepayment> for supported gateways.
1252 Available methods are: I<CC>, I<ECHECK> and I<LEC>
1254 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
1256 Most gateways require a reference to an original payment transaction to refund,
1257 so you probably need to specify a I<paynum>.
1259 I<amount> defaults to the original amount of the payment if not specified.
1261 I<reason> specifies a reason for the refund.
1263 I<paydate> specifies the expiration date for a credit card overriding the
1264 value from the customer record or the payment record. Specified as yyyy-mm-dd
1266 Implementation note: If I<amount> is unspecified or equal to the amount of the
1267 orignal payment, first an attempt is made to "void" the transaction via
1268 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1269 the normal attempt is made to "refund" ("credit") the transaction via the
1270 gateway is attempted.
1272 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1273 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1274 #if set, will override the value from the customer record.
1276 #If an I<invnum> is specified, this payment (if successful) is applied to the
1277 #specified invoice. If you don't specify an I<invnum> you might want to
1278 #call the B<apply_payments> method.
1282 #some false laziness w/realtime_bop, not enough to make it worth merging
1283 #but some useful small subs should be pulled out
1284 sub realtime_refund_bop {
1287 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1290 if (ref($_[0]) eq 'HASH') {
1291 %options = %{$_[0]};
1295 $options{method} = $method;
1299 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1300 warn " $_ => $options{$_}\n" foreach keys %options;
1304 # look up the original payment and optionally a gateway for that payment
1308 my $amount = $options{'amount'};
1310 my( $processor, $login, $password, @bop_options, $namespace ) ;
1311 my( $auth, $order_number ) = ( '', '', '' );
1313 if ( $options{'paynum'} ) {
1315 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1316 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1317 or return "Unknown paynum $options{'paynum'}";
1318 $amount ||= $cust_pay->paid;
1320 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1321 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1322 $cust_pay->paybatch;
1323 my $gatewaynum = '';
1324 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1326 if ( $gatewaynum ) { #gateway for the payment to be refunded
1328 my $payment_gateway =
1329 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1330 die "payment gateway $gatewaynum not found"
1331 unless $payment_gateway;
1333 $processor = $payment_gateway->gateway_module;
1334 $login = $payment_gateway->gateway_username;
1335 $password = $payment_gateway->gateway_password;
1336 $namespace = $payment_gateway->gateway_namespace;
1337 @bop_options = $payment_gateway->options;
1339 } else { #try the default gateway
1342 my $payment_gateway =
1343 $self->agent->payment_gateway('method' => $options{method});
1345 ( $conf_processor, $login, $password, $namespace ) =
1346 map { my $method = "gateway_$_"; $payment_gateway->$method }
1347 qw( module username password namespace );
1349 @bop_options = $payment_gateway->gatewaynum
1350 ? $payment_gateway->options
1351 : @{ $payment_gateway->get('options') };
1353 return "processor of payment $options{'paynum'} $processor does not".
1354 " match default processor $conf_processor"
1355 unless $processor eq $conf_processor;
1360 } else { # didn't specify a paynum, so look for agent gateway overrides
1361 # like a normal transaction
1363 my $payment_gateway =
1364 $self->agent->payment_gateway( 'method' => $options{method},
1365 #'payinfo' => $payinfo,
1367 my( $processor, $login, $password, $namespace ) =
1368 map { my $method = "gateway_$_"; $payment_gateway->$method }
1369 qw( module username password namespace );
1371 my @bop_options = $payment_gateway->gatewaynum
1372 ? $payment_gateway->options
1373 : @{ $payment_gateway->get('options') };
1376 return "neither amount nor paynum specified" unless $amount;
1378 eval "use $namespace";
1382 'type' => $options{method},
1384 'password' => $password,
1385 'order_number' => $order_number,
1386 'amount' => $amount,
1387 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
1389 $content{authorization} = $auth
1390 if length($auth); #echeck/ACH transactions have an order # but no auth
1391 #(at least with authorize.net)
1393 my $disable_void_after;
1394 if ($conf->exists('disable_void_after')
1395 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1396 $disable_void_after = $1;
1399 #first try void if applicable
1400 if ( $cust_pay && $cust_pay->paid == $amount
1402 ( not defined($disable_void_after) )
1403 || ( time < ($cust_pay->_date + $disable_void_after ) )
1406 warn " attempting void\n" if $DEBUG > 1;
1407 my $void = new Business::OnlinePayment( $processor, @bop_options );
1408 if ( $void->can('info') ) {
1409 if ( $cust_pay->payby eq 'CARD'
1410 && $void->info('CC_void_requires_card') )
1412 $content{'card_number'} = $cust_pay->payinfo;
1413 } elsif ( $cust_pay->payby eq 'CHEK'
1414 && $void->info('ECHECK_void_requires_account') )
1416 ( $content{'account_number'}, $content{'routing_code'} ) =
1417 split('@', $cust_pay->payinfo);
1418 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1421 $void->content( 'action' => 'void', %content );
1422 $void->test_transaction(1)
1423 if $conf->exists('business-onlinepayment-test_transaction');
1425 if ( $void->is_success ) {
1426 my $error = $cust_pay->void($options{'reason'});
1428 # gah, even with transactions.
1429 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1430 "error voiding payment: $error";
1434 warn " void successful\n" if $DEBUG > 1;
1439 warn " void unsuccessful, trying refund\n"
1443 my $address = $self->address1;
1444 $address .= ", ". $self->address2 if $self->address2;
1446 my($payname, $payfirst, $paylast);
1447 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1448 $payname = $self->payname;
1449 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1450 or return "Illegal payname $payname";
1451 ($payfirst, $paylast) = ($1, $2);
1453 $payfirst = $self->getfield('first');
1454 $paylast = $self->getfield('last');
1455 $payname = "$payfirst $paylast";
1458 my @invoicing_list = $self->invoicing_list_emailonly;
1459 if ( $conf->exists('emailinvoiceautoalways')
1460 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1461 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1462 push @invoicing_list, $self->all_emails;
1465 my $email = ($conf->exists('business-onlinepayment-email-override'))
1466 ? $conf->config('business-onlinepayment-email-override')
1467 : $invoicing_list[0];
1469 my $payip = exists($options{'payip'})
1472 $content{customer_ip} = $payip
1476 if ( $options{method} eq 'CC' ) {
1479 $content{card_number} = $payinfo = $cust_pay->payinfo;
1480 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1481 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1482 ($content{expiration} = "$2/$1"); # where available
1484 $content{card_number} = $payinfo = $self->payinfo;
1485 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1486 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1487 $content{expiration} = "$2/$1";
1490 } elsif ( $options{method} eq 'ECHECK' ) {
1493 $payinfo = $cust_pay->payinfo;
1495 $payinfo = $self->payinfo;
1497 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1498 $content{bank_name} = $self->payname;
1499 $content{account_type} = 'CHECKING';
1500 $content{account_name} = $payname;
1501 $content{customer_org} = $self->company ? 'B' : 'I';
1502 $content{customer_ssn} = $self->ss;
1503 } elsif ( $options{method} eq 'LEC' ) {
1504 $content{phone} = $payinfo = $self->payinfo;
1508 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1509 my %sub_content = $refund->content(
1510 'action' => 'credit',
1511 'customer_id' => $self->custnum,
1512 'last_name' => $paylast,
1513 'first_name' => $payfirst,
1515 'address' => $address,
1516 'city' => $self->city,
1517 'state' => $self->state,
1518 'zip' => $self->zip,
1519 'country' => $self->country,
1521 'phone' => $self->daytime || $self->night,
1524 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1526 $refund->test_transaction(1)
1527 if $conf->exists('business-onlinepayment-test_transaction');
1530 return "$processor error: ". $refund->error_message
1531 unless $refund->is_success();
1533 my $paybatch = "$processor:". $refund->authorization;
1534 $paybatch .= ':'. $refund->order_number
1535 if $refund->can('order_number') && $refund->order_number;
1537 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1538 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1539 last unless @cust_bill_pay;
1540 my $cust_bill_pay = pop @cust_bill_pay;
1541 my $error = $cust_bill_pay->delete;
1545 my $cust_refund = new FS::cust_refund ( {
1546 'custnum' => $self->custnum,
1547 'paynum' => $options{'paynum'},
1548 'refund' => $amount,
1550 'payby' => $bop_method2payby{$options{method}},
1551 'payinfo' => $payinfo,
1552 'paybatch' => $paybatch,
1553 'reason' => $options{'reason'} || 'card or ACH refund',
1555 my $error = $cust_refund->insert;
1557 $cust_refund->paynum(''); #try again with no specific paynum
1558 my $error2 = $cust_refund->insert;
1560 # gah, even with transactions.
1561 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1562 "error inserting refund ($processor): $error2".
1563 " (previously tried insert with paynum #$options{'paynum'}" .
1582 L<FS::cust_main>, L<FS::cust_main::Billing>