Merchant Account Services

Merchant Account Blog


Verifying Credit Cards Numbers Are Valid (Part 2)

As we discovered in Part 1 there is a set pattern to credit card numbers as well special identifiers for each card type (i.e. Visa cards start with a four). Knowing this allows us to validate a credit card number before we send it to the payment gateway to be sent to the processing bank and saves us time dealing with errors.

Unfortunately it is fairly common knowledge which credit cards start with which numbers so validating credit cards based on their starting number and length is not enough alone to prevent bogus credit cards from being submitted with a transaction. So how else can a web developer verify a credit card number is valid before submitting it to the payment gateway? All of the major credit card institutions use a checksum to validate their credit cards. Each digit of the credit card is multiplied by 1 or 2. The last digit of the multiplication is added for each number in the credit card. If the resulting number is divisible by 10 it is a valid credit card number.

Here is the PHP code:


// The credit card number
$cc_number = "4000123498762345";
//
// Our starting checksum
$checksum = 0;
//
// Alternating value of 1 or 2
$j = 1;
//
// Process each digit one by one starting at the right
for ($i = strlen($cc_number) - 1; $i >= 0; $i--)
{
// Extract the next digit and multiply by 1 or 2 on alternative digits.
$calc = substr($cc_number, $i, 1) * $j;
//
// If the result is in two digits add 1 to the checksum total
if ($calc > 9)
{
$checksum = $checksum + 1;
$calc = $calc - 10;
}
//
// Add the units element to the checksum total
$checksum += $calc;
//
// Switch the value of j
if ($j == 1)
{
$j = 2;
}
else
{
$j = 1;
}
}
//
// If checksum is divisible by 10 the credit card number is valid
if ($checksum % 10 == 0)
{
// It's a valid credit card number
}
else
{
// It's not valid
}

Leave a Reply

Leave Your Comments and Reviews about