如何从PHP中包含多个对象的响应中提取字符串?

如何解决如何从PHP中包含多个对象的响应中提取字符串?

我有一个$response变量,它从Square API调用中提取响应。 var_dump($response)提供以下输出:

object(Square\Http\ApiResponse)#26 (8) {
  ["request":"Square\Http\ApiResponse":private]=>
  object(Square\Http\HttpRequest)#15 (4) {
    ["httpMethod":"Square\Http\HttpRequest":private]=>
    string(4) "Post"
    ["headers":"Square\Http\HttpRequest":private]=>
    array(5) {
      ["user-agent"]=>
      string(29) "Square-PHP-SDK/6.1.0.20200722"
      ["Accept"]=>
      string(16) "application/json"
      ["content-type"]=>
      string(16) "application/json"
      ["Square-Version"]=>
      string(10) "2020-07-22"
      ["Authorization"]=>
      string(71) "Bearer EAAAEKqGJAcxq33I1vRGDoSdHuOjM1e0mD_yuMQwFpHnyPpuH-vqy3FCQSojC6Cv"
    }
    ["queryUrl":"Square\Http\HttpRequest":private]=>
    string(47) "https://connect.squareupsandbox.com/v2/payments"
    ["parameters":"Square\Http\HttpRequest":private]=>
    NULL
  }
  ["statusCode":"Square\Http\ApiResponse":private]=>
  int(200)
  ["reasonPhrase":"Square\Http\ApiResponse":private]=>
  NULL
  ["headers":"Square\Http\ApiResponse":private]=>
  array(13) {
    [0]=>
    string(15) "HTTP/1.1 200 OK"
    ["Date"]=>
    string(29) "Sun,30 Aug 2020 19:36:47 GMT"
    ["Frame-Options"]=>
    string(4) "DENY"
    ["X-Frame-Options"]=>
    string(4) "DENY"
    ["X-Content-Type-Options"]=>
    string(7) "nosniff"
    ["X-Xss-Protection"]=>
    string(13) "1; mode=block"
    ["Content-Type"]=>
    string(16) "application/json"
    ["Square-Version"]=>
    string(10) "2020-07-22"
    ["Squareup--Connect--V2--Common--Versionmetadata-Bin"]=>
    string(16) "CgoyMDIwLTA3LTIy"
    ["Vary"]=>
    string(27) "Accept-Encoding,User-Agent"
    ["Content-Encoding"]=>
    string(4) "gzip"
    ["Content-Length"]=>
    string(3) "568"
    ["Strict-Transport-Security"]=>
    string(45) "max-age=631152000; includeSubDomains; preload"
  }
  ["result":"Square\Http\ApiResponse":private]=>
  object(Square\Models\CreatePaymentResponse)#28 (2) {
    ["errors":"Square\Models\CreatePaymentResponse":private]=>
    NULL
    ["payment":"Square\Models\CreatePaymentResponse":private]=>
    object(Square\Models\Payment)#30 (28) {
      ["id":"Square\Models\Payment":private]=>
      string(29) "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"
      ["createdAt":"Square\Models\Payment":private]=>
      string(24) "2020-08-30T19:36:47.584Z"
      ["updatedAt":"Square\Models\Payment":private]=>
      string(24) "2020-08-30T19:36:47.771Z"
      ["amountMoney":"Square\Models\Payment":private]=>
      object(Square\Models\Money)#29 (2) {
        ["amount":"Square\Models\Money":private]=>
        int(100)
        ["currency":"Square\Models\Money":private]=>
        string(3) "USD"
      }
      ["tipMoney":"Square\Models\Payment":private]=>
      NULL
      ["totalMoney":"Square\Models\Payment":private]=>
      object(Square\Models\Money)#114 (2) {
        ["amount":"Square\Models\Money":private]=>
        int(100)
        ["currency":"Square\Models\Money":private]=>
        string(3) "USD"
      }
      ["appFeeMoney":"Square\Models\Payment":private]=>
      NULL
      ["processingFee":"Square\Models\Payment":private]=>
      NULL
      ["refundedMoney":"Square\Models\Payment":private]=>
      NULL
      ["status":"Square\Models\Payment":private]=>
      string(9) "COMPLETED"
      ["delayDuration":"Square\Models\Payment":private]=>
      string(6) "PT168H"
      ["delayAction":"Square\Models\Payment":private]=>
      string(6) "CANCEL"
      ["delayedUntil":"Square\Models\Payment":private]=>
      string(24) "2020-09-06T19:36:47.584Z"
      ["sourceType":"Square\Models\Payment":private]=>
      string(4) "CARD"
      ["cardDetails":"Square\Models\Payment":private]=>
      object(Square\Models\CardPaymentDetails)#92 (15) {
        ["status":"Square\Models\CardPaymentDetails":private]=>
        string(8) "CAPTURED"
        ["card":"Square\Models\CardPaymentDetails":private]=>
        object(Square\Models\Card)#37 (11) {
          ["id":"Square\Models\Card":private]=>
          NULL
          ["cardBrand":"Square\Models\Card":private]=>
          string(4) "VISA"
          ["last4":"Square\Models\Card":private]=>
          string(4) "1111"
          ["expMonth":"Square\Models\Card":private]=>
          int(12)
          ["expYear":"Square\Models\Card":private]=>
          int(2021)
          ["cardholderName":"Square\Models\Card":private]=>
          NULL
          ["billingAddress":"Square\Models\Card":private]=>
          NULL
          ["fingerprint":"Square\Models\Card":private]=>
          string(71) "sq-1-hkTPgBOAraVIsVGaBBcvVA8l9BNMGNv2Vz2BGjYytjR1YCLqMLS8S2MKrea0ZsrIdw"
          ["cardType":"Square\Models\Card":private]=>
          string(6) "CREDIT"
          ["prepaidType":"Square\Models\Card":private]=>
          NULL
          ["bin":"Square\Models\Card":private]=>
          string(6) "411111"
        }
        ["entryMethod":"Square\Models\CardPaymentDetails":private]=>
        string(5) "KEYED"
        ["cvvStatus":"Square\Models\CardPaymentDetails":private]=>
        string(12) "CVV_ACCEPTED"
        ["avsStatus":"Square\Models\CardPaymentDetails":private]=>
        string(12) "AVS_ACCEPTED"
        ["authResultCode":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationIdentifier":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationName":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["applicationCryptogram":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["verificationMethod":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["verificationResults":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["statementDescription":"Square\Models\CardPaymentDetails":private]=>
        string(24) "SQ *DEFAULT TEST ACCOUNT"
        ["deviceDetails":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["refundRequiresCardPresence":"Square\Models\CardPaymentDetails":private]=>
        NULL
        ["errors":"Square\Models\CardPaymentDetails":private]=>
        NULL
      }
      ["locationId":"Square\Models\Payment":private]=>
      string(13) "LH0MT7DEW5C1P"
      ["orderId":"Square\Models\Payment":private]=>
      string(27) "bJshmQ0AozoB1zVEH4iif0XpuaB"
      ["referenceId":"Square\Models\Payment":private]=>
      NULL
      ["customerId":"Square\Models\Payment":private]=>
      NULL
      ["employeeId":"Square\Models\Payment":private]=>
      NULL
      ["refundIds":"Square\Models\Payment":private]=>
      NULL
      ["buyerEmailAddress":"Square\Models\Payment":private]=>
      NULL
      ["billingAddress":"Square\Models\Payment":private]=>
      NULL
      ["shippingAddress":"Square\Models\Payment":private]=>
      NULL
      ["note":"Square\Models\Payment":private]=>
      NULL
      ["statementDescriptionIdentifier":"Square\Models\Payment":private]=>
      NULL
      ["receiptNumber":"Square\Models\Payment":private]=>
      string(4) "7PVO"
      ["receiptUrl":"Square\Models\Payment":private]=>
      string(73) "https://squareupsandbox.com/receipt/preview/7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"
    }
  }
  ["body":"Square\Http\ApiResponse":private]=>
  string(944) "{"payment": {"id": "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY","created_at": "2020-08-30T19:36:47.584Z","updated_at": "2020-08-30T19:36:47.771Z","amount_money": {"amount": 100,"currency": "USD"},"status": "COMPLETED","delay_duration": "PT168H","source_type": "CARD","card_details": {"status": "CAPTURED","card": {"card_brand": "VISA","last_4": "1111","exp_month": 12,"exp_year": 2021,"fingerprint": "sq-1-hkTPgBOAraVIsVGaBBcvVA8l9BNMGNv2Vz2BGjYytjR1YCLqMLS8S2MKrea0ZsrIdw","card_type": "CREDIT","bin": "411111"},"entry_method": "KEYED","cvv_status": "CVV_ACCEPTED","avs_status": "AVS_ACCEPTED","statement_description": "SQ *DEFAULT TEST ACCOUNT"},"location_id": "LH0MT7DEW5C1P","order_id": "bJshmQ0AozoB1zVEH4iif0XpuaB","total_money": {"amount": 100,"receipt_number": "7PVO","receipt_url": "https://squareupsandbox.com/receipt/preview/7PVOoMjV8mUoSaGWKrX1F8VDyHDZY","delay_action": "CANCEL","delayed_until": "2020-09-06T19:36:47.584Z"}}
"
  ["errors":"Square\Http\ApiResponse":private]=>
  array(0) {
  }
  ["cursor":"Square\Http\ApiResponse":private]=>
  NULL
}

但是,我只对该对象中的单个字符串感兴趣:

  object(Square\Models\CreatePaymentResponse)#28 (2) {
    ["errors":"Square\Models\CreatePaymentResponse":private]=>
    NULL
    ["payment":"Square\Models\CreatePaymentResponse":private]=>
    object(Square\Models\Payment)#30 (28) {
      ["id":"Square\Models\Payment":private]=>
      string(29) "7PVOoMjV8mUoSaGWKrX1F8VDyHDZY"

我没有太多处理对象和JSON的经验,并且我一直在进行的所有阅读和研究都无法处理类似的事情,因此,我在这里寻求专家的帮助。如何从整个响应中提取id字符串?

编辑:

每个评论和答案,这里是文档的链接:

https://developer.squareup.com/reference/square/payments-api/create-payment

以及我正在使用的代码部分:

// Initialize the Square client.
$client = new Square\SquareClient([
  'accessToken' => $access_token,'environment' => getenv('ENVIRONMENT')
]);

$payments_api = $client->getPaymentsApi();

$create_payment_request = new CreatePaymentRequest($nonce,uniqid(),$money);

// The SDK throws an exception if a Connect endpoint responds with anything besides
// a 200-level HTTP code. This block catches any exceptions that occur from the request.
try {
  $response = $payments_api->createPayment($create_payment_request);
  // If there was an error with the request we will
  // print them to the browser screen here
  if ($response->isError()) {
    echo 'Api response has Errors';
    $errors = $response->getErrors();
    echo '<ul>';
    foreach ($errors as $error) {
        echo '<li>❌ ' . $error->getDetail() . '</li>';
    }
    echo '</ul>';
    exit();
  }
  echo '<pre>';
  $resp_arr = (array)json_decode($response,true);
  var_dump($response);
  var_dump($resp_arr);
  echo '<br>';
  echo 'Payment ID:';
  echo $response->result->errors->payment->id;
  echo '</pre>';
} catch (Square\Exceptions\ApiException $e) {
  echo 'Caught exception!<br/>';
  echo('<strong>Response body:</strong><br/>');
  echo '<pre>'; var_dump($e->getResponseBody()); echo '</pre>';
  echo '<br/><strong>Context:</strong><br/>';
  echo '<pre>'; var_dump($e->getContext()); echo '</pre>';
  exit();
}

在此先感谢您的帮助!

Z

解决方法

从Square开发者论坛获得帮助。我能够使用getBody()调用来提取json响应并将其解码为数组:

$resp_arr = $response->getBody() ;
$resp_dec = json_decode($resp_arr,true) ;
$pmtid = $resp_dec["payment"] ["id"] ;
,

您已经尝试过吗?

echo $response->result->errors->payment->id;

此外,如果您更熟悉使用对象上的 array ,则可以将true用作json_decode()的参数,如下所示:>

$response = (array)json_decode($response,true);

通过这种方式,您将获得一个数组而不是对象

编辑

没有注意到他们是私人的。使用私有对象属性,您仍有一些方法来获取它。

  • 使用文档中提到的类来获取属性

  • 您可以尝试数组转换,然后在数组中搜索。

代码:

class Visibility {
    public $public = 'public';
    protected $protected = 'protected';
    private $private = 'private';
}

var_dump((array) new Visibility());

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)&gt; insert overwrite table dwd_trade_cart_add_inc &gt; select data.id, &gt; data.user_id, &gt; data.course_id, &gt; date_format(
错误1 hive (edu)&gt; insert into huanhuan values(1,&#39;haoge&#39;); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive&gt; show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 &lt;configuration&gt; &lt;property&gt; &lt;name&gt;yarn.nodemanager.res