Files
shopify-template/components/shopify/shop-pay-button.tsx
T
Rami BitarandClaude Opus 5 fe78293312 Call hydrogen's storefront.graphql directly, drop the compat shim
Completes the migration started in f8c3ef9. That commit put hydrogen
underneath the existing shopifyFetch wrapper; this one removes the
wrapper so every query uses the package's own client API.

- All 22 call sites now call storefront.graphql(DOCUMENT, { variables })
  (cachedStorefront for shop policies) instead of shopifyFetch, which
  emulated the old client's {query, variables} -> {data} shape.
- shopifyFetch is replaced by unwrapStorefrontResult(result, operation),
  which is only an error policy, not a transport wrapper: it returns
  data and throws when Shopify reports GraphQL errors, since hydrogen
  returns those rather than throwing. Naming the operation means a
  failure points at the call site instead of just at "Shopify".
- Environment reads move to services/shopify/config, so client.ts is
  only the hydrogen clients and shop-pay-button no longer imports from
  a query module just to get the store domain.
- Removes @shopify/storefront-api-client, the superseded client. It had
  no importers.

The SHOPIFY_STOREFRONT_API_URL export is gone too — hydrogen builds the
endpoint from storeDomain and apiVersion, and nothing else used it.

No behaviour change intended: same documents, same env var names, same
2025-07 API pin, same caching split between the two clients.

yarn typecheck passes with 0 errors. Verified against mock.shop: build
prerenders the policy pages, and in the browser product grid, search,
collection filters, cart restore, quantity update and discount-code
apply all work with no console errors. Customer account flows remain
untested — they need real credentials.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01JaxgqPbFxLsSuLPZom2kdC
2026-08-08 10:38:12 -04:00

101 lines
2.9 KiB
TypeScript

'use client';
import React from 'react';
import { SHOPIFY_STORE_DOMAIN } from '@/services/shopify/config';
import ShopPayLogo from '@/components/shopify/shop-pay-logo';
import { Loader } from '@/components/ui/loader';
import { Button } from '@/components/ui/button';
export interface ShopPayVariant {
id: string;
quantity?: number;
}
interface ShopPayButtonProps {
variants: ShopPayVariant[];
disabled?: boolean;
loading?: boolean;
className?: string;
/** Used when no permalink can be built (missing domain or unusable IDs). */
onFallbackClick?: () => void;
}
// Cart permalinks need the bare numeric ID; the Storefront API returns GIDs.
function toNumericVariantId(id: string): string | null {
const trimmed = id.trim();
const gid = trimmed.match(/^gid:\/\/shopify\/ProductVariant\/(\d+)/);
if (gid) return gid[1];
return /^\d+$/.test(trimmed) ? trimmed : null;
}
function toStoreUrl(domain?: string): string | null {
if (!domain) return null;
try {
return new URL(domain.startsWith('http') ? domain : `https://${domain}`)
.origin;
} catch {
return null;
}
}
// https://{shop}/cart/{variantId}:{qty},{variantId}:{qty}?payment=shop_pay
// Loads the cart and drops the buyer straight into the Shop Pay checkout.
export function buildShopPayUrl(variants: ShopPayVariant[]): string | null {
const storeUrl = toStoreUrl(SHOPIFY_STORE_DOMAIN);
if (!storeUrl || variants.length === 0) return null;
const lines: string[] = [];
for (const { id, quantity = 1 } of variants) {
const numericId = toNumericVariantId(id);
if (!numericId || !Number.isInteger(quantity) || quantity < 1) return null;
lines.push(`${numericId}:${quantity}`);
}
return `${storeUrl}/cart/${lines.join(',')}?payment=shop_pay`;
}
const BUTTON_CLASSES =
'flex h-11 w-full cursor-pointer items-center justify-center rounded-md bg-shop px-4 text-white transition-colors hover:bg-shop/85 disabled:cursor-not-allowed disabled:opacity-50';
const ShopPayButton: React.FC<ShopPayButtonProps> = ({
variants,
disabled = false,
loading = false,
className = '',
onFallbackClick,
}) => {
const shopPayUrl = buildShopPayUrl(variants);
const contents = (
<>
<span className="sr-only">Buy with</span>
{loading ? <Loader size={16} /> : <ShopPayLogo />}
</>
);
// An anchor keeps the checkout URL visible, openable in a new tab, and
// navigable without JS; the button only stands in when there's no URL.
if (shopPayUrl && !disabled) {
return (
<a
href={shopPayUrl}
className={`${BUTTON_CLASSES} ${className}`.trim()}
>
{contents}
</a>
);
}
return (
<Button
type="button"
onClick={onFallbackClick}
disabled={disabled || (!shopPayUrl && !onFallbackClick)}
className={`${BUTTON_CLASSES} ${className}`.trim()}
>
{contents}
</Button>
);
};
export default ShopPayButton;