【问题标题】:How to transport data from Javascript to PHP?如何将数据从 Javascript 传输到 PHP?
【发布时间】:2018-08-16 22:16:54
【问题描述】:

在 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                              

有没有办法在将 Javascript 中的输入发送到 PHP 之前对其进行清理,或者有什么方法可以在两种环境中获取匹配的字符串?

【问题讨论】:

    标签: javascript php google-apps-script


    【解决方案1】:

    我从未解决过实际问题。并认为将问题最小化会导致关于 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();
    }
    

    和 PHP

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

    总而言之,您无法可靠地将非 ASCII 从 Javascript 传输到 PHP,因此只能对所有内容进行 base64 编码。

    【讨论】:

    • Apps Script 中还有一个网络安全的 base64 选项 - 但是不确定这些差异对您的应用程序是否有意义。
    • 相关新闻。如果 GmailLabel 中有表情符号,那么它将编码为?如果你 Base64 编码和解码。
    猜你喜欢
    • 2021-08-09
    • 2011-03-05
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 2021-05-18
    • 1970-01-01
    • 2020-06-03
    相关资源
    最近更新 更多