HEX
Server: Apache/2.4.37 (CentOS Stream) OpenSSL/1.1.1k
System: Linux ysnet.com.tw 4.18.0-553.5.1.el8.x86_64 #1 SMP Tue May 21 05:46:01 UTC 2024 x86_64
User: test (521)
PHP: 7.4.33
Disabled: NONE
Upload Files
File: /var/www/test/ecpay_cancel.php
<?php
function _replaceChar($value)
{
    $search_list = array('%2d', '%5f', '%2e', '%21', '%2a', '%2A', '%28', '%29');
    $replace_list = array('-', '_', '.', '!', '*' , '*', '(', ')');
    return str_replace($search_list, $replace_list ,$value);
}

function _getMacValue($hash_key, $hash_iv, $form_array)
{
    $encode_str = "HashKey=" . $hash_key;
    foreach ($form_array as $key => $value) {
        $encode_str .= "&" . $key . "=" . $value;
    }
    $encode_str .= "&HashIV=" . $hash_iv;
    $encode_str = strtolower(urlencode($encode_str));
    $encode_str = _replaceChar($encode_str);
    return strtoupper(hash('sha256' ,$encode_str));
}

function merchantSort($a,$b)
{
    return strcasecmp($a, $b);
}

// 測試環境參數
$gateway_url = "https://payment.ecpay.com.tw/Cashier/CreditCardPeriodAction";
$hash_key = 'XxShkqxTo7kjadON';
$hash_iv = 'HZDgcHTqaaKCLKpl'; 

$MerchantTradeNo = $_GET['MerchantTradeNo'] ?? ''; // 若無則為空

$form_array = array(
    "MerchantID" => "3400296",
    "MerchantTradeNo" => $MerchantTradeNo,
    "Action" => "Cancel",
    "TimeStamp" => time(),
);

uksort($form_array, 'merchantSort');
$form_array['CheckMacValue'] = _getMacValue($hash_key, $hash_iv, $form_array);

// 使用 curl 發送 POST 請求
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $gateway_url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($form_array));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$response = curl_exec($ch);
curl_close($ch);

// 輸出 JSON 給 FileMaker
header('Content-Type: application/json');

// 嘗試解析回傳值並抽出 RtnCode
parse_str($response, $result);

echo json_encode([
    "success" => true,
    "RtnCode" => $result['RtnCode'] ?? 'Unknown',
    "RtnMsg" => $result['RtnMsg'] ?? '',
    "raw" => $result
]);
?>