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 pagereturn_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 spinnerdocument.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支付平台了。