I am trying to implement an API to read if user exists as a member in my mailchimp account and if it is not there then add this member to the list. I am using @marketing/mailchimp_marketing library as a reference (https://github.com/mailchimp/mailchimp-marketing-node). The issue: mailchimp is returning 'undefined'. Maybe I am missing something in the code and I am afraid setConfig is not been read (not sure). I really appreciate your support. This is the code used:
const md5 = require('md5');
const mailchimp = require('@mailchimp/mailchimp_marketing');
mailchimp.setConfig({
apiKey: 'my-api-key',
server: 'my-server',
});
const listId = '#listcode';
async function checkstatus(subscriber) { //subscriber is an object received from another js file through
//checkstatus function.
console.log(subscriber); // returns the object ok
const status_id = 'subscribed';
for (let i = 0; i < subscriber.length - 24; i++) {
const no_email = subscriber[i].email.toLowerCase();
const subscriberHash = md5(no_email);
const FNAME_Name = subscriber[i].nome;
const LNAME_Name = subscriber[i].sobrenome;
try {
const response = await mailchimp.lists.getListMember(
listId,
subscriberHash
);
console.log(`${response.status}`); // returns 'undefined'
} catch (e) {
console.error(e.status); // returns 'undefined'
console.log('nao cadastrado');
addmember(no_email, FNAME_Name, LNAME_Name, status_id);
}
}
alert('Done');
}
export { checkstatus };
async function addmember(no_email, FNAME_Name, LNAME_Name, status_id) {
try {
const run = async () => {
const additional = await mailchimp.lists.addListMember(listId, {
email_address: no_email,
status: status_id,
merge_fields: {
FNAME: FNAME_Name,
LNAME: LNAME_Name,
},
});
console.log(
`Successfully added contact as an audience member. The contact's id is ${additional.id}.`
);
};
run();
} catch (e) {
//console.error(e.status);
console.log(e.status);
}
return;
}