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;
253 return $error if $error;
257 local $SIG{HUP} = 'IGNORE';
258 local $SIG{INT} = 'IGNORE';
259 local $SIG{QUIT} = 'IGNORE';
260 local $SIG{TERM} = 'IGNORE';
261 local $SIG{TSTP} = 'IGNORE';
262 local $SIG{PIPE} = 'IGNORE';
264 my $oldAutoCommit = $FS::UID::AutoCommit;
265 local $FS::UID::AutoCommit = 0;
268 my $error = $self->SUPER::replace($old);
270 $dbh->rollback if $oldAutoCommit;
274 if ( $self->payby =~ /^(CARD|CHEK)$/
275 && ( ( $self->get('payinfo') ne $old->get('payinfo')
276 && $self->get('payinfo') !~ /^99\d{14}$/
278 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
283 # card/check/lec info has changed, want to retry realtime_ invoice events
284 my $error = $self->cust_main->retry_realtime;
286 $dbh->rollback if $oldAutoCommit;
291 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
298 Checks all fields to make sure this is a valid record. If there is
299 an error, returns the error, otherwise returns false. Called by the insert
308 $self->ut_numbern('custpaybynum')
309 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
310 || $self->ut_numbern('weight')
311 #encrypted #|| $self->ut_textn('payinfo')
312 #encrypted #|| $self->ut_textn('paycvv')
313 # || $self->ut_textn('paymask') #XXX something
314 #later #|| $self->ut_textn('paydate')
315 || $self->ut_numbern('paystart_month')
316 || $self->ut_numbern('paystart_year')
317 || $self->ut_numbern('payissue')
318 # || $self->ut_textn('payname') #XXX something
319 || $self->ut_alphan('paystate')
320 || $self->ut_textn('paytype')
321 || $self->ut_ipn('payip')
323 return $error if $error;
327 FS::payby->can_payby($self->table, $self->payby)
328 or return "Illegal payby: ". $self->payby;
330 # If it is encrypted and the private key is not availaible then we can't
331 # check the credit card.
332 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
334 # Need some kind of global flag to accept invalid cards, for testing
336 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
338 # In this block: detect card type; reject credit card / account numbers that
339 # are impossible or banned; reject other payment features (date, CVV length)
340 # that are inappropriate for the card type.
341 # However, if the payinfo is encrypted then just detect card type and assume
342 # the other checks were already done.
344 if ( !$ignore_invalid_card &&
345 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
347 my $payinfo = $self->payinfo;
349 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
350 or return gettext('invalid_card'); #. ": ". $self->payinfo;
352 $self->payinfo($payinfo);
354 or return gettext('invalid_card'); # . ": ". $self->payinfo;
356 my $cardtype = cardtype($payinfo);
357 $cardtype = 'Tokenized' if $self->payinfo =~ /^99\d{14}$/; #token
359 return gettext('unknown_card_type') if $cardtype eq "Unknown";
361 $self->set('paycardtype', $cardtype);
363 unless ( $ignore_banned_card ) {
364 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
366 if ( $ban->bantype eq 'warn' ) {
367 #or others depending on value of $ban->reason ?
368 return '_duplicate_card'.
369 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
370 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
371 ' (ban# '. $ban->bannum. ')'
372 unless $self->override_ban_warn;
374 return 'Banned credit card: banned on '.
375 time2str('%a %h %o at %r', $ban->_date).
376 ' by '. $ban->otaker.
377 ' (ban# '. $ban->bannum. ')';
382 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
383 if ( $cardtype eq 'American Express card' ) {
384 $self->paycvv =~ /^(\d{4})$/
385 or return "CVV2 (CID) for American Express cards is four digits.";
388 $self->paycvv =~ /^(\d{3})$/
389 or return "CVV2 (CVC2/CID) is three digits.";
396 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
398 return "Start date or issue number is required for $cardtype cards"
399 unless $self->paystart_month && $self->paystart_year or $self->payissue;
401 return "Start month must be between 1 and 12"
402 if $self->paystart_month
403 and $self->paystart_month < 1 || $self->paystart_month > 12;
405 return "Start year must be 1990 or later"
406 if $self->paystart_year
407 and $self->paystart_year < 1990;
409 return "Issue number must be beween 1 and 99"
411 and $self->payissue < 1 || $self->payissue > 99;
414 $self->paystart_month('');
415 $self->paystart_year('');
419 } elsif ( !$ignore_invalid_card &&
420 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
422 my $payinfo = $self->payinfo;
423 $payinfo =~ s/[^\d\@\.]//g;
424 if ( $conf->config('echeck-country') eq 'CA' ) {
425 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
426 or return 'invalid echeck account@branch.bank';
427 $payinfo = "$1\@$2.$3";
428 } elsif ( $conf->config('echeck-country') eq 'US' ) {
429 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
432 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
435 $self->payinfo($payinfo);
438 unless ( $ignore_banned_card ) {
439 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
441 if ( $ban->bantype eq 'warn' ) {
442 #or others depending on value of $ban->reason ?
443 return '_duplicate_ach' unless $self->override_ban_warn;
445 return 'Banned ACH account: banned on '.
446 time2str('%a %h %o at %r', $ban->_date).
447 ' by '. $ban->otaker.
448 ' (ban# '. $ban->bannum. ')';
453 } elsif ( $self->payby =~ /^CARD|DCRD$/ and $self->paymask ) {
454 # either ignoring invalid cards, or we can't decrypt the payinfo, but
455 # try to detect the card type anyway. this never returns failure, so
456 # the contract of $ignore_invalid_cards is maintained.
457 $self->set('paycardtype', cardtype($self->paymask));
459 $self->set('paycardtype', '');
462 # } elsif ( $self->payby eq 'PREPAY' ) {
464 # my $payinfo = $self->payinfo;
465 # $payinfo =~ s/\W//g; #anything else would just confuse things
466 # $self->payinfo($payinfo);
467 # $error = $self->ut_alpha('payinfo');
468 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
469 # return "Unknown prepayment identifier"
470 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
473 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
477 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
479 # shouldn't payinfo_check do this?
480 # (except we don't ever call payinfo_check from here)
481 return "Expiration date required"
482 if $self->paydate eq '' || $self->paydate eq '-';
485 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
486 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
487 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
488 ( $m, $y ) = ( $2, "19$1" );
489 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
490 ( $m, $y ) = ( $3, "20$2" );
492 return "Illegal expiration date: ". $self->paydate;
494 $m = sprintf('%02d',$m);
495 $self->paydate("$y-$m-01");
496 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
497 return gettext('expired_card')
500 !$ignore_expired_card
501 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
505 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
506 ( ! $conf->exists('require_cardname')
507 || $self->payby !~ /^(CARD|DCRD)$/ )
509 $self->payname( $self->first. " ". $self->getfield('last') );
512 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
513 $self->payname =~ /^([\w \,\.\-\']*)$/
514 or return gettext('illegal_name'). " payname: ". $self->payname;
517 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
518 or return gettext('illegal_name'). " payname: ". $self->payname;
524 if ( ! $self->custpaybynum
525 && $conf->exists('business-onlinepayment-verification') ) {
526 $error = $self->verify;
527 return $error if $error;
533 sub check_payinfo_cardtype {
536 return '' if $ignore_cardtype;
538 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
540 my $payinfo = $self->payinfo;
543 if ( $payinfo =~ /^99\d{14}$/ ) {
544 $self->set('paycardtype', 'Tokenized');
548 my %bop_card_types = map { $_=>1 } values %{ card_types() };
549 my $cardtype = cardtype($payinfo);
550 $self->set('paycardtype', $cardtype);
552 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
558 sub _banned_pay_hashref {
569 'payby' => $payby2ban{$self->payby},
570 'payinfo' => $self->payinfo,
571 #don't ever *search* on reason! #'reason' =>
575 sub _new_banned_pay_hashref {
577 my $hr = $self->_banned_pay_hashref;
578 $hr->{payinfo_hash} = 'SHA512';
579 $hr->{payinfo} = sha512_base64($hr->{payinfo});
583 =item paydate_mon_year
585 Returns a two element list consisting of the paydate month and year.
589 sub paydate_mon_year {
592 my $date = $self->paydate; # || '12-2037';
594 #false laziness w/elements/select-month_year.html
595 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
597 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
600 warn "unrecognized expiration date format: $date";
608 Returns a one line text label for this payment type.
625 my $name = $self->payby =~ /^(CARD|DCRD)$/
626 && $self->paycardtype || FS::payby->shortname($self->payby);
628 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
631 "$name: ". $self->paymask.
632 ( $self->payby =~ /^(CARD|DCRD)$/
633 ? ' Exp '. join('/', $self->paydate_mon_year)
644 my( $self, %opt ) = @_;
646 $opt{$_} = $self->$_() for qw( payinfo payname paydate );
648 if ( $self->locationnum ) {
649 my $cust_location = $self->cust_location;
650 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
653 $self->cust_main->realtime_bop({
654 'method' => FS::payby->payby2bop( $self->payby ),
666 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
670 # false laziness with check
672 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
673 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
674 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
675 ( $m, $y ) = ( $2, "19$1" );
676 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
677 ( $m, $y ) = ( $3, "20$2" );
679 return "Illegal expiration date: ". $self->paydate;
681 $m = sprintf('%02d',$m);
682 $opt{paydate} = "$y-$m-01";
684 $opt{$_} = $self->$_() for qw( payinfo payname paycvv );
686 if ( $self->locationnum ) {
687 my $cust_location = $self->cust_location;
688 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
691 $self->cust_main->realtime_verify_bop({
692 'method' => FS::payby->payby2bop( $self->payby ),
700 Returns a list of valid values for the paytype field (bank account type for
701 electronic check payment).
708 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
711 =item cgi_cust_payby_fields
713 Returns the field names used in the web interface (including some pseudo-fields).
717 sub cgi_cust_payby_fields {
719 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
720 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
723 =item cgi_hash_callback HASHREF OLD
725 Subroutine (not a class or object method). Processes a hash reference
726 of web interface contet (transfers the data from pseudo-fields to real fields).
728 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
729 payissue and payip. If the new field is blank but the old is not, the old field
734 sub cgi_hash_callback {
742 # the payby selector gives the choice of CARD or CHEK (or others, but
743 # those are the ones with auto and on-demand versions). if the user didn't
744 # choose a weight, then they mean DCRD/DCHK.
745 $hashref->{payby} = $noauto{$hashref->{payby}}
746 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
748 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
750 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
755 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
756 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
757 if $conf->config('echeck-country') eq 'CA';
758 $hashref->{payinfo} .= $hashref->{'payinfo2'};
760 $hashref->{payname} = $hashref->{'payname_CHEK'};
762 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
764 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
771 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
774 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
775 next if $hashref->{$field};
776 next unless $old->get($field);
777 $hashref->{$field} = $old->get($field);
787 Returns a qsearch hash expression to search for parameters specified in HASHREF.
806 my ($class, $params) = @_;
811 # initialize these to prevent warnings
813 'paydate_year' => '',
821 if ( $params->{'payby'} ) {
823 my @payby = ref( $params->{'payby'} )
824 ? @{ $params->{'payby'} }
825 : ( $params->{'payby'} );
827 @payby = grep /^([A-Z]{4})$/, @payby;
828 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
829 push @where, "cust_payby.payby $in_payby"
834 # paydate_year / paydate_month
837 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
839 $params->{'paydate_month'} =~ /^(\d\d?)$/
840 or die "paydate_year without paydate_month?";
844 'cust_payby.paydate IS NOT NULL',
845 "cust_payby.paydate != ''",
846 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
850 # setup queries, subs, etc. for the search
853 $orderby ||= 'ORDER BY custnum';
855 # here is the agent virtualization
857 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
859 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
861 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
862 # always make address fields available in results
863 for my $pre ('bill_', 'ship_') {
865 ' LEFT JOIN cust_location AS '.$pre.'location '.
866 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
868 # always make referral available in results
869 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
870 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
872 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
874 my @select = ( 'cust_payby.*',
875 #'cust_main.custnum',
876 # there's a good chance that we'll need these
877 'cust_main.bill_locationnum',
878 'cust_main.ship_locationnum',
879 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
882 my $select = join(', ', @select);
885 'table' => 'cust_payby',
887 'addl_from' => $addl_from,
889 'extra_sql' => $extra_sql,
890 'order_by' => $orderby,
891 'count_query' => $count_query,
904 local $ignore_banned_card = 1;
905 local $ignore_expired_card = 1;
906 local $ignore_invalid_card = 1;
907 $class->upgrade_set_cardtype;
915 L<FS::Record>, schema.html from the base documentation.