File: //proc/self/cwd/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
]);
?>