首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >Stripe支付表单获取测试密钥PHP

Stripe支付表单获取测试密钥PHP
EN

Stack Overflow用户
提问于 2022-03-16 18:35:02
回答 1查看 143关注 0票数 0

我使用Stripe支付作为我的支付处理,我使用模板https://stripe.com/docs/payments/quickstart。从理论上讲,您应该将测试密钥更改为livekey,这样支付才是真实的。

但是,GET获取:

未设置为livekey,因此错误代码:

代码语言:javascript
运行
复制
{
  "error": {
    "code": "payment_intent_invalid_parameter",
    "doc_url": "https://stripe.com/docs/error-codes/payment-intent-invalid-parameter",
    "message": "The client_secret provided does not match the client_secret associated with the PaymentIntent.",
    "param": "client_secret",
    "type": "invalid_request_error"
  }
}

我的守则是这样的:

checkout.js

代码语言:javascript
运行
复制
const stripe = Stripe("pk_live_51KDuPRH20gE5OH0BFLY0lMyxu7alzpR4UfUXn4f5kvHYlkER2TXrOqjEmUNZVp8fHAvULpmBs3jJCVYjvSeM7pqj00aWt4gNAu");

// The items the customer wants to buy
const items = [{ id: "xl-tshirt" }];

let elements;

initialize();
checkStatus();

document
  .querySelector("#payment-form")
  .addEventListener("submit", handleSubmit);

// Fetches a payment intent and captures the client secret
async function initialize() {
  const { clientSecret } = await fetch("create.php", {
    method: "POST",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify({ items }),
  }).then((r) => r.json());

  elements = stripe.elements({ clientSecret });

  const paymentElement = elements.create("payment");
  paymentElement.mount("#payment-element");
}

async function handleSubmit(e) {
  e.preventDefault();
  setLoading(true);

  const { error } = await stripe.confirmPayment({
    elements,
    confirmParams: {
      // Make sure to change this to your payment completion page
      return_url: "https://myred.love/map/success",
    },
  });

  // This point will only be reached if there is an immediate error when
  // confirming the payment. Otherwise, your customer will be redirected to
  // your `return_url`. For some payment methods like iDEAL, your customer will
  // be redirected to an intermediate site first to authorize the payment, then
  // redirected to the `return_url`.
  if (error.type === "card_error" || error.type === "validation_error") {
    showMessage(error.message);
  } else {
    showMessage("An unexpected error occured.");
  }

  setLoading(false);
}

// Fetches the payment intent status after payment submission
async function checkStatus() {
  const clientSecret = new URLSearchParams(window.location.search).get(
    "payment_intent_client_secret"
  );

  if (!clientSecret) {
    return;
  }

  const { paymentIntent } = await stripe.retrievePaymentIntent(clientSecret);

  switch (paymentIntent.status) {
    case "succeeded":
      showMessage("Payment succeeded!");
      break;
    case "processing":
      showMessage("Your payment is processing.");
      break;
    case "requires_payment_method":
      showMessage("Your payment was not successful, please try again.");
      break;
    default:
      showMessage("Something went wrong.");
      break;
  }
}

// ------- UI helpers -------

function showMessage(messageText) {
  const messageContainer = document.querySelector("#payment-message");

  messageContainer.classList.remove("hidden");
  messageContainer.textContent = messageText;

  setTimeout(function () {
    messageContainer.classList.add("hidden");
    messageText.textContent = "";
  }, 4000);
}

// Show a spinner on payment submission
function setLoading(isLoading) {
  if (isLoading) {
    // Disable the button and show a spinner
    document.querySelector("#submit").disabled = true;
    document.querySelector("#spinner").classList.remove("hidden");
    document.querySelector("#button-text").classList.add("hidden");
  } else {
    document.querySelector("#submit").disabled = false;
    document.querySelector("#spinner").classList.add("hidden");
    document.querySelector("#button-text").classList.remove("hidden");
  }
}

create.php

代码语言:javascript
运行
复制
<?php
include('../includes/connection.php');
require 'vendor/autoload.php';



session_start();

// This is your test secret API key.
\Stripe\Stripe::setApiKey('sk_live_...');

function calculateOrderAmount(array $items): int {
    // Replace this constant with a calculation of the order's amount
    // Calculate the order total on the server to prevent
    // people from directly manipulating the amount on the client
    1400;
}

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

try {
    // retrieve JSON from POST body
    $jsonStr = file_get_contents('php://input');
    $jsonObj = json_decode($jsonStr);

    // Create a PaymentIntent with amount and currency
    $paymentIntent = \Stripe\PaymentIntent::create([
        'amount' => calculateOrderAmount($jsonObj->items),
        'currency' => 'eur',
        'automatic_payment_methods' => [
            'enabled' => true,
        ],
    ]);

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

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

payment.php

代码语言:javascript
运行
复制
<head>
   
    <script src="https://js.stripe.com/v3/"></script>
    <script src="checkout.js" defer></script>
  </head>
<body>
<form id="payment-form" class="col-sm-12">
                                              <div id="payment-element">
                                                <!--Stripe.js injects the Payment Element-->
                                              </div>
                                              <hr class="my-4">
                                              <button class="buy-now btn btn-sm height-auto px-4 py-3 
                                              btn-primary" class="add-to-cart" id="submit">
                                                <div class="spinner hidden" id="spinner"></div>
                                                <span  id="button-text">Jetzt bezahlen</span>
                                              </button>
                                              <div id="payment-message" class="hidden"></div>
                                            </form>
</body>
EN

回答 1

Stack Overflow用户

发布于 2022-11-22 06:24:23

与react stripe -js相同的问题是,使用我的pk_live设置条带承诺,但是会话请求使用我的pk_test键。

代码语言:javascript
运行
复制
    import { Elements } from '@stripe/react-stripe-js'
    import { loadStripe } from '@stripe/stripe-js/pure'
    
    const MyCheckout = ({customer}) => {

    const stripe= loadStripe(
        'pk_live_xxxxxxxxxxxxxxxxxxxxx'
       )
    return <Elements options={options} stripe={stripe}>
         <Checkout
            clientData={{
            ...clientData,
            customerId: customer.id
            }}
            stripePromise={stripe}
          />
       </Elements>
     }

我可以看到邮政/v1/付款的意图和客户要求在我的生活条纹帐户,然后我的背有活的秘密密钥.

我使用AWS放大和nextjs,并且在我的本地env的过程中一切都很好,不能复制.

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/71502616

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档