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 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
190 unless exists($options->{payment_gateway});
192 $options->{payment_gateway};
196 my ($self, $options) = @_;
199 'login' => $options->{payment_gateway}->gateway_username,
200 'password' => $options->{payment_gateway}->gateway_password,
205 my ($self, $options) = @_;
207 $options->{payment_gateway}->gatewaynum
208 ? $options->{payment_gateway}->options
209 : @{ $options->{payment_gateway}->get('options') };
214 my ($self, $options) = @_;
216 unless ( $options->{'description'} ) {
217 if ( $conf->exists('business-onlinepayment-description') ) {
218 my $dtempl = $conf->config('business-onlinepayment-description');
220 my $agent = $self->agent->agent;
222 $options->{'description'} = eval qq("$dtempl");
224 $options->{'description'} = 'Internet services';
228 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
229 $options->{invnum} ||= '';
230 $options->{payname} = $self->payname unless exists( $options->{payname} );
234 my ($self, $options) = @_;
237 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
238 $content{customer_ip} = $payip if length($payip);
240 $content{invoice_number} = $options->{'invnum'}
241 if exists($options->{'invnum'}) && length($options->{'invnum'});
243 $content{email_customer} =
244 ( $conf->exists('business-onlinepayment-email_customer')
245 || $conf->exists('business-onlinepayment-email-override') );
247 my ($payname, $payfirst, $paylast);
248 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
249 ($payname = $options->{payname}) =~
250 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
251 or return "Illegal payname $payname";
252 ($payfirst, $paylast) = ($1, $2);
254 $payfirst = $self->getfield('first');
255 $paylast = $self->getfield('last');
256 $payname = "$payfirst $paylast";
259 $content{last_name} = $paylast;
260 $content{first_name} = $payfirst;
262 $content{name} = $payname;
264 $content{address} = exists($options->{'address1'})
265 ? $options->{'address1'}
267 my $address2 = exists($options->{'address2'})
268 ? $options->{'address2'}
270 $content{address} .= ", ". $address2 if length($address2);
272 $content{city} = exists($options->{city})
275 $content{state} = exists($options->{state})
278 $content{zip} = exists($options->{zip})
281 $content{country} = exists($options->{country})
282 ? $options->{country}
285 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
286 $content{phone} = $self->daytime || $self->night;
291 my %bop_method2payby = (
300 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
303 if (ref($_[0]) eq 'HASH') {
306 my ( $method, $amount ) = ( shift, shift );
308 $options{method} = $method;
309 $options{amount} = $amount;
313 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
314 warn " $_ => $options{$_}\n" foreach keys %options;
317 return $self->fake_bop(%options) if $options{'fake'};
319 $self->_bop_defaults(\%options);
322 # set trans_is_recur based on invnum if there is one
325 my $trans_is_recur = 0;
326 if ( $options{'invnum'} ) {
328 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
329 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
335 $cust_bill->cust_bill_pkg;
338 if grep { $_->freq ne '0' } @part_pkg;
346 my $payment_gateway = $self->_payment_gateway( \%options );
347 my $namespace = $payment_gateway->gateway_namespace;
349 eval "use $namespace";
353 # check for banned credit card/ACH
356 my $ban = qsearchs('banned_pay', {
357 'payby' => $bop_method2payby{$options{method}},
358 'payinfo' => md5_base64($options{payinfo}),
360 return "Banned credit card" if $ban;
366 my $bop_content = $self->_bop_content(\%options);
367 return $bop_content unless ref($bop_content);
369 my @invoicing_list = $self->invoicing_list_emailonly;
370 if ( $conf->exists('emailinvoiceautoalways')
371 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
372 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
373 push @invoicing_list, $self->all_emails;
376 my $email = ($conf->exists('business-onlinepayment-email-override'))
377 ? $conf->config('business-onlinepayment-email-override')
378 : $invoicing_list[0];
382 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
384 $content{card_number} = $options{payinfo};
385 $paydate = exists($options{'paydate'})
386 ? $options{'paydate'}
388 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
389 $content{expiration} = "$2/$1";
391 my $paycvv = exists($options{'paycvv'})
394 $content{cvv2} = $paycvv
397 my $paystart_month = exists($options{'paystart_month'})
398 ? $options{'paystart_month'}
399 : $self->paystart_month;
401 my $paystart_year = exists($options{'paystart_year'})
402 ? $options{'paystart_year'}
403 : $self->paystart_year;
405 $content{card_start} = "$paystart_month/$paystart_year"
406 if $paystart_month && $paystart_year;
408 my $payissue = exists($options{'payissue'})
409 ? $options{'payissue'}
411 $content{issue_number} = $payissue if $payissue;
413 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
414 'trans_is_recur' => $trans_is_recur,
418 $content{recurring_billing} = 'YES';
419 $content{acct_code} = 'rebill'
420 if $conf->exists('credit_card-recurring_billing_acct_code');
423 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
424 ( $content{account_number}, $content{routing_code} ) =
425 split('@', $options{payinfo});
426 $content{bank_name} = $options{payname};
427 $content{bank_state} = exists($options{'paystate'})
428 ? $options{'paystate'}
429 : $self->getfield('paystate');
430 $content{account_type}= (exists($options{'paytype'}) && $options{'paytype'})
431 ? uc($options{'paytype'})
432 : uc($self->getfield('paytype')) || 'PERSONAL CHECKING';
433 $content{account_name} = $self->getfield('first'). ' '.
434 $self->getfield('last');
436 $content{customer_org} = $self->company ? 'B' : 'I';
437 $content{state_id} = exists($options{'stateid'})
438 ? $options{'stateid'}
439 : $self->getfield('stateid');
440 $content{state_id_state} = exists($options{'stateid_state'})
441 ? $options{'stateid_state'}
442 : $self->getfield('stateid_state');
443 $content{customer_ssn} = exists($options{'ss'})
446 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
447 $content{phone} = $options{payinfo};
448 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
458 my $balance = exists( $options{'balance'} )
459 ? $options{'balance'}
462 $self->select_for_update; #mutex ... just until we get our pending record in
464 #the checks here are intended to catch concurrent payments
465 #double-form-submission prevention is taken care of in cust_pay_pending::check
468 return "The customer's balance has changed; $options{method} transaction aborted."
469 if $self->balance < $balance;
470 #&& $self->balance < $options{amount}; #might as well anyway?
472 #also check and make sure there aren't *other* pending payments for this cust
474 my @pending = qsearch('cust_pay_pending', {
475 'custnum' => $self->custnum,
476 'status' => { op=>'!=', value=>'done' }
478 # This is a problem. A self-service third party payment that fails somehow
479 # can't be retried, EVER, until someone manually clears it. Totally
480 # arbitrary fix: if the existing payment is more than two minutes old,
481 # kill it. This doesn't limit how long it can take the pending payment
482 # to complete, only how long it will obstruct new payments.
485 if ( time - $_->_date > 120 ) {
486 my $error = $_->delete;
487 warn "error deleting stale pending payment ".$_->paypendingnum.": $error"
488 if $error; # not fatal, it will fail anyway
491 push @still_pending, $_;
494 @pending = @still_pending;
496 return "A payment is already being processed for this customer (".
497 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
498 "); $options{method} transaction aborted."
501 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
503 my $cust_pay_pending = new FS::cust_pay_pending {
504 'custnum' => $self->custnum,
505 #'invnum' => $options{'invnum'},
506 'paid' => $options{amount},
508 'payby' => $bop_method2payby{$options{method}},
509 'payinfo' => $options{payinfo},
510 'paydate' => $paydate,
511 'recurring_billing' => $content{recurring_billing},
512 'pkgnum' => $options{'pkgnum'},
514 'gatewaynum' => $payment_gateway->gatewaynum || '',
515 'session_id' => $options{session_id} || '',
516 'jobnum' => $options{depend_jobnum} || '',
518 $cust_pay_pending->payunique( $options{payunique} )
519 if defined($options{payunique}) && length($options{payunique});
520 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
521 return $cpp_new_err if $cpp_new_err;
523 my( $action1, $action2 ) =
524 split( /\s*\,\s*/, $payment_gateway->gateway_action );
526 my $transaction = new $namespace( $payment_gateway->gateway_module,
527 $self->_bop_options(\%options),
530 $transaction->content(
531 'type' => $options{method},
532 $self->_bop_auth(\%options),
533 'action' => $action1,
534 'description' => $options{'description'},
535 'amount' => $options{amount},
536 #'invoice_number' => $options{'invnum'},
537 'customer_id' => $self->custnum,
539 'reference' => $cust_pay_pending->paypendingnum, #for now
540 'callback_url' => $payment_gateway->gateway_callback_url,
545 $cust_pay_pending->status('pending');
546 my $cpp_pending_err = $cust_pay_pending->replace;
547 return $cpp_pending_err if $cpp_pending_err;
551 my $BOP_TESTING_SUCCESS = 1;
553 unless ( $BOP_TESTING ) {
554 $transaction->test_transaction(1)
555 if $conf->exists('business-onlinepayment-test_transaction');
556 $transaction->submit();
558 if ( $BOP_TESTING_SUCCESS ) {
559 $transaction->is_success(1);
560 $transaction->authorization('fake auth');
562 $transaction->is_success(0);
563 $transaction->error_message('fake failure');
567 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
569 return { reference => $cust_pay_pending->paypendingnum,
570 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
572 } elsif ( $transaction->is_success() && $action2 ) {
574 $cust_pay_pending->status('authorized');
575 my $cpp_authorized_err = $cust_pay_pending->replace;
576 return $cpp_authorized_err if $cpp_authorized_err;
578 my $auth = $transaction->authorization;
579 my $ordernum = $transaction->can('order_number')
580 ? $transaction->order_number
584 new Business::OnlinePayment( $payment_gateway->gateway_module,
585 $self->_bop_options(\%options),
590 type => $options{method},
592 $self->_bop_auth(\%options),
593 order_number => $ordernum,
594 amount => $options{amount},
595 authorization => $auth,
596 description => $options{'description'},
599 foreach my $field (qw( authorization_source_code returned_ACI
600 transaction_identifier validation_code
601 transaction_sequence_num local_transaction_date
602 local_transaction_time AVS_result_code )) {
603 $capture{$field} = $transaction->$field() if $transaction->can($field);
606 $capture->content( %capture );
608 $capture->test_transaction(1)
609 if $conf->exists('business-onlinepayment-test_transaction');
612 unless ( $capture->is_success ) {
613 my $e = "Authorization successful but capture failed, custnum #".
614 $self->custnum. ': '. $capture->result_code.
615 ": ". $capture->error_message;
623 # remove paycvv after initial transaction
626 #false laziness w/misc/process/payment.cgi - check both to make sure working
628 if ( length($self->paycvv)
629 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
631 my $error = $self->remove_cvv;
633 warn "WARNING: error removing cvv: $error\n";
642 if ( $transaction->can('card_token') && $transaction->card_token ) {
644 $self->card_token($transaction->card_token);
646 if ( $options{'payinfo'} eq $self->payinfo ) {
647 $self->payinfo($transaction->card_token);
648 my $error = $self->replace;
650 warn "WARNING: error storing token: $error, but proceeding anyway\n";
660 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
672 if (ref($_[0]) eq 'HASH') {
675 my ( $method, $amount ) = ( shift, shift );
677 $options{method} = $method;
678 $options{amount} = $amount;
681 if ( $options{'fake_failure'} ) {
682 return "Error: No error; test failure requested with fake_failure";
686 #if ( $payment_gateway->gatewaynum ) { # agent override
687 # $paybatch = $payment_gateway->gatewaynum. '-';
690 #$paybatch .= "$processor:". $transaction->authorization;
692 #$paybatch .= ':'. $transaction->order_number
693 # if $transaction->can('order_number')
694 # && length($transaction->order_number);
696 my $paybatch = 'FakeProcessor:54:32';
698 my $cust_pay = new FS::cust_pay ( {
699 'custnum' => $self->custnum,
700 'invnum' => $options{'invnum'},
701 'paid' => $options{amount},
703 'payby' => $bop_method2payby{$options{method}},
704 #'payinfo' => $payinfo,
705 'payinfo' => '4111111111111111',
706 'paybatch' => $paybatch,
707 #'paydate' => $paydate,
708 'paydate' => '2012-05-01',
710 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
712 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
715 $cust_pay->invnum(''); #try again with no specific invnum
716 my $error2 = $cust_pay->insert( $options{'manual'} ?
717 ( 'manual' => 1 ) : ()
720 # gah, even with transactions.
721 my $e = 'WARNING: Card/ACH debited but database not updated - '.
722 "error inserting (fake!) payment: $error2".
723 " (previously tried insert with invnum #$options{'invnum'}" .
730 if ( $options{'paynum_ref'} ) {
731 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
739 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
741 # Wraps up processing of a realtime credit card, ACH (electronic check) or
742 # phone bill transaction.
744 sub _realtime_bop_result {
745 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
747 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
750 warn "$me _realtime_bop_result: pending transaction ".
751 $cust_pay_pending->paypendingnum. "\n";
752 warn " $_ => $options{$_}\n" foreach keys %options;
755 my $payment_gateway = $options{payment_gateway}
756 or return "no payment gateway in arguments to _realtime_bop_result";
758 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
759 my $cpp_captured_err = $cust_pay_pending->replace;
760 return $cpp_captured_err if $cpp_captured_err;
762 if ( $transaction->is_success() ) {
765 if ( $payment_gateway->gatewaynum ) { # agent override
766 $paybatch = $payment_gateway->gatewaynum. '-';
769 $paybatch .= $payment_gateway->gateway_module. ":".
770 $transaction->authorization;
772 $paybatch .= ':'. $transaction->order_number
773 if $transaction->can('order_number')
774 && length($transaction->order_number);
776 my $cust_pay = new FS::cust_pay ( {
777 'custnum' => $self->custnum,
778 'invnum' => $options{'invnum'},
779 'paid' => $cust_pay_pending->paid,
781 'payby' => $cust_pay_pending->payby,
782 'payinfo' => $options{'payinfo'},
783 'paybatch' => $paybatch,
784 'paydate' => $cust_pay_pending->paydate,
785 'pkgnum' => $cust_pay_pending->pkgnum,
786 'discount_term' => $options{'discount_term'},
788 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
789 $cust_pay->payunique( $options{payunique} )
790 if defined($options{payunique}) && length($options{payunique});
792 my $oldAutoCommit = $FS::UID::AutoCommit;
793 local $FS::UID::AutoCommit = 0;
796 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
798 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
801 $cust_pay->invnum(''); #try again with no specific invnum
802 my $error2 = $cust_pay->insert( $options{'manual'} ?
803 ( 'manual' => 1 ) : ()
806 # gah. but at least we have a record of the state we had to abort in
807 # from cust_pay_pending now.
808 my $e = "WARNING: $options{method} captured but payment not recorded -".
809 " error inserting payment (". $payment_gateway->gateway_module.
811 " (previously tried insert with invnum #$options{'invnum'}" .
812 ": $error ) - pending payment saved as paypendingnum ".
813 $cust_pay_pending->paypendingnum. "\n";
819 my $jobnum = $cust_pay_pending->jobnum;
821 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
823 unless ( $placeholder ) {
824 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
825 my $e = "WARNING: $options{method} captured but job $jobnum not ".
826 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
831 $error = $placeholder->delete;
834 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
835 my $e = "WARNING: $options{method} captured but could not delete ".
836 "job $jobnum for paypendingnum ".
837 $cust_pay_pending->paypendingnum. ": $error\n";
844 if ( $options{'paynum_ref'} ) {
845 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
848 $cust_pay_pending->status('done');
849 $cust_pay_pending->statustext('captured');
850 $cust_pay_pending->paynum($cust_pay->paynum);
851 my $cpp_done_err = $cust_pay_pending->replace;
853 if ( $cpp_done_err ) {
855 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
856 my $e = "WARNING: $options{method} captured but payment not recorded - ".
857 "error updating status for paypendingnum ".
858 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
864 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
866 if ( $options{'apply'} ) {
867 my $apply_error = $self->apply_payments_and_credits;
868 if ( $apply_error ) {
869 warn "WARNING: error applying payment: $apply_error\n";
870 #but we still should return no error cause the payment otherwise went
881 my $perror = $payment_gateway->gateway_module. " error: ".
882 $transaction->error_message;
884 my $jobnum = $cust_pay_pending->jobnum;
886 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
888 if ( $placeholder ) {
889 my $error = $placeholder->depended_delete;
890 $error ||= $placeholder->delete;
891 warn "error removing provisioning jobs after declined paypendingnum ".
892 $cust_pay_pending->paypendingnum. ": $error\n";
894 my $e = "error finding job $jobnum for declined paypendingnum ".
895 $cust_pay_pending->paypendingnum. "\n";
901 unless ( $transaction->error_message ) {
904 if ( $transaction->can('response_page') ) {
906 'page' => ( $transaction->can('response_page')
907 ? $transaction->response_page
910 'code' => ( $transaction->can('response_code')
911 ? $transaction->response_code
914 'headers' => ( $transaction->can('response_headers')
915 ? $transaction->response_headers
921 "No additional debugging information available for ".
922 $payment_gateway->gateway_module;
925 $perror .= "No error_message returned from ".
926 $payment_gateway->gateway_module. " -- ".
927 ( ref($t_response) ? Dumper($t_response) : $t_response );
931 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
932 && $conf->exists('emaildecline', $self->agentnum)
933 && grep { $_ ne 'POST' } $self->invoicing_list
934 && ! grep { $transaction->error_message =~ /$_/ }
935 $conf->config('emaildecline-exclude', $self->agentnum)
938 # Send a decline alert to the customer.
939 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
942 # include the raw error message in the transaction state
943 $cust_pay_pending->setfield('error', $transaction->error_message);
944 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
945 $error = $msg_template->send( 'cust_main' => $self,
946 'object' => $cust_pay_pending );
950 my @templ = $conf->config('declinetemplate');
951 my $template = new Text::Template (
953 SOURCE => [ map "$_\n", @templ ],
954 ) or return "($perror) can't create template: $Text::Template::ERROR";
956 or return "($perror) can't compile template: $Text::Template::ERROR";
960 scalar( $conf->config('company_name', $self->agentnum ) ),
962 join("\n", $conf->config('company_address', $self->agentnum ) ),
963 'error' => $transaction->error_message,
966 my $error = send_email(
967 'from' => $conf->config('invoice_from', $self->agentnum ),
968 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
969 'subject' => 'Your payment could not be processed',
970 'body' => [ $template->fill_in(HASH => $templ_hash) ],
974 $perror .= " (also received error sending decline notification: $error)"
979 $cust_pay_pending->status('done');
980 $cust_pay_pending->statustext("declined: $perror");
981 my $cpp_done_err = $cust_pay_pending->replace;
982 if ( $cpp_done_err ) {
983 my $e = "WARNING: $options{method} declined but pending payment not ".
984 "resolved - error updating status for paypendingnum ".
985 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
987 $perror = "$e ($perror)";
995 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
997 Verifies successful third party processing of a realtime credit card,
998 ACH (electronic check) or phone bill transaction via a
999 Business::OnlineThirdPartyPayment realtime gateway. See
1000 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
1002 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
1004 The additional options I<payname>, I<city>, I<state>,
1005 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1006 if set, will override the value from the customer record.
1008 I<description> is a free-text field passed to the gateway. It defaults to
1009 "Internet services".
1011 If an I<invnum> is specified, this payment (if successful) is applied to the
1012 specified invoice. If you don't specify an I<invnum> you might want to
1013 call the B<apply_payments> method.
1015 I<quiet> can be set true to surpress email decline notices.
1017 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
1018 resulting paynum, if any.
1020 I<payunique> is a unique identifier for this payment.
1022 Returns a hashref containing elements bill_error (which will be undefined
1023 upon success) and session_id of any associated session.
1027 sub realtime_botpp_capture {
1028 my( $self, $cust_pay_pending, %options ) = @_;
1030 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1033 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1034 warn " $_ => $options{$_}\n" foreach keys %options;
1037 eval "use Business::OnlineThirdPartyPayment";
1041 # select the gateway
1044 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1046 my $payment_gateway;
1047 my $gatewaynum = $cust_pay_pending->getfield('gatewaynum');
1048 $payment_gateway = $gatewaynum ? qsearchs( 'payment_gateway',
1049 { gatewaynum => $gatewaynum }
1051 : $self->agent->payment_gateway( 'method' => $method,
1052 # 'invnum' => $cust_pay_pending->invnum,
1053 # 'payinfo' => $cust_pay_pending->payinfo,
1056 $options{payment_gateway} = $payment_gateway; # for the helper subs
1062 my @invoicing_list = $self->invoicing_list_emailonly;
1063 if ( $conf->exists('emailinvoiceautoalways')
1064 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1065 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1066 push @invoicing_list, $self->all_emails;
1069 my $email = ($conf->exists('business-onlinepayment-email-override'))
1070 ? $conf->config('business-onlinepayment-email-override')
1071 : $invoicing_list[0];
1075 $content{email_customer} =
1076 ( $conf->exists('business-onlinepayment-email_customer')
1077 || $conf->exists('business-onlinepayment-email-override') );
1080 # run transaction(s)
1084 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1085 $self->_bop_options(\%options),
1088 $transaction->reference({ %options });
1090 $transaction->content(
1092 $self->_bop_auth(\%options),
1093 'action' => 'Post Authorization',
1094 'description' => $options{'description'},
1095 'amount' => $cust_pay_pending->paid,
1096 #'invoice_number' => $options{'invnum'},
1097 'customer_id' => $self->custnum,
1098 'referer' => 'http://cleanwhisker.420.am/',
1099 'reference' => $cust_pay_pending->paypendingnum,
1101 'phone' => $self->daytime || $self->night,
1103 # plus whatever is required for bogus capture avoidance
1106 $transaction->submit();
1109 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1111 if ( $options{'apply'} ) {
1112 my $apply_error = $self->apply_payments_and_credits;
1113 if ( $apply_error ) {
1114 warn "WARNING: error applying payment: $apply_error\n";
1119 bill_error => $error,
1120 session_id => $cust_pay_pending->session_id,
1125 =item default_payment_gateway
1127 DEPRECATED -- use agent->payment_gateway
1131 sub default_payment_gateway {
1132 my( $self, $method ) = @_;
1134 die "Real-time processing not enabled\n"
1135 unless $conf->exists('business-onlinepayment');
1137 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1140 my $bop_config = 'business-onlinepayment';
1141 $bop_config .= '-ach'
1142 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1143 my ( $processor, $login, $password, $action, @bop_options ) =
1144 $conf->config($bop_config);
1145 $action ||= 'normal authorization';
1146 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1147 die "No real-time processor is enabled - ".
1148 "did you set the business-onlinepayment configuration value?\n"
1151 ( $processor, $login, $password, $action, @bop_options )
1154 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1156 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
1157 via a Business::OnlinePayment realtime gateway. See
1158 L<http://420.am/business-onlinepayment> for supported gateways.
1160 Available methods are: I<CC>, I<ECHECK> and I<LEC>
1162 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
1164 Most gateways require a reference to an original payment transaction to refund,
1165 so you probably need to specify a I<paynum>.
1167 I<amount> defaults to the original amount of the payment if not specified.
1169 I<reason> specifies a reason for the refund.
1171 I<paydate> specifies the expiration date for a credit card overriding the
1172 value from the customer record or the payment record. Specified as yyyy-mm-dd
1174 Implementation note: If I<amount> is unspecified or equal to the amount of the
1175 orignal payment, first an attempt is made to "void" the transaction via
1176 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1177 the normal attempt is made to "refund" ("credit") the transaction via the
1178 gateway is attempted.
1180 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1181 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1182 #if set, will override the value from the customer record.
1184 #If an I<invnum> is specified, this payment (if successful) is applied to the
1185 #specified invoice. If you don't specify an I<invnum> you might want to
1186 #call the B<apply_payments> method.
1190 #some false laziness w/realtime_bop, not enough to make it worth merging
1191 #but some useful small subs should be pulled out
1192 sub realtime_refund_bop {
1195 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1198 if (ref($_[0]) eq 'HASH') {
1199 %options = %{$_[0]};
1203 $options{method} = $method;
1207 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1208 warn " $_ => $options{$_}\n" foreach keys %options;
1212 # look up the original payment and optionally a gateway for that payment
1216 my $amount = $options{'amount'};
1218 my( $processor, $login, $password, @bop_options, $namespace ) ;
1219 my( $auth, $order_number ) = ( '', '', '' );
1221 if ( $options{'paynum'} ) {
1223 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1224 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1225 or return "Unknown paynum $options{'paynum'}";
1226 $amount ||= $cust_pay->paid;
1228 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1229 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1230 $cust_pay->paybatch;
1231 my $gatewaynum = '';
1232 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1234 if ( $gatewaynum ) { #gateway for the payment to be refunded
1236 my $payment_gateway =
1237 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1238 die "payment gateway $gatewaynum not found"
1239 unless $payment_gateway;
1241 $processor = $payment_gateway->gateway_module;
1242 $login = $payment_gateway->gateway_username;
1243 $password = $payment_gateway->gateway_password;
1244 $namespace = $payment_gateway->gateway_namespace;
1245 @bop_options = $payment_gateway->options;
1247 } else { #try the default gateway
1250 my $payment_gateway =
1251 $self->agent->payment_gateway('method' => $options{method});
1253 ( $conf_processor, $login, $password, $namespace ) =
1254 map { my $method = "gateway_$_"; $payment_gateway->$method }
1255 qw( module username password namespace );
1257 @bop_options = $payment_gateway->gatewaynum
1258 ? $payment_gateway->options
1259 : @{ $payment_gateway->get('options') };
1261 return "processor of payment $options{'paynum'} $processor does not".
1262 " match default processor $conf_processor"
1263 unless $processor eq $conf_processor;
1268 } else { # didn't specify a paynum, so look for agent gateway overrides
1269 # like a normal transaction
1271 my $payment_gateway =
1272 $self->agent->payment_gateway( 'method' => $options{method},
1273 #'payinfo' => $payinfo,
1275 my( $processor, $login, $password, $namespace ) =
1276 map { my $method = "gateway_$_"; $payment_gateway->$method }
1277 qw( module username password namespace );
1279 my @bop_options = $payment_gateway->gatewaynum
1280 ? $payment_gateway->options
1281 : @{ $payment_gateway->get('options') };
1284 return "neither amount nor paynum specified" unless $amount;
1286 eval "use $namespace";
1290 'type' => $options{method},
1292 'password' => $password,
1293 'order_number' => $order_number,
1294 'amount' => $amount,
1295 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
1297 $content{authorization} = $auth
1298 if length($auth); #echeck/ACH transactions have an order # but no auth
1299 #(at least with authorize.net)
1301 my $disable_void_after;
1302 if ($conf->exists('disable_void_after')
1303 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1304 $disable_void_after = $1;
1307 #first try void if applicable
1308 if ( $cust_pay && $cust_pay->paid == $amount
1310 ( not defined($disable_void_after) )
1311 || ( time < ($cust_pay->_date + $disable_void_after ) )
1314 warn " attempting void\n" if $DEBUG > 1;
1315 my $void = new Business::OnlinePayment( $processor, @bop_options );
1316 if ( $void->can('info') ) {
1317 if ( $cust_pay->payby eq 'CARD'
1318 && $void->info('CC_void_requires_card') )
1320 $content{'card_number'} = $cust_pay->payinfo;
1321 } elsif ( $cust_pay->payby eq 'CHEK'
1322 && $void->info('ECHECK_void_requires_account') )
1324 ( $content{'account_number'}, $content{'routing_code'} ) =
1325 split('@', $cust_pay->payinfo);
1326 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1329 $void->content( 'action' => 'void', %content );
1330 $void->test_transaction(1)
1331 if $conf->exists('business-onlinepayment-test_transaction');
1333 if ( $void->is_success ) {
1334 my $error = $cust_pay->void($options{'reason'});
1336 # gah, even with transactions.
1337 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1338 "error voiding payment: $error";
1342 warn " void successful\n" if $DEBUG > 1;
1347 warn " void unsuccessful, trying refund\n"
1351 my $address = $self->address1;
1352 $address .= ", ". $self->address2 if $self->address2;
1354 my($payname, $payfirst, $paylast);
1355 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1356 $payname = $self->payname;
1357 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1358 or return "Illegal payname $payname";
1359 ($payfirst, $paylast) = ($1, $2);
1361 $payfirst = $self->getfield('first');
1362 $paylast = $self->getfield('last');
1363 $payname = "$payfirst $paylast";
1366 my @invoicing_list = $self->invoicing_list_emailonly;
1367 if ( $conf->exists('emailinvoiceautoalways')
1368 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1369 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1370 push @invoicing_list, $self->all_emails;
1373 my $email = ($conf->exists('business-onlinepayment-email-override'))
1374 ? $conf->config('business-onlinepayment-email-override')
1375 : $invoicing_list[0];
1377 my $payip = exists($options{'payip'})
1380 $content{customer_ip} = $payip
1384 if ( $options{method} eq 'CC' ) {
1387 $content{card_number} = $payinfo = $cust_pay->payinfo;
1388 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1389 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1390 ($content{expiration} = "$2/$1"); # where available
1392 $content{card_number} = $payinfo = $self->payinfo;
1393 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1394 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1395 $content{expiration} = "$2/$1";
1398 } elsif ( $options{method} eq 'ECHECK' ) {
1401 $payinfo = $cust_pay->payinfo;
1403 $payinfo = $self->payinfo;
1405 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1406 $content{bank_name} = $self->payname;
1407 $content{account_type} = 'CHECKING';
1408 $content{account_name} = $payname;
1409 $content{customer_org} = $self->company ? 'B' : 'I';
1410 $content{customer_ssn} = $self->ss;
1411 } elsif ( $options{method} eq 'LEC' ) {
1412 $content{phone} = $payinfo = $self->payinfo;
1416 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1417 my %sub_content = $refund->content(
1418 'action' => 'credit',
1419 'customer_id' => $self->custnum,
1420 'last_name' => $paylast,
1421 'first_name' => $payfirst,
1423 'address' => $address,
1424 'city' => $self->city,
1425 'state' => $self->state,
1426 'zip' => $self->zip,
1427 'country' => $self->country,
1429 'phone' => $self->daytime || $self->night,
1432 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1434 $refund->test_transaction(1)
1435 if $conf->exists('business-onlinepayment-test_transaction');
1438 return "$processor error: ". $refund->error_message
1439 unless $refund->is_success();
1441 my $paybatch = "$processor:". $refund->authorization;
1442 $paybatch .= ':'. $refund->order_number
1443 if $refund->can('order_number') && $refund->order_number;
1445 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1446 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1447 last unless @cust_bill_pay;
1448 my $cust_bill_pay = pop @cust_bill_pay;
1449 my $error = $cust_bill_pay->delete;
1453 my $cust_refund = new FS::cust_refund ( {
1454 'custnum' => $self->custnum,
1455 'paynum' => $options{'paynum'},
1456 'refund' => $amount,
1458 'payby' => $bop_method2payby{$options{method}},
1459 'payinfo' => $payinfo,
1460 'paybatch' => $paybatch,
1461 'reason' => $options{'reason'} || 'card or ACH refund',
1463 my $error = $cust_refund->insert;
1465 $cust_refund->paynum(''); #try again with no specific paynum
1466 my $error2 = $cust_refund->insert;
1468 # gah, even with transactions.
1469 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1470 "error inserting refund ($processor): $error2".
1471 " (previously tried insert with paynum #$options{'paynum'}" .
1490 L<FS::cust_main>, L<FS::cust_main::Billing>