【问题标题】:I need to get the json STRIPE API data converted into php我需要将 json STRIPE API 数据转换成 php
【发布时间】:2021-03-22 10:28:04
【问题描述】:

我需要帮助将一些 json 数据转换为 php 数组。我正在使用 STRIPE API。它首先被输入到一个javascript数组中

// The items the customer wants to buy
var purchase = {
  
  items: [{ id: 2235 }]
};

然后像这样 ajaxed

fetch("create.php", {
  method: "POST",
  headers: {
    "Content-Type": "application/json"
  },
  body: JSON.stringify(purchase)
})

在服务器端 (php)

header('Content-Type: application/json');

try {
  // retrieve JSON from POST body
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str);
    //echo $json_obj;


  $paymentIntent = \Stripe\PaymentIntent::create([
    'amount' => calculateOrderAmount($json_obj->items),
    'currency' => 'usd',
  ]);

  $output = [
    'clientSecret' => $paymentIntent->client_secret,
  ];

  echo json_encode($output);
} catch (Error $e) {
  http_response_code(500);
  echo json_encode(['error' => $e->getMessage()]);
}

我遇到麻烦的是 calculateOrderAmount 函数。该函数看起来像这样(返回只是硬编码,但我将替换为一个数量)

function calculateOrderAmount(array $items): int {
  // I need to loop through the array and break out the 
  // product ids
    
    
    
  return 1400;
}

对于我的一生,我无法弄清楚如何遍历数组并获取 id 值。我打算循环遍历数组 id,从我的 mySQL 数据库中获取值并返回它。 谁能告诉我该怎么做?

【问题讨论】:

    标签: javascript php jquery arrays stripe-payments


    【解决方案1】:

    我建议更改您的 json_decode() 调用以包含第二个参数,该参数指定 JSON 将被解码为 PHP 对象 (false) 还是关联数组 (true),如下所示:

    $json_obj = json_decode($json_str, false);
    

    这样,您在解码 JSON 时无需依赖 JSON_OBJECT_AS_ARRAY 标志设置来确定获取对象还是数组。

    接下来,在calculateOrderAmount() 中,您可以执行以下操作:

    foreach($items as $item) {
      // Do something with $item->id
    }
    

    【讨论】:

    • 工作就像一个魅力.. 谢谢 :) 我知道我需要研究 json_decode() 有点大声笑。
    猜你喜欢
    • 2013-10-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 1970-01-01
    • 2014-09-10
    • 1970-01-01
    相关资源
    最近更新 更多