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;
241 if ( $conf->exists('business-onlinepayment-verification') ) {
242 $error = $self->verify;
243 return $error if $error;
247 local $SIG{HUP} = 'IGNORE';
248 local $SIG{INT} = 'IGNORE';
249 local $SIG{QUIT} = 'IGNORE';
250 local $SIG{TERM} = 'IGNORE';
251 local $SIG{TSTP} = 'IGNORE';
252 local $SIG{PIPE} = 'IGNORE';
254 my $oldAutoCommit = $FS::UID::AutoCommit;
255 local $FS::UID::AutoCommit = 0;
258 my $error = $self->SUPER::replace($old);
260 $dbh->rollback if $oldAutoCommit;
264 if ( $self->payby =~ /^(CARD|CHEK)$/
265 && ( ( $self->get('payinfo') ne $old->get('payinfo')
266 && $self->get('payinfo') !~ /^99\d{14}$/
268 || grep { $self->get($_) ne $old->get($_) } qw(paydate payname)
273 # card/check/lec info has changed, want to retry realtime_ invoice events
274 my $error = $self->cust_main->retry_realtime;
276 $dbh->rollback if $oldAutoCommit;
281 $dbh->commit or die $dbh->errstr if $oldAutoCommit;
288 Checks all fields to make sure this is a valid record. If there is
289 an error, returns the error, otherwise returns false. Called by the insert
298 $self->ut_numbern('custpaybynum')
299 || $self->ut_foreign_key('custnum', 'cust_main', 'custnum')
300 || $self->ut_numbern('weight')
301 #encrypted #|| $self->ut_textn('payinfo')
302 #encrypted #|| $self->ut_textn('paycvv')
303 # || $self->ut_textn('paymask') #XXX something
304 #later #|| $self->ut_textn('paydate')
305 || $self->ut_numbern('paystart_month')
306 || $self->ut_numbern('paystart_year')
307 || $self->ut_numbern('payissue')
308 # || $self->ut_textn('payname') #XXX something
309 || $self->ut_alphan('paystate')
310 || $self->ut_textn('paytype')
311 || $self->ut_ipn('payip')
313 return $error if $error;
317 FS::payby->can_payby($self->table, $self->payby)
318 or return "Illegal payby: ". $self->payby;
320 # If it is encrypted and the private key is not availaible then we can't
321 # check the credit card.
322 my $check_payinfo = ! $self->is_encrypted($self->payinfo);
324 # Need some kind of global flag to accept invalid cards, for testing
326 #XXX if ( !$import && $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
327 if ( !$ignore_invalid_card &&
328 $check_payinfo && $self->payby =~ /^(CARD|DCRD)$/ ) {
330 my $payinfo = $self->payinfo;
332 $payinfo =~ /^(\d{13,16}|\d{8,9})$/
333 or return gettext('invalid_card'); #. ": ". $self->payinfo;
335 $self->payinfo($payinfo);
337 or return gettext('invalid_card'); # . ": ". $self->payinfo;
339 return gettext('unknown_card_type')
340 if $self->payinfo !~ /^99\d{14}$/ #token
341 && cardtype($self->payinfo) eq "Unknown";
343 unless ( $ignore_banned_card ) {
344 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
346 if ( $ban->bantype eq 'warn' ) {
347 #or others depending on value of $ban->reason ?
348 return '_duplicate_card'.
349 ': disabled from'. time2str('%a %h %o at %r', $ban->_date).
350 ' until '. time2str('%a %h %o at %r', $ban->_end_date).
351 ' (ban# '. $ban->bannum. ')'
352 unless $self->override_ban_warn;
354 return 'Banned credit card: banned on '.
355 time2str('%a %h %o at %r', $ban->_date).
356 ' by '. $ban->otaker.
357 ' (ban# '. $ban->bannum. ')';
362 if (length($self->paycvv) && !$self->is_encrypted($self->paycvv)) {
363 if ( cardtype($self->payinfo) eq 'American Express card' ) {
364 $self->paycvv =~ /^(\d{4})$/
365 or return "CVV2 (CID) for American Express cards is four digits.";
368 $self->paycvv =~ /^(\d{3})$/
369 or return "CVV2 (CVC2/CID) is three digits.";
376 my $cardtype = cardtype($payinfo);
377 if ( $cardtype =~ /^(Switch|Solo)$/i ) {
379 return "Start date or issue number is required for $cardtype cards"
380 unless $self->paystart_month && $self->paystart_year or $self->payissue;
382 return "Start month must be between 1 and 12"
383 if $self->paystart_month
384 and $self->paystart_month < 1 || $self->paystart_month > 12;
386 return "Start year must be 1990 or later"
387 if $self->paystart_year
388 and $self->paystart_year < 1990;
390 return "Issue number must be beween 1 and 99"
392 and $self->payissue < 1 || $self->payissue > 99;
395 $self->paystart_month('');
396 $self->paystart_year('');
400 } elsif ( !$ignore_invalid_card &&
401 $check_payinfo && $self->payby =~ /^(CHEK|DCHK)$/ ) {
403 my $payinfo = $self->payinfo;
404 $payinfo =~ s/[^\d\@\.]//g;
405 if ( $conf->config('echeck-country') eq 'CA' ) {
406 $payinfo =~ /^(\d+)\@(\d{5})\.(\d{3})$/
407 or return 'invalid echeck account@branch.bank';
408 $payinfo = "$1\@$2.$3";
409 } elsif ( $conf->config('echeck-country') eq 'US' ) {
410 $payinfo =~ /^(\d+)\@(\d{9})$/ or return 'invalid echeck account@aba';
413 $payinfo =~ /^(\d+)\@(\d+)$/ or return 'invalid echeck account@routing';
416 $self->payinfo($payinfo);
419 unless ( $ignore_banned_card ) {
420 my $ban = FS::banned_pay->ban_search( %{ $self->_banned_pay_hashref } );
422 if ( $ban->bantype eq 'warn' ) {
423 #or others depending on value of $ban->reason ?
424 return '_duplicate_ach' unless $self->override_ban_warn;
426 return 'Banned ACH account: banned on '.
427 time2str('%a %h %o at %r', $ban->_date).
428 ' by '. $ban->otaker.
429 ' (ban# '. $ban->bannum. ')';
434 # } elsif ( $self->payby eq 'PREPAY' ) {
436 # my $payinfo = $self->payinfo;
437 # $payinfo =~ s/\W//g; #anything else would just confuse things
438 # $self->payinfo($payinfo);
439 # $error = $self->ut_alpha('payinfo');
440 # return "Illegal prepayment identifier: ". $self->payinfo if $error;
441 # return "Unknown prepayment identifier"
442 # unless qsearchs('prepay_credit', { 'identifier' => $self->payinfo } );
447 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
451 } elsif ( $self->payby =~ /^(CARD|DCRD)$/ ) {
453 # shouldn't payinfo_check do this?
454 return "Expiration date required"
455 if $self->paydate eq '' || $self->paydate eq '-';
458 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
459 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
460 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
461 ( $m, $y ) = ( $2, "19$1" );
462 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
463 ( $m, $y ) = ( $3, "20$2" );
465 return "Illegal expiration date: ". $self->paydate;
467 $m = sprintf('%02d',$m);
468 $self->paydate("$y-$m-01");
469 my($nowm,$nowy)=(localtime(time))[4,5]; $nowm++; $nowy+=1900;
470 return gettext('expired_card')
473 !$ignore_expired_card
474 && ( $y<$nowy || ( $y==$nowy && $1<$nowm ) );
478 if ( $self->payname eq '' && $self->payby !~ /^(CHEK|DCHK)$/ &&
479 ( ! $conf->exists('require_cardname')
480 || $self->payby !~ /^(CARD|DCRD)$/ )
482 $self->payname( $self->first. " ". $self->getfield('last') );
485 if ( $self->payby =~ /^(CHEK|DCHK)$/ ) {
486 $self->payname =~ /^([\w \,\.\-\']*)$/
487 or return gettext('illegal_name'). " payname: ". $self->payname;
490 $self->payname =~ /^([\w \,\.\-\'\&]*)$/
491 or return gettext('illegal_name'). " payname: ". $self->payname;
497 if ( ! $self->custpaybynum
498 && $conf->exists('business-onlinepayment-verification') ) {
499 $error = $self->verify;
500 return $error if $error;
506 sub check_payinfo_cardtype {
509 return '' if $ignore_cardtype;
511 return '' unless $self->payby =~ /^(CARD|CHEK)$/;
513 my $payinfo = $self->payinfo;
516 return '' if $payinfo =~ /^99\d{14}$/; #token
518 my %bop_card_types = map { $_=>1 } values %{ card_types() };
519 my $cardtype = cardtype($payinfo);
521 return "$cardtype not accepted" unless $bop_card_types{$cardtype};
527 sub _banned_pay_hashref {
538 'payby' => $payby2ban{$self->payby},
539 'payinfo' => $self->payinfo,
540 #don't ever *search* on reason! #'reason' =>
544 sub _new_banned_pay_hashref {
546 my $hr = $self->_banned_pay_hashref;
547 $hr->{payinfo_hash} = 'SHA512';
548 $hr->{payinfo} = sha512_base64($hr->{payinfo});
552 =item paydate_mon_year
554 Returns a two element list consisting of the paydate month and year.
558 sub paydate_mon_year {
561 my $date = $self->paydate; # || '12-2037';
563 #false laziness w/elements/select-month_year.html
564 if ( $date =~ /^(\d{4})-(\d{1,2})-\d{1,2}$/ ) { #PostgreSQL date format
566 } elsif ( $date =~ /^(\d{1,2})-(\d{1,2}-)?(\d{4}$)/ ) {
569 warn "unrecognized expiration date format: $date";
577 Returns a one line text label for this payment type.
594 my $name = $self->payby =~ /^(CARD|DCRD)$/
595 && cardtype($self->paymask) || FS::payby->shortname($self->payby);
597 ( $self->payby =~ /^(CARD|CHEK)$/ ? $weight{$self->weight}. ' automatic '
600 "$name: ". $self->paymask.
601 ( $self->payby =~ /^(CARD|DCRD)$/
602 ? ' Exp '. join('/', $self->paydate_mon_year)
613 my( $self, %opt ) = @_;
615 $opt{$_} = $self->$_() for qw( payinfo payname paydate );
617 if ( $self->locationnum ) {
618 my $cust_location = $self->cust_location;
619 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
622 $self->cust_main->realtime_bop({
623 'method' => FS::payby->payby2bop( $self->payby ),
635 return '' unless $self->payby =~ /^(CARD|DCRD)$/;
639 # false laziness with check
641 if ( $self->paydate =~ /^(\d{1,2})[\/\-](\d{2}(\d{2})?)$/ ) {
642 ( $m, $y ) = ( $1, length($2) == 4 ? $2 : "20$2" );
643 } elsif ( $self->paydate =~ /^19(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
644 ( $m, $y ) = ( $2, "19$1" );
645 } elsif ( $self->paydate =~ /^(20)?(\d{2})[\/\-](\d{1,2})[\/\-]\d+$/ ) {
646 ( $m, $y ) = ( $3, "20$2" );
648 return "Illegal expiration date: ". $self->paydate;
650 $m = sprintf('%02d',$m);
651 $opt{paydate} = "$y-$m-01";
653 $opt{$_} = $self->$_() for qw( payinfo payname paycvv );
655 if ( $self->locationnum ) {
656 my $cust_location = $self->cust_location;
657 $opt{$_} = $cust_location->$_() for qw( address1 address2 city state zip );
660 $self->cust_main->realtime_verify_bop({
661 'method' => FS::payby->payby2bop( $self->payby ),
669 Returns a list of valid values for the paytype field (bank account type for
670 electronic check payment).
677 ('', 'Personal checking', 'Personal savings', 'Business checking', 'Business savings');
680 =item cgi_cust_payby_fields
682 Returns the field names used in the web interface (including some pseudo-fields).
686 sub cgi_cust_payby_fields {
688 [qw( payby payinfo paydate_month paydate_year paycvv payname weight
689 payinfo1 payinfo2 payinfo3 paytype paystate payname_CHEK )];
692 =item cgi_hash_callback HASHREF OLD
694 Subroutine (not a class or object method). Processes a hash reference
695 of web interface contet (transfers the data from pseudo-fields to real fields).
697 If OLD object is passed, also preserves locationnum, paystart_month, paystart_year,
698 payissue and payip. If the new field is blank but the old is not, the old field
703 sub cgi_hash_callback {
711 $hashref->{payby} = $noauto{$hashref->{payby}}
712 if ! $hashref->{weight} && exists $noauto{$hashref->{payby}};
714 if ( $hashref->{payby} =~ /^(CHEK|DCHK)$/ ) {
716 unless ( grep $hashref->{$_}, qw(payinfo1 payinfo2 payinfo3 payname_CHEK)) {
721 $hashref->{payinfo} = $hashref->{payinfo1}. '@';
722 $hashref->{payinfo} .= $hashref->{payinfo3}.'.'
723 if $conf->config('echeck-country') eq 'CA';
724 $hashref->{payinfo} .= $hashref->{'payinfo2'};
726 $hashref->{payname} = $hashref->{'payname_CHEK'};
728 } elsif ( $hashref->{payby} =~ /^(CARD|DCRD)$/ ) {
730 unless ( grep $hashref->{$_}, qw( payinfo paycvv payname ) ) {
737 $hashref->{paydate}= $hashref->{paydate_month}. '-'. $hashref->{paydate_year};
740 foreach my $field ( qw(locationnum paystart_month paystart_year payissue payip) ) {
741 next if $hashref->{$field};
742 next unless $old->get($field);
743 $hashref->{$field} = $old->get($field);
753 Returns a qsearch hash expression to search for parameters specified in HASHREF.
772 my ($class, $params) = @_;
777 # initialize these to prevent warnings
779 'paydate_year' => '',
787 if ( $params->{'payby'} ) {
789 my @payby = ref( $params->{'payby'} )
790 ? @{ $params->{'payby'} }
791 : ( $params->{'payby'} );
793 @payby = grep /^([A-Z]{4})$/, @payby;
794 my $in_payby = 'IN(' . join(',', map {"'$_'"} @payby) . ')';
795 push @where, "cust_payby.payby $in_payby"
800 # paydate_year / paydate_month
803 if ( $params->{'paydate_year'} =~ /^(\d{4})$/ ) {
805 $params->{'paydate_month'} =~ /^(\d\d?)$/
806 or die "paydate_year without paydate_month?";
810 'cust_payby.paydate IS NOT NULL',
811 "cust_payby.paydate != ''",
812 "CAST(cust_payby.paydate AS timestamp) < CAST('$year-$month-01' AS timestamp )"
816 # setup queries, subs, etc. for the search
819 $orderby ||= 'ORDER BY custnum';
821 # here is the agent virtualization
823 $FS::CurrentUser::CurrentUser->agentnums_sql(table => 'cust_main');
825 my $extra_sql = scalar(@where) ? ' WHERE '. join(' AND ', @where) : '';
827 my $addl_from = ' LEFT JOIN cust_main USING ( custnum ) ';
828 # always make address fields available in results
829 for my $pre ('bill_', 'ship_') {
831 ' LEFT JOIN cust_location AS '.$pre.'location '.
832 'ON (cust_main.'.$pre.'locationnum = '.$pre.'location.locationnum) ';
835 my $count_query = "SELECT COUNT(*) FROM cust_payby $addl_from $extra_sql";
837 my @select = ( 'cust_payby.*',
838 #'cust_main.custnum',
839 # there's a good chance that we'll need these
840 'cust_main.bill_locationnum',
841 'cust_main.ship_locationnum',
842 FS::UI::Web::cust_sql_fields($params->{'cust_fields'}),
845 my $select = join(', ', @select);
848 'table' => 'cust_payby',
850 'addl_from' => $addl_from,
852 'extra_sql' => $extra_sql,
853 'order_by' => $orderby,
854 'count_query' => $count_query,
866 L<FS::Record>, schema.html from the base documentation.