使用适用于Laravel的HTTPful库检索JSON响应

时间:2013-03-30 15:51:53

标签: php json laravel httpful

我目前正在使用Mandrill作为电子邮件发送/入站服务和Laravel 3.x构建电子邮件客户端(入站和出站发送)。

为了发送消息,我使用HTTPful bundleMandrill在我的mail / compose POST方法中使用以下代码。

$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array( 
  'key' => '{removedAPIkey}',
  'message' => array (
    'to'    =>  array( array( "email" => $_to ) ),
    'from_name'   =>  Auth::user()->name,
    'from_email'  =>  Auth::user()->email,
    'subject' =>  $_subject,
    'html'    =>  $_body
    ),
  'async' => true
        );

$request = Httpful::post($url)->sendsJson()->body($data)->send();

链接到上面更好的格式化代码:http://paste.laravel.com/m79

现在,从API日志中可以看出,请求是正确的(使用预期的JSON),并且会发回以下格式的响应:

[
  {
      "email": "test@test.com",
      "status": "queued",
      "_id": "longmessageID"
  }
]

但是,我要做的是从请求中访问响应(特别是_id属性),它是JSON中的。现在据我所知,HTTPful类应该自动执行此操作(使用json_decode())。但是,访问:

$request->_id;

无法正常工作,我不完全确定如何获取这些数据(这是必需的,因此我可以将其录制为软弹跳,硬弹跳和拒绝邮件,以获得类似postmaster的功能)

任何帮助都将不胜感激。

修改

使用以下代码导致邮件被发送但返回错误:

$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array( 
  'key' => '{removedAPIkey}',
  'message' => array (
    'to'    =>  array( array( "email" => $_to ) ),
    'from_name'   =>  Auth::user()->name,
    'from_email'  =>  Auth::user()->email,
    'subject' =>  $_subject,
    'html'    =>  $_body
    ),
  'async' => true
        );

$request = Httpful::post($url)->sendsJson()->body($data)->send();

if ( $request[0]->status == "queued" ) {
    $success = true;
}

抛出异常的结果:Cannot use object of type Httpful\Response as array

1 个答案:

答案 0 :(得分:1)

我必须说,非常感谢Aiias的帮助。我自己设法解决了这个问题(我必须花上几个小时看这个)。对于任何想要知道的人,HTTPful包都有一个body数组,其中保存了响应。因此,下面的代码有效:

$url = 'https://mandrillapp.com/api/1.0/messages/send.json';
$data = array( 
  'key' => '{removedAPIkey}',
  'message' => array (
    'to'    =>  array( array( "email" => $_to ) ),
    'from_name'   =>  Auth::user()->name,
    'from_email'  =>  Auth::user()->email,
    'subject' =>  $_subject,
    'html'    =>  $_body
    ),
  'async' => true
        );

$request = Httpful::post($url)->sendsJson()->body($data)->send();

if ( $request->body[0]->status == "queued" ) {
    $success = true;
}

再一次,非常感谢Aiias为我清除了一些重大的困惑!