Wednesday, December 18, 2013

PHP: Detect Credit Card Type and Simplify Payment Form

Simplifying forms is the way to go to improve the payment experience. It's pretty much becoming the standard to not ask the credit card type anymore.

Here's a clean way to do it in PHP 5.4+.
Note: To work with PHP 5.3 below, change square brackets with "array()".

function getCreditCardType($str, $format = 'string')
    {
        if (empty($str)) {
            return false;
        }

        $matchingPatterns = [
            'visa' => '/^4[0-9]{12}(?:[0-9]{3})?$/',
            'mastercard' => '/^5[1-5][0-9]{14}$/',
            'amex' => '/^3[47][0-9]{13}$/',
            'diners' => '/^3(?:0[0-5]|[68][0-9])[0-9]{11}$/',
            'discover' => '/^6(?:011|5[0-9]{2})[0-9]{12}$/',
            'jcb' => '/^(?:2131|1800|35\d{3})\d{11}$/',
            'any' => '/^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$/'
        ];

        $ctr = 1;
        foreach ($matchingPatterns as $key=>$pattern) {
            if (preg_match($pattern, $str)) {
                return $format == 'string' ? $key : $ctr;
            }
            $ctr++;
        }
    }

You can further enhance the experience on the UI part by adding a javascript equivalent of the above function and have it dynamically change credit card logos indicating credit card type dynamically as people type their credit card number.

This implementation was based on an answer found here. Fyi, Google, Github etc are using the same method for their payment forms and a lot more are doing so as the day pass by to improve their conversions.
  • Related Links Widget for Blogspot

No comments: