【问题标题】:Receiving JSON in php, and using data在 php 中接收 JSON,并使用数据
【发布时间】:2016-03-20 18:22:36
【问题描述】:

我一直在尝试通过 Shopify 管理部分设置 Shopify webhook (documentation here)。到目前为止,我无法使用多种方法获取测试 webhook 中发送的任何数据,但我知道它正在发送,因为我创建了一个 Requestbin 并且已经看到数据通过了。

我在 Stackoverflow 上找到了这段代码。

    header('Access-Control-Allow-Origin: *');
    $postdata = file_get_contents("php://input");
    $file = "log.txt";
    $current = file_get_contents($file);
    $current .= $postdata;
    file_put_contents($file, $current);

    echo $current;

到目前为止,它是我能够用来实际查看任何 JSON 的唯一代码。但我不想每次触发 webhook 时都将 JSON 写入“log.txt”文件。但是,一旦我尝试以任何方式删除或调整代码,我就再也看不到任何 JSON。看来我必须将$postdata 写入文件,然后检索内容以获取数组。

是否可以访问 JSON 而无需先将其写入另一个文件?

【问题讨论】:

  • $data = json_decode(file_get_contents('php://input')); 应该是接收 JSON 所需的全部内容。 var_dump($data); 在这种情况下是否显示不正确的信息?
  • var_dump($data); 仅在我使用 $data = json_decode(file_get_contents('php://input')); 时返回 NULL
  • 删除 json_decode 后会得到什么?任何来自 php://input 的东西?我想知道是否有些请求不包含任何数据,或者它是以其他格式通过的。
  • 如果我只删除 json_decode 和 var_dump 文件_get_contents,我最终会得到string(0) ""
  • 对于调试,请尝试file_put_contents('./request.txt', print_r($_SERVER, true) . "\n" . print_r($_POST, true) . "\n\n", FILE_APPEND); 以查看正在发送的标头和内容。有什么有用的吗?

标签: php json shopify webhooks


【解决方案1】:

首先,我的基本思考过程在 webhook 的工作方式上存在缺陷。

header('Access-Control-Allow-Origin: *');
$postdata = file_get_contents("php://input");
$file = "log.txt";
$current = file_get_contents($file);
$current .= $postdata;
file_put_contents($file, $current);

echo $current;

此代码需要将file_get_contents("php://input") 的内容写入文本文件的原因是因为 Shopify webhook 发送的 POST 请求只是短暂地点击了页面。刷新页面后,您就会丢失所有 POST 数据……我知道这似乎很明显。也就是说,我需要一种方法来确定 JSON Shopify 发送出去是否在我的服务器上运行良好。所以我创造了这个......

$json = json_decode(file_get_contents("php://input"));
file_put_contents('./realRequests.txt', $json->id . "\n", FILE_APPEND);

每次 Shopify 触发 webhook 时都会捕获订单的 ID,并将其写入请求文件中的新行。这样你就知道你可以从 shopify 接收工作代码。

【讨论】:

    猜你喜欢
    • 2017-05-31
    • 2018-03-22
    • 2013-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-17
    相关资源
    最近更新 更多