首页 > 解决方案 > 如何从 webhook 中获取数据?

问题描述

我正在使用来自 Laposta 的 webhook,当用户取消订阅时事通讯时,它将被激活。

$sJsonData = @file_get_contents('php://input');

mail('xxx@xx.com', 'webhook json',$sJsonData); // Email to myself to see what's within the webhook

// Decode JSON data to PHP associative array
$arr = json_decode($sJsonData, true);

// Access values from the associative array
$event1 = $arr["event"];
$event2 = $arr["data"]["event"];
$event3 = $arr["data"]["data"]["event"];

mail('xxx@xx.com', 'webhook', 'event1 = ' . $event1 . ' and event2 = ' . $event2  . ' and event3 = ' . $event3); // Email to myself to see what's the value of the variable $event1(2,3)

我收到的第一封电子邮件是这样的:

{
"data": [
    {
        "type": "member",
        "event": "deactivated",
        "data": {
            "member_id": "***",
            "list_id": "***",
            "email": "xxx@xx.com",
            "state": "unsubscribed",
            "signup_date": "2020-11-18 15:50:34",
            "modified": "2020-11-23 16:56:25",
            "confirm_date": null,
            "ip": "***",
            "source_url": "",
            "custom_fields": {
                "spelersnaam": "***"
            }
        },
        "info": {
            "source": "external",
            "action": "unsubscribed",
            "date_event": "2020-11-23 17:05:15"
        }
    }
],
"date_requested": "2020-11-23 17:05:20"
}

但是在我的第二封邮件中,所有 3 个变量都是空的。

我究竟做错了什么?

我想要 3 个变量中的数据 email、state 和 date_event,这样我就可以发出 MySQL 请求来更改我数据库中的这条记录。

亲切的问候,

阿里

标签: phparrayswebhooks

解决方案


经过一些反复试验后,我编写了这个工作代码:

if (is_array($arr) && isset($arr["data"][0]["data"])) {
    $arrLength = count($arr["data"]);
    for ($i = 0; $i < $arrLength; $i++) {
        $Item = $arr["data"][$i];
        echo $Item["event"];
        echo $Item["data"]["email"];
    }
}

推荐阅读