在 NodeJS 中使用 Mailchimp API 执行 OAuth2

Execute OAuth2 with the Mailchimp API in NodeJS

这个问题可能会因为质量较低的问题而临时禁止我,但无论如何都可以。

我一直在关注 MailChimp 的 OAuth2 教程 (https://developer.mailchimp.com/documentation/mailchimp/guides/how-to-use-oauth2/),但在使用代码和 secret/key 参数发出 post 请求时卡住了。我得到的最接近的是 400 Bad Request 响应。我的代码:

var args = { headers: { "Content-Type": "application/json" }, body: "grant_type=authorization_code&client_id=" + client_id + "&client_secret=" + client_secret + "&redirect_uri=" + encoded_url + "&code=" + req.query.code, url: "https://login.mailchimp.com/oauth2/token" }; var r = request.post(args, function(err, req, body){ console.log(err) console.log(req) })

任何帮助或教程都会很棒。谷歌搜索了很多年,但仍然没有接近。

好吧,我也运行陷入了同样的困境,终于找到了。我的代码与你的非常相似:

this.globals.request({
        method: "POST",
        uri: "https://login.mailchimp.com/oauth2/token",
        form:  {
            grant_type: "authorization_code",
            client_id: this.globals.mailchimp_client_id,
            client_secret: this.globals.mailchimp_client_secret,
            redirect_uri: encodeURIComponent(fullUrl),
            code: req.query.code
        }
    },
    function (error, response, body) {
        if (error || response.statusCode !== 200) {
            self.globals.logger.debug(self.moduleName, "getMailchimpToken", "Error " + response.statusCode + "(" + response.statusMessage + ") from mailchimp: " + error, true);
            body = {};
        }
        self.globals.logger.debug(self.moduleName, "getMailchimpToken", "got body: " + JSON.stringify(body), false);
        deferred.resolve(body);
});

这里的问题,我怀疑你的问题是你在表单数据中使用了编码的 URL,但请求将再次对其进行编码。当我查看查询字符串时,我看到了

&redirect_uri=http%253A%252F%252F

%s 所在的位置 re-encoded。将 encodeURIComponent(fullUrl), 更改为 fullUrl,它起作用了。

一个我不清楚的重要说明 - redirect_uri 应该与 OAuth 调用中使用的相同,包括路径。请注意,根据 Mailchimp 文档,您可以将实际调用中的路径与注册应用程序时使用的 redirect_url 不同,这可能很重要。