Skip to content

Commit

Permalink
Add pending param to payment requests (#46)
Browse files Browse the repository at this point in the history
* fixes

* Update page.tsx

* add logs

* add ver
  • Loading branch information
syvlabs authored Oct 4, 2024
1 parent a071c74 commit a0c8fb9
Show file tree
Hide file tree
Showing 6 changed files with 47 additions and 14 deletions.
11 changes: 9 additions & 2 deletions example/src/app/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,13 @@ const Form: FC<FormProps> = (props) => {

const [validationErrors, setValidationErrors] = useState<Record<string, string[]>>({});

const prParams = {
overridePaymentRequest: {
amount: { amountAtom: 420, currency: 'usd' },
pending: true,
},
};

const resetErrors = useCallback(() => {
setValidationErrors({});
setOverlayMessage(null);
Expand Down Expand Up @@ -156,7 +163,7 @@ const Form: FC<FormProps> = (props) => {
</button>

<button
onClick={() => applePay.startFlow({ overridePaymentRequestAmount: { amountAtom: 420, currency: 'usd' } })}
onClick={() => applePay.startFlow(prParams)}
disabled={!applePay.isAvailable}
className={classNames(
'px-4 py-2 mt-2 w-full rounded-lg',
Expand All @@ -169,7 +176,7 @@ const Form: FC<FormProps> = (props) => {
</button>

<button
onClick={() => googlePay.startFlow({ overridePaymentRequestAmount: { amountAtom: 420, currency: 'usd' } })}
onClick={() => googlePay.startFlow(prParams)}
disabled={!googlePay.isAvailable}
className={classNames(
'px-4 py-2 mt-2 w-full rounded-lg',
Expand Down
38 changes: 28 additions & 10 deletions lib/hooks/use-payment-requests.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ import { constructSubmitEventPayload } from '../utils/event';
import { getErrorMessage } from '../utils/errors';
import { CdeConnection } from '../utils/cde-connection';
import { DynamicPreview, getCheckoutPreviewAmount } from './use-dynamic-preview';
import { useEffect } from 'react';
import { useEffect, useState } from 'react';
import { getPrefill } from '../utils/cde-client';

const PaymentRequestProvider = z.enum(['apple_pay', 'google_pay']);
Expand Down Expand Up @@ -65,15 +65,16 @@ export const usePaymentRequests = (
});
const isLoading = secureToken === undefined || availableCPMs === undefined || !formDiv || !cdeConn;
const previewAmount = dynamicPreview.amount;
const [isSetupMode, setIsSetupMode] = useState<boolean | null>(null);

// TODO: add more processors here once we have more processors supporting PaymentRequest API
useEffect(() => {
if (!hasGlobalPaymentRequest() || !previewAmount) {
if (!hasGlobalPaymentRequest() || !previewAmount || isSetupMode === null) {
return;
}
const pr = getGlobalPaymentRequest();
updatePrWithAmount(pr, previewAmount);
}, [previewAmount]);
updatePrWithAmount(pr, previewAmount, isSetupMode);
}, [previewAmount, isSetupMode]);

// Stripe-based Payment Requests
useAsyncEffect(async () => {
Expand All @@ -82,6 +83,10 @@ export const usePaymentRequests = (
return;
}

// @ts-expect-error window typing
window['ojs_version'] = __APP_VERSION__;
console.log('OJS version', __APP_VERSION__);

const stripeCpm = availableCPMs.find(
(cpm) =>
cpm.processor_name === 'stripe' && PaymentRequestProvider.options.map((s) => String(s)).includes(cpm.provider)
Expand All @@ -92,8 +97,14 @@ export const usePaymentRequests = (
const stripePubKey = parseStripePubKey(stripeCpm.metadata);
const prefill = await getPrefill(cdeConn);
const isSetupMode = prefill.mode === 'setup';
setIsSetupMode(isSetupMode);
const initialPreview = await getCheckoutPreviewAmount(cdeConn, secureToken, isSetupMode, undefined);
const pr = await createStripePaymentRequest(stripePubKey, initialPreview.amountAtom, initialPreview.currency);
const pr = await createStripePaymentRequest(
stripePubKey,
initialPreview.amountAtom,
initialPreview.currency,
isSetupMode
);
setGlobalPaymentRequest(pr);
const canMakePayment = await pr.canMakePayment();
console.log('Can make payment?', canMakePayment);
Expand Down Expand Up @@ -148,18 +159,25 @@ const startPaymentRequestUserFlow = async (
params?: PaymentRequestStartParams
): Promise<void> => {
try {
console.log('[startFlow] triggered');
if (!validateFormFields(formDiv, onValidationError, stripeCpm)) {
return;
}
console.log('[startFlow] post-validate');
const pr = getGlobalPaymentRequest();
if (params?.overridePaymentRequestAmount) {
updatePrWithAmount(pr, params.overridePaymentRequestAmount);
console.log('[startFlow] pr:', pr, 'override:', params?.overridePaymentRequest);
if (params?.overridePaymentRequest) {
const override = params?.overridePaymentRequest;
updatePrWithAmount(pr, override.amount, override.pending);
}
console.log('[startFlow] showing PR...');
pr.show();
console.log('[startFlow] PR shown. Waiting...');
const pmAddedEvent = await waitForUserToAddPaymentMethod(pr);
console.log('[startFlow] PR fulfilled. Completing flow...');
onUserCompleteUIFlow(pmAddedEvent, stripeCpm);
} catch (e) {
console.error(e);
console.error('[startFlow] Error:', e);
onError(getErrorMessage(e));
}
};
Expand All @@ -184,6 +202,6 @@ const getGlobalPaymentRequest = (): PaymentRequest => {
return window['ojs_pr'];
};

const updatePrWithAmount = (pr: PaymentRequest, amount: Amount): void => {
pr.update({ total: { amount: amount.amountAtom, label: 'Total' }, currency: amount.currency });
const updatePrWithAmount = (pr: PaymentRequest, amount: Amount, isPending: boolean): void => {
pr.update({ total: { amount: amount.amountAtom, label: 'Total', pending: isPending }, currency: amount.currency });
};
5 changes: 4 additions & 1 deletion lib/utils/shared-models.ts
Original file line number Diff line number Diff line change
Expand Up @@ -269,7 +269,10 @@ export const Amount = z.object({
export type Amount = z.infer<typeof Amount>;

export type PaymentRequestStartParams = {
overridePaymentRequestAmount?: Amount;
overridePaymentRequest?: {
amount: Amount;
pending: boolean;
};
};

// Using vanilla TS type here because we can't make named function args in zod
Expand Down
2 changes: 2 additions & 0 deletions lib/vite-env.d.ts
Original file line number Diff line number Diff line change
@@ -1 +1,3 @@
/// <reference types="vite/client" />

declare const __APP_VERSION__: string;
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@getopenpay/openpay-js-react",
"version": "0.0.16",
"version": "0.0.17",
"description": "Accept payments through OpenPay, right on your site",
"author": "OpenPay <info@getopenpay.com> (https://getopenpay.com)",
"type": "module",
Expand Down
3 changes: 3 additions & 0 deletions vite.config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,7 @@ export default defineConfig({
tsconfigPath: resolve(__dirname, 'tsconfig.build.json'),
}),
],
define: {
__APP_VERSION__: JSON.stringify(process.env.npm_package_version),
},
});

0 comments on commit a0c8fb9

Please sign in to comment.