| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311 |
- "use client";
- import {useRef} from "react";
- import { redirect, RedirectType } from 'next/navigation';
- import { usePlaceOrder } from "@/utils/hooks/usePlaceOrder";
- import {
- usePayPal,
- useEligibleMethods,
- INSTANCE_LOADING_STATE,
- usePayPalOneTimePaymentSession,
- usePayPalGuestPaymentSession,
- usePayLaterOneTimePaymentSession,
- type OnApproveDataOneTimePayments,
- type OnErrorData,
- type OnCompleteData,
- type OnCancelDataOneTimePayments,
- } from "@paypal/react-paypal-js/sdk-v6";
- import { overlayLoading } from "@/components/theme/ui/kernel/loading/api";
- import { confirmDialog } from "@/components/theme/ui/kernel/confirm/api";
- export default function PaypalButton({
- createOrder,
- onPaymentClick,
- isRePay
- }:{
- createOrder: () => Promise<{orderId: string;webOrderId: string;error: boolean;msg: string;}>;
- onPaymentClick: () => Promise<boolean>;
- isRePay?: boolean;
- }) {
- const {createPaymentCallback} = usePlaceOrder();
- const gatewayOrderIdRef = useRef("");
- const webOrderIdRef = useRef("");
- // paypal sdk 是否加载完成
- const { loadingStatus } = usePayPal();
- // Fetch eligibility(资格) for one-time payment flow
- const {
- error: eligibilityError,
- eligiblePaymentMethods,
- isLoading: isEligibilityLoading,
- } = useEligibleMethods({
- payload: {
- currencyCode: "USD", // @todo 需要根据用户选择的货币走
- paymentFlow: "ONE_TIME_PAYMENT",
- },
- });
- const isLoading = loadingStatus === INSTANCE_LOADING_STATE.PENDING;
- const isPayLaterEligible =
- !isEligibilityLoading && eligiblePaymentMethods?.isEligible("paylater");
- // const isCreditEligible =
- // !isEligibilityLoading && eligiblePaymentMethods?.isEligible("credit");
- const handlerPaypalClick = async (buttonHandlerClick: () => Promise<void | {
- redirectURL?: string | undefined;
- }>) => {
- overlayLoading.start();
- const vaild = await onPaymentClick();
- console.log('789----', vaild);
- if(vaild) {
- const res = await createOrder();
- if(res.error) {
- overlayLoading.stop();
- confirmDialog({
- title: "Warning",
- content: res.msg + " Create order failed. Please try again.",
- noCancel: true,
- }).then(() => {});
- } else {
- gatewayOrderIdRef.current = res.orderId;
- webOrderIdRef.current = res.webOrderId;
- return buttonHandlerClick();
- }
-
- } else {
- overlayLoading.stop();
- }
- }
- // paypal支付回调配置
- const paypalOnHandlerConfig = {
- createOrder: async () => {
- // const res = await createOrder();
- // gatewayOrderIdRef.current = res.orderId;
- // webOrderIdRef.current = res.webOrderId;
- const res = {
- orderId: gatewayOrderIdRef.current,
- webOrderId: webOrderIdRef.current
- };
- return res;
- },
-
- onApprove: async (data: OnApproveDataOneTimePayments) => {
- console.log("Payment approved:", data);
- const resCallback = await createPaymentCallback({
- orderId: Number(webOrderIdRef.current),
- gatewayOrderId: data.orderId || gatewayOrderIdRef.current,
- status: 'success',
- });
- if(!resCallback.error) {
- // 支付成功,跳转到成功落地页
- confirmDialog({
- title: "Payment Success",
- content: "Your payment was successful. Will redirect to success page.",
- noCancel: true,
- }).then(() => {
- redirect('/paymentresult/result?orderId=' + webOrderIdRef.current + '&return_result=success', RedirectType.replace);
- });
- } else {
- // callback 失败,提示错误
- confirmDialog({
- title: "Somthing Wrong",
- content: resCallback.msg + " Please contact customer service." + " OrderId: "+ webOrderIdRef.current,
- noCancel: true,
- }).then(() => {
- redirect('/', RedirectType.replace);
- });
-
- }
- },
- onCancel: async (data: OnCancelDataOneTimePayments) => {
- /**
- * {oederId: paypalOrderId}
- */
- console.log("Payment cancelled:", data);
- await createPaymentCallback({
- orderId: Number(webOrderIdRef.current),
- gatewayOrderId: data.orderId || gatewayOrderIdRef.current,
- status: 'cancel',
- });
- if(!isRePay) {
- overlayLoading.stop();
- redirect('/paymentresult/result?orderId=' + webOrderIdRef.current + '&return_result=cancel', RedirectType.replace);
- /*
- if(isGuest) {
- await cancelOrder({
- orderId: Number(webOrderIdRef.current),
- });
- // 重新获取购物车
- dispatch(fetchCartDetail());
- confirmDialog({
- title: "Order Cancelled",
- content: "Your order has been cancelled. Will redirect to home page.",
- noCancel: true,
- }).then(() => {
- redirect('/' , RedirectType.replace);
- });
-
- } else {
- // 登录用户 跳转二次支付页面 提醒用户可以二次支付
- confirmDialog({
- title: "Payment cancelled",
- content: "Will redirect to unpaied page.",
- noCancel: true,
- }).then(() => {
- redirect('/checkout/continuetopay?orderid=' + webOrderIdRef.current, RedirectType.replace);
- });
- }
- */
- } else {
- // 登录用户在二次支付页面
- confirmDialog({
- title: "Payment cancelled",
- content: "You canceled the payment.",
- noCancel: true,
- }).then(() => { });
- }
- },
- onError: async (data: OnErrorData) => {
- console.error("Payment error:", data);
- /**
- * code: string;
- name: string;
- isRecoverable: boolean;
- */
- await createPaymentCallback({
- orderId: Number(webOrderIdRef.current),
- gatewayOrderId: gatewayOrderIdRef.current,
- status: 'failure',
- });
- if(!isRePay) {
- overlayLoading.stop();
- redirect('/paymentresult/result?orderId=' + webOrderIdRef.current + '&return_result=failure', RedirectType.replace);
- /*
- if(isGuest) {
-
- await cancelOrder({
- orderId: Number(webOrderIdRef.current),
- });
- // 重新获取购物车
- dispatch(fetchCartDetail());
- confirmDialog({
- title: "Payment Failed",
- content: data.message + " Will redirect to home page.",
- noCancel: true,
- }).then(() => {
- redirect('/', RedirectType.replace);
- });
- } else {
- // 弹出错误提示弹窗:显示错误信息
- // 如果是登录用户,跳转二次支付页面 提醒用户可以二次支付
- confirmDialog({
- title: "Payment Failed",
- content: data.message + " Will redirect to unpaied page.",
- noCancel: true,
- }).then(() => {
- redirect('/checkout/continuetopay?orderid=' + webOrderIdRef.current, RedirectType.replace);
- });
- }
- */
- } else {
-
- // 登录用户 二次支付页面
- confirmDialog({
- title: "Payment Failed",
- content: data.message,
- noCancel: true,
- }).then(() => { });
-
- }
-
- },
- onComplete: (data: OnCompleteData) => {
- overlayLoading.stop();
- console.log("Payment session completed");
- console.log("On Complete data:", data);
- },
- // onShippingAddressChange: (data) => {},
- // onShippingOptionsChange: (data) => {
- // }
- };
- const {
- // isPending: paypalButtonPending,
- error: paypalButtonError,
- handleClick: paypalButtonHandleClick,
- } = usePayPalOneTimePaymentSession({
- presentationMode: "auto",
- ...paypalOnHandlerConfig
- });
- const {
- buttonRef: guestButtonRef,
- // isPending: guestButtonPending,
- error: guestButtonError,
- handleClick: guestButtonHandleClick,
- } = usePayPalGuestPaymentSession(paypalOnHandlerConfig);
- const payLaterDetails = eligiblePaymentMethods?.getDetails("paylater");
- const {
- // isPending: paylaterButtonPending,
- // error: paylaterButtonError,
- handleClick: paylaterButtonHandleClick,
- } = usePayLaterOneTimePaymentSession({
- presentationMode: "auto",
- ...paypalOnHandlerConfig
- });
- return (
- <div className="w-full">
- {
- isLoading ? (
- <div className="test-ly-12 font-medium text-center">
- Loading paypal payment methods...
- </div>
- ) : eligibilityError ? (
- <div className="test-ly-12 font-medium text-center text-ly-errorcolor">
- Failed to load paypal payment options. Please refresh the page.
- </div>
- ) : (
- <>
- {paypalButtonError ?
- <p className="text-ly-errorcolor text-ly-12">Error: {paypalButtonError.message}</p>
- :
- <paypal-button onClick={() => {
- return handlerPaypalClick(paypalButtonHandleClick);
- }} type="pay" className="w-full" />
- }
- {guestButtonError ?
- <p className="text-ly-errorcolor text-ly-12">Error: {guestButtonError.message}</p>
- :
- <paypal-basic-card-container className="w-full mt-3">
- <paypal-basic-card-button ref={guestButtonRef} onClick={() => handlerPaypalClick(guestButtonHandleClick)} />
- </paypal-basic-card-container>
- }
-
- {isPayLaterEligible &&
- <paypal-pay-later-button className="w-full mt-3"
- onClick={() => handlerPaypalClick(paylaterButtonHandleClick)}
- countryCode={payLaterDetails?.countryCode}
- productCode={payLaterDetails?.productCode}
- />
- }
-
- </>
- )
- }
-
- </div>
- );
- }
|