Skip to content

Instantly share code, notes, and snippets.

@Qasem-h
Created October 3, 2020 20:21
Show Gist options
  • Save Qasem-h/2f00ee01985afccd541e0a643d14c7cf to your computer and use it in GitHub Desktop.
Save Qasem-h/2f00ee01985afccd541e0a643d14c7cf to your computer and use it in GitHub Desktop.
gatway.ts
import React, { useEffect, useRef, useState } from "react";
import { IFormError, IPaymentGatewayConfig } from "@types";
import { CompleteCheckout_checkoutComplete_order } from "@saleor/sdk/lib/mutations/gqlTypes/CompleteCheckout";
import { ErrorMessage } from "@components/atoms";
interface IResourceConfig {
src: string;
integrity: string;
crossOrigin: string;
}
interface TapPaySubmitState {
data?: any;
isValid?: boolean;
}
interface TapPaySubmitDropin {
handleAction?: (data?: any) => any;
}
interface TapPayError {
error?: string;
}
export interface IProps {
config: IPaymentGatewayConfig[];
formRef?: React.RefObject<HTMLFormElement>;
processPayment: () => void;
submitPayment: (data: {
confirmationData: any;
confirmationNeeded: boolean;
}) => Promise<any>;
submitPaymentSuccess: (
order?: CompleteCheckout_checkoutComplete_order
) => void;
errors?: IFormError[];
onError: (errors: IFormError[]) => void;
}
const TapPayPaymentGateway: React.FC<IProps> = ({
config,
formRef,
processPayment,
submitPayment,
submitPaymentSuccess,
errors,
onError
}: IProps) => {
const [dropin, setDropin] = useState<any>();
const gatewayRef = useRef<HTMLDivElement>(null);
const onSubmitTapPayForm = async (state?: TapPaySubmitState) => {
console.log("state", state?.data);
if (!state?.isValid) {
onError([new Error("error in state")]);
} else {
console.log("state", state?.data);
const payment = await submitPayment(state?.data);
if (payment.errors?.length) {
onError(payment.errors);
} else {
let paymentAction;
try {
paymentAction = JSON.parse(payment.confirmationData);
} catch (parseError) {
onError([new Error("error on the paymentAction")]);
}
try {
console.log("confirmationData", payment);
dropin.handleAction(paymentAction);
} catch (error) {
onError([new Error(error)]);
}
}
}
};
const onTapPayError = (error?: TapPayError) => {
if (error?.error) {
onError([{ message: error.error }]);
} else {
onError([new Error("error in tappay")]);
}
};
useEffect(() => {
if (true) {
(formRef?.current as any)?.addEventListener("submitComplete", () => {
onSubmitTapPayForm();
});
}
}, [formRef, true]);
const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
event.preventDefault();
processPayment();
};
return (
<form ref={formRef} onSubmit={handleSubmit}>
<div ref={gatewayRef} />
<ErrorMessage errors={errors} />
</form>
);
};
export { TapPayPaymentGateway };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment