【问题标题】:Retrieving JSON response using HTTPful library for Laravel使用 Laravel 的 HTTPful 库检索 JSON 响应
【发布时间】:2013-03-21 04:05:03
【问题描述】:

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

为了发送消息,我使用HTTPful bundleMandrill 在我的邮件/撰写 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

【问题讨论】:

  • 请使用“回答您自己的问题”编辑器将您的修复移至答案。这将帮助其他人在需要时轻松查看解决方案。
  • 同意迈克·安东尼的观点
  • 全部完成!感谢您指出这一点,完全忘记了!
  • 没问题 - 你能把它标记为接受吗?
  • 不是现在,StackOverflow 要求您等待 2 天才能接受自己的答案。

标签: php json laravel httpful


【解决方案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 为我解决了一些重大困惑!

【讨论】:

    猜你喜欢
    • 2015-11-02
    • 1970-01-01
    • 1970-01-01
    • 2019-12-27
    • 1970-01-01
    • 2014-01-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多