Reputation: 45
I am building a public shopify app and I want to add a POST route that allows a metafield to be created.
In the shopify-api-node
module the following is stated:
accessToken
- Required for public apps - A string representing the permanent OAuth 2.0 access token. This option is mutually exclusive with the apiKey and password options. If you are looking for a premade solution to obtain an access token, take a look at the shopify-token module."
Here is the object that needs the shopName
and accessToken
const shopify = new Shopify({
shopName: 'your-shop-name',
accessToken: 'your-oauth-token'
});
In the Shopify Node / Express documentation it has you add in /shopify/callback
route qwhich includes the the Oauth
:
// Shopify Callback Route //
app.get('/shopify/callback', (req, res) => {
const { shop, hmac, code, state } = req.query;
/// ... skipping over code ... ///
request.post(accessTokenRequestUrl, { json: accessTokenPayload })
.then((accessTokenResponse) => {
const accessToken = accessTokenResponse.access_token;
// DONE: Use access token to make API call to 'shop' endpoint
const shopRequestUrl = 'https://' + shop + '/admin/api/2019-04/shop.json';
const shopRequestHeaders = {
'X-Shopify-Access-Token': accessToken,
};
});
/// ... skipping over code ... ///
});
Instead of using the shopify-token module
can I access/should I access this information from the /shopify/callback
route in the following manner (see below)? Or is there a better way to do this / can you provide examples?
Server.js
// Declare new global variables //
var accessTokenExport;
var shopExport;
// New Function //
function exportTokens(accessToken) {
accessTokenExport = accessToken;
shopExport = shop;
}
// Shopify Callback Route //
app.get('/shopify/callback', (req, res) => {
// Export variables to New Function
exportTokens(shop, accessToken);
});
// New POST route //
app.post("/api/createMetafield", function (req, res) {
const shopify = new Shopify({
shopName: shopExport,
accessToken: accessTokenExport
});
shopify.metafield.create({
key: 'warehouse',
value: 25,
value_type: 'integer',
namespace: 'inventory',
owner_resource: 'metafield',
// owner_id: 632910392
}).then(
metafield => console.log(metafield),
err => console.error(err)
);
})
Upvotes: 1
Views: 2762
Reputation: 778
This is not the right way to use store access token
Because shopify/callback
url call once only when store admin install your app but access token is useful for most of the time
To use store access token for your system you can do as below
shopify/callback
API call when your app installing by shop admin that time you can store this access token in database and when it require simply getting from your db and this access token is accessible for life time till store admin not uninstall your app
Upvotes: 0