Skip to content
Back to Blog
Search
OAuth / Distributed Systems• 24 Aug 2026• 5 min read

Keeping a Shopee token alive after the three auth calls

generateAuthLink(), fetchToken(), refreshToken(): three calls, and they work on the first try against your own test shop.

I wrote shopee-api-client, so I can say those three functions really are all there is. They sign a request and send it. They do not know how many of your processes hold the same refresh token or whether the seller has revoked access, and they remember nothing between calls. The three problems below stay quiet while you test one shop on one machine.

1. The three auth endpoints sign differently from the rest of the package

Shop API calls include the access token and shop ID in the signing string:

// common/helper.ts
function signRequest(path, config, timestamp) {
  const { partnerId, accessToken, shopId, partnerKey } = config;
  const params = [partnerId, path, timestamp.toString(), accessToken, shopId]
    .filter((item) => item !== null && item !== undefined);
  const baseString = params.reduce((prev, curr) => (prev += curr), '');
  return createHmac('sha256', partnerKey).update(baseString).digest('hex');
}

The three auth calls sign only the partner ID, path and timestamp:

// common/helper.ts
function signPublicRequest(path, config, timestamp) {
  const { partnerId, partnerKey } = config;
  const baseString = `${partnerId}${path}${timestamp}`;
  return createHmac('sha256', partnerKey).update(baseString).digest('hex');
}

In the version shown here, the auth-link helper and both token methods use the same formula in separate places.

Tidy that if you like, but not by routing them through the regular signer. Its .filter() drops the undefined access token without a word, while the configured shopId still lands in the string. You get a well-formed, wrong signature, and on the auth endpoints that error reads exactly like a used auth code or an expired refresh token.

2. The refresh token is state shared by every worker

These are the values recorded in my source notes from Shopee’s documentation dated 2022-09-28. Check the platform documentation before using them:

The refresh token is single-use, and every call returns a new one. A fresh access token lives 4 hours, a fresh refresh token 30 days. After a refresh, the old access token stays valid for another 5 minutes and the old refresh token for another 4 hours.

The two trailing windows exist so requests already in flight with the old token do not fail while another process finishes refreshing. A token cache older than four hours holds a refresh token that is already dead.

Two workers can read the same refresh token for one shop and try to rotate it at once:

Worker A reads refresh_token = "R1"
Worker B reads refresh_token = "R1"   // nobody has written to the DB yet

Worker A: POST R1  ->  new access_token, refresh_token = "R2"
Worker B: POST R1  ->  error, R1 has already been consumed

A writes R2 to the DB.
B retries with R1, which is dead for good, and retries forever.

The package does not coordinate this. refreshToken() sends one request and returns the result. Coordination belongs to the application, and one shop on one process never reproduces this.

Lock per shop, so unrelated shops still refresh in parallel. This sketch shows the order of operations; in production, make sure only the owner can release the lock and that it outlives the refresh.

async function refreshShopToken(shopId: string) {
  const lockKey = `shopee:refresh:${shopId}`;
  const acquired = await redis.set(lockKey, "1", "NX", "EX", 30);
  if (!acquired) return; // another worker is refreshing this shop

  try {
    const fresh = await db.getShopeeConfig(shopId); // re-read AFTER taking the lock
    const shopee = new ShopeeModule(fresh);
    const token = await shopee.refreshToken();
    await db.saveShopeeToken(shopId, token); // write immediately, do not batch
  } finally {
    await redis.del(lockKey);
  }
}

Read the current token again after taking the lock. Save the new pair before releasing it.

setConfig() mutates the instance in place:

// module/shopee/index.ts
setConfig(config: ShopeeConfig) {
  Object.assign(this.config, config);
}

One shared module with a setConfig() call per shop is what almost everyone writes first; I did too. It holds until two requests overlap: shop A’s request waits on the network, shop B’s request swaps the config, and A signs with B’s token. Nothing fails: the call is valid and goes to the wrong shop.

The package describes the config type, but does not manage its storage:

// config.request.ts
export interface ShopeeConfigList {
  [shopId: string]: ShopeeConfig;
}

Create a ShopeeModule per request, with the config read fresh for that request’s shopId. One instance serves one shop for its whole life.

3. Seller authorization, which a refresh cannot renew

A refresh token cannot renew the seller’s authorization. When that authorization expires, the seller has to grant access again.

No API tells you how much authorization a shop has left, and the token in your hand cannot tell you either. Shopee warns about a week ahead through push code 12:

{
  "code": 12,
  "data": {
    "shop_expire_soon": [23213, 243242, 342343],
    "expire_before": 1619740800
  }
}

Miss that push and one shop’s sync jobs start failing in bulk, and no retry brings them back. Only the seller can re-authorize, so persist the warning and contact them before it lapses.

The authorization link accepts either a shop ID or a main account ID:

// fetchTokenWithAuthCode
if (!shopId && !mainAccountId) {
  throw new Error('[Shopee API] fetchToken requires either shopId or mainAccountId in config.');
}
if (shopId && mainAccountId) {
  throw new Error('[Shopee API] fetchToken accepts only one of shopId or mainAccountId.');
}

A main account authorizing several shops sends shop_id_list instead of shop_id. A handler that reads only shop_id works all through development, then fetches a token for none of the shops when the first main account authorizes a batch.

What belongs to the application

All three problems come from treating a transport client as a lifecycle manager. The package signs requests and sends them. Who may refresh, who writes the result, which shop’s config sits in which instance, and what happens when a seller stops agreeing are decisions for the application.

If you test one thing before shipping, run two workers refreshing the same shop at the same time. It takes under thirty lines.

OAuth / Distributed SystemsRSSBack to Blog