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
127 Creates a new record. To add the record to the database, see L<"insert">.
129 Note that this stores the hash reference, not a distinct copy of the hash it
130 points to. You can ask the object for a copy with the I<hash> method.
134 # the new method can be inherited from FS::Record, if a table method is defined
136 sub table { 'cust_payby'; }
140 Adds this record to the database. If there is an error, returns the error,
141 otherwise returns false.
148 local $SIG{HUP} = 'IGNORE';
149 local $SIG{INT} = 'IGNORE';
150 local $SIG{QUIT} = 'IGNORE';
151 local $SIG{TERM} = 'IGNORE';
152 local $SIG{TSTP} = 'IGNORE';
153 local $SIG{PIPE} = 'IGNORE';
155 my $oldAutoCommit = $FS::UID::AutoCommit;
156 local $FS::UID::AutoCommit = 0;
159 my $error = $self->check_payinfo_cardtype
160 || $self->SUPER::insert;
162 $dbh->rollback if $oldAutoCommit;
166 if ( $self->payby =~ /^(CARD|CHEK)$/ ) {
167 # new auto card/check info, want to retry realtime_ invoice events
168 # (new customer? that's okay, they won't have any)
169 my $error = $self->cust_main->retry_realtime;
171 $dbh->rollback if $oldAutoCommit;
176 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
183 Delete this record from the database.
185 =item replace OLD_RECORD
187 Replaces the OLD_RECORD with this one in the database. If there is an error,
188 returns the error, otherwise returns false.
195 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
197 : $self->replace_old;
199 if ( length($old->paycvv) && $self->paycvv =~ /^\s*[\*x]*\s*$/ ) {
200 $self->paycvv($old->paycvv);
203 if ( $self->payby =~ /^(CARD|DCRD)$/
204 && ( $self->payinfo =~ /xx/
205 || $self->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
210 $self->payinfo($old->payinfo);
212 } elsif ( $self->payby =~ /^(CHEK|DCHK)$/ && $self->payinfo =~ /xx/ ) {
213 #fix for #3085 "edit of customer's routing code only surprisingly causes
214 #nothing to happen...
215 # this probably won't do the right thing when we don't have the
216 # public key (can't actually get the real $old->payinfo)
217 my($new_account, $new_aba) = split('@', $self->payinfo);
218 my($old_account, $old_aba) = split('@', $old->payinfo);
219 $new_account = $old_account if $new_account =~ /xx/;
220 $new_aba = $old_aba if $new_aba =~ /xx/;
221 $self->payinfo($new_account.'@'.$new_aba);
224 local($ignore_expired_card) = 1
225 if $old->payby =~ /^(CARD|DCRD)$/
226 && $self->payby =~ /^(CARD|DCRD)$/
227 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
229 local($ignore_banned_card) = 1
230 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
231 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
232 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
234 if ( $self->payby =~ /^(CARD|DCRD)$/
235 && $old->payinfo ne $self->payinfo
236 && $old->paymask ne $self->paymask )
238 my $error = $self->check_payinfo_cardtype;
239 return $error if $error;
242 local $SIG{HUP} = 'IGNORE';
243 local $SIG{INT} = 'IGNORE';
244 local $SIG{QUIT} = 'IGNORE';
245 local $SIG{TERM} = 'IGNORE';
246 local $SIG{TSTP} = 'IGNORE';
247 local $SIG{PIPE} = 'IGNORE';
249 my $oldAutoCommit = $FS::UID::AutoCommit;
250 local $FS::UID::AutoCommit = 0;
253 my $error = $self->SUPER::replace($old);
255 $dbh->rollback if $oldAutoCommit;
259 if ( $self->payby =~ /^(CARD|CHEK)$/
260 && ( ( $self->get('payinfo') ne $old->get('payinfo')
261 && $self->get('payinfo') !~ /^99\d{14}$/
263 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
268 # card/check/lec info has changed, want to retry realtime_ invoice events
269 my $error = $self->cust_main->retry_realtime;
271 $dbh->rollback if $oldAutoCommit;
276 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
283 Checks all fields to make sure this is a valid record. If there is
284 an error, returns the error, otherwise returns false. Called by the insert
293 $self->ut_numbern('custpaybynum')
294 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
295 || $self->ut_numbern('weight')
296 #encrypted #|| $self->ut_textn('payinfo')
297 #encrypted #|| $self->ut_textn('paycvv')
298 # || $self->ut_textn('paymask') #XXX something
299 #later #|| $self->ut_textn('paydate')
300 || $self->ut_numbern('paystart_month')
301 || $self->ut_numbern('paystart_year')
302 || $self->ut_numbern('payissue')
303 # || $self->ut_textn('payname') #XXX something
304 || $self->ut_alphan('paystate')
305 || $self->ut_textn('paytype')
306 || $self->ut_ipn('payip')
308 return $error if $error;
312 FS::payby->can_payby($self->table, $self->payby)
313 or return "Illegal payby: ". $self->payby;
315 # If it is encrypted and the private key is not availaible then we can't
316 # check the credit card.
317 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
319 # Need some kind of global flag to accept invalid cards, for testing
321 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
322 if ( !$ignore_invalid_card &&
323 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
325 my $payinfo = $self->payinfo;
327 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
328 or return gettext('invalid_card'); #. ": ". $self->payinfo;
330 $self->payinfo($payinfo);
332 or return gettext('invalid_card'); # . ": ". $self->payinfo;
334 return gettext('unknown_card_type')
335 if $self->payinfo !~ /^99\d{14}$/ #token
336 && cardtype($self->payinfo) eq "Unknown";
338 unless ( $ignore_banned_card ) {
339 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
341 if ( $ban->bantype eq 'warn' ) {
342 #or others depending on value of $ban->reason ?
343 return '_duplicate_card'.
344 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
345 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
346 ' (ban# '. $ban->bannum. ')'
347 unless $self->override_ban_warn;
349 return 'Banned credit card: banned on '.
350 time2str('%a %h %o at %r', $ban->_date).
351 ' by '. $ban->otaker.
352 ' (ban# '. $ban->bannum. ')';
357 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
358 if ( cardtype($self->payinfo) eq 'American Express card' ) {
359 $self->paycvv =~ /^(\d{4})$/
360 or return "CVV2 (CID) for American Express cards is four digits.";
363 $self->paycvv =~ /^(\d{3})$/
364 or return "CVV2 (CVC2/CID) is three digits.";
371 my $cardtype = cardtype($payinfo);
372 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
374 return "Start date or issue number is required for $cardtype cards"
375 unless $self->paystart_month && $self->paystart_year or $self->payissue;
377 return "Start month must be between 1 and 12"
378 if $self->paystart_month
379 and $self->paystart_month < 1 || $self->paystart_month > 12;
381 return "Start year must be 1990 or later"
382 if $self->paystart_year
383 and $self->paystart_year < 1990;
385 return "Issue number must be beween 1 and 99"
387 and $self->payissue < 1 || $self->payissue > 99;
390 $self->paystart_month('');
391 $self->paystart_year('');
395 } elsif ( !$ignore_invalid_card &&
396 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
398 my $payinfo = $self->payinfo;
399 $payinfo =~ s/[^\d\@\.]//g;
400 if ( $conf->config('echeck-country') eq 'CA' ) {
401 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
402 or return 'invalid echeck account@branch.bank';
403 $payinfo = "$1\@$2.$3";
404 } elsif ( $conf->config('echeck-country') eq 'US' ) {
405 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
408 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
411 $self->payinfo($payinfo);
414 unless ( $ignore_banned_card ) {
415 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
417 if ( $ban->bantype eq 'warn' ) {
418 #or others depending on value of $ban->reason ?
419 return '_duplicate_ach' unless $self->override_ban_warn;
421 return 'Banned ACH account: banned on '.
422 time2str('%a %h %o at %r', $ban->_date).
423 ' by '. $ban->otaker.
424 ' (ban# '. $ban->bannum. ')';
429 # } elsif ( $self->payby eq 'PREPAY' ) {
431 # my $payinfo = $self->payinfo;
432 # $payinfo =~ s/\W//g; #anything else would just confuse things
433 # $self->payinfo($payinfo);
434 # $error = $self->ut_alpha('payinfo');
435 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
436 # return "Unknown prepayment identifier"
437 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
442 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
446 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
448 # shouldn't payinfo_check do this?
449 return "Expiration date required"
450 if $self->paydate eq '' || $self->paydate eq '-';
453 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
454 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
455 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
456 ( $m, $y ) = ( $2, "19$1" );
457 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
458 ( $m, $y ) = ( $3, "20$2" );
460 return "Illegal expiration date: ". $self->paydate;
462 $m = sprintf('%02d',$m);
463 $self->paydate("$y-$m-01");
464 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
465 return gettext('expired_card')
468 !$ignore_expired_card
469 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
473 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
474 ( ! $conf->exists('require_cardname')
475 || $self->payby !~ /^(CARD|DCRD)$/ )
477 $self->payname( $self->first. " ". $self->getfield('last') );
480 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
481 $self->payname =~ /^([\w \,\.\-\']*)$/
482 or return gettext('illegal_name'). " payname: ". $self->payname;
485 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
486 or return gettext('illegal_name'). " payname: ". $self->payname;
497 sub check_payinfo_cardtype {
500 return '' if $ignore_cardtype;
502 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
504 my $payinfo = $self->payinfo;
507 return '' if $payinfo =~ /^99\d{14}$/; #token
509 my %bop_card_types = map { $_=>1 } values %{ card_types() };
510 my $cardtype = cardtype($payinfo);
512 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
518 sub _banned_pay_hashref {
529 'payby' => $payby2ban{$self->payby},
530 'payinfo' => $self->payinfo,
531 #don't ever *search* on reason! #'reason' =>
535 sub _new_banned_pay_hashref {
537 my $hr = $self->_banned_pay_hashref;
538 $hr->{payinfo_hash} = 'SHA512';
539 $hr->{payinfo} = sha512_base64($hr->{payinfo});
543 =item paydate_mon_year
545 Returns a two element list consisting of the paydate month and year.
549 sub paydate_mon_year {
552 my $date = $self->paydate; # || '12-2037';
554 #false laziness w/elements/select-month_year.html
555 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
557 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
560 warn "unrecognized expiration date format: $date";
568 Returns a one line text label for this payment type.
585 my $name = $self->payby =~ /^(CARD|DCRD)$/
586 && cardtype($self->paymask) || FS::payby->shortname($self->payby);
588 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
591 "$name: ". $self->paymask.
592 ( $self->payby =~ /^(CARD|DCRD)$/
593 ? ' Exp '. join('/', $self->paydate_mon_year)
604 my( $self, %opt ) = @_;
606 $opt{$_} = $self->$_() for qw( payinfo payname paydate );
608 if ( $self->locationnum ) {
609 my $cust_location = $self->cust_location;
610 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
613 $self->cust_main->realtime_bop({
614 'method' => FS::payby->payby2bop( $self->payby ),
622 Returns a list of valid values for the paytype field (bank account type for
623 electronic check payment).
630 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
633 =item cgi_cust_payby_fields
635 Returns the field names used in the web interface (including some pseudo-fields).
639 sub cgi_cust_payby_fields {
641 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
642 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
645 =item cgi_hash_callback HASHREF OLD
647 Subroutine (not a class or object method). Processes a hash reference
648 of web interface contet (transfers the data from pseudo-fields to real fields).
650 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
651 payissue and payip. If the new field is blank but the old is not, the old field
656 sub cgi_hash_callback {
664 $hashref->{payby} = $noauto{$hashref->{payby}}
665 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
667 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
669 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
674 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
675 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
676 if $conf->config('echeck-country') eq 'CA';
677 $hashref->{payinfo} .= $hashref->{'payinfo2'};
679 $hashref->{payname} = $hashref->{'payname_CHEK'};
681 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
683 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
690 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
693 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
694 next if $hashref->{$field};
695 next unless $old->get($field);
696 $hashref->{$field} = $old->get($field);
706 Returns a qsearch hash expression to search for parameters specified in HASHREF.
725 my ($class, $params) = @_;
730 # initialize these to prevent warnings
732 'paydate_year' => '',
740 if ( $params->{'payby'} ) {
742 my @payby = ref( $params->{'payby'} )
743 ? @{ $params->{'payby'} }
744 : ( $params->{'payby'} );
746 @payby = grep /^([A-Z]{4})$/, @payby;
747 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
748 push @where, "cust_payby.payby $in_payby"
753 # paydate_year / paydate_month
756 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
758 $params->{'paydate_month'} =~ /^(\d\d?)$/
759 or die "paydate_year without paydate_month?";
763 'cust_payby.paydate IS NOT NULL',
764 "cust_payby.paydate != ''",
765 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
769 # setup queries, subs, etc. for the search
772 $orderby ||= 'ORDER BY custnum';
774 # here is the agent virtualization
776 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
778 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
780 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
781 # always make address fields available in results
782 for my $pre ('bill_', 'ship_') {
784 ' LEFT JOIN cust_location AS '.$pre.'location '.
785 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
788 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
790 my @select = ( 'cust_payby.*',
791 #'cust_main.custnum',
792 # there's a good chance that we'll need these
793 'cust_main.bill_locationnum',
794 'cust_main.ship_locationnum',
795 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
798 my $select = join(', ', @select);
801 'table' => 'cust_payby',
803 'addl_from' => $addl_from,
805 'extra_sql' => $extra_sql,
806 'order_by' => $orderby,
807 'count_query' => $count_query,
819 L<FS::Record>, schema.html from the base documentation.