попытка интегрировать stripe payment в php выдает ошибки json

#php #html #json #stripe-payments

#php #HTML #json #stripe-платежи

Вопрос:

Я следую документации, чтобы включить stripe payment в мое веб-приложение, и я получаю следующую ошибку при проверке элемента my page.

 SyntaxError: Unexpected end of JSON input
 

это указывает на эту строку

 checkoutButton.addEventListener("click", function () {
      fetch("/daily-sub.php", {
        method: "POST",
      })
        .then(function (response) {
          return response.json();
        })
        .then(function (session) {
          return stripe.redirectToCheckout({ sessionId: session.id });
        })
        .then(function (result) {
          // If redirectToCheckout fails due to a browser or network
          // error, you should display the localized error message to your
          // customer using error.message.
          if (result.error) {
            alert(result.error.message);
          }
        })
        .catch(function (error) {
          console.error("Error:", error);
        });
    });
 

однако в моем журнале ошибок apache я получаю эту ошибку

 Uncaught (Status 400) (Request req_UgtiYTz1TvAO4B) Not a valid URL /vendor/stripe/stripe-php/lib/Exception/ApiErrorException.php line 38
 

ошибка, приведенная выше, указывает на этот код

  $instance = new static($message);
 

все, что я пытаюсь сделать, это создать простую проверку с помощью stripe.

это код, который я использовал, чтобы попытаться достичь этого:

checkout.html

  <!DOCTYPE html>
    <html>
      <head>
        <title>Buy cool new product</title>
        
        <script src="https://polyfill.io/v3/polyfill.min.js?version=3.52.1amp;features=fetch"></script>
        <script src="https://js.stripe.com/v3/"></script>
      </head>
      <body>
        <section>
          <div class="product">
            <img
              src="https://i.imgur.com/EHyR2nP.png"
              alt="The cover of Stubborn Attachments"
            />
            <div class="description">
              <h3>Stubborn Attachments</h3>
              <h5>$20.00</h5>
            </div>
          </div>
          <button id="checkout-button">Checkout</button>
        </section>
      </body>
      <script type="text/javascript">
        // Create an instance of the Stripe object with your publishable API key
        var stripe = Stripe("pk_test_51Htt1MJsCP23BRielu7Sm8TYmxp1JFfh43Epik4adlxpcj853sj6BjBG0fd322IrtOABSebJHc0gfd32fdf6d00WYOrShjR");
        var checkoutButton = document.getElementById("checkout-button");
        checkoutButton.addEventListener("click", function () {
          fetch("/daily-sub.php", {
            method: "POST",
          })
            .then(function (response) {
              return response.json();
            })
            .then(function (session) {
              return stripe.redirectToCheckout({ sessionId: session.id });
            })
            .then(function (result) {
              // If redirectToCheckout fails due to a browser or network
              // error, you should display the localized error message to your
              // customer using error.message.
              if (result.error) {
                alert(result.error.message);
              }
            })
            .catch(function (error) {
              console.error("Error:", error);
            });
        });
      </script>
    </html>
 

daily-sub.php

 <?php
require 'vendor/autoload.php';

StripeStripe::setApiKey('sk_test_51Htt1MJsCP2rfedIBCr2zNH7qIecAqwEDQlxSOrfedVTBpXK4YlR323sdsskCC00Bdfd22EYxX');
header('Content-Type: application/json');
$checkout_session = StripeCheckoutSession::create([
  'payment_method_types' => ['card'],
  'line_items' => [[
    'price_data' => [
      'currency' => 'aud',
      'unit_amount' => 1,
      'product_data' => [
        'name' => 'Daily Subscription',
        'images' => ["https://i.imgur.com/EHyR2nP.png"],
      ],
    ],
    'quantity' => 1,
  ]],
  'mode' => 'payment',
  'success_url' => 'https:://google.com',
  'cancel_url' => 'https:://youtube.com',
]);

echo json_encode(['id' => $checkout_session->id]);
?>
 

Комментарии:

1. Я думаю, вы неправильно установили библиотеку Stripe PHP.

2. @barmar Я использовал для этого composer, и он сказал, что успешно, без ошибок. Есть ли способ проверить?

3. Я неправильно прочитал сообщение об ошибке.

Ответ №1:

 'success_url' => 'https:://google.com',
'cancel_url' => 'https:://youtube.com',
 

Ни один из этих URL-адресов не является допустимым, поскольку они имеют двойные двоеточия.