使用 php 获取条带表单数据

约瑟夫之吻

我想创建一个带有条纹的自定义表单(用于姓名、电子邮件、地址等),但我不知道如何获取可以在我的 php 文件中使用的表单数据。几年前,可以使用 post 方法轻松发送所有内容,但现在我不知道如何自定义给定的表单。

JS代码:

fetch("../create.php", {
 method: "POST",
 headers: {
"Content-Type": "application/json"
},
 body: JSON.stringify(purchase)
 })
.then(function(result) {
  return result.json();
 })
.then(function(data) {
  var elements = stripe.elements();

var card = elements.create("card", { style: style });
card.mount("#card-element");

card.on("change", function (event) {
  document.querySelector("button").disabled = event.empty;
  document.querySelector("#card-error").textContent = event.error ? event.error.message : "";
});

var form = document.getElementById("payment-form");

form.addEventListener("submit", function(event) {
  event.preventDefault();
    const name = form.querySelector('#name');
  payWithCard(stripe, card, data.clientSecret);
 });
});

PHP:

<?php

require 'vendor/autoload.php';

\Stripe\Stripe::setApiKey('sk_test:my_api_key');

function calculateOrderAmount(array $items): int {
   return 1400;
}

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

try {
  $json_str = file_get_contents('php://input');
  $json_obj = json_decode($json_str);

  $paymentIntent = \Stripe\PaymentIntent::create([
  'amount' => calculateOrderAmount($json_obj->items),
  'currency' => 'usd',
  ]);

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

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

HTML:

 <form id="payment-form">
  <div id="card-element"><!--Stripe.js injects the Card Element--></div>
  <button id="submit">
    <div class="spinner hidden" id="spinner"></div>
    <span id="button-text">Pay now</span>
  </button>
  <p id="card-error" role="alert"></p>
  <p class="result-message hidden">
    Payment succeeded, see the result in your
    <a href="" target="_blank">Stripe dashboard.</a> Refresh the page to pay again.
  </p>
</form>
贾斯汀迈克尔

使用异步支付流程,您需要在客户端处理更多的支付流程,以支持 SCA 和 3D Secure 之类的东西。通常这意味着使用异步 JavaScript 调用而不是 HTML 表单将信息发送到您的服务器。

您在问题中提到了姓名、电子邮件等表单字段,但您共享的代码不包含此类内容,因此很难针对您的情况提供特定的答案。相反,我可以提供一些基本的指导......

如果您的页面上有这样的 HTML 元素:

<input id="email" type="email">

您可以使用 JavaScript 获取该输入的值,如下所示:

var email = document.querySelector('#email').value;

然后你可以使用这样的代码将它发送到你的服务器异步:

fetch("server.php", {
    method: "POST",
    headers: {
        "Content-Type": "application/json"
    },
    body: JSON.stringify({
        email: email
    })
}).then(/*...*/);

然后,server.php您可以执行以下操作来获取电子邮件值:

<?php
$rawBody = @file_get_contents('php://input');
$body = json_decode($body, true);
$email = $body['email'];

您当然应该添加错误处理、服务器端输入验证等,但这些是基本构建块。

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章