Here is the script for updating member's subscribe status.
const https = require('https');
const fs = require('fs');
const querystring = require('querystring')
const listId = '2c51d1ee79'
const subscriberHash = '8526a3835c5727b71ce1088f4e96da22' // md5 of '276489620@qq.com'
const postData = JSON.stringify({
'status': 'unsubscribed'
})
const options = {
hostname: 'us19.api.mailchimp.com',
path: `/3.0/lists/${listId}/members/${subscriberHash}`,
method: 'PATCH',
headers: {
'Authorization': 'Basic YOUR-TOKEN-HERE-us19',
'Content-Type': 'application/json',
'Content-Length': postData.length
},
};
const req = https.request(options, (res) => {
console.log('statusCode:', res.statusCode);
console.log('headers:', res.headers);
res.setEncoding('utf8');
res.on('data', (chunk) => {
console.log(`BODY: ${chunk}`);
});
res.on('end', () => {
console.log('No more data in response.');
});
});
req.on('error', (e) => {
console.error(`problem with request: ${e.message}`);
});
// write data to request body
req.write(postData);
req.end();
I'm struggling with the error response of 411 in the beginning before I changed the following two snippet:
#1:
// Wrong, postData is 'status=unsubscribed'
const postData = querystring.stringify({
'status': 'unsubscribed'
});
// Correct, postData is '{"status": "unsubscribed"}'
const postData = JSON.stringify({
'status': 'unsubscribed'
})
#2:
// add 'Content-Length': postData.length in the headers
const options = {
hostname: 'us19.api.mailchimp.com',
path: `/3.0/lists/${listId}/members/${subscriberHash}`,
method: 'PATCH',
headers: {
'Authorization': 'Basic YOUR-TOKEN-HERE-us19',
'Content-Type': 'application/json',
'Content-Length': postData.length // This is important. Without the request length, response of 411 Bad Request will be got.
},
};
Then I saw the member 276489620@qq.com's status turned from subscribed
to unsubscribed
in Mailchimp's admin page.
So the next updating(the data from postgresql) would be as easy as this.