如何将数据从Javascript传输到PHP?



在Javascript中,我有:

function authenticateAndFetch(payload) {
const endpoint = PropertiesService.getScriptProperties().getProperty('WEBHOOK_URL');
const hmac_key = PropertiesService.getScriptProperties().getProperty('HMAC_SHA_256_KEY');
var send_data = JSON.stringify(payload)
const signature = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, send_data)
.map(function(chr){return (chr+256).toString(16).slice(-2)})
.join(''); // Golf https://stackoverflow.com/a/49759368/300224
const fetch_options = {
'method': 'post',
'payload': {'gmail_details': send_data, 'signature': signature},
'muteHttpExceptions': true
};
const response = UrlFetchApp.fetch(endpoint, fetch_options);
return response.getContentText();
}

然后在PHP中,我用以下命令验证了这一点:

$detailsString = $_POST['gmail_details'];
$correctSignature = md5($detailsString);

经过一些日志记录和漫长的一天,我发现Javascript和PHP将为包含以下数据的字符串生成不同的md5总和:

HEX: 65 20 c2 97 20 44                              

有没有办法在将输入发送到PHP之前清理Javascript中的输入,或者有没有办法在两个环境中获得匹配的字符串?

我从未解决过实际问题。并认为最小化问题将导致Google App Script或PHP上的错误报告。但是这里有一个解决方法,让我继续前进,而且效率非常低:

function authenticateAndFetch(payload) {
const endpoint = PropertiesService.getScriptProperties().getProperty('WEBHOOK_URL');
const hmac_key = PropertiesService.getScriptProperties().getProperty('HMAC_SHA_256_KEY');
var send_data = JSON.stringify(payload);
send_data = Utilities.base64Encode(send_data); // https://stackoverflow.com/q/51866469/300224
const signature = Utilities.computeDigest(Utilities.DigestAlgorithm.MD5, send_data)
.map(function(chr){return (chr+256).toString(16).slice(-2)})
.join(''); // Golf https://stackoverflow.com/a/49759368/300224

const fetch_options = {
'method': 'post',
'payload': {'gmail_details': send_data, 'signature': signature},
'muteHttpExceptions': true
};
const response = UrlFetchApp.fetch(endpoint, fetch_options);
return response.getContentText();
}

和菲律宾比索

$detailsString = $_POST['gmail_details'];
$detailsString = base64_decode($_POST['gmail_details']);
$correctSignature = md5($detailsString);

总之,你不能可靠地将非ASCII从Javascript传输到PHP,所以只有base64编码所有内容。

最新更新