1

I'm trying to make a simple oauth2 flow using the documentation from Mailchimp.

I keep getting 400 invalid_client.

Stuck on what is going wrong and would like some help.

index.js:

import express from "express";
import querystring from "querystring";
import bodyParser from "body-parser";
import fetch from "node-fetch";
import { URLSearchParams } from "url";
import https from "https";
import fs from "fs";

const app = express();
app.use(bodyParser.json());
app.use(
    bodyParser.urlencoded({
        extended: true
    })
);

const MAILCHIMP_CLIENT_ID = "x";
const MAILCHIMP_CLIENT_SECRET =
    "x";
const BASE_URL = "https://127.0.0.1:3000";
const OAUTH_CALLBACK = `${BASE_URL}/oauth-callback/mailchimp`;

app.get("/", function (req, res) {
    res.send(
        '<p>Welcome to the sample Mailchimp OAuth app! Click <a href="/auth/mailchimp">here</a> to log in</p>'
    );
});

app.get("/auth/mailchimp", (req, res) => {
    res.redirect(
        `https://login.mailchimp.com/oauth2/authorize?${querystring.stringify({
            response_type: "code",
            client_id: MAILCHIMP_CLIENT_ID,
            redirect_uri: OAUTH_CALLBACK
        })}`
    );
});

app.get("/oauth-callback/mailchimp", async (req, res) => {
    const {
        query: { code }
    } = req;

    const tokenResponse = await fetch(
        "https://login.mailchimp.com/oauth2/token",
        {
            method: "POST",
            body: new URLSearchParams({
                grant_type: "authorization_code",
                client_id: MAILCHIMP_CLIENT_ID,
                client_secret: MAILCHIMP_CLIENT_SECRET,
                redirect_uri: OAUTH_CALLBACK,
                code
            })
        }
    );

    const { access_token } = await tokenResponse.json();
    console.log("access_token: ", access_token);

    const metadataResponse = await fetch(
        "https://login.mailchimp.com/oauth2/metadata",
        {
            headers: {
                Authorization: `OAuth ${access_token}`
            }
        }
    );

    const { dc } = await metadataResponse.json();
    console.log("dc: ", dc);

})

...

https.createServer(options, app).listen(3000, () => {
    console.log('Server ...);
})

package.json

{
  ...
  "type": "module",
  "main": "index.js",
  "scripts": {
    "start": "node index.js",
    "start:https": "HTTPS=true node index.js"
  },
  "dependencies": {
    "@mailchimp/mailchimp_marketing": "^3.0.61",
    "body-parser": "^1.19.0",
    "express": "^4.17.1",
    "node-fetch": "^3.0.0",
    "querystring": "^0.2.0"
  }
}

I have tried to check that the id, secret and redirect_uri are equal when creating the url and sending the post request for a token. But maybe there is some issues with it still? These seems to be common issues that I have found in other treads.

The goal for this question is to get the access_token.

Thanks in advance!

eh12
  • 11
  • 3

0 Answers0