Créer une classe de validation de carte de crédit avec php

Contenu du snippet

Bien que les options en ligne de paiement telles que PayPal soient devenues extrêmement populaires dans les dernières années, la majorité de magasins en ligne emploient toujours une certaine sorte de système marchand pour accepter des paiements par carte de crédit de leur Websites. Avant que vous chiffriez réellement la carte de crédit de votre client numérote à une base de données ou les expédie à un serveur marchand, il est une bonne idée de mettre en application votre propre routine de validation de carte de crédit.

Source / Exemple :


<STRONG>Although online payment options such as PayPal have become extremely 
popular in the last couple of years, the majority of online stores still use 
some sort of merchant system to accept credit card payments from their Websites. 
Before you actually encrypt your customer's credit card numbers to a database or 
forward them to a merchant server, it's a good idea to implement your own credit 
card validation routine.</STRONG>
<P>In this article we're going to work through the development of a 
class=glossary title="PHP, or Hypertext Preprocessor, is an open source, 
server-side programming language."PHP</A> class that stores the details of a 
credit card and validates its number using the Mod 10 algorithm. To implement 
the class we'll create in this article, you should have access to an 
class=glossary title="Apache is one of the world's most widely-used Web 
servers.Apache</A> web server running PHP 4.1.0 or later.</P>
<H5>Credit Card Validation</H5>
<P>What do we actually mean when we say "validate a credit card number"? Quite 
simply it means that we run a credit card number through a special algorithm 
known as the Mod 10 algorithm.</P>
<P>This algorithm processes some simple numerical data validation routines 
against the number, and the result of this algorithm can be used to determine 
whether or not a credit card number is valid. There are several different types 
of credit cards that one can use to make a purchase, however they can all be 
validated using the Mod 10 algorithm.</P>
<P>As well as passing the Mod 10 algorithm, a credit card number must also pass 
several different formatting rules. A list of these rules for each of the six 
most popular credit cards is shown below:</P>
<P>
<UL>
<LI><STRONG>mastercard:</STRONG> Must have a prefix of 51 to 55, and must be 16 
digits in length. 
<LI><STRONG>Visa:</STRONG> Must have a prefix of 4, and must be either 13 or 16 
digits in length. 
<DIV id=adz style="DISPLAY: block"></DIV>
<LI><STRONG>American Express:</STRONG> Must have a prefix of 34 or 37, and must 
be 15 digits in length. 
<LI><STRONG>Diners Club: </STRONG>Must have a prefix of 300 to 305, 36, or 38, 
and must be 14 digits in length. 
<LI><STRONG>Discover:</STRONG> Must have a prefix of 6011, and must be 16 digits 
in length. 
<LI><STRONG>JCB:</STRONG> Must have a prefix of 3, 1800, or 2131, and must be 
either 15 or 16 digits in length. </LI></UL>
<P></P>
<P>As mentioned earlier, in this article we will create a PHP class that will 
hold the details of a credit card number and expose a function that indicates 
whether or not the number of that credit card is valid (i.e. whether it passed 
the Mod 10 algorithm or not). Before we create that class however, let's look at 
how the Mod 10 algorithm works.</P>
<H5>The Mod 10 Algorithm</H5>
<P>There are three steps that the Mod 10 algorithm takes to determine whether or 
not a credit card number is valid. We will use the valid credit card number 
378282246310005 to demonstrate these steps:</P>
<P><EM><STRONG>Step One</STRONG></EM></P>
<P>The number is reversed and the value of every second digit is doubled, 
starting with the digit in second place:</P>
<P>378282246310005</P>
<P>becomes...</P>
<P>500013642282873</P>
<P>and the value of every second digit is doubled:</P>
<P>5 0 0 0 1 3 6 4 2 2 8 2 8 7 3</P>
<P>x2 x2 x2 x2 x2 x2 x2</P>
<P>-------------------------------------------</P>
<P>0 0 6 8 4 4 14</P>
<P><EM><STRONG>Step Two</STRONG></EM></P>
<P>The values of the numbers that resulted from multiplying every second digit 
by two are added together (i.e. in our example above, multiplying the 7 by two 
resulted in 14, which is 1 + 4 = 5). The result of these additions is added to 
the value of every digit that was not multiplied (i.e. the first digit, the 
third, the fifth, etc):</P>
<P>5 + (0) + 0 + (0) + 1 + (6) + 6 + (8) + 2 + (4) + 8 + (4) + 8 + (1 + 4) + 
3</P>
<P>= 60</P>
<P><EM><STRONG>Step Three</STRONG></EM></P>
<P>When a modulus operation is applied to the result of step two, the <FONT 
color=#186125>remainder must equal 0 in order for the </FONT><FONT 
color=#186125>// number to pass the Mod 10 algorithm. </FONT>The modulus 
operator simply returns the remainder of a division, for example:</P>
<P>10 MOD 5 = 0 (5 goes into 10 two times and has a remainder of 0)</P>
<P>20 MOD 6 = 2 (6 goes into 20 three times and has a remainder of 2)</P>
<P>43 MOD 4 = 3 (4 goes into 43 ten times and has a remainder of 3)</P>
<P>So for our test credit card number 378282246310005, we apply a modulus of 10 
to the result from step two, like this:</P>
<P>60 MOD 10 = 0</P>
<P>The modulus operation returns 0, indicating that the credit card number is 
valid.</P>
<DIV id=adz> </DIV>
<P>Now that we understand the Mod 10 algorithm, it's really quite easy to create 
our own version to validate credit card numbers with glossary PHP, or Hypertext 
Preprocessor, is an open source, server-side programming language.PHP</A>. Let's 
create our credit card class now.</P>
<H5>Creating the CCreditCard Class</H5>
<P>Let's now create a PHP class that we can use to store and validate the 
details of a credit card. Our class will be able to hold the cardholder's name, 
the card type (mastercard, visa, etc), the card number, and the expiry month and 
date.</P>
<P>Create a new PHP file called class.creditcard.php. As we walk through the 
following steps, copy-paste each piece of code shown to the file and save 
it.</P>
<P>We start of by defining several card type constants. These values will be 
used to represent the type of card that our class will be validating:</P>
<P><CODE><?php <BR><BR>define("CARD_TYPE_MC", 0); <BR>define("CARD_TYPE_VS", 
1); <BR>define("CARD_TYPE_AX", 2); <BR>define("CARD_TYPE_DC", 3); 
<BR>define("CARD_TYPE_DS", 4); <BR>define("CARD_TYPE_JC", 5);
</P>
<P>Next, we have our class declaration. Our class is called
CCreditCard
. Note that there is an extra 'C' at the front of the
class name intentionally: it's a common programming practice to prefix the name
of a class with 'C' to in fact indicate that it is a class.</P>
<P>We also define five member variables, which will be used internally to hold
the credit card's name, type, number, expiry month and year:</P>
<P>
class CCreditCard <BR>{ <BR><FONT color=#186125>// Class Members 
<BR></FONT>var $__ccName = ''; <BR>var $__ccType = ''; <BR>var $__ccNum = ''; 
<BR>var $__ccExpM = 0; <BR>var $__ccExpY = 0;
</P>
<P>Next we have our class' custom constructor. A constructor is a function that
has the same names as the class in which it exists. It returns no value. It is
special in the sense that it is automatically executed whenever we create a new
instance of that class.</P>
<P>Whenever we want to create a new instance of our
CCreditCard

class, we must explicitly pass in five arguments to its constructor: the
cardholder's name, card type, number, and expiry date. Because we have created
our own custom constructor ( class="glossary" title="PHP, or Hypertext
Preprocessor, is an open source, server-side programming language.PHP</A>
implements a default constructor that accepts no arguments if we don't
explicitly create one), we must pass in values for each of these five arguments
every time we instantiate the class. If we omit them, PHP will raise an
error.</P>
<P>
// Constructor <BR>function CCreditCard($name, $type, $num, $expm, 
$expy) <BR>{
</P>
<P>If the value of the
$name
variable passed into the constructor
is empty, then we use the
die() 
function to terminate the
instantiation of our class and output an error message telling the user that
they must pass a name to the constructor:</P>
<P>
// Set member variables <BR>if(!empty($name)) <BR>{ 
<BR>$this->__ccName = $name; <BR>} <BR>else <BR>{ <BR>die('Must pass name to 
constructor'); <BR>}
</P>
<P>Our
CCreditCard
class is flexible: it accepts several different
ways to specify the type of card that is being stored. For example, if we want
to add the details of a mastercard to a new instance of our
CCreditCard
class, then we could pass in the following values for
the
$type 
variable of the constructor: "mc", "mastercard", "m", or
"1".</P>
<P>We make sure that a valid card type has been passed in, and set the value of
our classes
$__ccType
variable to one of the constant card type
values that we defined earlier:</P>
<P>
// Make sure card type is valid <BR>switch(strtolower($type)) <BR>{ 
<BR>  case 'mc': <BR>  case 'mastercard': <BR>  case 'm': <BR>  case '1': <BR>  
  $this->__ccType = CARD_TYPE_MC; <BR>    break; <BR>  case 'vs': <BR>  case 
'visa': <BR>  case 'v': <BR>  case '2': <BR>    $this->__ccType = 
CARD_TYPE_VS; <BR>    break; <BR>  case 'ax': <BR>  case 'american express': 
<BR>  case 'a': <BR>  case '3': <BR>    $this->__ccType = CARD_TYPE_AX; <BR>  
  break; <BR>  case 'dc': <BR>  case 'diners club': <BR>  case '4': <BR>    
$this->__ccType = CARD_TYPE_DC; <BR>    break; <BR>  case 'ds': <BR>  case 
'discover': <BR>  case '5': <BR>    $this->__ccType = CARD_TYPE_DS; <BR>    
break; <BR>  case 'jc': <BR>  case 'jcb': <BR>  case '6': <BR>    
$this->__ccType = CARD_TYPE_JC; <BR>    break; <BR>  default: <BR>    
die('Invalid type ' . $type . ' passed to constructor'); <BR>}
</P>
<P>If an invalid card type is passed in, then the default branch of our switch
statement will be called, resulting in our script terminating with the
die()
function.</P>
<P>We can take advantage of class="glossary" title="PHP, or Hypertext
Preprocessor, is an open source, server-side programming language. PHP</A>'s
built-in support for regular expressions by using the
ereg_replace

function to strip out all non-numeric characters from the credit card
number:</P>
<P>
// Don't check the number yet, <BR><FONT color=#186125>// just kill all 
non numerics <BR></FONT>if(!empty($num)) <BR>{ <BR>  $cardNumber = 
ereg_replace("[^0-9]", "", $num); <BR><BR>  // Make sure the card number isnt 
empty <BR>  if(!empty($cardNumber)) <BR>  { <BR>    $this->__ccNum = 
$cardNumber; <BR>  } <BR>  else <BR>  { <BR>    die('Must pass number to 
constructor'); <BR>  } <BR>} <BR>else <BR>{ <BR>  die('Must pass number to 
constructor'); <BR>}
</P>
<P>We finish off our
CCreditCard 
constructor by making sure that
both the expiry month and year are valid, numerical values:</P>
<P>
if(!is_numeric($expm) || $expm < 1 || $expm > 12) <BR>{ <BR>  
die('Invalid expiry month of ' . $expm . ' passed to constructor'); <BR>} 
<BR>else <BR>{ <BR>  $this->__ccExpM = $expm; <BR>} <BR><BR><FONT 
color=#186125>// Get the current year <BR></FONT>$currentYear = date('Y'); 
<BR>settype($currentYear, 'integer'); <BR><BR>if(!is_numeric($expy) || $expy 
< $currentYear || $expy <BR>> $currentYear + 10) <BR>{ <BR>  die('Invalid 
expiry year of ' . $expy . ' passed to constructor'); <BR>} <BR>else <BR>{ <BR>  
$this->__ccExpY = $expy; <BR>} <BR>}
</P>
<P>In our
CCreditCard
class, the only way to set the values of the
credit card's details is through the constructor. To retrieve the values of our
class-specific variables (
$__ccName
,
$__ccType
, etc),
we create several functions, like this: </P>
<P>
function Name() <BR>{ <BR>  return $this->__ccName; <BR>} 
<BR><BR>function Type() <BR>{ <BR>  switch($this->__ccType) <BR>    { <BR>    
case CARD_TYPE_MC: <BR>      return 'mastercard [1]'; <BR>      break; <BR>    
case CARD_TYPE_VS: <BR>      return 'Visa [2]'; <BR>      break; <BR>    case 
CARD_TYPE_AX: <BR>      return 'Amex [3]'; <BR>      break; <BR>    case 
CARD_TYPE_DC: <BR>      return 'Diners Club [4]'; <BR>      break; <BR>    case 
CARD_TYPE_DS: <BR>      return 'Discover [5]'; <BR>      break; <BR>    case 
CARD_TYPE_JC: <BR>      return 'JCB [6]'; <BR>      break; <BR>    default: 
<BR>      return 'Unknown [-1]'; <BR>  } <BR>} <BR><BR>function Number() <BR>{ 
<BR>  return $this->__ccNum; <BR>} <BR><BR>function ExpiryMonth() <BR>{ <BR>  
return $this->__ccExpM; <BR>} <BR><BR>function ExpiryYear() <BR>{ <BR>  
return $this->__ccExpY; <BR>}
</P>
<P>These functions allow us to retrieve the values of the variables contained
within our class. For example, if I created an instance of our
CCreditCard
class called
$cc1
, then I could retrieve
its expiration month using
$cc1->ExpiryMonth()
.</P>
<P>A common function when working with credit cards is displaying the details
that you've captured from that user back to them as a confirmation. For example,
if the user entered a credit card number of 4111111111111111, then you might
want to only show part of the number to them, such as 4111111111111xxxx. Our
CCreditCard 
class contains a function called
SafeNumber
, which accepts two arguments. The first is the character
to mask the digits with, and the second is the number of digits to mask (from
the right):</P>
<P>
function SafeNumber($char = 'x', $numToHide = 4) <BR>{ <BR>  // Return 
only part of the number <BR>  if($numToHide < 4) <BR>  { <BR>    $numToHide = 
4; <BR>  } <BR><BR>  if($numToHide > 10) <BR>  { <BR>    $numToHide = 10; 
<BR>  } <BR><BR>  $cardNumber = $this->__ccNum; <BR>  $cardNumber = 
substr($cardNumber, 0, strlen($cardNumber) - $numToHide); <BR><BR>  for($i = 0; 
$i < $numToHide; $i++) <BR>  { <BR>    $cardNumber .= $char; <BR>  } 
<BR><BR>  return $cardNumber; <BR>}
</P>
<P>If we had an instance of our
CCreditCard
class called
$cc1 
and the credit card number stored in this class was 4242424242424242,
then we could mask the last 6 digits like this:
echo 
$cc1->SafeNumber('x', 6)
.</P>
<P>The last function contained in our
CCreditCard
class is called
IsValid
, and implements the Mod 10 algorithm against the credit
card number of our class, returning true/false.</P>
<P>It starts of by setting two variables (
$validFormat
and
$passCheck
) to false:</P>
<P>
function IsValid() <BR>{ <BR>  // Not valid by default <BR>  
$validFormat = false; <BR>  $passCheck = false;
</P>
<P>Next we make sure that the credit card number is formatted correctly. We use
class="glossary" title="PHP, or Hypertext Preprocessor, is an open source,
server-side programming language. PHP</A>'s
ereg
function to do
this. The regular expression that must be matched is different for each
card:</P>
<P>
// Is the number in the correct format? <BR>switch($this->__ccType) 
<BR>{ <BR>  case CARD_TYPE_MC: <BR>    $validFormat = ereg("^5[1-5][0-9]{14}$", 
$this->__ccNum); <BR>    break; <BR>case CARD_TYPE_VS: <BR>    $validFormat = 
ereg("^4[0-9]{12}([0-9]{3})?$", $this->__ccNum); <BR>    break; <BR>case 
CARD_TYPE_AX: <BR>    $validFormat = ereg("^3[47][0-9]{13}$", 
$this->__ccNum); <BR>    break; <BR>case CARD_TYPE_DC: <BR>    $validFormat = 
ereg("^3(0[0-5]|[68][0-9])[0-9]{11}$", $this->__ccNum); <BR>    break; 
<BR>case CARD_TYPE_DS: <BR>    $validFormat = ereg("^6011[0-9]{12}$", 
$this->__ccNum); <BR>    break; <BR>case CARD_TYPE_JC: <BR>    $validFormat = 
ereg("^(3[0-9]{4}|2131|1800)[0-9]{11}$", $this->__ccNum); <BR>    break; 
<BR>  default: <BR>  // Should never be executed <BR>  $validFormat = false; 
<BR>}
</P>
<P>At this point,
$validFormat
will be true (
ereg

returns true/false) if the credit card number is in the correct format, and
false if it's not.</P>
<P>We now implement a class="glossary" title="PHP, or Hypertext Preprocessor, is
an open source, server-side programming language.' PHP</A> version of the Mod 10
algorithm, using exactly the same steps that we described earlier:</P>
<P>
// Is the number valid? <BR>$cardNumber = strrev($this->__ccNum); 
<BR>$numSum = 0; <BR><BR>for($i = 0; $i < strlen($cardNumber); $i++) <BR>{ 
<BR>  $currentNum = substr($cardNumber, $i, 1); <BR><BR><FONT color=#186125>// 
Double every second digit <BR></FONT>if($i % 2 == 1) <BR>{ <BR>  $currentNum *= 
2; <BR>} <BR><BR><FONT color=#186125>// Add digits of 2-digit numbers togethe 
</FONT><FONT color=#186125>// r <BR></FONT>if($currentNum > 9) <BR>{ <BR>  
$firstNum = $currentNum % 10; <BR>  $secondNum = ($currentNum - $firstNum) / 10; 
<BR>  $currentNum = $firstNum + $secondNum; <BR>} <BR><BR>$numSum += 
$currentNum; <BR>}
</P>
<P>The
$numSum
variable will contain the sum of all of the
variables from step two of the Mod 10 algorithm, which we described earlier.
PHP's symbol for the modulus operator is '
%
', so we assign
true/false to the
$passCheck 
variable, depending on whether or not
$numSum
has a modulus of zero:</P>
<P>
// If the total has no remainder it's OK <BR>$passCheck = ($numSum % 10 
== 0);
</P>
<P>If both
$validFormat 
and
$passCheck
are true, then
we return true, to indicate that the card number is valid. If not, we return
false, to indicate that either the card number was in an incorrect format, or if
failed the Mod 10 check:</P>
<P>
  if($validFormat &amp;&amp; $passCheck) return true; <BR>  else return 
false; <BR> } <BR>} <BR>?>
</P>
<DIV id=adz> </DIV>
<P>And that's all there is to our
CCreditCard
class! Let's now look
at a simple validation example using HTML forms, PHP, and an instance of our
CCreditCard
class.</P>
<H5>Using our CCreditCard Class</H5>
<P>Create a new file called testcc.php and save it in the same directory as the
class.creditcard.php file. Enter the following code into testcc.php:</P>
<P>
<?php include('class.creditcard.php'); ?> <BR><?php 
<BR>if(!isset($submit)) <BR>{ <BR>?> <BR><BR>  <h2>Validate Credit 
Card</h2> <BR>  <form name="frmCC" action="testcc.php" 
method="post"> <BR><BR>  Cardholders name: <input type="text" 
name="ccName"><br> <BR>  Card number: <input type="text" 
name="ccNum"><br> <BR>  Card type: <select name="ccType"> <BR>  
<option value="1">mastercard</option> <BR>  <option 
value="2">Visa</option> <BR>  <option 
value="3">Amex</option> <BR>  <option 
value="4">Diners</option> <BR>  <option 
value="5">Discover</option> <BR>  <option 
value="6">JCB</option> <BR>  </select><br> <BR><BR>  Expiry 
Date: <select name="ccExpM">  <BR><BR>  <?php <BR><BR>    for($i = 1; 
$i < 13; $i++) <BR>    { echo '<option>' . $i . '</option>'; } 
<BR><BR>  ?>  <BR><BR>  </select> <BR><BR>  <select 
name="ccExpY"> <BR><BR>  <?php <BR><BR>    for($i = 2002; $i < 2013; 
$i++) <BR>    { echo '<option>' . $i . '</option>'; } <BR><BR>  
?>  <BR><BR>  </select><br><br> <BR><BR>  <input 
type="submit" name="submit" value="Validate"> <BR>  </form> <BR><BR>  
<? <BR><BR>  } <BR>  else <BR>  { <BR>  // Check if the card is valid <BR>  
$cc = new CCreditCard($ccName, $ccType, $ccNum, $ccExpM, $ccExpY); <BR><BR>  
?> <BR><BR>  <h2>Validation Results</h2> <BR>  <b>Name: 
</b><?=$cc->Name(); ?><br> <BR>  <b>Number: 
</b><?=$cc->SafeNumber('x', 6); ?><br> <BR>  <b>Type: 
</b><?=$cc->Type(); ?><br> <BR>  <b>Expires: 
</b><?=$cc->ExpiryMonth() . '/' . <BR>  $cc->ExpiryYear(); 
?><br><br> <BR><BR>  <?php <BR> <BR>    echo '<font 
color="blue" size="2"><b>';  <BR><BR>    if($cc->IsValid()) <BR>    
echo 'VALID CARD'; <BR>    else <BR>    echo 'INVALID CARD'; <BR><BR>    echo 
'</b></font>'; <BR>  } <BR>?>
</P>
<P>Run the script in your browser and see what happens...</P>
</code>

A voir également

Vous n'êtes pas encore membre ?

inscrivez-vous, c'est gratuit et ça prend moins d'une minute !

Les membres obtiennent plus de réponses que les utilisateurs anonymes.

Le fait d'être membre vous permet d'avoir un suivi détaillé de vos demandes et codes sources.

Le fait d'être membre vous permet d'avoir des options supplémentaires.

Du même auteur (XzaB)