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 $options->{payment_gateway} = $self->agent->payment_gateway( %$options )
182 unless exists($options->{payment_gateway});
184 $options->{payment_gateway};
188 my ($self, $options) = @_;
191 'login' => $options->{payment_gateway}->gateway_username,
192 'password' => $options->{payment_gateway}->gateway_password,
197 my ($self, $options) = @_;
199 $options->{payment_gateway}->gatewaynum
200 ? $options->{payment_gateway}->options
201 : @{ $options->{payment_gateway}->get('options') };
206 my ($self, $options) = @_;
208 unless ( $options->{'description'} ) {
209 if ( $conf->exists('business-onlinepayment-description') ) {
210 my $dtempl = $conf->config('business-onlinepayment-description');
212 my $agent = $self->agent->agent;
214 $options->{'description'} = eval qq("$dtempl");
216 $options->{'description'} = 'Internet services';
220 $options->{payinfo} = $self->payinfo unless exists( $options->{payinfo} );
221 $options->{invnum} ||= '';
222 $options->{payname} = $self->payname unless exists( $options->{payname} );
226 my ($self, $options) = @_;
229 my $payip = exists($options->{'payip'}) ? $options->{'payip'} : $self->payip;
230 $content{customer_ip} = $payip if length($payip);
232 $content{invoice_number} = $options->{'invnum'}
233 if exists($options->{'invnum'}) && length($options->{'invnum'});
235 $content{email_customer} =
236 ( $conf->exists('business-onlinepayment-email_customer')
237 || $conf->exists('business-onlinepayment-email-override') );
239 my ($payname, $payfirst, $paylast);
240 if ( $options->{payname} && $options->{method} ne 'ECHECK' ) {
241 ($payname = $options->{payname}) =~
242 /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
243 or return "Illegal payname $payname";
244 ($payfirst, $paylast) = ($1, $2);
246 $payfirst = $self->getfield('first');
247 $paylast = $self->getfield('last');
248 $payname = "$payfirst $paylast";
251 $content{last_name} = $paylast;
252 $content{first_name} = $payfirst;
254 $content{name} = $payname;
256 $content{address} = exists($options->{'address1'})
257 ? $options->{'address1'}
259 my $address2 = exists($options->{'address2'})
260 ? $options->{'address2'}
262 $content{address} .= ", ". $address2 if length($address2);
264 $content{city} = exists($options->{city})
267 $content{state} = exists($options->{state})
270 $content{zip} = exists($options->{zip})
273 $content{country} = exists($options->{country})
274 ? $options->{country}
277 $content{referer} = 'http://cleanwhisker.420.am/'; #XXX fix referer :/
278 $content{phone} = $self->daytime || $self->night;
283 my %bop_method2payby = (
292 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
295 if (ref($_[0]) eq 'HASH') {
298 my ( $method, $amount ) = ( shift, shift );
300 $options{method} = $method;
301 $options{amount} = $amount;
305 warn "$me realtime_bop (new): $options{method} $options{amount}\n";
306 warn " $_ => $options{$_}\n" foreach keys %options;
309 return $self->fake_bop(%options) if $options{'fake'};
311 $self->_bop_defaults(\%options);
314 # set trans_is_recur based on invnum if there is one
317 my $trans_is_recur = 0;
318 if ( $options{'invnum'} ) {
320 my $cust_bill = qsearchs('cust_bill', { 'invnum' => $options{'invnum'} } );
321 die "invnum ". $options{'invnum'}. " not found" unless $cust_bill;
327 $cust_bill->cust_bill_pkg;
330 if grep { $_->freq ne '0' } @part_pkg;
338 my $payment_gateway = $self->_payment_gateway( \%options );
339 my $namespace = $payment_gateway->gateway_namespace;
341 eval "use $namespace";
345 # check for banned credit card/ACH
348 my $ban = qsearchs('banned_pay', {
349 'payby' => $bop_method2payby{$options{method}},
350 'payinfo' => md5_base64($options{payinfo}),
352 return "Banned credit card" if $ban;
358 my $bop_content = $self->_bop_content(\%options);
359 return $bop_content unless ref($bop_content);
361 my @invoicing_list = $self->invoicing_list_emailonly;
362 if ( $conf->exists('emailinvoiceautoalways')
363 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
364 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
365 push @invoicing_list, $self->all_emails;
368 my $email = ($conf->exists('business-onlinepayment-email-override'))
369 ? $conf->config('business-onlinepayment-email-override')
370 : $invoicing_list[0];
374 if ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'CC' ) {
376 $content{card_number} = $options{payinfo};
377 $paydate = exists($options{'paydate'})
378 ? $options{'paydate'}
380 $paydate =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
381 $content{expiration} = "$2/$1";
383 my $paycvv = exists($options{'paycvv'})
386 $content{cvv2} = $paycvv
389 my $paystart_month = exists($options{'paystart_month'})
390 ? $options{'paystart_month'}
391 : $self->paystart_month;
393 my $paystart_year = exists($options{'paystart_year'})
394 ? $options{'paystart_year'}
395 : $self->paystart_year;
397 $content{card_start} = "$paystart_month/$paystart_year"
398 if $paystart_month && $paystart_year;
400 my $payissue = exists($options{'payissue'})
401 ? $options{'payissue'}
403 $content{issue_number} = $payissue if $payissue;
405 if ( $self->_bop_recurring_billing( 'payinfo' => $options{'payinfo'},
406 'trans_is_recur' => $trans_is_recur,
410 $content{recurring_billing} = 'YES';
411 $content{acct_code} = 'rebill'
412 if $conf->exists('credit_card-recurring_billing_acct_code');
415 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'ECHECK' ){
416 ( $content{account_number}, $content{routing_code} ) =
417 split('@', $options{payinfo});
418 $content{bank_name} = $options{payname};
419 $content{bank_state} = exists($options{'paystate'})
420 ? $options{'paystate'}
421 : $self->getfield('paystate');
422 $content{account_type} = exists($options{'paytype'})
423 ? uc($options{'paytype'}) || 'CHECKING'
424 : uc($self->getfield('paytype')) || 'CHECKING';
425 $content{account_name} = $self->getfield('first'). ' '.
426 $self->getfield('last');
428 $content{customer_org} = $self->company ? 'B' : 'I';
429 $content{state_id} = exists($options{'stateid'})
430 ? $options{'stateid'}
431 : $self->getfield('stateid');
432 $content{state_id_state} = exists($options{'stateid_state'})
433 ? $options{'stateid_state'}
434 : $self->getfield('stateid_state');
435 $content{customer_ssn} = exists($options{'ss'})
438 } elsif ( $namespace eq 'Business::OnlinePayment' && $options{method} eq 'LEC' ) {
439 $content{phone} = $options{payinfo};
440 } elsif ( $namespace eq 'Business::OnlineThirdPartyPayment' ) {
450 my $balance = exists( $options{'balance'} )
451 ? $options{'balance'}
454 $self->select_for_update; #mutex ... just until we get our pending record in
456 #the checks here are intended to catch concurrent payments
457 #double-form-submission prevention is taken care of in cust_pay_pending::check
460 return "The customer's balance has changed; $options{method} transaction aborted."
461 if $self->balance < $balance;
462 #&& $self->balance < $options{amount}; #might as well anyway?
464 #also check and make sure there aren't *other* pending payments for this cust
466 my @pending = qsearch('cust_pay_pending', {
467 'custnum' => $self->custnum,
468 'status' => { op=>'!=', value=>'done' }
470 return "A payment is already being processed for this customer (".
471 join(', ', map 'paypendingnum '. $_->paypendingnum, @pending ).
472 "); $options{method} transaction aborted."
475 #okay, good to go, if we're a duplicate, cust_pay_pending will kick us out
477 my $cust_pay_pending = new FS::cust_pay_pending {
478 'custnum' => $self->custnum,
479 #'invnum' => $options{'invnum'},
480 'paid' => $options{amount},
482 'payby' => $bop_method2payby{$options{method}},
483 'payinfo' => $options{payinfo},
484 'paydate' => $paydate,
485 'recurring_billing' => $content{recurring_billing},
486 'pkgnum' => $options{'pkgnum'},
488 'gatewaynum' => $payment_gateway->gatewaynum || '',
489 'session_id' => $options{session_id} || '',
490 'jobnum' => $options{depend_jobnum} || '',
492 $cust_pay_pending->payunique( $options{payunique} )
493 if defined($options{payunique}) && length($options{payunique});
494 my $cpp_new_err = $cust_pay_pending->insert; #mutex lost when this is inserted
495 return $cpp_new_err if $cpp_new_err;
497 my( $action1, $action2 ) =
498 split( /\s*\,\s*/, $payment_gateway->gateway_action );
500 my $transaction = new $namespace( $payment_gateway->gateway_module,
501 $self->_bop_options(\%options),
504 $transaction->content(
505 'type' => $options{method},
506 $self->_bop_auth(\%options),
507 'action' => $action1,
508 'description' => $options{'description'},
509 'amount' => $options{amount},
510 #'invoice_number' => $options{'invnum'},
511 'customer_id' => $self->custnum,
513 'reference' => $cust_pay_pending->paypendingnum, #for now
518 $cust_pay_pending->status('pending');
519 my $cpp_pending_err = $cust_pay_pending->replace;
520 return $cpp_pending_err if $cpp_pending_err;
524 my $BOP_TESTING_SUCCESS = 1;
526 unless ( $BOP_TESTING ) {
527 $transaction->test_transaction(1)
528 if $conf->exists('business-onlinepayment-test_transaction');
529 $transaction->submit();
531 if ( $BOP_TESTING_SUCCESS ) {
532 $transaction->is_success(1);
533 $transaction->authorization('fake auth');
535 $transaction->is_success(0);
536 $transaction->error_message('fake failure');
540 if ( $transaction->is_success() && $namespace eq 'Business::OnlineThirdPartyPayment' ) {
542 return { reference => $cust_pay_pending->paypendingnum,
543 map { $_ => $transaction->$_ } qw ( popup_url collectitems ) };
545 } elsif ( $transaction->is_success() && $action2 ) {
547 $cust_pay_pending->status('authorized');
548 my $cpp_authorized_err = $cust_pay_pending->replace;
549 return $cpp_authorized_err if $cpp_authorized_err;
551 my $auth = $transaction->authorization;
552 my $ordernum = $transaction->can('order_number')
553 ? $transaction->order_number
557 new Business::OnlinePayment( $payment_gateway->gateway_module,
558 $self->_bop_options(\%options),
563 type => $options{method},
565 $self->_bop_auth(\%options),
566 order_number => $ordernum,
567 amount => $options{amount},
568 authorization => $auth,
569 description => $options{'description'},
572 foreach my $field (qw( authorization_source_code returned_ACI
573 transaction_identifier validation_code
574 transaction_sequence_num local_transaction_date
575 local_transaction_time AVS_result_code )) {
576 $capture{$field} = $transaction->$field() if $transaction->can($field);
579 $capture->content( %capture );
581 $capture->test_transaction(1)
582 if $conf->exists('business-onlinepayment-test_transaction');
585 unless ( $capture->is_success ) {
586 my $e = "Authorization successful but capture failed, custnum #".
587 $self->custnum. ': '. $capture->result_code.
588 ": ". $capture->error_message;
596 # remove paycvv after initial transaction
599 #false laziness w/misc/process/payment.cgi - check both to make sure working
601 if ( length($self->paycvv)
602 && ! grep { $_ eq cardtype($options{payinfo}) } $conf->config('cvv-save')
604 my $error = $self->remove_cvv;
606 warn "WARNING: error removing cvv: $error\n";
615 if ( $transaction->can('card_token') && $transaction->card_token ) {
617 $self->card_token($transaction->card_token);
619 if ( $options{'payinfo'} eq $self->payinfo ) {
620 $self->payinfo($transaction->card_token);
621 my $error = $self->replace;
623 warn "WARNING: error storing token: $error, but proceeding anyway\n";
633 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
645 if (ref($_[0]) eq 'HASH') {
648 my ( $method, $amount ) = ( shift, shift );
650 $options{method} = $method;
651 $options{amount} = $amount;
654 if ( $options{'fake_failure'} ) {
655 return "Error: No error; test failure requested with fake_failure";
659 #if ( $payment_gateway->gatewaynum ) { # agent override
660 # $paybatch = $payment_gateway->gatewaynum. '-';
663 #$paybatch .= "$processor:". $transaction->authorization;
665 #$paybatch .= ':'. $transaction->order_number
666 # if $transaction->can('order_number')
667 # && length($transaction->order_number);
669 my $paybatch = 'FakeProcessor:54:32';
671 my $cust_pay = new FS::cust_pay ( {
672 'custnum' => $self->custnum,
673 'invnum' => $options{'invnum'},
674 'paid' => $options{amount},
676 'payby' => $bop_method2payby{$options{method}},
677 #'payinfo' => $payinfo,
678 'payinfo' => '4111111111111111',
679 'paybatch' => $paybatch,
680 #'paydate' => $paydate,
681 'paydate' => '2012-05-01',
683 $cust_pay->payunique( $options{payunique} ) if length($options{payunique});
685 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
688 $cust_pay->invnum(''); #try again with no specific invnum
689 my $error2 = $cust_pay->insert( $options{'manual'} ?
690 ( 'manual' => 1 ) : ()
693 # gah, even with transactions.
694 my $e = 'WARNING: Card/ACH debited but database not updated - '.
695 "error inserting (fake!) payment: $error2".
696 " (previously tried insert with invnum #$options{'invnum'}" .
703 if ( $options{'paynum_ref'} ) {
704 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
712 # item _realtime_bop_result CUST_PAY_PENDING, BOP_OBJECT [ OPTION => VALUE ... ]
714 # Wraps up processing of a realtime credit card, ACH (electronic check) or
715 # phone bill transaction.
717 sub _realtime_bop_result {
718 my( $self, $cust_pay_pending, $transaction, %options ) = @_;
720 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
723 warn "$me _realtime_bop_result: pending transaction ".
724 $cust_pay_pending->paypendingnum. "\n";
725 warn " $_ => $options{$_}\n" foreach keys %options;
728 my $payment_gateway = $options{payment_gateway}
729 or return "no payment gateway in arguments to _realtime_bop_result";
731 $cust_pay_pending->status($transaction->is_success() ? 'captured' : 'declined');
732 my $cpp_captured_err = $cust_pay_pending->replace;
733 return $cpp_captured_err if $cpp_captured_err;
735 if ( $transaction->is_success() ) {
738 if ( $payment_gateway->gatewaynum ) { # agent override
739 $paybatch = $payment_gateway->gatewaynum. '-';
742 $paybatch .= $payment_gateway->gateway_module. ":".
743 $transaction->authorization;
745 $paybatch .= ':'. $transaction->order_number
746 if $transaction->can('order_number')
747 && length($transaction->order_number);
749 my $cust_pay = new FS::cust_pay ( {
750 'custnum' => $self->custnum,
751 'invnum' => $options{'invnum'},
752 'paid' => $cust_pay_pending->paid,
754 'payby' => $cust_pay_pending->payby,
755 'payinfo' => $options{'payinfo'},
756 'paybatch' => $paybatch,
757 'paydate' => $cust_pay_pending->paydate,
758 'pkgnum' => $cust_pay_pending->pkgnum,
759 'discount_term' => $options{'discount_term'},
761 #doesn't hurt to know, even though the dup check is in cust_pay_pending now
762 $cust_pay->payunique( $options{payunique} )
763 if defined($options{payunique}) && length($options{payunique});
765 my $oldAutoCommit = $FS::UID::AutoCommit;
766 local $FS::UID::AutoCommit = 0;
769 #start a transaction, insert the cust_pay and set cust_pay_pending.status to done in a single transction
771 my $error = $cust_pay->insert($options{'manual'} ? ( 'manual' => 1 ) : () );
774 $cust_pay->invnum(''); #try again with no specific invnum
775 my $error2 = $cust_pay->insert( $options{'manual'} ?
776 ( 'manual' => 1 ) : ()
779 # gah. but at least we have a record of the state we had to abort in
780 # from cust_pay_pending now.
781 my $e = "WARNING: $options{method} captured but payment not recorded -".
782 " error inserting payment (". $payment_gateway->gateway_module.
784 " (previously tried insert with invnum #$options{'invnum'}" .
785 ": $error ) - pending payment saved as paypendingnum ".
786 $cust_pay_pending->paypendingnum. "\n";
792 my $jobnum = $cust_pay_pending->jobnum;
794 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
796 unless ( $placeholder ) {
797 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
798 my $e = "WARNING: $options{method} captured but job $jobnum not ".
799 "found for paypendingnum ". $cust_pay_pending->paypendingnum. "\n";
804 $error = $placeholder->delete;
807 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
808 my $e = "WARNING: $options{method} captured but could not delete ".
809 "job $jobnum for paypendingnum ".
810 $cust_pay_pending->paypendingnum. ": $error\n";
817 if ( $options{'paynum_ref'} ) {
818 ${ $options{'paynum_ref'} } = $cust_pay->paynum;
821 $cust_pay_pending->status('done');
822 $cust_pay_pending->statustext('captured');
823 $cust_pay_pending->paynum($cust_pay->paynum);
824 my $cpp_done_err = $cust_pay_pending->replace;
826 if ( $cpp_done_err ) {
828 $dbh->rollback or die $dbh->errstr if $oldAutoCommit;
829 my $e = "WARNING: $options{method} captured but payment not recorded - ".
830 "error updating status for paypendingnum ".
831 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
837 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
839 if ( $options{'apply'} ) {
840 my $apply_error = $self->apply_payments_and_credits;
841 if ( $apply_error ) {
842 warn "WARNING: error applying payment: $apply_error\n";
843 #but we still should return no error cause the payment otherwise went
854 my $perror = $payment_gateway->gateway_module. " error: ".
855 $transaction->error_message;
857 my $jobnum = $cust_pay_pending->jobnum;
859 my $placeholder = qsearchs( 'queue', { 'jobnum' => $jobnum } );
861 if ( $placeholder ) {
862 my $error = $placeholder->depended_delete;
863 $error ||= $placeholder->delete;
864 warn "error removing provisioning jobs after declined paypendingnum ".
865 $cust_pay_pending->paypendingnum. "\n";
867 my $e = "error finding job $jobnum for declined paypendingnum ".
868 $cust_pay_pending->paypendingnum. "\n";
874 unless ( $transaction->error_message ) {
877 if ( $transaction->can('response_page') ) {
879 'page' => ( $transaction->can('response_page')
880 ? $transaction->response_page
883 'code' => ( $transaction->can('response_code')
884 ? $transaction->response_code
887 'headers' => ( $transaction->can('response_headers')
888 ? $transaction->response_headers
894 "No additional debugging information available for ".
895 $payment_gateway->gateway_module;
898 $perror .= "No error_message returned from ".
899 $payment_gateway->gateway_module. " -- ".
900 ( ref($t_response) ? Dumper($t_response) : $t_response );
904 if ( !$options{'quiet'} && !$realtime_bop_decline_quiet
905 && $conf->exists('emaildecline')
906 && grep { $_ ne 'POST' } $self->invoicing_list
907 && ! grep { $transaction->error_message =~ /$_/ }
908 $conf->config('emaildecline-exclude')
911 # Send a decline alert to the customer.
912 my $msgnum = $conf->config('decline_msgnum', $self->agentnum);
915 # include the raw error message in the transaction state
916 $cust_pay_pending->setfield('error', $transaction->error_message);
917 my $msg_template = qsearchs('msg_template', { msgnum => $msgnum });
918 $error = $msg_template->send( 'cust_main' => $self,
919 'object' => $cust_pay_pending );
923 my @templ = $conf->config('declinetemplate');
924 my $template = new Text::Template (
926 SOURCE => [ map "$_\n", @templ ],
927 ) or return "($perror) can't create template: $Text::Template::ERROR";
929 or return "($perror) can't compile template: $Text::Template::ERROR";
933 scalar( $conf->config('company_name', $self->agentnum ) ),
935 join("\n", $conf->config('company_address', $self->agentnum ) ),
936 'error' => $transaction->error_message,
939 my $error = send_email(
940 'from' => $conf->config('invoice_from', $self->agentnum ),
941 'to' => [ grep { $_ ne 'POST' } $self->invoicing_list ],
942 'subject' => 'Your payment could not be processed',
943 'body' => [ $template->fill_in(HASH => $templ_hash) ],
947 $perror .= " (also received error sending decline notification: $error)"
952 $cust_pay_pending->status('done');
953 $cust_pay_pending->statustext("declined: $perror");
954 my $cpp_done_err = $cust_pay_pending->replace;
955 if ( $cpp_done_err ) {
956 my $e = "WARNING: $options{method} declined but pending payment not ".
957 "resolved - error updating status for paypendingnum ".
958 $cust_pay_pending->paypendingnum. ": $cpp_done_err \n";
960 $perror = "$e ($perror)";
968 =item realtime_botpp_capture CUST_PAY_PENDING [ OPTION => VALUE ... ]
970 Verifies successful third party processing of a realtime credit card,
971 ACH (electronic check) or phone bill transaction via a
972 Business::OnlineThirdPartyPayment realtime gateway. See
973 L<http://420.am/business-onlinethirdpartypayment> for supported gateways.
975 Available options are: I<description>, I<invnum>, I<quiet>, I<paynum_ref>, I<payunique>
977 The additional options I<payname>, I<city>, I<state>,
978 I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
979 if set, will override the value from the customer record.
981 I<description> is a free-text field passed to the gateway. It defaults to
984 If an I<invnum> is specified, this payment (if successful) is applied to the
985 specified invoice. If you don't specify an I<invnum> you might want to
986 call the B<apply_payments> method.
988 I<quiet> can be set true to surpress email decline notices.
990 I<paynum_ref> can be set to a scalar reference. It will be filled in with the
991 resulting paynum, if any.
993 I<payunique> is a unique identifier for this payment.
995 Returns a hashref containing elements bill_error (which will be undefined
996 upon success) and session_id of any associated session.
1000 sub realtime_botpp_capture {
1001 my( $self, $cust_pay_pending, %options ) = @_;
1003 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1006 warn "$me realtime_botpp_capture: pending transaction $cust_pay_pending\n";
1007 warn " $_ => $options{$_}\n" foreach keys %options;
1010 eval "use Business::OnlineThirdPartyPayment";
1014 # select the gateway
1017 my $method = FS::payby->payby2bop($cust_pay_pending->payby);
1019 my $payment_gateway = $cust_pay_pending->gatewaynum
1020 ? qsearchs( 'payment_gateway',
1021 { gatewaynum => $cust_pay_pending->gatewaynum }
1023 : $self->agent->payment_gateway( 'method' => $method,
1024 # 'invnum' => $cust_pay_pending->invnum,
1025 # 'payinfo' => $cust_pay_pending->payinfo,
1028 $options{payment_gateway} = $payment_gateway; # for the helper subs
1034 my @invoicing_list = $self->invoicing_list_emailonly;
1035 if ( $conf->exists('emailinvoiceautoalways')
1036 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1037 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1038 push @invoicing_list, $self->all_emails;
1041 my $email = ($conf->exists('business-onlinepayment-email-override'))
1042 ? $conf->config('business-onlinepayment-email-override')
1043 : $invoicing_list[0];
1047 $content{email_customer} =
1048 ( $conf->exists('business-onlinepayment-email_customer')
1049 || $conf->exists('business-onlinepayment-email-override') );
1052 # run transaction(s)
1056 new Business::OnlineThirdPartyPayment( $payment_gateway->gateway_module,
1057 $self->_bop_options(\%options),
1060 $transaction->reference({ %options });
1062 $transaction->content(
1064 $self->_bop_auth(\%options),
1065 'action' => 'Post Authorization',
1066 'description' => $options{'description'},
1067 'amount' => $cust_pay_pending->paid,
1068 #'invoice_number' => $options{'invnum'},
1069 'customer_id' => $self->custnum,
1070 'referer' => 'http://cleanwhisker.420.am/',
1071 'reference' => $cust_pay_pending->paypendingnum,
1073 'phone' => $self->daytime || $self->night,
1075 # plus whatever is required for bogus capture avoidance
1078 $transaction->submit();
1081 $self->_realtime_bop_result( $cust_pay_pending, $transaction, %options );
1084 bill_error => $error,
1085 session_id => $cust_pay_pending->session_id,
1090 =item default_payment_gateway
1092 DEPRECATED -- use agent->payment_gateway
1096 sub default_payment_gateway {
1097 my( $self, $method ) = @_;
1099 die "Real-time processing not enabled\n"
1100 unless $conf->exists('business-onlinepayment');
1102 #warn "default_payment_gateway deprecated -- use agent->payment_gateway\n";
1105 my $bop_config = 'business-onlinepayment';
1106 $bop_config .= '-ach'
1107 if $method =~ /^(ECHECK|CHEK)$/ && $conf->exists($bop_config. '-ach');
1108 my ( $processor, $login, $password, $action, @bop_options ) =
1109 $conf->config($bop_config);
1110 $action ||= 'normal authorization';
1111 pop @bop_options if scalar(@bop_options) % 2 && $bop_options[-1] =~ /^\s*$/;
1112 die "No real-time processor is enabled - ".
1113 "did you set the business-onlinepayment configuration value?\n"
1116 ( $processor, $login, $password, $action, @bop_options )
1119 =item realtime_refund_bop METHOD [ OPTION => VALUE ... ]
1121 Refunds a realtime credit card, ACH (electronic check) or phone bill transaction
1122 via a Business::OnlinePayment realtime gateway. See
1123 L<http://420.am/business-onlinepayment> for supported gateways.
1125 Available methods are: I<CC>, I<ECHECK> and I<LEC>
1127 Available options are: I<amount>, I<reason>, I<paynum>, I<paydate>
1129 Most gateways require a reference to an original payment transaction to refund,
1130 so you probably need to specify a I<paynum>.
1132 I<amount> defaults to the original amount of the payment if not specified.
1134 I<reason> specifies a reason for the refund.
1136 I<paydate> specifies the expiration date for a credit card overriding the
1137 value from the customer record or the payment record. Specified as yyyy-mm-dd
1139 Implementation note: If I<amount> is unspecified or equal to the amount of the
1140 orignal payment, first an attempt is made to "void" the transaction via
1141 the gateway (to cancel a not-yet settled transaction) and then if that fails,
1142 the normal attempt is made to "refund" ("credit") the transaction via the
1143 gateway is attempted.
1145 #The additional options I<payname>, I<address1>, I<address2>, I<city>, I<state>,
1146 #I<zip>, I<payinfo> and I<paydate> are also available. Any of these options,
1147 #if set, will override the value from the customer record.
1149 #If an I<invnum> is specified, this payment (if successful) is applied to the
1150 #specified invoice. If you don't specify an I<invnum> you might want to
1151 #call the B<apply_payments> method.
1155 #some false laziness w/realtime_bop, not enough to make it worth merging
1156 #but some useful small subs should be pulled out
1157 sub realtime_refund_bop {
1160 local($DEBUG) = $FS::cust_main::DEBUG if $FS::cust_main::DEBUG > $DEBUG;
1163 if (ref($_[0]) eq 'HASH') {
1164 %options = %{$_[0]};
1168 $options{method} = $method;
1172 warn "$me realtime_refund_bop (new): $options{method} refund\n";
1173 warn " $_ => $options{$_}\n" foreach keys %options;
1177 # look up the original payment and optionally a gateway for that payment
1181 my $amount = $options{'amount'};
1183 my( $processor, $login, $password, @bop_options, $namespace ) ;
1184 my( $auth, $order_number ) = ( '', '', '' );
1186 if ( $options{'paynum'} ) {
1188 warn " paynum: $options{paynum}\n" if $DEBUG > 1;
1189 $cust_pay = qsearchs('cust_pay', { paynum=>$options{'paynum'} } )
1190 or return "Unknown paynum $options{'paynum'}";
1191 $amount ||= $cust_pay->paid;
1193 $cust_pay->paybatch =~ /^((\d+)\-)?(\w+):\s*([\w\-\/ ]*)(:([\w\-]+))?$/
1194 or return "Can't parse paybatch for paynum $options{'paynum'}: ".
1195 $cust_pay->paybatch;
1196 my $gatewaynum = '';
1197 ( $gatewaynum, $processor, $auth, $order_number ) = ( $2, $3, $4, $6 );
1199 if ( $gatewaynum ) { #gateway for the payment to be refunded
1201 my $payment_gateway =
1202 qsearchs('payment_gateway', { 'gatewaynum' => $gatewaynum } );
1203 die "payment gateway $gatewaynum not found"
1204 unless $payment_gateway;
1206 $processor = $payment_gateway->gateway_module;
1207 $login = $payment_gateway->gateway_username;
1208 $password = $payment_gateway->gateway_password;
1209 $namespace = $payment_gateway->gateway_namespace;
1210 @bop_options = $payment_gateway->options;
1212 } else { #try the default gateway
1215 my $payment_gateway =
1216 $self->agent->payment_gateway('method' => $options{method});
1218 ( $conf_processor, $login, $password, $namespace ) =
1219 map { my $method = "gateway_$_"; $payment_gateway->$method }
1220 qw( module username password namespace );
1222 @bop_options = $payment_gateway->gatewaynum
1223 ? $payment_gateway->options
1224 : @{ $payment_gateway->get('options') };
1226 return "processor of payment $options{'paynum'} $processor does not".
1227 " match default processor $conf_processor"
1228 unless $processor eq $conf_processor;
1233 } else { # didn't specify a paynum, so look for agent gateway overrides
1234 # like a normal transaction
1236 my $payment_gateway =
1237 $self->agent->payment_gateway( 'method' => $options{method},
1238 #'payinfo' => $payinfo,
1240 my( $processor, $login, $password, $namespace ) =
1241 map { my $method = "gateway_$_"; $payment_gateway->$method }
1242 qw( module username password namespace );
1244 my @bop_options = $payment_gateway->gatewaynum
1245 ? $payment_gateway->options
1246 : @{ $payment_gateway->get('options') };
1249 return "neither amount nor paynum specified" unless $amount;
1251 eval "use $namespace";
1255 'type' => $options{method},
1257 'password' => $password,
1258 'order_number' => $order_number,
1259 'amount' => $amount,
1260 'referer' => 'http://cleanwhisker.420.am/', #XXX fix referer :/
1262 $content{authorization} = $auth
1263 if length($auth); #echeck/ACH transactions have an order # but no auth
1264 #(at least with authorize.net)
1266 my $disable_void_after;
1267 if ($conf->exists('disable_void_after')
1268 && $conf->config('disable_void_after') =~ /^(\d+)$/) {
1269 $disable_void_after = $1;
1272 #first try void if applicable
1273 if ( $cust_pay && $cust_pay->paid == $amount
1275 ( not defined($disable_void_after) )
1276 || ( time < ($cust_pay->_date + $disable_void_after ) )
1279 warn " attempting void\n" if $DEBUG > 1;
1280 my $void = new Business::OnlinePayment( $processor, @bop_options );
1281 if ( $void->can('info') ) {
1282 if ( $cust_pay->payby eq 'CARD'
1283 && $void->info('CC_void_requires_card') )
1285 $content{'card_number'} = $cust_pay->payinfo;
1286 } elsif ( $cust_pay->payby eq 'CHEK'
1287 && $void->info('ECHECK_void_requires_account') )
1289 ( $content{'account_number'}, $content{'routing_code'} ) =
1290 split('@', $cust_pay->payinfo);
1291 $content{'name'} = $self->get('first'). ' '. $self->get('last');
1294 $void->content( 'action' => 'void', %content );
1295 $void->test_transaction(1)
1296 if $conf->exists('business-onlinepayment-test_transaction');
1298 if ( $void->is_success ) {
1299 my $error = $cust_pay->void($options{'reason'});
1301 # gah, even with transactions.
1302 my $e = 'WARNING: Card/ACH voided but database not updated - '.
1303 "error voiding payment: $error";
1307 warn " void successful\n" if $DEBUG > 1;
1312 warn " void unsuccessful, trying refund\n"
1316 my $address = $self->address1;
1317 $address .= ", ". $self->address2 if $self->address2;
1319 my($payname, $payfirst, $paylast);
1320 if ( $self->payname && $options{method} ne 'ECHECK' ) {
1321 $payname = $self->payname;
1322 $payname =~ /^\s*([\w \,\.\-\']*)?\s+([\w\,\.\-\']+)\s*$/
1323 or return "Illegal payname $payname";
1324 ($payfirst, $paylast) = ($1, $2);
1326 $payfirst = $self->getfield('first');
1327 $paylast = $self->getfield('last');
1328 $payname = "$payfirst $paylast";
1331 my @invoicing_list = $self->invoicing_list_emailonly;
1332 if ( $conf->exists('emailinvoiceautoalways')
1333 || $conf->exists('emailinvoiceauto') && ! @invoicing_list
1334 || ( $conf->exists('emailinvoiceonly') && ! @invoicing_list ) ) {
1335 push @invoicing_list, $self->all_emails;
1338 my $email = ($conf->exists('business-onlinepayment-email-override'))
1339 ? $conf->config('business-onlinepayment-email-override')
1340 : $invoicing_list[0];
1342 my $payip = exists($options{'payip'})
1345 $content{customer_ip} = $payip
1349 if ( $options{method} eq 'CC' ) {
1352 $content{card_number} = $payinfo = $cust_pay->payinfo;
1353 (exists($options{'paydate'}) ? $options{'paydate'} : $cust_pay->paydate)
1354 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/ &&
1355 ($content{expiration} = "$2/$1"); # where available
1357 $content{card_number} = $payinfo = $self->payinfo;
1358 (exists($options{'paydate'}) ? $options{'paydate'} : $self->paydate)
1359 =~ /^\d{2}(\d{2})[\/\-](\d+)[\/\-]\d+$/;
1360 $content{expiration} = "$2/$1";
1363 } elsif ( $options{method} eq 'ECHECK' ) {
1366 $payinfo = $cust_pay->payinfo;
1368 $payinfo = $self->payinfo;
1370 ( $content{account_number}, $content{routing_code} )= split('@', $payinfo );
1371 $content{bank_name} = $self->payname;
1372 $content{account_type} = 'CHECKING';
1373 $content{account_name} = $payname;
1374 $content{customer_org} = $self->company ? 'B' : 'I';
1375 $content{customer_ssn} = $self->ss;
1376 } elsif ( $options{method} eq 'LEC' ) {
1377 $content{phone} = $payinfo = $self->payinfo;
1381 my $refund = new Business::OnlinePayment( $processor, @bop_options );
1382 my %sub_content = $refund->content(
1383 'action' => 'credit',
1384 'customer_id' => $self->custnum,
1385 'last_name' => $paylast,
1386 'first_name' => $payfirst,
1388 'address' => $address,
1389 'city' => $self->city,
1390 'state' => $self->state,
1391 'zip' => $self->zip,
1392 'country' => $self->country,
1394 'phone' => $self->daytime || $self->night,
1397 warn join('', map { " $_ => $sub_content{$_}\n" } keys %sub_content )
1399 $refund->test_transaction(1)
1400 if $conf->exists('business-onlinepayment-test_transaction');
1403 return "$processor error: ". $refund->error_message
1404 unless $refund->is_success();
1406 my $paybatch = "$processor:". $refund->authorization;
1407 $paybatch .= ':'. $refund->order_number
1408 if $refund->can('order_number') && $refund->order_number;
1410 while ( $cust_pay && $cust_pay->unapplied < $amount ) {
1411 my @cust_bill_pay = $cust_pay->cust_bill_pay;
1412 last unless @cust_bill_pay;
1413 my $cust_bill_pay = pop @cust_bill_pay;
1414 my $error = $cust_bill_pay->delete;
1418 my $cust_refund = new FS::cust_refund ( {
1419 'custnum' => $self->custnum,
1420 'paynum' => $options{'paynum'},
1421 'refund' => $amount,
1423 'payby' => $bop_method2payby{$options{method}},
1424 'payinfo' => $payinfo,
1425 'paybatch' => $paybatch,
1426 'reason' => $options{'reason'} || 'card or ACH refund',
1428 my $error = $cust_refund->insert;
1430 $cust_refund->paynum(''); #try again with no specific paynum
1431 my $error2 = $cust_refund->insert;
1433 # gah, even with transactions.
1434 my $e = 'WARNING: Card/ACH refunded but database not updated - '.
1435 "error inserting refund ($processor): $error2".
1436 " (previously tried insert with paynum #$options{'paynum'}" .
1455 L<FS::cust_main>, L<FS::cust_main::Billing>