We used the approach to make an authenticated fetch call from the React app frontend to NodeJS backend when the app starts to get the session id. From there we used the methods provided by Shopify to retreive the session from the id and register the service through the shopify api rest CarrierService.
As we also saw only one carrier service is allowed so we have a simple check, if present with the same name we dont register it again.
React code at component: (this fetch is the authenticatedFetch provided by shopify)
export const registerPriceListService = (fetch) => {
return fetch(“/api/carrierService/register”, {
method: “GET”,
headers: { “Content-Type”: “application/json” },
}).then((response) => response.json());
};
and inside useEffect with await the above.
Backend side:
app.get(“/api/carrierService/register”, async (req, res) => {
try {
const sessionId = await shopify.api.session.getCurrentId({
isOnline: false,
rawRequest: req,
rawResponse: res,
});
const sessionStorage = new SessionStorage(); // Remember here is your implementation of storage
const session = await sessionStorage.loadSession(sessionId);
if (!session) {
throw new Error(“No session present”);
}
const serviceName = “Calculating Prices Provider”;
const serviceCallbackUrl = https://${session?.shop}/api/retrieve-prices;
const response = await axios.get(
https://${session.shop}/admin/api/${shopify.api.config.apiVersion}/carrier_services.json,
{ headers: { “X-Shopify-Access-Token”: ${session.accessToken} } }
);
const foundService = response?.data?.carrier_services?.find(
(service) => service?.name === serviceName
);
// This check here is because error is produced if already an entity exists. Remove this to update fields.
if (!foundService) {
// This assignment of ‘id’ triggers the update. Use this to change the name or callback_url
// carrierService.id = foundService.id;
const carrierService = new shopify.api.rest.CarrierService({ session });
carrierService.name = serviceName;
carrierService.callback_url = serviceCallbackUrl;
carrierService.service_discovery = true;
await carrierService.save({
update: true,
});
}
res.status(201).send({ success: true });
} catch (error) {
res.status(204).send({ success: true });
}
});
I think thats all on registering the service it self.