This is an industry standard algorithm I ported to python. It works on all major credit cards. You pass in the credit card number as a string and it returns 1 for a valid card or 0 for an invalid card
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def cardLuhnChecksumIsValid(card_number):
""" checks to make sure that the card passes a luhn mod-10 checksum """
sum = 0
num_digits = len(card_number)
oddeven = num_digits & 1
for count in range(0, num_digits):
digit = int(card_number[count])
if not (( count & 1 ) ^ oddeven ):
digit = digit * 2
if digit > 9:
digit = digit - 9
sum = sum + digit
return ( (sum % 10) == 0 )
|
This recipe was originally written for a now-defunct e-commerce application used within Zope.
It will save you time and money before trying to process a bad card with your credit card vendor, because you won't waste money trying to authorize a bad card with your credit card processing vendor.
The full suite of creditValidation methods are available here:
Checksum calculation.
Another take...
That checksum is wrong. It does not match the other 2 listed here, and it returns "7" for my credit card. What is it for?
Integer only version. Here is a integer-only version that avoids string casts. You may need "from __future__ import division" to use the "//" floor operator.
generating many luhn numbers.
Incorrect LUHN checksum implementation. This LUHN implementation is actually incorrect. The card number digits must be traversed from end to beginning (reverse the direction the for loop counts) or some (but not all) perfectly valid card numbers will be rejected.
http://david.theresistance.net/files/creditValidation.py <-- Address Not Found
Here's another version, just written to see how Python compares to C in such a case.
You can find details and execution timing results here.
As this is my very first coding experience with Python, comments and advices are welcome :-)