【问题标题】:How to access JSON object returned by Google Calendar Api如何访问 Google Calendar Api 返回的 JSON 对象
【发布时间】:2016-02-22 02:02:15
【问题描述】:

我正在使用这段代码从 Google 日历 API 中捕获异常

//authorize the client
      try{
          $client = $this->gcal_sync_auth($crm_user_id);
        }
      catch (Exception $ex) 
        {
      $message = $ex->getMessage();
      die("could not connect ". $message);
        }

$ex->getMessage() 工作正常,并将异常消息作为字符串返回,但其格式如下。我从来没有遇到过这样的数组。它看起来像 JSON,但格式不正确。我如何才能访问/打印“无效的电子邮件或用户 ID”而没有其他内容。

    Google_Auth_Exception Object
(
    [message:protected] => Error refreshing the OAuth2 token, message: '{
  "error" : "invalid_grant",
  "error_description" : "Invalid email or User ID"
}'
    [string:Exception:private] => 
    [code:protected] => 400
    [file:protected] => xxx/application/third_party/Google_API/src/Google/Auth/OAuth2.php
    [line:protected] => 364
    [trace:Exception:private] => Array
        (
            [0] => Array
                (
                    [file] => xxx/application/third_party/Google_API/src/Google/Auth/OAuth2.php
                    [line] => 315
                    [function] => refreshTokenRequest
                    [class] => Google_Auth_OAuth2
                    [type] => ->
                    [args] => Array
                        (
                            [0] => Array
                                (
                                    [grant_type] => assertion
                                    [assertion_type] => http://oauth.net/grant_type/jwt/1.0/bearer
                                    [assertion] =>
                                    [serviceAccountName] =>              xxxxx@xxxxxx.iam.gserviceaccount.com
                                    [scopes] => https://www.googleapis.com/auth/calendar
                                    [privateKey] =>

【问题讨论】:

  • 阅读错误信息并按照它的指示进行操作。重置您的 outh2 密钥,编写有效的电子邮件
  • 谢谢。但你甚至读过我的问题吗?我正在尝试解析异常消息,以便打印出最终用户更容易理解的内容。
  • 如果你这样做会得到什么:print_r($ex);
  • 同样的东西,但它下面有更多的数组。
  • 请显示完整的错误数组。你有没有得到这样的东西:developers.google.com/google-apps/calendar/v3/errors

标签: php error-handling exception-handling google-api google-api-php-client


【解决方案1】:

在朋友的帮助下,这是我现在的工作方式。希望它可以帮助别人。您可以将其直接内联到您的代码中,如下所示,或者将其放入函数中以重用它。

try{
    $client = $this->gcal_sync_auth($crm_user_id);
   }
 catch (Google_Auth_Exception $ex) {
    $parts = explode("'", $ex->getMessage());
     array_pop($parts);
     array_shift($parts);
    $error = json_decode(implode("'", $parts));
 }

然后你可以简单地访问 JSON 中的error_description

$error->error_description

【讨论】:

    猜你喜欢
    • 2021-10-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 2013-03-26
    • 1970-01-01
    • 2016-02-13
    相关资源
    最近更新 更多