最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

reactjs - Apple Pay Integration Issue: Payment Sheet Closing Immediately After Merchant Validation - Stack Overflow

programmeradmin3浏览0评论

I am facing an issue while integrating Apple Pay in my React.js application. The onvalidatemerchant callback works perfectly, and the merchant validation is successfully completed. However, after the Apple Pay session is validated, the payment sheet appears briefly and then closes immediately without triggering the onpaymentauthorized event.

I have provided the relevant code snippets and API implementation below. I would greatly appreciate your insights on resolving this issue.

import React, { useEffect, useRef, useState } from "react";
// Relevant imports

const ApplePayButton = ({ paymentType, handlePayment, cartSummary }) => {
  const [applePaySession, setApplePaySession] = useState(null);
  const cartSummaryRef = useRef(cartSummary);

  useEffect(() => {
    cartSummaryRef.current = cartSummary;
  }, [cartSummary]);

  const setupApplePaySession = async () => {
    if (!window.ApplePaySession || !ApplePaySession.canMakePayments()) {
      console.log("Apple Pay is not supported on this device/browser.");
      return;
    }

    const paymentRequest = {
      countryCode: "US",
      currencyCode: "USD",
      merchantCapabilities: ["supports3DS"],
      supportedNetworks: ["visa", "masterCard", "amex"],
      total: {
        label: "Total",
        amount: `${cartSummaryRef.current?.total?.amount || "10.00"}`,
      },
      requiredBillingContactFields: ["postalAddress", "email", "phone", "name"],
    };

    const session = new ApplePaySession(6, paymentRequest);
    setApplePaySession(session);

    session.onvalidatemerchant = async (event) => {
      try {
        const response = await createAndValidateApplePaySession({
          validation_url: event.validationURL,
          provider: "APPLE_PAY",
        });

        if (response?.status && response?.data?.applePaySession) {
          const merchantSession = JSON.parse(
            response.data.applePaySession.session_details
          );
          sessionpleteMerchantValidation(merchantSession);
        } else {
          console.error("Merchant validation failed: Invalid response.");
        }
      } catch (error) {
        console.error(`Merchant validation error: ${JSON.stringify(error)}`);
      }
    };

    session.onpaymentauthorized = (event) => {
      console.log("Payment authorized:", event.payment);
    };

    session.oncancel = () => {
      console.log("Payment cancelled.");
    };

    session.onerror = (event) => {
      console.error(`Apple Pay error: ${JSON.stringify(event)}`);
    };

    session.begin();
  };

  return (
    <>
      {paymentType === "APPLE_PAY" && (
        <apple-pay-button
          buttonstyle="black"
          type="plain"
          locale="en"
          onClick={setupApplePaySession}
        />
      )}
    </>
  );
};

export default ApplePayButton;


createAndValidateApplePaySession = async (data) => {
  const { validation_url } = data;
  const apiUrl = `${this.finixUrl}/apple_pay_sessions`;
  const base64Credentials = Buffer.from(this.credentials).toString("base64");

  const body = {
    validation_url,
    merchant_identity: process.env.FINIX_APPLE_PAY_MERCHANT_ID,
    domain: process.env.FINIX_APPLE_PAY_DOMAIN,
    display_name: process.env.FINIX_APPLE_PAY_DISPLAY_NAME,
  };

  const requestData = {
    url: apiUrl,
    data: body,
    headers: {
      "Content-Type": "application/json",
      Authorization: `Basic ${base64Credentials}`,
    },
  };

  try {
    const response = await axios.post(requestData.url, requestData.data, {
      headers: requestData.headers,
    });
    return response?.data;
  } catch (error) {
    console.error("Merchant validation failed:", error);
    return error;
  }
};

Current Behavior:

  • Apple Pay button renders successfully.
  • Clicking the button triggers the setupApplePaySession function.
  • The merchant validation completes successfully via the onvalidatemerchant callback, and a valid merchant session is received from the API.
  • The Apple Pay sheet appears briefly and then closes immediately.
  • The onpaymentauthorized callback is never triggered.

Expected Behavior: The payment sheet should remain open after merchant validation, allowing the user to select a payment method and authorize the payment. The onpaymentauthorized callback should then be triggered to handle the payment token.

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论