本文提供一個開箱即用的 PHP 類,支援主流卡組織(Visa、MasterCard、Amex、Discover、JCB、Diners 等)的前綴規則,自動計算 Luhn 校驗位,生成的卡號可通過標準驗證,**僅供測試/教學用途,嚴禁非法使用**。
<?php
class CreditCardGenerator {
private static $prefixes = [
'visa' => ['4', '4539', '4556', '4916', '4532', '4929', '40240071', '4485', '4716'],
'mastercard' => ['51', '52', '53', '54', '55'],
'amex' => ['34', '37'],
'discover' => ['6011'],
'diners' => ['300', '301', '302', '303', '36', '38'],
'enroute' => ['2014', '2149'],
'jcb' => ['35'],
'voyager' => ['8699'],
];
private static $lengths = [
'visa' => [13, 16],
'mastercard' => [16],
'amex' => [15],
'discover' => [16],
'diners' => [14],
'enroute' => [15],
'jcb' => [16],
'voyager' => [15],
];
public static function generate(string $type, int $count = 1): array {
$type = strtolower($type);
if (!isset(self::$prefixes[$type])) {
throw new InvalidArgumentException("Unsupported card type: $type");
}
$prefixList = self::$prefixes[$type];
$lengths = self::$lengths[$type];
$results = [];
for ($i = 0; $i < $count; $i++) {
$prefix = $prefixList[array_rand($prefixList)];
$len = $lengths[array_rand($lengths)];
$results[] = self::completeNumber($prefix, $len);
}
return $results;
}
private static function completeNumber(string $prefix, int $length): string {
$num = $prefix;
while (strlen($num) < $length - 1) {
$num .= random_int(0, 9);
}
// Luhn 校驗位計算
$sum = 0;
$rev = strrev($num);
for ($i = 0; $i < strlen($rev); $i++) {
$d = (int)$rev[$i];
if ($i % 2 === 0) { // 原右數第 2、4... 位
$d *= 2;
if ($d > 9) $d -= 9;
}
$sum += $d;
}
$check = (10 - $sum % 10) % 10;
return $num . $check;
}
}
// 使用示例
foreach (['visa', 'mastercard', 'amex', 'discover'] as $type) {
echo strtoupper($type) . ":\n";
foreach (CreditCardGenerator::generate($type, 3) as $card) {
echo " $card\n";
}
}
/* 輸出示例
VISA:
4539000000000007
4556000000000004
4916000000000001
MASTERCARD:
5200000000000002
...
*/
$fh = fopen('test_cards.csv', 'w');
fputcsv($fh, ['Type', 'CardNumber']);
foreach (['visa','mastercard','amex'] as $t) {
foreach (CreditCardGenerator::generate($t, 100) as $c) {
fputcsv($fh, [$t, $c]);
}
}
fclose($fh);
代碼採用現代 PHP 8 風格(嚴格類型、random_int、異常處理),可直接集成至項目或單元測試套件。