PaymentMethodCheckout.tsx 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. "use client";
  2. import Image from "next/image";
  3. import { Ref, useImperativeHandle } from "react";
  4. import { useForm, get } from "react-hook-form";
  5. import { CheckoutPaymentMethod } from "@/types/checkout/type";
  6. import { AirwallexCardElements } from "@/lib/Airwallex/airwallexInit";
  7. import { useCustomToast } from "@/utils/hooks/useToast";
  8. import AirwallexCardInput from "./PaymentMethodAdditional/AirwallexCardInput";
  9. import {useAirwallexCard} from "@/lib/Airwallex/useAirwallexCard";
  10. /**
  11. * 关于如何确定默认选中哪个支付方式:
  12. * 从购物车详情中获取支付方式 A,支付方式列表中有A,那么把A标记为默认选中;如果支付方式列表中没有A,把paypal标记为默认选中;
  13. */
  14. export interface RefPaymentMethodsHandle {
  15. getSelectPaymentMethod: () => string;
  16. getSelectPaymentTitle: () => string;
  17. validatePaymentMethod: () => Promise<boolean>;
  18. getAirwallexCardElements: () => AirwallexCardElements;
  19. validateAirwallexCard: () => boolean;
  20. }
  21. export function PaymentMethodCheckout({
  22. ref,
  23. paymentMethods,
  24. selectedPaymentMethod,
  25. onPaymentMethodChange,
  26. }: {
  27. ref: Ref<RefPaymentMethodsHandle>;
  28. paymentMethods: CheckoutPaymentMethod[];
  29. selectedPaymentMethod: string;
  30. onPaymentMethodChange: (value: string) => Promise<boolean>;
  31. }) {
  32. const { showToast } = useCustomToast();
  33. const {airwallexCardState,getCardElements} = useAirwallexCard(true,{
  34. cardNumber: 'airwallex_cardNumber',
  35. cvc: 'airwallex_cvc',
  36. expiry: 'airwallex_expiry'
  37. });
  38. let defaultValue = '';
  39. const findItem = paymentMethods.find((item) => item.method === selectedPaymentMethod);
  40. if(findItem !== undefined) {
  41. defaultValue = selectedPaymentMethod;
  42. } else {
  43. paymentMethods.forEach((item) => {
  44. if(item.method === 'paypal_smart_button') {
  45. defaultValue = item.method;
  46. }
  47. });
  48. }
  49. const {
  50. register,
  51. getValues,
  52. trigger,
  53. formState: { errors }
  54. } = useForm({
  55. mode: "onChange",
  56. reValidateMode: "onChange",
  57. defaultValues: {
  58. paymentMethod: defaultValue,
  59. }
  60. });
  61. // 参考 https://github.com/react-hook-form/error-message/blob/master/src/ErrorMessage.tsx
  62. const paymentMethodError = get(errors, "paymentMethod");
  63. const paymentMethodOnChange = async (event: React.ChangeEvent<HTMLInputElement>) => {
  64. onPaymentMethodChange(event.target.value);
  65. };
  66. useImperativeHandle(ref, () => {
  67. return {
  68. // 获取用户选择的支付方式
  69. getSelectPaymentMethod: () => {
  70. return getValues('paymentMethod');
  71. },
  72. getSelectPaymentTitle: () => {
  73. const nowValue = getValues('paymentMethod');
  74. const findItem = paymentMethods.find((item) => item.method === nowValue);
  75. return findItem?.title ?? '';
  76. },
  77. // 触发校验
  78. validatePaymentMethod: () => {
  79. return trigger();
  80. },
  81. // 获取airwallex card 支付创建的elements
  82. getAirwallexCardElements: () => {
  83. return getCardElements();
  84. },
  85. validateAirwallexCard: () => {
  86. if(!airwallexCardState.cardNumberReady) {
  87. showToast('Card number input has not ready. Please wait a minute.', 'danger');
  88. return false;
  89. }
  90. if(!airwallexCardState.expiryReady) {
  91. showToast('Card expiry date input has not ready. Please wait a minute.', 'danger');
  92. return false;
  93. }
  94. if(!airwallexCardState.cvcReady) {
  95. showToast('Card cvc input has not ready. Please wait a minute.', 'danger');
  96. return false;
  97. }
  98. if(!airwallexCardState.cardNumberValid) {
  99. showToast('Please input your card number.', 'danger');
  100. return false;
  101. }
  102. if(!airwallexCardState.cvcValid) {
  103. showToast('Please input cvc.', 'danger');
  104. return false;
  105. }
  106. if(!airwallexCardState.expiryValid) {
  107. showToast('Please input expiry date.', 'danger');
  108. return false;
  109. }
  110. return true;
  111. }
  112. }
  113. },[getCardElements,paymentMethods,airwallexCardState]);
  114. const airwallexOtherInfoShow = selectedPaymentMethod === 'airwallex' && airwallexCardState.cardNumberReady && airwallexCardState.expiryReady && airwallexCardState.cvcReady;
  115. return (
  116. <form name="shipping method" className="w-full">
  117. <div className="mt-3 w-full">
  118. <ul className="w-full">
  119. {
  120. paymentMethods.map((item) => {
  121. return (
  122. <li className="w-full mt-3" key={item.method}>
  123. <label htmlFor={"paymentmethod-" + item.method}
  124. className="group box-border flex items-center relative bg-ly-lightgray p-3 rounded-sm has-checked:bg-white has-checked:border-1 has-checked:border-ly-green"
  125. >
  126. <p className="pr-2 flex-none relative">
  127. <Image className="block h-8 w-auto" width={32} height={32} src={item.icon || ''} alt={"Payment Method " + item.title} />
  128. </p>
  129. <p className="text-ly-12 text-[#666666] ml-1">{item.description}</p>
  130. <div className="absolute top-1/2 -translate-y-1/2 right-3 flex items-center">
  131. <svg className="check w-4 h-4 hidden group-has-[:checked]:block" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><rect x="1" y="1" width="14" height="14" rx="1" fill="#000000" ></rect><path stroke="rgba(255, 255, 255, 1)" strokeWidth="1.5" strokeLinecap="square" d="M5.3335 8L7.3335 10L11.3335 6"></path></svg>
  132. <svg className="uncheck w-4 h-4 block group-has-[:checked]:hidden" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" width="16" height="16" viewBox="0 0 16 16" fill="none"><rect x="1" y="1" width="14" height="14" rx="1" fill="#FFFFFF" ></rect><path fill="rgba(0, 0, 0, 1)" d="M2 0.5L14 0.5C14.8284 0.5 15.5 1.17157 15.5 2L15.5 14C15.5 14.8284 14.8284 15.5 14 15.5L2 15.5C1.17157 15.5 0.5 14.8284 0.5 14L0.5 2C0.5 1.17157 1.17157 0.5 2 0.5ZM2 1.5C1.72386 1.5 1.5 1.72386 1.5 2L1.5 14C1.5 14.2761 1.72386 14.5 2 14.5L14 14.5C14.2761 14.5 14.5 14.2761 14.5 14L14.5 2C14.5 1.72386 14.2761 1.5 14 1.5L2 1.5Z"></path></svg>
  133. </div>
  134. <input id={"paymentmethod-" + item.method}
  135. className="absolute w-6 h-6 opacity-0"
  136. type="radio"
  137. value={item.method}
  138. {...register('paymentMethod', {
  139. required: 'Please select a payment method.',
  140. onChange: (event) => {
  141. paymentMethodOnChange(event);
  142. },
  143. })}
  144. />
  145. </label>
  146. { item.method === "airwallex" &&
  147. <div className="w-full mt-3"
  148. style={{display: airwallexOtherInfoShow ? 'block' : 'none'}}
  149. >
  150. <AirwallexCardInput
  151. cardNumberErrorMsg={airwallexCardState.cardNumberErrorMsg}
  152. expiryErrorMsg={airwallexCardState.expiryErrorMsg}
  153. cvcErrorMsg={airwallexCardState.cvcErrorMsg}
  154. />
  155. </div>
  156. }
  157. </li>
  158. )
  159. })
  160. }
  161. </ul>
  162. {paymentMethodError && <p className="text-red-500 text-ly-12">{paymentMethodError.message}</p>}
  163. </div>
  164. </form>
  165. );
  166. }