为什么将格式化变量用PHP发送到PayPal API时不会按预期缩进?

huangapple go评论60阅读模式
英文:

Why does formatting variable wont work as indented when being sent to PayPal API with PHP

问题

这段代码用于将表单数据发送到PayPal API,以促使用户登录并处理付款。您遇到的问题主要涉及到PayPal API的错误响应,其中有三个错误:

  1. "transactions[0].amount.currency" 报错 "Required field missing",这表示在请求中缺少必需的货币字段。

  2. "transactions[0].amount.total" 和 "transactions[0].item_list.items[0].price" 报错 "Currency amount must be non-negative number, contain exactly 2 decimal places separated by '.' (JPY contains 0 decimal places), optional thousands separator ',' and limited to 7 digits before the decimal point and currency which is a valid ISO Currency Code",这表示货币金额必须是非负数,必须精确到小数点后两位,以小数点分隔,可选千位分隔符“,”,小数点前限制为7位数字,货币必须是有效的ISO货币代码。

根据您提供的代码和错误信息,我注意到有一些地方可能导致这些错误:

  1. 请确保 $currency$price 的值都是有效的。在代码中,您根据 $form_data['form_fields']['currency'] 的值设置了 $currency,然后对 $amount 进行了格式化。确保这些值都正确设置,并且 $currency 是有效的ISO货币代码。

  2. 确保 return_urlcancel_url 的值是有效的URL,而不是 "X"。这些URL应该指向PayPal的实际返回和取消页面。

  3. 检查 $price 变量的值,确保它被正确格式化。根据您提供的代码,它似乎已经格式化为两位小数,但仍然会导致错误。您可能需要进一步检查 $price 变量的值和格式化步骤,以确保它满足PayPal的要求。

请仔细检查这些方面,并确保您的代码中没有其他可能引发这些错误的问题。如果问题仍然存在,您可能需要与PayPal的技术支持或开发者文档联系,以获取更多关于错误的详细信息和解决方案。

英文:

I am working on a wordpress website of a restoraunt that has Gift Cards bought in form via PayPal API in PHP, I'm not the one that wrote code on rediricting URL but it's only calling API using data sent to it with $_SESSION variable.


class GCS_Card_Action extends \ElementorPro\Modules\Forms\Classes\Action_Base {
    public function get_name() {
      return "gift_card";
    }

    public function get_label() {
      return __('Gift Card', 'gift-cards-spending');
    }

    public function run($record, $ajax_handler) {
      @session_start();
      $_SESSION["giftCardFormData"]=json_encode($_POST);
      $form_data = json_decode($_SESSION['giftCardFormData'], true);
      $currency_symbol = $form_data['form_fields']['currency'];

      if ($currency_symbol == '€') {
        $currency = 'EUR';
      } elseif ($currency_symbol == '£') {
        $currency = 'GBP';
      } elseif ($currency_symbol == '$') {
        $currency = 'USD';
      }

      $form_data['form_fields']['currency'] = $currency;
      $amount = floatval($form_data['form_fields']['amount']);

      $price = abs($amount);

    if ($currency != "JPY") {
        $price = number_format($price, 2, ".", "");
    } else {
        $price = number_format($price, 0, ".", "");
    }

    $paypal_request = [
          "intent" => "sale",
          "payer" => [
              "payment_method" => "paypal"
          ],
          "transactions" => [
              [
                  "amount" => [
                      "total" => $price,
                      "currency" => $currency
                  ],
                  
                  "item_list" => [
                      "items" => [
                          [
                              "name" => $form_data['form_fields']['name'],
                              "price" => $price,
                              "currency" => $currency,
                              "quantity" => 1
                          ]
                      ]
                  ]
              ]
          ],
          "redirect_urls" => [
              "return_url" => "X",
              "cancel_url" => "X"
          ]
      ];


      //$request = array_merge($paypal_request, $form_data);
      $request = $paypal_request;

      $_SESSION['paypal_request'] = json_encode($request);
      $redirUrl="/ig-payment";
      $ajax_handler->add_response_data('redirect_url', $redirUrl);
    }

    public function register_settings_section($widget) {
      
    }

    public function on_export($element) {
      
    }
}

This code is ran after submitting the form, sends data to PayPal API that prompts user to login with account and process payment.

I get these three errors

{
  "name": "VALIDATION_ERROR",
  "message": "Invalid request - see details",
  "debug_id": "14a52a47cf143",
  "information_link": "https://developer.paypal.com/docs/api/payments/#errors",
  "details": [
    {
      "field": "transactions[0].amount.total",
      "location": "body",
      "issue": "Currency amount must be non-negative number, contain exactly 2 decimal places separated by '.' (JPY contains 0 decimal places), optional thousands separator ',', limited to 7 digits before the decimal point and currency which is a valid ISO Currency Code"
    },
    {
      "field": "transactions[0].item_list.items[0].price",
      "location": "body",
      "issue": "Currency amount must be non-negative number, contain exactly 2 decimal places separated by '.' (JPY contains 0 decimal places), optional thousands separator ',', limited to 7 digits before the decimal point and currency which is a valid ISO Currency Code"
    },
    {
      "field": "transactions[0].amount.currency",
      "location": "body",
      "issue": "Required field missing"
    }
  ]
}

As you can see transactions[0].amount.currency is there in a structure but it throws Required field missing error

And for transactions[0].amount.total and transactions[0].item_list.items[0].price i get
Currency amount must be non-negative number, contain exactly 2 decimal places separated by '.' (JPY contains 0 decimal places), optional thousands separator ',', limited to 7 digits before the decimal point and currency which is a valid ISO Currency Code
Even if i formatted price variable using

if ($currency != "JPY") {
        $price = number_format($price, 2, ".", "");
    } else {
        $price = number_format($price, 0, ".", "");
}

If i try to echo $_SESSION['paypal_request'] out i get this output

{
  "intent": "sale",
  "payer": { "payment_method": "paypal" },
  "transactions": [
    {
      "amount": { "total": "25.00", "currency": "GBP" },
      "item_list": {
        "items": [
          {
            "name": "EMAIL",
            "price": "25.00",
            "currency": "GBP",
            "quantity": 1
          }
        ]
      }
    }
  ],
  "redirect_urls": {
    "return_url": "X",
    "cancel_url": "X"
  }
}

I tried searching for this error and could only found examples of Vue and React, tried translating it to PHP but it just wont work.

答案1

得分: 0

看起来价格实际上因某种原因变成了无效的数字,比如零。你可以在开发者控制面板中找到PayPal的日志:https://developer.paypal.com/dashboard/dashboard/sandbox


你正在使用已弃用的旧v1/payments API。我建议将其更改为使用当前的v2/checkout/orders API

对于支付批准,不需要将用户从您的网站重定向回来,您可以将该API与JS SDK一起使用:https://developer.paypal.com/demo/checkout/#/pattern/server

英文:

It looks like the price is actually becoming an invalid number like zero for some reason. You can probably find PayPal's logs in the developer dashboard: https://developer.paypal.com/dashboard/dashboard/sandbox


You are using the old v1/payments API, which is deprecated. I would recommend changing it to use the current v2/checkout/orders API.

For payer approval, rather than redirecting away from your site and back you can pair that API with the JS SDK: https://developer.paypal.com/demo/checkout/#/pattern/server

答案2

得分: 0

原来接收页面的代码被某人更改,以处理所有数据,我不需要更改符号或任何内容,只需将$_POST发送到该页面,这是我开始处理它时的代码状态。

但是,当有人编辑了该代码时,他们使$_SESSION读取了错误的变量,导致它只返回了一个空数组。

英文:

Turns out that code on the receiving page was changed by someone to do everything with data and I didn't need to change symbols or anything, just send $_POST to that page, which was the state of code when I first started working on it.

But also, when someone edited that code, they made $_SESSION read the wrong variable and it only returned an empty array.

huangapple
  • 本文由 发表于 2023年2月14日 00:57:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/75438969.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定