Skip to content

Commit

Permalink
Working
Browse files Browse the repository at this point in the history
  • Loading branch information
cpcramer committed Dec 10, 2024
1 parent ebde620 commit 0cb9f87
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 59 deletions.
48 changes: 48 additions & 0 deletions src/app/api/charges/route.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
import { COINBASE_COMMERCE_API_KEY } from 'src/config';
import { COMMERCE_API_URL } from 'src/links';
import { NextResponse } from 'next/server';
import type { ChargeDetails } from 'src/types';

export async function POST(request: Request) {
if (!COINBASE_COMMERCE_API_KEY) {
return NextResponse.json(
{ error: 'Missing Coinbase Commerce API key' },
{ status: 500 }
);
}

try {
const chargeDetails: ChargeDetails = await request.json();

const res = await fetch(`${COMMERCE_API_URL}/charges`, {
method: 'POST',
body: JSON.stringify(chargeDetails),
headers: {
'Content-Type': 'application/json',
'X-CC-Api-Key': COINBASE_COMMERCE_API_KEY,
},
});

if (!res.ok) {
const errorText = await res.text();
console.error('API Error:', {
status: res.status,
statusText: res.statusText,
errorText,
});
return NextResponse.json(
{ error: `HTTP error! status: ${res.status}` },
{ status: res.status }
);
}

const { data } = await res.json();
return NextResponse.json({ id: data.id });
} catch (error) {
console.error('Error creating charge:', error);
return NextResponse.json(
{ error: 'Failed to create charge' },
{ status: 500 }
);
}
}
70 changes: 35 additions & 35 deletions src/components/OnchainStoreCart.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,11 @@
import { useCallback, useMemo } from 'react';
import { useOnchainStoreContext } from './OnchainStoreProvider';
import useCreateCharge from 'src/hooks/useCreateCharge';
import {
Checkout,
CheckoutButton,
LifecycleStatus,
} from '@coinbase/onchainkit/checkout';
// import useCreateCharge from 'src/hooks/useCreateCharge';
// import {
// Checkout,
// CheckoutButton,
// LifecycleStatus,
// } from '@coinbase/onchainkit/checkout';
import type { OnchainStoreCartReact } from 'src/types';
import OnchainStoreModal from './OnchainStoreModal';
import { MockCheckoutButton } from './MockCheckoutButton';
Expand All @@ -27,36 +27,36 @@ export default function OnchainStoreCart({

// TODO: comment back in to enable checkout flow

const { createCharge } = useCreateCharge();
// const { createCharge } = useCreateCharge();

const handleStatusChange = useCallback((status: LifecycleStatus) => {
console.log('onStatus', status);
}, []);
// const handleStatusChange = useCallback((status: LifecycleStatus) => {
// console.log('onStatus', status);
// }, []);

const chargeHandler = useCallback(() => {
const description = Object.keys(quantities)
.map((productId) => {
return `${productId}(${quantities[productId]})`;
})
.join(',');
const chargeDetails = {
name: 'commerce template charge',
description,
pricing_type: 'fixed_price',
local_price: {
amount: totalSum.toString(),
currency: 'USD',
},
};
return createCharge(chargeDetails);
}, [createCharge, quantities, totalSum]);
// const chargeHandler = useCallback(() => {
// const description = Object.keys(quantities)
// .map((productId) => {
// return `${productId}(${quantities[productId]})`;
// })
// .join(',');
// const chargeDetails = {
// name: 'commerce template charge',
// description,
// pricing_type: 'fixed_price',
// local_price: {
// amount: totalSum.toString(),
// currency: 'USD',
// },
// };
// return createCharge(chargeDetails);
// }, [createCharge, quantities, totalSum]);

const key = useMemo(() => {
if (!quantities) return '';
const productIds = Object.keys(quantities);
const values = Object.values(quantities).flat();
return `${productIds.join('.')}-${values.join('.')}`;
}, [quantities]);
// const key = useMemo(() => {
// if (!quantities) return '';
// const productIds = Object.keys(quantities);
// const values = Object.values(quantities).flat();
// return `${productIds.join('.')}-${values.join('.')}`;
// }, [quantities]);

const closeModal = useCallback(() => {
setShowModal?.(false);
Expand All @@ -80,7 +80,7 @@ export default function OnchainStoreCart({
</h2>
<div className="w-64">
{/* TODO: comment back in to enable checkout flow */}
<Checkout
{/* <Checkout
key={key}
onStatus={handleStatusChange}
chargeHandler={chargeHandler}
Expand All @@ -90,7 +90,7 @@ export default function OnchainStoreCart({
text="Pay with Crypto"
disabled={!totalSum}
/>
</Checkout>
</Checkout> */}

{/* TODO: remove, for demo purposes only */}
<MockCheckoutButton onClick={openModal} />
Expand Down
30 changes: 6 additions & 24 deletions src/hooks/useCreateCharge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,42 +15,24 @@ export type ChargeDetails = {

const useCreateCharge = () => {
const createCharge = useCallback(async (chargeDetails: ChargeDetails) => {
console.log('=== CreateCharge Debug ===');
console.log({
hasCommerceKey: !!COINBASE_COMMERCE_API_KEY,
commerceKeyLength: COINBASE_COMMERCE_API_KEY?.length,
chargeDetails,
});

if (!COINBASE_COMMERCE_API_KEY) {
console.error('Commerce API Key is missing or empty');
throw new Error('Missing Coinbase Commerce API key');
}

try {
const res = await fetch(`${COMMERCE_API_URL}/charges`, {
const res = await fetch('/api/charges', {
method: 'POST',
body: JSON.stringify(chargeDetails),
headers: {
'Content-Type': 'application/json',
'X-CC-Api-Key': COINBASE_COMMERCE_API_KEY,
},
});

if (!res.ok) {
const errorText = await res.text();
console.error('API Error:', {
status: res.status,
statusText: res.statusText,
errorText,
});
throw new Error(`HTTP error! status: ${res.status}`);
const error = await res.json();
throw new Error(error.error || 'Failed to create charge');
}

const { data } = await res.json();
return data.id;
const { id } = await res.json();
return id;
} catch (error) {
console.error('Detailed error in createCharge:', error);
console.error('Error in createCharge:', error);
throw error;
}
}, []);
Expand Down
10 changes: 10 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,3 +45,13 @@ export type OnchainStoreModalReact = {
export type MockCheckoutButtonReact = {
onClick: () => void;
};

export type ChargeDetails = {
name?: string;
description?: string;
pricing_type?: string;
local_price?: {
amount: string;
currency: string;
};
};

0 comments on commit 0cb9f87

Please sign in to comment.