我正在尝试为 Mandrill 创建一个 webhook,当以前发送的电子邮件被退回时,它将向发件人发送电子邮件。我能够从 Mandrill 接收 JSON 数据,但无法解析要发送给原始发送方的数据:
<?php
require_once 'mandrill-api-php/src/Mandrill.php'; //Not required with Composer
$mandrill = new Mandrill('*myapikey*');
$json = stripslashes($_POST['mandrill_events']);
$jsondata = json_decode($json,true);
$subject = $jsondata['event'];
$message = "STRIPSLASHES: ".$json."----JSONDATA----".$jsondata;
$emailAddress = "*me@mydomain.com*";
mail($emailAddress, $subject, $message);
?>
以下是$json数据在$message变量中的外观。它是从我收到的测试电子邮件中复制和粘贴的文字:
STRIPSLASHES: [{"event":"spam","msg":{"ts":1365109999,"subject":"this an example webhook message","email":"example.webhook@mandrillapp.com","sender":"example.sender@mandrillapp.com","tags":["webhook-example"],"opens":[{"ts":1365111111}],"clicks":[{"ts":1365111111,"url":"http://mandrill.com"}],"state":"已发送","metadata":{"user_id":111},"_id":"examplea_id_version aexamplea_version_id user_id http://mandrill.com 1365111111 1365111111 example.sender@mandrillapp.com example.webhook@mandrillapp.com 1365109999 1422475458 aid":"examplea--------1422475458 a
我注意到$json正在输出 json 数据,但有一个前导和结束括号,而不是以波浪括号开头。所以我决定像调用数组一样调用数据,但无济于事。
在测试中,而不是做$json = 条带斜杠(...我将上面的 json 数据复制并粘贴为文字字符串。删除前导/结束括号后,我能够解析一些数据。
为什么不尝试使用 PHP 删除括号?
$json = ltrim($json, "[");
$json = rtrim($json, ']");
然后传递给解码器?
实际上,我能够通过以不同的方式"抓取"json数据来修复它,并在收到它时正确格式化它:
$rawdata = file_get_contents('php://input');
$decodeurl = urldecode($data);
$jsonready = substr($decodeurl, 16);
$data = json_decode($jsonready, true);
$recipient = $data['0']['msg']['email'];
//etc, etc, etc
我遵循了这个例子:
https://sendy.co/forum/discussion/1137/using-mandrill-webhook-for-bounces-complaints/p1
我希望这对那些试图使用Mandrill的API的人有所帮助!