javascript 如何使用Stripe添加送货地址

zbq4xfa0  于 2023-05-27  发布在  Java
关注(0)|答案(4)|浏览(229)

我正在尝试使用JavaScript,React和Stripe创建电子商务网站。
对于我的生活,我不知道如何在我的结帐中包括账单和送货地址。我试着在网上找到一个答案,但找不到一个我能适应的工作解决方案。答案很明显,除了我。
我感谢任何帮助!我把代码写在下面。谢谢你。

import React, { useState, useEffect } from "react";
import CheckoutProduct from "./CheckoutProduct";
import "./Payment.css";
import { useStateValue } from "./StateProvider";
import { Link, useHistory } from "react-router-dom";
import { CardElement, useStripe, useElements } from "@stripe/react-stripe-js";
import CurrencyFormat from "react-currency-format";
import { getBasketTotal } from "./reducer";
import axios from "./axios";
import { db } from "./firebase";

function Payment() {
  const [{ basket, user }, dispatch] = useStateValue();
  const history = useHistory();

  const stripe = useStripe();
  const elements = useElements();

  const [succeeded, setSucceeded] = useState(false);
  const [processing, setProcessing] = useState("");
  const [error, setError] = useState(null);
  const [disabled, setDisabled] = useState(true);
  const [clientSecret, setClientSecret] = useState(true);

  useEffect(() => {
    const getClientSecret = async () => {
      const response = await axios({
        method: "post",
        url: `/payments/create?total=${getBasketTotal(basket) * 100}`,
      });
      setClientSecret(response.data.clientSecret);
    };

    getClientSecret();
  }, [basket]);

  console.log("THE SECRET IS >>>", clientSecret);

  const handleSubmit = async (event) => {
    event.preventDefault();
    setProcessing(true);

    const payload = await stripe
      .confirmCardPayment(clientSecret, {
        payment_method: {
          card: elements.getElement(CardElement),
        },
      })
      .then(({ paymentIntent }) => {
        db.collection("users")
          .doc(user?.uid)
          .collection("orders")
          .doc(paymentIntent.id)
          .set({
            basket: basket,
            amount: paymentIntent.amount,
            created: paymentIntent.created,
          });

        setSucceeded(true);
        setError(null);
        setProcessing(false);

        dispatch({
          type: "EMPTY_BASKET",
        });

        history.replace("/orders");
      });
  };

  const handleChange = (event) => {
    setDisabled(event.empty);
    setError(event.error ? event.error.message : "");
  };

  return (
    <div className="payment">
      <div className="payment__container">
        <h1>
          Checkout (<Link to="/checkout">{basket?.length} items</Link>)
        </h1>
        <div className="payment__section">
          <div className="payment__title">
            <h3>Delivery Address</h3>
          </div>
          <div className="payment__address">
            <p>{user?.email}</p>
          </div>
        </div>
        <div className="payment__section">
          <div className="payment__title">
            <h3>Review Items and Delivery</h3>
          </div>
          <div className="payment__items">
            {basket.map((item) => (
              <CheckoutProduct
                id={item.id}
                title={item.title}
                image={item.image}
                price={item.price}
                rating={item.rating}
              />
            ))}
          </div>
        </div>
        <div className="payment__section">
          <div className="payment__title">
            <h3>Payment Method</h3>
          </div>
          <div className="payment__details">
            <form onSubmit={handleSubmit}>
              <CardElement onChange={handleChange} />
              <div className="payment__priceContainer">
                <CurrencyFormat
                  renderText={(value) => (
                    <>
                      <h3>Order Total: {value}</h3>
                    </>
                  )}
                  decimalScale={2}
                  value={getBasketTotal(basket)}
                  displayType={"text"}
                  thousandSeparator={true}
                  prefix={"$"}
                />
                <button disabled={processing || disabled || succeeded}>
                  <span>{processing ? <p>Processing</p> : "Buy Now"}</span>
                </button>
              </div>
              {error && <div>{error}</div>}
            </form>
          </div>
        </div>
      </div>
    </div>
  );
}

export default Payment;
ttcibm8c

ttcibm8c1#

Stripe允许您通过在创建结账会话时添加shipping_address_collection来收集物品交付的送货地址。
根据条纹:
您还必须通过使用一组由两个字母组成的ISO国家/地区代码配置allowed countries属性来指定允许送货到的国家/地区。这些国家/地区会显示在结账时的“送货地址”表单的“国家/地区”下拉列表中。
`

const session = await stripe.checkout.sessions.create({
//other details
shipping_address_collection: {
allowed_countries: ['US', 'CA'],
},

});`
有关https://stripe.com/docs/payments/checkout/shipping的更多详细信息,请查看条带文档

svmlkihl

svmlkihl2#

Stripe没有直接收集账单详细信息的元素,但您可以在表单中构建它。假设您收集了相关字段,您将在调用confirmCardPayment时通过传递billing_details参数来传递信息,如here所示:

const payload = await stripe
  .confirmCardPayment(clientSecret, {
    payment_method: {
      card: elements.getElement(CardElement),
      billing_details: {
        name: 'Jenny Rosen',
        address: {
          line1: '1 Main street',
          city: 'San Francisco',
          postal_code: '90210',
          state: 'CA',
          country: 'US',
        },
      },
    },
  });

类似地,您可以在shipping参数的同一调用中传递发货详细信息

const payload = await stripe
  .confirmCardPayment(clientSecret, {
    payment_method: {
      card: elements.getElement(CardElement),
    },
    shipping: {
      name: 'Jenny Shipping',
      address: {
        line1: '1 Main street',
        city: 'San Francisco',
        postal_code: '90210',
        state: 'CA',
        country: 'US',
      },
    },
  });

您可以在一次调用中合并这两种功能。

b1payxdu

b1payxdu3#

如果使用reactjs,你可以像这样要求账单地址

billing_address_collection: 'required'
a11xaf1n

a11xaf1n4#

您可以使用shipping_address_collection,如下所示:

const session = await stripe.checkout.sessions.create({
  ...
  shipping_address_collection: {
    allowed_countries: ['US', 'CA'],
  },
  ...
});

另外,您也可以使用payment_intent_data.shipping将收货地址传递给Stripe DashboardPayments中的Shipping部分,如下所示。* 这不会将收货地址传递给Stripe Checkout,而是会传递给Stripe DashboardPayments中的Shipping部分,并且您不能同时使用shipping_address_collectionpayment_intent_data.shipping,否则会出现错误:

const session = await stripe.checkout.sessions.create({
  ...
  payment_intent_data: {
    shipping: {
      name: 'John Smith',
      address: {
        country: 'USA',
        state: 'California',
        city: 'San Francisco',
        line1: '58 Middle Point Rd',
        line2: '',
        postal_code: '94124'
      }
    }
  },
  /*
  shipping_address_collection: {
    allowed_countries: ['US', 'CA'],
  },
  */
  ...
});

相关问题