萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 信用卡驗證類:支援所有主流卡種的完整實作

前言

繼上一篇介紹通用驗證邏輯後,本文提供一個更完整、可直接投入生產環境的 PHP 信用卡驗證類。此類別封裝了卡號格式驗證、卡片類型識別、Luhn 校驗碼計算與有效期檢查,並提供靜態方法供直接呼叫。

類別架構設計

<?php
class CreditCardValidator {
    // 卡片類型定義:[名稱 => [前綴正則, 允許長度陣列]]
    private static $cardTypes = [
        'visa'             => ['/^4/', [13, 16]],
        'mastercard'       => ['/^(5[1-5]|2[2-7])/', [16]],
        'amex'             => ['/^3[47]/', [15]],
        'diners_club'      => ['/^3(0[0-5]|[68])/', [14]],
        'jcb'              => ['/^35(2[89]|[3-8])/', [16]],
        'discover'         => ['/^6(011|5|4[4-9])/', [16]],
        'unionpay'         => ['/^62/', [16, 17, 18, 19]],
    ];

    /**
     * 完整驗證入口
     *
     * @param string $number 卡號(可含空格/連字號)
     * @param string $expiry 有效期 MM/YY 或 MMYY
     * @return array ['valid'=bool, 'type'=string|null, 'message'=string]
     */
    public static function validate(string $number, string $expiry): array {
        $cleanNumber = preg_replace('/\D/', '', $number);
        $cleanExpiry = preg_replace('/\D/', '', $expiry);

        // 1. 基本長度檢查
        if (strlen($cleanNumber) < 13 || strlen($cleanNumber) > 19) {
            return ['valid' => false, 'type' => null, 'message' => '卡號長度不正確'];
        }

        // 2. 識別卡片類型
        $type = self::detectType($cleanNumber);
        if (!$type) {
            return ['valid' => false, 'type' => null, 'message' => '不支援的卡片類型'];
        }

        // 3. Luhn 校驗
        if (!self::luhnCheck($cleanNumber)) {
            return ['valid' => false, 'type' => $type, 'message' => '卡號校驗碼錯誤'];
        }

        // 4. 有效期檢查
        if (!self::validateExpiry($cleanExpiry)) {
            return ['valid' => false, 'type' => $type, 'message' => '卡片已過期'];
        }

        return ['valid' => true, 'type' => $type, 'message' => '驗證通過'];
    }

    private static function detectType(string $number): ?string {
        foreach (self::$cardTypes as $type => [$pattern, $lengths]) {
            if (preg_match($pattern, $number) && in_array(strlen($number), $lengths)) {
                return $type;
            }
        }
        return null;
    }

    private static function luhnCheck(string $number): bool {
        $sum = 0;
        $len = strlen($number);
        for ($i = $len - 1; $i >= 0; $i--) {
            $digit = (int)$number[$i];
            if (($len - $i) % 2 === 0) {
                $digit *= 2;
                if ($digit > 9) $digit -= 9;
            }
            $sum += $digit;
        }
        return $sum % 10 === 0;
    }

    private static function validateExpiry(string $expiry): bool {
        if (strlen($expiry) !== 4) return false;
        $month = (int)substr($expiry, 0, 2);
        $year = (int)substr($expiry, 2, 2) + 2000;
        if ($month < 1 || $month > 12) return false;
        $expireDate = strtotime("{$year}-{$month}-01");
        $now = strtotime(date('Y-m-01'));
        return $expireDate >= $now;
    }
}

使用範例

$result = CreditCardValidator::validate('4567 1234 5678 9101', '06/25');
if ($result['valid']) {
    echo "卡片類型:{$result['type']} - 驗證通過";
} else {
    echo "驗證失敗:{$result['message']}";
}

擴充性設計

  • 新增卡片類型只需在 $cardTypes 陣列加入前綴正則與長度限制。
  • 可輕易整合 BIN 資料庫(如 Binlist.net)進行更精準的發卡銀行、卡片等級識別。
  • 支援依賴注入,便於單元測試與 Mock。

總結

這個驗證類結構清晰、擴充性強,涵蓋了從格式檢查到業務邏輯驗證的完整流程。實際部署時,建議搭配前端 JavaScript 即時驗證(如 Cleave.js 格式化輸入),並在後端再次驗證,構建雙重防線。

copyright © 萬盛學電腦網 all rights reserved