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;
24 install_callback FS::UID sub {
26 #yes, need it for stuff below (prolly should be cached)
27 $ignore_invalid_card = $conf->exists('allow_invalid_cards');
32 FS::cust_payby - Object methods for cust_payby records
38 $record = new FS::cust_payby \%hash;
39 $record = new FS::cust_payby { 'column' => 'value' };
41 $error = $record->insert;
43 $error = $new_record->replace($old_record);
45 $error = $record->delete;
47 $error = $record->check;
51 An FS::cust_payby object represents customer stored payment information.
52 FS::cust_payby inherits from FS::Record. The following fields are currently
126 Creates a new record. To add the record to the database, see L<"insert">.
128 Note that this stores the hash reference, not a distinct copy of the hash it
129 points to. You can ask the object for a copy with the I<hash> method.
133 # the new method can be inherited from FS::Record, if a table method is defined
135 sub table { 'cust_payby'; }
139 Adds this record to the database. If there is an error, returns the error,
140 otherwise returns false.
147 local $SIG{HUP} = 'IGNORE';
148 local $SIG{INT} = 'IGNORE';
149 local $SIG{QUIT} = 'IGNORE';
150 local $SIG{TERM} = 'IGNORE';
151 local $SIG{TSTP} = 'IGNORE';
152 local $SIG{PIPE} = 'IGNORE';
154 my $oldAutoCommit = $FS::UID::AutoCommit;
155 local $FS::UID::AutoCommit = 0;
158 my $error = $self->check_payinfo_cardtype
159 || $self->SUPER::insert;
161 $dbh->rollback if $oldAutoCommit;
165 if ( $self->payby =~ /^(CARD|CHEK)$/ ) {
166 # new auto card/check info, want to retry realtime_ invoice events
167 # (new customer? that's okay, they won't have any)
168 my $error = $self->cust_main->retry_realtime;
170 $dbh->rollback if $oldAutoCommit;
175 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
182 Delete this record from the database.
184 =item replace OLD_RECORD
186 Replaces the OLD_RECORD with this one in the database. If there is an error,
187 returns the error, otherwise returns false.
194 my $old = ( blessed($_[0]) && $_[0]->isa('FS::Record') )
196 : $self->replace_old;
198 if ( length($old->paycvv) && $self->paycvv =~ /^\s*[\*x]*\s*$/ ) {
199 $self->paycvv($old->paycvv);
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 local($ignore_expired_card) = 1
224 if $old->payby =~ /^(CARD|DCRD)$/
225 && $self->payby =~ /^(CARD|DCRD)$/
226 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
228 local($ignore_banned_card) = 1
229 if ( $old->payby =~ /^(CARD|DCRD)$/ && $self->payby =~ /^(CARD|DCRD)$/
230 || $old->payby =~ /^(CHEK|DCHK)$/ && $self->payby =~ /^(CHEK|DCHK)$/ )
231 && ( $old->payinfo eq $self->payinfo || $old->paymask eq $self->paymask );
233 if ( $self->payby =~ /^(CARD|DCRD)$/
234 && $old->payinfo ne $self->payinfo
235 && $old->paymask ne $self->paymask )
237 my $error = $self->check_payinfo_cardtype;
238 return $error if $error;
241 local $SIG{HUP} = 'IGNORE';
242 local $SIG{INT} = 'IGNORE';
243 local $SIG{QUIT} = 'IGNORE';
244 local $SIG{TERM} = 'IGNORE';
245 local $SIG{TSTP} = 'IGNORE';
246 local $SIG{PIPE} = 'IGNORE';
248 my $oldAutoCommit = $FS::UID::AutoCommit;
249 local $FS::UID::AutoCommit = 0;
252 my $error = $self->SUPER::replace($old);
254 $dbh->rollback if $oldAutoCommit;
258 if ( $self->payby =~ /^(CARD|CHEK)$/
259 && ( ( $self->get('payinfo') ne $old->get('payinfo')
260 && $self->get('payinfo') !~ /^99\d{14}$/
262 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
267 # card/check/lec info has changed, want to retry realtime_ invoice events
268 my $error = $self->cust_main->retry_realtime;
270 $dbh->rollback if $oldAutoCommit;
275 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
282 Checks all fields to make sure this is a valid record. If there is
283 an error, returns the error, otherwise returns false. Called by the insert
292 $self->ut_numbern('custpaybynum')
293 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
294 || $self->ut_numbern('weight')
295 #encrypted #|| $self->ut_textn('payinfo')
296 #encrypted #|| $self->ut_textn('paycvv')
297 # || $self->ut_textn('paymask') #XXX something
298 #later #|| $self->ut_textn('paydate')
299 || $self->ut_numbern('paystart_month')
300 || $self->ut_numbern('paystart_year')
301 || $self->ut_numbern('payissue')
302 # || $self->ut_textn('payname') #XXX something
303 || $self->ut_alphan('paystate')
304 || $self->ut_textn('paytype')
305 || $self->ut_ipn('payip')
307 return $error if $error;
311 FS::payby->can_payby($self->table, $self->payby)
312 or return "Illegal payby: ". $self->payby;
314 # If it is encrypted and the private key is not availaible then we can't
315 # check the credit card.
316 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
318 # Need some kind of global flag to accept invalid cards, for testing
320 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
321 if ( !$ignore_invalid_card &&
322 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
324 my $payinfo = $self->payinfo;
326 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
327 or return gettext('invalid_card'); #. ": ". $self->payinfo;
329 $self->payinfo($payinfo);
331 or return gettext('invalid_card'); # . ": ". $self->payinfo;
333 return gettext('unknown_card_type')
334 if $self->payinfo !~ /^99\d{14}$/ #token
335 && cardtype($self->payinfo) eq "Unknown";
337 unless ( $ignore_banned_card ) {
338 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
340 if ( $ban->bantype eq 'warn' ) {
341 #or others depending on value of $ban->reason ?
342 return '_duplicate_card'.
343 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
344 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
345 ' (ban# '. $ban->bannum. ')'
346 unless $self->override_ban_warn;
348 return 'Banned credit card: banned on '.
349 time2str('%a %h %o at %r', $ban->_date).
350 ' by '. $ban->otaker.
351 ' (ban# '. $ban->bannum. ')';
356 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
357 if ( cardtype($self->payinfo) eq 'American Express card' ) {
358 $self->paycvv =~ /^(\d{4})$/
359 or return "CVV2 (CID) for American Express cards is four digits.";
362 $self->paycvv =~ /^(\d{3})$/
363 or return "CVV2 (CVC2/CID) is three digits.";
370 my $cardtype = cardtype($payinfo);
371 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
373 return "Start date or issue number is required for $cardtype cards"
374 unless $self->paystart_month && $self->paystart_year or $self->payissue;
376 return "Start month must be between 1 and 12"
377 if $self->paystart_month
378 and $self->paystart_month < 1 || $self->paystart_month > 12;
380 return "Start year must be 1990 or later"
381 if $self->paystart_year
382 and $self->paystart_year < 1990;
384 return "Issue number must be beween 1 and 99"
386 and $self->payissue < 1 || $self->payissue > 99;
389 $self->paystart_month('');
390 $self->paystart_year('');
394 } elsif ( !$ignore_invalid_card &&
395 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
397 my $payinfo = $self->payinfo;
398 $payinfo =~ s/[^\d\@\.]//g;
399 if ( $conf->config('echeck-country') eq 'CA' ) {
400 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
401 or return 'invalid echeck account@branch.bank';
402 $payinfo = "$1\@$2.$3";
403 } elsif ( $conf->config('echeck-country') eq 'US' ) {
404 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
407 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
410 $self->payinfo($payinfo);
413 unless ( $ignore_banned_card ) {
414 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
416 if ( $ban->bantype eq 'warn' ) {
417 #or others depending on value of $ban->reason ?
418 return '_duplicate_ach' unless $self->override_ban_warn;
420 return 'Banned ACH account: banned on '.
421 time2str('%a %h %o at %r', $ban->_date).
422 ' by '. $ban->otaker.
423 ' (ban# '. $ban->bannum. ')';
428 # } elsif ( $self->payby eq 'PREPAY' ) {
430 # my $payinfo = $self->payinfo;
431 # $payinfo =~ s/\W//g; #anything else would just confuse things
432 # $self->payinfo($payinfo);
433 # $error = $self->ut_alpha('payinfo');
434 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
435 # return "Unknown prepayment identifier"
436 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
441 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
445 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
447 # shouldn't payinfo_check do this?
448 return "Expiration date required"
449 if $self->paydate eq '' || $self->paydate eq '-';
452 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
453 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
454 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
455 ( $m, $y ) = ( $2, "19$1" );
456 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
457 ( $m, $y ) = ( $3, "20$2" );
459 return "Illegal expiration date: ". $self->paydate;
461 $m = sprintf('%02d',$m);
462 $self->paydate("$y-$m-01");
463 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
464 return gettext('expired_card')
467 !$ignore_expired_card
468 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
472 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
473 ( ! $conf->exists('require_cardname')
474 || $self->payby !~ /^(CARD|DCRD)$/ )
476 $self->payname( $self->first. " ". $self->getfield('last') );
479 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
480 $self->payname =~ /^([\w \,\.\-\']*)$/
481 or return gettext('illegal_name'). " payname: ". $self->payname;
484 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
485 or return gettext('illegal_name'). " payname: ". $self->payname;
496 sub check_payinfo_cardtype {
499 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
501 my $payinfo = $self->payinfo;
504 return '' if $payinfo =~ /^99\d{14}$/; #token
506 my %bop_card_types = map { $_=>1 } values %{ card_types() };
507 my $cardtype = cardtype($payinfo);
509 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
515 sub _banned_pay_hashref {
526 'payby' => $payby2ban{$self->payby},
527 'payinfo' => $self->payinfo,
528 #don't ever *search* on reason! #'reason' =>
532 sub _new_banned_pay_hashref {
534 my $hr = $self->_banned_pay_hashref;
535 $hr->{payinfo_hash} = 'SHA512';
536 $hr->{payinfo} = sha512_base64($hr->{payinfo});
540 =item paydate_mon_year
542 Returns a two element list consisting of the paydate month and year.
546 sub paydate_mon_year {
549 my $date = $self->paydate; # || '12-2037';
551 #false laziness w/elements/select-month_year.html
552 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
554 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
557 warn "unrecognized expiration date format: $date";
565 Returns a one line text label for this payment type.
582 my $name = $self->payby =~ /^(CARD|DCRD)$/
583 && cardtype($self->paymask) || FS::payby->shortname($self->payby);
585 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
588 "$name: ". $self->paymask.
589 ( $self->payby =~ /^(CARD|DCRD)$/
590 ? ' Exp '. join('/', $self->paydate_mon_year)
601 my( $self, %opt ) = @_;
603 $opt{$_} = $self->$_() for qw( payinfo payname paydate );
605 if ( $self->locationnum ) {
606 my $cust_location = $self->cust_location;
607 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
610 $self->cust_main->realtime_bop({
611 'method' => FS::payby->payby2bop( $self->payby ),
619 Returns a list of valid values for the paytype field (bank account type for
620 electronic check payment).
627 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
630 =item cgi_cust_payby_fields
632 Returns the field names used in the web interface (including some pseudo-fields).
636 sub cgi_cust_payby_fields {
638 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
639 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
642 =item cgi_hash_callback HASHREF OLD
644 Subroutine (not a class or object method). Processes a hash reference
645 of web interface contet (transfers the data from pseudo-fields to real fields).
647 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
648 payissue and payip. If the new field is blank but the old is not, the old field
653 sub cgi_hash_callback {
661 $hashref->{payby} = $noauto{$hashref->{payby}}
662 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
664 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
666 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
671 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
672 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
673 if $conf->config('echeck-country') eq 'CA';
674 $hashref->{payinfo} .= $hashref->{'payinfo2'};
676 $hashref->{payname} = $hashref->{'payname_CHEK'};
678 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
680 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
687 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
690 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
691 next if $hashref->{$field};
692 next unless $old->get($field);
693 $hashref->{$field} = $old->get($field);
703 Returns a qsearch hash expression to search for parameters specified in HASHREF.
722 my ($class, $params) = @_;
727 # initialize these to prevent warnings
729 'paydate_year' => '',
737 if ( $params->{'payby'} ) {
739 my @payby = ref( $params->{'payby'} )
740 ? @{ $params->{'payby'} }
741 : ( $params->{'payby'} );
743 @payby = grep /^([A-Z]{4})$/, @payby;
744 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
745 push @where, "cust_payby.payby $in_payby"
750 # paydate_year / paydate_month
753 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
755 $params->{'paydate_month'} =~ /^(\d\d?)$/
756 or die "paydate_year without paydate_month?";
760 'cust_payby.paydate IS NOT NULL',
761 "cust_payby.paydate != ''",
762 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
766 # setup queries, subs, etc. for the search
769 $orderby ||= 'ORDER BY custnum';
771 # here is the agent virtualization
773 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
775 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
777 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
778 # always make address fields available in results
779 for my $pre ('bill_', 'ship_') {
781 ' LEFT JOIN cust_location AS '.$pre.'location '.
782 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
785 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
787 my @select = ( 'cust_payby.*',
788 #'cust_main.custnum',
789 # there's a good chance that we'll need these
790 'cust_main.bill_locationnum',
791 'cust_main.ship_locationnum',
792 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
795 my $select = join(', ', @select);
798 'table' => 'cust_payby',
800 'addl_from' => $addl_from,
802 'extra_sql' => $extra_sql,
803 'order_by' => $orderby,
804 'count_query' => $count_query,
816 L<FS::Record>, schema.html from the base documentation.