1 package FS::cust_payby;
2 use base qw( FS::payinfo_Mixin FS::cust_main_Mixin FS::Record );
5 use Scalar::Util qw( blessed );
6 use Digest::SHA qw( sha512_base64 );
7 use Business::CreditCard qw( validate cardtype );
9 use FS::Msgcat qw( gettext );
10 use FS::Misc qw( card_types );
11 use FS::Record; #qw( qsearch qsearchs );
16 our @encrypted_fields = ('payinfo', 'paycvv');
17 sub nohistory_fields { ('payinfo', 'paycvv'); }
19 our $ignore_expired_card = 0;
20 our $ignore_banned_card = 0;
21 our $ignore_invalid_card = 0;
22 our $ignore_cardtype = 0;
25 install_callback FS::UID sub {
27 #yes, need it for stuff below (prolly should be cached)
28 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
33 FS::cust_payby - Object methods for cust_payby records
39 $record = new FS::cust_payby \%hash;
40 $record = new FS::cust_payby { 'column' => 'value' };
42 $error = $record->insert;
44 $error = $new_record->replace($old_record);
46 $error = $record->delete;
48 $error = $record->check;
52 An FS::cust_payby object represents customer stored payment information.
53 FS::cust_payby inherits from FS::Record. The following fields are currently
120 The credit card type (deduced from the card number).
130 Creates a new record. To add the record to the database, see L<"insert">.
132 Note that this stores the hash reference, not a distinct copy of the hash it
133 points to. You can ask the object for a copy with the I<hash> method.
137 # the new method can be inherited from FS::Record, if a table method is defined
139 sub table { 'cust_payby'; }
143 Adds this record to the database. If there is an error, returns the error,
144 otherwise returns false.
151 local $SIG{HUP} = 'IGNORE';
152 local $SIG{INT} = 'IGNORE';
153 local $SIG{QUIT} = 'IGNORE';
154 local $SIG{TERM} = 'IGNORE';
155 local $SIG{TSTP} = 'IGNORE';
156 local $SIG{PIPE} = 'IGNORE';
158 my $oldAutoCommit = $FS::UID::AutoCommit;
159 local $FS::UID::AutoCommit = 0;
162 my $error = $self->check_payinfo_cardtype
163 || $self->SUPER::insert;
165 $dbh->rollback if $oldAutoCommit;
169 if ( $self->payby =~ /^(CARD|CHEK)$/ ) {
170 # new auto card/check info, want to retry realtime_ invoice events
171 # (new customer? that's okay, they won't have any)
172 my $error = $self->cust_main->retry_realtime;
174 $dbh->rollback if $oldAutoCommit;
179 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
186 Delete this record from the database.
188 =item replace OLD_RECORD
190 Replaces the OLD_RECORD with this one in the database. If there is an error,
191 returns the error, otherwise returns false.
198 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
200 : $self->replace_old;
202 if ( $self->payby =~ /^(CARD|DCRD)$/
203 && ( $self->payinfo =~ /xx/
204 || $self->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
209 $self->payinfo($old->payinfo);
211 } elsif ( $self->payby =~ /^(CHEK|DCHK)$/ && $self->payinfo =~ /xx/ ) {
212 #fix for #3085 "edit of customer's routing code only surprisingly causes
213 #nothing to happen...
214 # this probably won't do the right thing when we don't have the
215 # public key (can't actually get the real $old->payinfo)
216 my($new_account, $new_aba) = split('@', $self->payinfo);
217 my($old_account, $old_aba) = split('@', $old->payinfo);
218 $new_account = $old_account if $new_account =~ /xx/;
219 $new_aba = $old_aba if $new_aba =~ /xx/;
220 $self->payinfo($new_account.'@'.$new_aba);
223 # only unmask paycvv if payinfo stayed the same
224 if ( $self->payby =~ /^(CARD|DCRD)$/ and $self->paycvv =~ /^\s*[\*x]+\s*$/ ) {
225 if ( $old->payinfo eq $self->payinfo
226 && $old->paymask eq $self->paymask
228 $self->paycvv($old->paycvv);
234 local($ignore_expired_card) = 1
235 if $old->payby =~ /^(CARD|DCRD)$/
236 && $self->payby =~ /^(CARD|DCRD)$/
237 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
239 local($ignore_banned_card) = 1
240 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
241 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
242 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
244 if ( $self->payby =~ /^(CARD|DCRD)$/
245 && $old->payinfo ne $self->payinfo
246 && $old->paymask ne $self->paymask )
248 my $error = $self->check_payinfo_cardtype;
249 return $error if $error;
251 if ( $conf->exists('business-onlinepayment-verification') ) {
252 $error = $self->verify;
254 $error = $self->tokenize;
256 return $error if $error;
260 local $SIG{HUP} = 'IGNORE';
261 local $SIG{INT} = 'IGNORE';
262 local $SIG{QUIT} = 'IGNORE';
263 local $SIG{TERM} = 'IGNORE';
264 local $SIG{TSTP} = 'IGNORE';
265 local $SIG{PIPE} = 'IGNORE';
267 my $oldAutoCommit = $FS::UID::AutoCommit;
268 local $FS::UID::AutoCommit = 0;
271 my $error = $self->SUPER::replace($old);
273 $dbh->rollback if $oldAutoCommit;
277 if ( $self->payby =~ /^(CARD|CHEK)$/
278 && ( ( $self->get('payinfo') ne $old->get('payinfo')
281 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
286 # card/check/lec info has changed, want to retry realtime_ invoice events
287 my $error = $self->cust_main->retry_realtime;
289 $dbh->rollback if $oldAutoCommit;
294 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
301 Checks all fields to make sure this is a valid record. If there is
302 an error, returns the error, otherwise returns false. Called by the insert
311 $self->ut_numbern('custpaybynum')
312 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
313 || $self->ut_numbern('weight')
314 #encrypted #|| $self->ut_textn('payinfo')
315 #encrypted #|| $self->ut_textn('paycvv')
316 # || $self->ut_textn('paymask') #XXX something
317 #later #|| $self->ut_textn('paydate')
318 || $self->ut_numbern('paystart_month')
319 || $self->ut_numbern('paystart_year')
320 || $self->ut_numbern('payissue')
321 # || $self->ut_textn('payname') #XXX something
322 || $self->ut_alphan('paystate')
323 || $self->ut_textn('paytype')
324 || $self->ut_ipn('payip')
326 return $error if $error;
330 FS::payby->can_payby($self->table, $self->payby)
331 or return "Illegal payby: ". $self->payby;
333 # If it is encrypted and the private key is not availaible then we can't
334 # check the credit card.
335 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
337 # Need some kind of global flag to accept invalid cards, for testing
339 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
341 # In this block: detect card type; reject credit card / account numbers that
342 # are impossible or banned; reject other payment features (date, CVV length)
343 # that are inappropriate for the card type.
344 # However, if the payinfo is encrypted then just detect card type and assume
345 # the other checks were already done.
347 if ( !$ignore_invalid_card &&
348 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
350 my $payinfo = $self->payinfo;
352 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
353 or return gettext('invalid_card'); #. ": ". $self->payinfo;
355 $self->payinfo($payinfo);
357 or return gettext('invalid_card'); # . ": ". $self->payinfo;
359 # see parallel checks in check_payinfo_cardtype & payinfo_Mixin::payinfo_check
361 if ( $self->tokenized ) {
362 if ( $self->paymask =~ /^\d+x/ ) {
363 $cardtype = cardtype($self->paymask);
366 #return "paycardtype required ".
367 # "(can't derive from a token and no paymask w/prefix provided)";
370 $cardtype = cardtype($self->payinfo);
373 return gettext('unknown_card_type') if $cardtype eq "Unknown";
375 $self->set('paycardtype', $cardtype);
377 unless ( $ignore_banned_card ) {
378 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
380 if ( $ban->bantype eq 'warn' ) {
381 #or others depending on value of $ban->reason ?
382 return '_duplicate_card'.
383 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
384 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
385 ' (ban# '. $ban->bannum. ')'
386 unless $self->override_ban_warn;
388 return 'Banned credit card: banned on '.
389 time2str('%a %h %o at %r', $ban->_date).
390 ' by '. $ban->otaker.
391 ' (ban# '. $ban->bannum. ')';
396 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
397 if ( $cardtype eq 'American Express card' ) {
398 $self->paycvv =~ /^(\d{4})$/
399 or return "CVV2 (CID) for American Express cards is four digits.";
402 $self->paycvv =~ /^(\d{3})$/
403 or return "CVV2 (CVC2/CID) is three digits.";
410 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
412 return "Start date or issue number is required for $cardtype cards"
413 unless $self->paystart_month && $self->paystart_year or $self->payissue;
415 return "Start month must be between 1 and 12"
416 if $self->paystart_month
417 and $self->paystart_month < 1 || $self->paystart_month > 12;
419 return "Start year must be 1990 or later"
420 if $self->paystart_year
421 and $self->paystart_year < 1990;
423 return "Issue number must be beween 1 and 99"
425 and $self->payissue < 1 || $self->payissue > 99;
428 $self->paystart_month('');
429 $self->paystart_year('');
433 } elsif ( !$ignore_invalid_card &&
434 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
436 my $payinfo = $self->payinfo;
437 $payinfo =~ s/[^\d\@\.]//g;
438 if ( $conf->config('echeck-country') eq 'CA' ) {
439 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
440 or return 'invalid echeck account@branch.bank';
441 $payinfo = "$1\@$2.$3";
442 } elsif ( $conf->config('echeck-country') eq 'US' ) {
443 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
446 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
449 $self->payinfo($payinfo);
452 unless ( $ignore_banned_card ) {
453 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
455 if ( $ban->bantype eq 'warn' ) {
456 #or others depending on value of $ban->reason ?
457 return '_duplicate_ach' unless $self->override_ban_warn;
459 return 'Banned ACH account: banned on '.
460 time2str('%a %h %o at %r', $ban->_date).
461 ' by '. $ban->otaker.
462 ' (ban# '. $ban->bannum. ')';
467 } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
468 # either ignoring invalid cards, or we can't decrypt the payinfo, but
469 # try to detect the card type anyway. this never returns failure, so
470 # the contract of $ignore_invalid_cards is maintained.
471 $self->set('paycardtype', cardtype($self->paymask));
473 $self->set('paycardtype', '');
476 # } elsif ( $self->payby eq 'PREPAY' ) {
478 # my $payinfo = $self->payinfo;
479 # $payinfo =~ s/\W//g; #anything else would just confuse things
480 # $self->payinfo($payinfo);
481 # $error = $self->ut_alpha('payinfo');
482 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
483 # return "Unknown prepayment identifier"
484 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
487 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
491 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
493 # shouldn't payinfo_check do this?
494 # (except we don't ever call payinfo_check from here)
495 return "Expiration date required"
496 if $self->paydate eq '' || $self->paydate eq '-';
499 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
500 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
501 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
502 ( $m, $y ) = ( $2, "19$1" );
503 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
504 ( $m, $y ) = ( $3, "20$2" );
506 return "Illegal expiration date: ". $self->paydate;
508 $m = sprintf('%02d',$m);
509 $self->paydate("$y-$m-01");
510 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
511 return gettext('expired_card')
514 !$ignore_expired_card
515 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
519 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
520 ( ! $conf->exists('require_cardname')
521 || $self->payby !~ /^(CARD|DCRD)$/ )
523 $self->payname( $self->first. " ". $self->getfield('last') );
526 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
527 $self->payname =~ /^([\w \,\.\-\']*)$/
528 or return gettext('illegal_name'). " payname: ". $self->payname;
531 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
532 or return gettext('illegal_name'). " payname: ". $self->payname;
538 if ( ! $self->custpaybynum ) {
539 if ($conf->exists('business-onlinepayment-verification')) {
540 $error = $self->verify;
542 $error = $self->tokenize;
544 return $error if $error;
550 sub check_payinfo_cardtype {
553 return '' if $ignore_cardtype;
555 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
557 my $payinfo = $self->payinfo;
560 # see parallel checks in cust_payby::check & payinfo_Mixin::payinfo_check
561 if ( $self->tokenized($payinfo) ) {
562 if ( $self->paymask =~ /^\d+x/ ) {
563 $self->set('paycardtype', cardtype($self->paymask));
565 $self->set('paycardtype', '');
566 #return "paycardtype required ".
567 # "(can't derive from a token and no paymask w/prefix provided)";
572 my %bop_card_types = map { $_=>1 } values %{ card_types() };
573 my $cardtype = cardtype($payinfo);
574 $self->set('paycardtype', $cardtype);
576 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
582 sub _banned_pay_hashref {
593 'payby' => $payby2ban{$self->payby},
594 'payinfo' => $self->payinfo,
595 #don't ever *search* on reason! #'reason' =>
599 sub _new_banned_pay_hashref {
601 my $hr = $self->_banned_pay_hashref;
602 $hr->{payinfo_hash} = 'SHA512';
603 $hr->{payinfo} = sha512_base64($hr->{payinfo});
607 =item paydate_mon_year
609 Returns a two element list consisting of the paydate month and year.
613 sub paydate_mon_year {
616 my $date = $self->paydate; # || '12-2037';
618 #false laziness w/elements/select-month_year.html
619 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
621 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
624 warn "unrecognized expiration date format: $date";
632 Returns a one line text label for this payment type.
649 my $name = $self->payby =~ /^(CARD|DCRD)$/
650 && $self->paycardtype || FS::payby->shortname($self->payby);
652 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
655 "$name: ". $self->paymask.
656 ( $self->payby =~ /^(CARD|DCRD)$/
657 ? ' Exp '. join('/', $self->paydate_mon_year)
665 Runs a L<realtime_bop|FS::cust_main::Billing_Realtime::realtime_bop> transaction on this card
670 my( $self, %opt ) = @_;
672 $self->cust_main->realtime_bop({
674 'cust_payby' => $self,
681 Runs a L<realtime_tokenize|FS::cust_main::Billing_Realtime::realtime_tokenize> transaction on this card
687 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
689 $self->cust_main->realtime_tokenize({
690 'cust_payby' => $self,
697 Runs a L<realtime_verify_bop|FS::cust_main::Billing_Realtime/realtime_verify_bop> transaction on this card
703 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
705 $self->cust_main->realtime_verify_bop({
706 'cust_payby' => $self,
713 Returns a list of valid values for the paytype field (bank account type for
714 electronic check payment).
721 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
724 =item cgi_cust_payby_fields
726 Returns the field names used in the web interface (including some pseudo-fields).
730 sub cgi_cust_payby_fields {
732 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
733 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
736 =item cgi_hash_callback HASHREF OLD
738 Subroutine (not a class or object method). Processes a hash reference
739 of web interface contet (transfers the data from pseudo-fields to real fields).
741 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
742 payissue and payip. If the new field is blank but the old is not, the old field
747 sub cgi_hash_callback {
755 # the payby selector gives the choice of CARD or CHEK (or others, but
756 # those are the ones with auto and on-demand versions). if the user didn't
757 # choose a weight, then they mean DCRD/DCHK.
758 $hashref->{payby} = $noauto{$hashref->{payby}}
759 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
761 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
763 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
768 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
769 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
770 if $conf->config('echeck-country') eq 'CA';
771 $hashref->{payinfo} .= $hashref->{'payinfo2'};
773 $hashref->{payname} = $hashref->{'payname_CHEK'};
775 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
777 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
784 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
787 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
788 next if $hashref->{$field};
789 next unless $old->get($field);
790 $hashref->{$field} = $old->get($field);
800 Returns a qsearch hash expression to search for parameters specified in HASHREF.
819 my ($class, $params) = @_;
824 # initialize these to prevent warnings
826 'paydate_year' => '',
834 if ( $params->{'payby'} ) {
836 my @payby = ref( $params->{'payby'} )
837 ? @{ $params->{'payby'} }
838 : ( $params->{'payby'} );
840 @payby = grep /^([A-Z]{4})$/, @payby;
841 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
842 push @where, "cust_payby.payby $in_payby"
847 # paydate_year / paydate_month
850 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
852 $params->{'paydate_month'} =~ /^(\d\d?)$/
853 or die "paydate_year without paydate_month?";
857 'cust_payby.paydate IS NOT NULL',
858 "cust_payby.paydate != ''",
859 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
863 # setup queries, subs, etc. for the search
866 $orderby ||= 'ORDER BY custnum';
868 # here is the agent virtualization
870 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
872 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
874 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
875 # always make address fields available in results
876 for my $pre ('bill_', 'ship_') {
878 ' LEFT JOIN cust_location AS '.$pre.'location '.
879 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
881 # always make referral available in results
882 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
883 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
885 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
887 my @select = ( 'cust_payby.*',
888 #'cust_main.custnum',
889 # there's a good chance that we'll need these
890 'cust_main.bill_locationnum',
891 'cust_main.ship_locationnum',
892 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
895 my $select = join(', ', @select);
898 'table' => 'cust_payby',
900 'addl_from' => $addl_from,
902 'extra_sql' => $extra_sql,
903 'order_by' => $orderby,
904 'count_query' => $count_query,
917 local $ignore_banned_card = 1;
918 local $ignore_expired_card = 1;
919 local $ignore_invalid_card = 1;
920 $class->upgrade_set_cardtype;
928 L<FS::Record>, schema.html from the base documentation.