Stripe国际支付平台接入

Stripe 是一家科技公司,致力于为互联网经济打造基础设施。所有公司,无论规模大小,从初创公司到上市企业,都可以用我们的软件来收款和管理他们的线上业务。

引用stripe 公司介绍的一段话:“我们的使命是:增加互联网 GDP”。

Stripe支持130+种币值。

首先我需要在Stripe平台拿到俩个参数【可发布密钥】和【密钥】在这里:

然后我们就可以用 这俩个参数接入支付。

PHP开发为例

首页安装stripe依赖包

//安装依赖
composer require stripe/stripe-php

//引用
require_once('vendor/autoload.php');

然后安装好之后在服务端创建一个alipay支付:

      \Stripe\Stripe::setApiKey($_ENV["STRIPE_SECRET_KEY"]);

            header('Content-Type: application/json');
            try {
                // retrieve JSON from POST body
                $jsonStr = file_get_contents('php://input');
                $jsonObj = json_decode($jsonStr);

                $paymentIntent = \Stripe\PaymentIntent::create([
                    'amount' => $money,
                    'currency' => 'cny',
                    '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()]);
            }

上面会返回一个client_secret,客户端通过ajax请求得到这个secret。

客户端页面:

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <title>Accept a payment</title>
    <meta name="description" content="A demo of a payment on Stripe" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <link rel="stylesheet" href="/css/checkout.css" />
      <script src="https://js.stripe.com/v3/"></script>
  </head>
  <body>
    <!-- Display a payment form -->
    <form id="payment-form">
        <h3 style="text-align: center;">PayMoney:¥{{$moeny}}</h3>
      <div id="payment-element">
      </div>
      <button id="submit">
        <div class="spinner hidden" id="spinner"></div>
        <span id="button-text">Pay now</span>
      </button>
      <div id="payment-message" class="hidden"></div>
    </form>
      <script>
          const stripe = Stripe('<?= $_ENV["STRIPE_PUBLISHABLE_KEY"]; ?>', {
              apiVersion: '2020-08-27',
          });
      </script>
    <script src="/js/checkout.js?v=1.0" defer></script>
  </body>
</html>

引用的checkout.js代码:

//测试
const items = [{ id: "xl-tshirt" }];
let elements;
initialize();
checkStatus();
document
  .querySelector("#payment-form")
  .addEventListener("submit", handleSubmit);
async function initialize() {
  const { clientSecret } = await fetch("/index/getStripePay", {
    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: `${window.location.origin}/index/payresult`,
    },
  });

  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");
  }
}

在浏览器打开支付页面如图:有 Alipay 和银行卡2种支付方式

 下一步客户支付成功后服务端做回调验证:

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

$input = file_get_contents('php://input');
$body = json_decode($input);
$event = null;

try {
  // Make sure the event is coming from Stripe by checking the signature header
  $event = \Stripe\Webhook::constructEvent(
    $input,
    $_SERVER['HTTP_STRIPE_SIGNATURE'],
    $_ENV['STRIPE_WEBHOOK_SECRET']
  );
}
catch (Exception $e) {
  http_response_code(403);
  echo json_encode([ 'error' => $e->getMessage() ]);
  exit;
}

if ($event->type == 'payment_intent.succeeded') {
  // Fulfill any orders, e-mail receipts, etc
  // To cancel the payment you will need to issue a Refund (https://stripe.com/docs/api/refunds)
  error_log('💰 Payment received!');
}
else if ($event->type == 'payment_intent.payment_failed') {
  error_log('❌ Payment failed.');
}

echo json_encode(['status' => 'success']);

这样我们就成功地接入Stripe支付平台了。

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值