首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >无法获取店铺名称

无法获取店铺名称
EN

Stack Overflow用户
提问于 2021-06-20 17:22:44
回答 1查看 279关注 0票数 3

在以前的版本中,我用来获取当前店铺名称是这样的:

代码语言:javascript
复制
router.get("/api/app", async (ctx) => {
  let shop = ctx.session.shop;
});

但是,在新版本中,我不能使用ctx.session.shop获取当前商店名称,我在名为name的日志中看不到任何对象,我在reffer对象上看到会话令牌和商店名称,但我认为还有另一种方法可以直接访问它们。

那么,我如何获取当前的店铺名称?下面是我的代码:

代码语言:javascript
复制
import "@babel/polyfill";
import dotenv from "dotenv";
import "isomorphic-fetch";
import createShopifyAuth, { verifyRequest } from "@shopify/koa-shopify-auth";
import Shopify, { ApiVersion } from "@shopify/shopify-api";
import Koa from "koa";
import session from "koa-session";
import next from "next";
import Router from "koa-router";
import koaBody from "koa-body";

dotenv.config();
const port = parseInt(process.env.PORT, 10) || 8081;
const dev = process.env.NODE_ENV !== "production";
const app = next({
  dev,
});
const handle = app.getRequestHandler();

Shopify.Context.initialize({
  API_KEY: process.env.SHOPIFY_API_KEY,
  API_SECRET_KEY: process.env.SHOPIFY_API_SECRET,
  SCOPES: process.env.SCOPES.split(","),
  HOST_NAME: process.env.HOST.replace(/https:\/\//, ""),
  API_VERSION: ApiVersion.October20,
  IS_EMBEDDED_APP: true,
  SESSION_STORAGE: new Shopify.Session.MemorySessionStorage(),
});

// Storing the currently active shops in memory will force them to re-login when your server restarts. You should
// persist this object in your app.
const ACTIVE_SHOPIFY_SHOPS = {};

const server = new Koa();
const router = new Router();

router.get("/api/test", async (ctx) => {
  return (ctx.body = ctx.session);
});



app.prepare().then(async () => {
  server.keys = [Shopify.Context.API_SECRET_KEY];

  server.use(
    session(
      {
        sameSite: "none",
        secure: true,
      },
      server
    )
  );

  server.use(
    createShopifyAuth({
      async afterAuth(ctx) {
        // Access token and shop available in ctx.state.shopify
        const { shop, accessToken, scope } = ctx.state.shopify;
        const host = ctx.query.host;
        ACTIVE_SHOPIFY_SHOPS[shop] = scope;

        const response = await Shopify.Webhooks.Registry.register({
          shop,
          accessToken,
          path: "/webhooks",
          topic: "APP_UNINSTALLED",
          webhookHandler: async (topic, shop, body) =>
            delete ACTIVE_SHOPIFY_SHOPS[shop],
        });

        if (!response.success) {
          console.log(
            `Failed to register APP_UNINSTALLED webhook: ${response.result}`
          );
        }

        // Redirect to app with shop parameter upon auth
        ctx.redirect(`/?shop=${shop}&host=${host}`);
      },
    })
  );

  const handleRequest = async (ctx) => {
    await handle(ctx.req, ctx.res);
    ctx.respond = false;
    ctx.res.statusCode = 200;
  };

  router.get("/", async (ctx) => {
    const shop = ctx.query.shop;

    // This shop hasn't been seen yet, go through OAuth to create a session
    if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
      ctx.redirect(`/auth?shop=${shop}`);
    } else {
      await handleRequest(ctx);
    }
  });

  router.post("/webhooks", async (ctx) => {
    try {
      await Shopify.Webhooks.Registry.process(ctx.req, ctx.res);
      console.log(`Webhook processed, returned status code 200`);
    } catch (error) {
      console.log(`Failed to process webhook: ${error}`);
    }
  });

  router.post(
    "/graphql",
    verifyRequest({ returnHeader: true }),
    async (ctx, next) => {
      await Shopify.Utils.graphqlProxy(ctx.req, ctx.res);
    }
  );

  router.get("(/_next/static/.*)", handleRequest); // Static content is clear
  router.get("/_next/webpack-hmr", handleRequest); // Webpack content is clear
  router.get("(.*)", verifyRequest(), handleRequest); // Everything else must have sessions

  server.use(router.allowedMethods());
  server.use(router.routes());
  server.listen(port, () => {
    console.log(`> Ready on http://localhost:${port}`);
  });
});

提前谢谢。

EN

回答 1

Stack Overflow用户

发布于 2021-11-23 16:12:19

下面是如何在您的server.js文件中执行此操作:对于索引路由,即router.get("/"),设置可以获取的商店名称的cookie,如下所示。一旦设置了cookie,当店主从管理员打开应用程序时,现在当您从合作伙伴门户中设置的重定向链接打开应用程序时,店铺名称将从先前设置的cookie自动设置

完整代码:

代码语言:javascript
复制
    router.get("/", async ctx => {
    const shop = ctx.query.shop
    if (shop) {
        console.log("setting cookie");
        ctx.cookies.set("shop_name", shop, {
            secure: true,
            sameSite: 'none',
            httpOnly: false
        })
    }

    if (ctx.request.header.cookie) {
        var cookies_fetched = parseCookie(ctx.request.header.cookie)

        // This shop hasn't been seen yet, go through OAuth to create a session
        if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
            ctx.redirect(`/auth?shop=${cookies_fetched.shop_name}`)
        } else {
            await handleRequest(ctx)
        }
    } else {
        if (ACTIVE_SHOPIFY_SHOPS[shop] === undefined) {
            ctx.redirect(`/auth?shop=${shop}`)
        } else {
            await handleRequest(ctx)
        }
    }
})
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/68054395

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档