0

我试图在用户打开我的Shopify 应用程序后立即注册一个新的webhook ,但是在重定向时我收到以下错误

[ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头

这是我这样做的代码:

let accessToken = ''

app.get('/shopify/register_webhook', (req, res) => {
  const { shop, hmac, code, state } = req.query;
  const stateCookie = cookie.parse(req.headers.cookie).state;

  // Verifying Cookie
  if (state !== stateCookie) {
    return res.status(403).send('Request origin cannot be verified');
  }

  // Verifying Hmac
  if (shop && hmac && code) {
    const map = Object.assign({}, req.query);
    delete map['hmac'];
    const message = querystring.stringify(map);
    const generatedHash = crypto
      .createHmac('sha256', apiSecret)
      .update(message)
      .digest('hex');

    if(generatedHash !== hmac){
      return res.status(400).send('HMAC verification failed');
    }

    // Appending Access Token to the shop Url
    const accessTokenRequestUrl = 'https://' + shop + '/admin/oauth/access_token';
    const accessTokenPayload = {
        client_id: apiKey,
        client_secret: apiSecret,
        code
    };

    // Making an API Request And getting an API response
    request.post(accessTokenRequestUrl, {json: accessTokenPayload })
    // Promise for Access Token Response
      .then((accessTokenResponse) => {
        accessToken = accessTokenResponse.access_token;
        res.redirect('/webhook');
    }).catch((error) => {
      res.send(error.statusCode).send(error);
    })
  } else {
    res.status(400).send('Required parameters missing');
  }
});

app.get('/webhook', (req, res) => {
  const apiRequestUrl = 'https://'+shop+'/admin/webhooks.json';
        const apiRequestHeader = {
            'X-Shopify-Access-Token': accessToken,
            'Content-type': 'application/json'
        };
        let address = forwardingAddress+'/shopify/webhook';
        let payload = {
          "webhook": {
            "topic": "app/uninstalled",
            "address": address,
            "format": "json"
          }
        };  
        request.post({
          url: apiRequestUrl,
          body: payload,
          headers: apiRequestHeader,
          json: true
         })
        .then((apiResponse) => {
          res.send('ok');
        }).catch((error) => {
          res.send(error);
        });
});

所以我重定向到一个新的端点,但仍然得到同样的错误。我还必须在标题中提供访问令牌。

有人能帮我吗。

4

0 回答 0