Our Partner & Developer boards on the community are moving to a brand new home: the .dev community forums! While you can still access past discussions here, for all your future app and storefront building questions, head over to the new forums.

We're moving the community! Starting July 7, the current community will be read-only for approx. 2 weeks. You can browse content, but posting will be temporarily unavailable. Learn more

How retrieve metafield data with a post purchase extension

How retrieve metafield data with a post purchase extension

AntoineBil
Shopify Partner
3 0 0


Hello, i'm working on a Shopify application with a post purchase extension and I'd like to understand how I could recover my metafield data saved with the app installation. It seems that with a post purchase extension we don't have access to the useAppMetafield or useApi methods. The idea is that the user arrives on the application, can choose an offer to display, save it and then retrieve the data in the extension to display it. I'd like to do all this with a metafield but it's impossible to retrieve the data. I've also tried authenticating to graphQL with the extension's request token to make a classic query, but with this type of extension it doesn't seem to work. Do you have any ideas? thank you very much

Replies 2 (2)

_amal
Shopify Partner
7 1 2

I've created a sample code based on the Shopify documentation, but I haven't tested it yet. Could you please try the metafield API snippets in my code? If you encounter any issues, I apologize for the inconvenience.

import {
	render,
	Banner,
	useExtensionInput,
} from '@shopify/post-purchase-ui-extensions-react';
import { useEffect } from 'react';

render('Checkout::PostPurchase::Render', () => <App />);

export function App() {
	const { storage, calculateChangeset } = useExtensionInput();
	const metafields = storage.initialData.shop.metafields;

	useEffect(() => {
		async function setMetafield() {
			try {
				// Attempt to set a new metafield using the calculateChangeset API
				// (https://shopify.dev/docs/api/checkout-extensions/post-purchase/api#changeset)

				const result = await calculateChangeset({
					changes: [
						{
							key: 'resource_name',
							namespace: 'global',
							value: 'product',
							valueType: 'string',
							type: 'set_metafield', // Action to set the metafield
						},
					],
				});
				console.log('Metafield set successfully:', result);
			} catch (error) {
				console.error('Failed to set metafield:', error);
			}
		}
		setMetafield();
	}, [calculateChangeset]);

	return <Banner title="Sample code, not tested" />;
}

 

AntoineBil
Shopify Partner
3 0 0

Thank you for you answer. Finally I did a request to my app to retrieve the datas from it and send it back to the extension and it works with the authentification.