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 ( $self->payby =~ /^(CARD|DCRD)$/
200 && ( $self->payinfo =~ /xx/
201 || $self->payinfo =~ /^\s*N\/A\s+\(tokenized\)\s*$/
206 $self->payinfo($old->payinfo);
208 } elsif ( $self->payby =~ /^(CHEK|DCHK)$/ && $self->payinfo =~ /xx/ ) {
209 #fix for #3085 "edit of customer's routing code only surprisingly causes
210 #nothing to happen...
211 # this probably won't do the right thing when we don't have the
212 # public key (can't actually get the real $old->payinfo)
213 my($new_account, $new_aba) = split('@', $self->payinfo);
214 my($old_account, $old_aba) = split('@', $old->payinfo);
215 $new_account = $old_account if $new_account =~ /xx/;
216 $new_aba = $old_aba if $new_aba =~ /xx/;
217 $self->payinfo($new_account.'@'.$new_aba);
220 # don't preserve paycvv if it was passed blank and payinfo changed
221 unless ( $self->payby =~ /^(CARD|DCRD)$/
222 && $old->payinfo ne $self->payinfo
223 && $old->paymask ne $self->paymask
224 && $self->paycvv =~ /^\s*$/ )
226 if ( length($old->paycvv) && $self->paycvv =~ /^\s*[\*x]*\s*$/ ) {
227 $self->paycvv($old->paycvv);
231 local($ignore_expired_card) = 1
232 if $old->payby =~ /^(CARD|DCRD)$/
233 && $self->payby =~ /^(CARD|DCRD)$/
234 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
236 local($ignore_banned_card) = 1
237 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
238 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
239 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
241 if ( $self->payby =~ /^(CARD|DCRD)$/
242 && $old->payinfo ne $self->payinfo
243 && $old->paymask ne $self->paymask )
245 my $error = $self->check_payinfo_cardtype;
246 return $error if $error;
248 if ( $conf->exists('business-onlinepayment-verification') ) {
249 $error = $self->verify;
250 return $error if $error;
254 local $SIG{HUP} = 'IGNORE';
255 local $SIG{INT} = 'IGNORE';
256 local $SIG{QUIT} = 'IGNORE';
257 local $SIG{TERM} = 'IGNORE';
258 local $SIG{TSTP} = 'IGNORE';
259 local $SIG{PIPE} = 'IGNORE';
261 my $oldAutoCommit = $FS::UID::AutoCommit;
262 local $FS::UID::AutoCommit = 0;
265 my $error = $self->SUPER::replace($old);
267 $dbh->rollback if $oldAutoCommit;
271 if ( $self->payby =~ /^(CARD|CHEK)$/
272 && ( ( $self->get('payinfo') ne $old->get('payinfo')
273 && $self->get('payinfo') !~ /^99\d{14}$/
275 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
280 # card/check/lec info has changed, want to retry realtime_ invoice events
281 my $error = $self->cust_main->retry_realtime;
283 $dbh->rollback if $oldAutoCommit;
288 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
295 Checks all fields to make sure this is a valid record. If there is
296 an error, returns the error, otherwise returns false. Called by the insert
305 $self->ut_numbern('custpaybynum')
306 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
307 || $self->ut_numbern('weight')
308 #encrypted #|| $self->ut_textn('payinfo')
309 #encrypted #|| $self->ut_textn('paycvv')
310 # || $self->ut_textn('paymask') #XXX something
311 #later #|| $self->ut_textn('paydate')
312 || $self->ut_numbern('paystart_month')
313 || $self->ut_numbern('paystart_year')
314 || $self->ut_numbern('payissue')
315 # || $self->ut_textn('payname') #XXX something
316 || $self->ut_alphan('paystate')
317 || $self->ut_textn('paytype')
318 || $self->ut_ipn('payip')
320 return $error if $error;
324 FS::payby->can_payby($self->table, $self->payby)
325 or return "Illegal payby: ". $self->payby;
327 # If it is encrypted and the private key is not availaible then we can't
328 # check the credit card.
329 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
331 # Need some kind of global flag to accept invalid cards, for testing
333 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
334 if ( !$ignore_invalid_card &&
335 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
337 my $payinfo = $self->payinfo;
339 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
340 or return gettext('invalid_card'); #. ": ". $self->payinfo;
342 $self->payinfo($payinfo);
344 or return gettext('invalid_card'); # . ": ". $self->payinfo;
346 return gettext('unknown_card_type')
347 if $self->payinfo !~ /^99\d{14}$/ #token
348 && cardtype($self->payinfo) eq "Unknown";
350 unless ( $ignore_banned_card ) {
351 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
353 if ( $ban->bantype eq 'warn' ) {
354 #or others depending on value of $ban->reason ?
355 return '_duplicate_card'.
356 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
357 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
358 ' (ban# '. $ban->bannum. ')'
359 unless $self->override_ban_warn;
361 return 'Banned credit card: banned on '.
362 time2str('%a %h %o at %r', $ban->_date).
363 ' by '. $ban->otaker.
364 ' (ban# '. $ban->bannum. ')';
369 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
370 if ( cardtype($self->payinfo) eq 'American Express card' ) {
371 $self->paycvv =~ /^(\d{4})$/
372 or return "CVV2 (CID) for American Express cards is four digits.";
375 $self->paycvv =~ /^(\d{3})$/
376 or return "CVV2 (CVC2/CID) is three digits.";
383 my $cardtype = cardtype($payinfo);
384 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
386 return "Start date or issue number is required for $cardtype cards"
387 unless $self->paystart_month && $self->paystart_year or $self->payissue;
389 return "Start month must be between 1 and 12"
390 if $self->paystart_month
391 and $self->paystart_month < 1 || $self->paystart_month > 12;
393 return "Start year must be 1990 or later"
394 if $self->paystart_year
395 and $self->paystart_year < 1990;
397 return "Issue number must be beween 1 and 99"
399 and $self->payissue < 1 || $self->payissue > 99;
402 $self->paystart_month('');
403 $self->paystart_year('');
407 } elsif ( !$ignore_invalid_card &&
408 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
410 my $payinfo = $self->payinfo;
411 $payinfo =~ s/[^\d\@\.]//g;
412 if ( $conf->config('echeck-country') eq 'CA' ) {
413 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
414 or return 'invalid echeck account@branch.bank';
415 $payinfo = "$1\@$2.$3";
416 } elsif ( $conf->config('echeck-country') eq 'US' ) {
417 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
420 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
423 $self->payinfo($payinfo);
426 unless ( $ignore_banned_card ) {
427 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
429 if ( $ban->bantype eq 'warn' ) {
430 #or others depending on value of $ban->reason ?
431 return '_duplicate_ach' unless $self->override_ban_warn;
433 return 'Banned ACH account: banned on '.
434 time2str('%a %h %o at %r', $ban->_date).
435 ' by '. $ban->otaker.
436 ' (ban# '. $ban->bannum. ')';
441 # } elsif ( $self->payby eq 'PREPAY' ) {
443 # my $payinfo = $self->payinfo;
444 # $payinfo =~ s/\W//g; #anything else would just confuse things
445 # $self->payinfo($payinfo);
446 # $error = $self->ut_alpha('payinfo');
447 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
448 # return "Unknown prepayment identifier"
449 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
454 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
458 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
460 # shouldn't payinfo_check do this?
461 return "Expiration date required"
462 if $self->paydate eq '' || $self->paydate eq '-';
465 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
466 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
467 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
468 ( $m, $y ) = ( $2, "19$1" );
469 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
470 ( $m, $y ) = ( $3, "20$2" );
472 return "Illegal expiration date: ". $self->paydate;
474 $m = sprintf('%02d',$m);
475 $self->paydate("$y-$m-01");
476 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
477 return gettext('expired_card')
480 !$ignore_expired_card
481 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
485 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
486 ( ! $conf->exists('require_cardname')
487 || $self->payby !~ /^(CARD|DCRD)$/ )
489 $self->payname( $self->first. " ". $self->getfield('last') );
492 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
493 $self->payname =~ /^([\w \,\.\-\']*)$/
494 or return gettext('illegal_name'). " payname: ". $self->payname;
497 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
498 or return gettext('illegal_name'). " payname: ". $self->payname;
504 if ( ! $self->custpaybynum
505 && $conf->exists('business-onlinepayment-verification') ) {
506 $error = $self->verify;
507 return $error if $error;
513 sub check_payinfo_cardtype {
516 return '' if $ignore_cardtype;
518 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
520 my $payinfo = $self->payinfo;
523 return '' if $payinfo =~ /^99\d{14}$/; #token
525 my %bop_card_types = map { $_=>1 } values %{ card_types() };
526 my $cardtype = cardtype($payinfo);
528 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
534 sub _banned_pay_hashref {
545 'payby' => $payby2ban{$self->payby},
546 'payinfo' => $self->payinfo,
547 #don't ever *search* on reason! #'reason' =>
551 sub _new_banned_pay_hashref {
553 my $hr = $self->_banned_pay_hashref;
554 $hr->{payinfo_hash} = 'SHA512';
555 $hr->{payinfo} = sha512_base64($hr->{payinfo});
559 =item paydate_mon_year
561 Returns a two element list consisting of the paydate month and year.
565 sub paydate_mon_year {
568 my $date = $self->paydate; # || '12-2037';
570 #false laziness w/elements/select-month_year.html
571 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
573 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
576 warn "unrecognized expiration date format: $date";
584 Returns a one line text label for this payment type.
601 my $name = $self->payby =~ /^(CARD|DCRD)$/
602 && cardtype($self->paymask) || FS::payby->shortname($self->payby);
604 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
607 "$name: ". $self->paymask.
608 ( $self->payby =~ /^(CARD|DCRD)$/
609 ? ' Exp '. join('/', $self->paydate_mon_year)
620 my( $self, %opt ) = @_;
622 $opt{$_} = $self->$_() for qw( payinfo payname paydate );
624 if ( $self->locationnum ) {
625 my $cust_location = $self->cust_location;
626 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
629 $self->cust_main->realtime_bop({
630 'method' => FS::payby->payby2bop( $self->payby ),
642 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
646 # false laziness with check
648 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
649 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
650 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
651 ( $m, $y ) = ( $2, "19$1" );
652 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
653 ( $m, $y ) = ( $3, "20$2" );
655 return "Illegal expiration date: ". $self->paydate;
657 $m = sprintf('%02d',$m);
658 $opt{paydate} = "$y-$m-01";
660 $opt{$_} = $self->$_() for qw( payinfo payname paycvv );
662 if ( $self->locationnum ) {
663 my $cust_location = $self->cust_location;
664 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
667 $self->cust_main->realtime_verify_bop({
668 'method' => FS::payby->payby2bop( $self->payby ),
676 Returns a list of valid values for the paytype field (bank account type for
677 electronic check payment).
684 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
687 =item cgi_cust_payby_fields
689 Returns the field names used in the web interface (including some pseudo-fields).
693 sub cgi_cust_payby_fields {
695 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
696 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
699 =item cgi_hash_callback HASHREF OLD
701 Subroutine (not a class or object method). Processes a hash reference
702 of web interface contet (transfers the data from pseudo-fields to real fields).
704 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
705 payissue and payip. If the new field is blank but the old is not, the old field
710 sub cgi_hash_callback {
718 $hashref->{payby} = $noauto{$hashref->{payby}}
719 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
721 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
723 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
728 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
729 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
730 if $conf->config('echeck-country') eq 'CA';
731 $hashref->{payinfo} .= $hashref->{'payinfo2'};
733 $hashref->{payname} = $hashref->{'payname_CHEK'};
735 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
737 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
744 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
747 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
748 next if $hashref->{$field};
749 next unless $old->get($field);
750 $hashref->{$field} = $old->get($field);
760 Returns a qsearch hash expression to search for parameters specified in HASHREF.
779 my ($class, $params) = @_;
784 # initialize these to prevent warnings
786 'paydate_year' => '',
794 if ( $params->{'payby'} ) {
796 my @payby = ref( $params->{'payby'} )
797 ? @{ $params->{'payby'} }
798 : ( $params->{'payby'} );
800 @payby = grep /^([A-Z]{4})$/, @payby;
801 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
802 push @where, "cust_payby.payby $in_payby"
807 # paydate_year / paydate_month
810 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
812 $params->{'paydate_month'} =~ /^(\d\d?)$/
813 or die "paydate_year without paydate_month?";
817 'cust_payby.paydate IS NOT NULL',
818 "cust_payby.paydate != ''",
819 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
823 # setup queries, subs, etc. for the search
826 $orderby ||= 'ORDER BY custnum';
828 # here is the agent virtualization
830 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
832 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
834 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
835 # always make address fields available in results
836 for my $pre ('bill_', 'ship_') {
838 ' LEFT JOIN cust_location AS '.$pre.'location '.
839 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
841 # always make referral available in results
842 # (maybe we should be using FS::UI::Web::join_cust_main instead?)
843 $addl_from .= ' LEFT JOIN (select refnum, referral from part_referral) AS part_referral_x ON (cust_main.refnum = part_referral_x.refnum) ';
845 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
847 my @select = ( 'cust_payby.*',
848 #'cust_main.custnum',
849 # there's a good chance that we'll need these
850 'cust_main.bill_locationnum',
851 'cust_main.ship_locationnum',
852 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
855 my $select = join(', ', @select);
858 'table' => 'cust_payby',
860 'addl_from' => $addl_from,
862 'extra_sql' => $extra_sql,
863 'order_by' => $orderby,
864 'count_query' => $count_query,
876 L<FS::Record>, schema.html from the base documentation.