MailChimp: set Language with nodejs SDK - node.js

I'm trying to set a suscriber's Language with MailChimp nodejs SDK while adding him/her to a list.
The nodejs SDK calls the API https://us2.api.mailchimp.com/3.0/lists/<list-ID>/members, and it successfully creates a new member. However, it doesn't set the user's language. I read online that I have to pass the Accept-Language header with my HTTP request, so it is what I did.
In order to be able to add a custom header using the SDK, I slightly edited the SDK to add a defaultHeaders option. With this modification, the header is correctly set, but unfortunately it doesn't change anything: the new member still doesn't have the language set.
Here is my code:
import mailchimp from "#mailchimp/mailchimp_marketing";
export const handler = async(event) => {
const params = JSON.parse(event.body);
mailchimp.setConfig({
apiKey: process.env.apiKey,
server: process.env.server,
defaultHeaders: {
'Accept-Language': event.headers['accept-language'],
},
});
const email = params.email;
const firstname = params.name.substring(0, params.name.indexOf(' ')) || "";
const lastname = params.name.substring(params.name.indexOf(' ') + 1) || "";
return await mailchimp.lists.addListMember(process.env.listId,
{
email_address: email,
status: 'subscribed',
email_type: 'html',
merge_fields: {
FNAME: firstname,
LNAME: lastname,
},
}
);
};
The generated request is the following:
Request {
method: 'POST',
url: 'https://us2.api.mailchimp.com/3.0/lists/<list-ID>/members',
header: {
'User-Agent': 'node-superagent/3.8.1',
Authorization: 'Basic XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX=',
'Accept-Language': 'fr-FR,fr;q=0.9,en-US;q=0.8,en;q=0.7',
'Content-Type': 'application/json',
Accept: 'application/json'
},
writable: true,
cookies: '',
qs: {},
qsRaw: [],
data: {
email_address: '<the-tested-email-address>',
status: 'subscribed',
email_type: 'html',
merge_fields: { FNAME: 'Firstname', LNAME: 'Lastname' }
},
}
Still, the created member doesn't have the language set.
Please help me, it would really be appreciated 🙏
How can I set a new member's language when creating it using MailChimp API?

Related

format request to send dynamic link push notification nodejs

I am attempting to add dynamic links to push notifications so users tap them and open to a specific app page. I have been following the documentation and the links do not open to the page they should when I tap the push notifications but when tested in the browser the links do open to the correct page. From what I have read, there are 2 possible solutions depending on the version of firebase the project is using. The older "way" is to add a click_action property to the apns payload object, the newer way is to create a webpush object with the fcm_options property set to the value of the link. Neither of these options seems to work regardless of where the objects are placed in the request. Is my request formatted incorrectly or am I possibly missing something? Below is the current request:
const [title, body, deepLink] = titleAndBody;
let accessToken = await getAccessToken();
accessToken = "Bearer " + accessToken;
const options = {
method: "POST",
url: URL,
headers: {
Authorization: accessToken,
"Content-Type": "application/json",
},
body: JSON.stringify({
message: {
token: fcmToken,
notification: {
body: body,
title: title,
},
webpush: {
fcm_options: {
link: deepLink,
}
},
apns: {
headers: {
priority: "10",
},
payload: {
//click_action: deepLink,
aps: {
badge: 0,
mutable_content: 1,
},
},
}
},
}),
};```

How to add a contact to ActiveCampaign using API v1 contact_sync/contact_add

I am having trouble adding a contact to ActiveCampaign. I read a post in here: How to add a contact to a list in ActiveCampaign API v3 and am using v1 of the API. I used their contact_sync documentation to the best of my availability.
I'm developing using Gatsby/React --> GitHub --> Netlify, using a lamda function for the POST request.
Here is my axios POST:
{
method: 'post',
url: 'https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxxxxx&api_action=contact_sync&api_output=json',
headers: { 'Content-Type': 'Content-Type: application/x-www-form-urlencoded' },
body: {
email: 'email#email.com',
first_name: 'John'
}
}
And received the following response:
{
result_code: 0,
result_message: 'Could not add contact; missing email address',
result_output: 'json'
}
I'm talking to their endpoint. I just can't figure out how to feed the endpoint the email address?
Does anyone have a working example they would be kind enough to share? Guidance of any kind would be greatly appreciated!
I wanted to make sure to close this and share my answer.
Thanks so much to #reza jafari for his comment in this post where he brought to my attention the code window on the right margin of Postman where you can choose the language/server from a dropdown and it provides the correctly formatted response.
(I don't have enough reputation to upvote #reza's response so wanted to acknowledge it here.)
I was able to get my post working in Postman, and this little trick squared me away. I'll go ahead and post my solution to close this post.
const axios = require("axios")
const qs = require("qs")
exports.handler = async function (event) {
const { email, first_name } = JSON.parse(event.body)
const data = qs.stringify({
email: email,
first_name: first_name,
tags: '"api"',
"p[1]": "1",
})
const config = {
method: "post",
url: "https://ACCOUNT.api-us1.com/admin/api.php?api_key=xxxxxxxxx&api_action=contact_sync&api_output=json",
headers: {
"Api-Token":
"xxxxxxxxx",
"Content-Type": "application/x-www-form-urlencoded",
},
data: data,
}
try {
const response = await axios(config)
return {
statusCode: 200,
body: JSON.stringify(response.data),
}
} catch (err) {
return {
statusCode: 500,
body: JSON.stringify(err),
}
}
}

Got request :request body parameter is empty

I am using 'node-oauth2-server' module to generate Oauth2.0 token, but I am getting below error when trying to generate token using request :
Error :
400, {
code: 400,
message: 'Invalid or missing grant_type parameter',
name: 'invalid_request'
}
Request details :
const apiResponse= httpRequest('http://localhost:3000/auth/refresh-token-for-product',
{
form:{
username: data.userId+"/"+data.id,
password: data.password,
grant_type: "password",
client_id: 'null',
client_secret: 'null'
},
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
//'Authorization': data.header
}
})
Note : It is working fine on localhost, the issue is on serve only. I am doing request on same server to grant token hence url like localhost is fine.
This was due to confusing docs of got module , I am getting req.body to empty. I called got request with body and form option like below and it is working now.
const apiResponse= httpRequest('http://localhost:3000/auth/refresh-token-for-product',
{
form : true, //here is the change
body : { //here is the change
username: data.userId+"/"+data.id,
password: data.password,
grant_type: "password",
client_id: 'null',
client_secret: 'null'
},
headers:{
'Content-Type': 'application/x-www-form-urlencoded',
//'Authorization': data.header
}
})

How to pass data from angular to node js server?

My app.component.ts contains
login() {
var user = `{ email: ${this.email}, password: ${this.password} }`
const headers = new HttpHeaders()
.set('Authorization', 'my-auth-token')
.set('Content-Type', 'application/json');
this.http.post('http://localhost:3000/signin', user, {
headers: headers
}).subscribe(data => {
});
console.log(`email: ${this.email} password: ${this.password}`)
}
When trying to get the data in node I get
error: SyntaxError: Unexpected token e in JSON at position 2
I am using
req.body
to get the data.
What is the correct way to parse the JSON data? Also wanted to know if this is the correct way to pass form data from angular to node?
var user = {
email: this.email,
password: this.password
}
...
this.http.post('http://localhost:3000/signin',user).subscribe(...)
With Angular 6 HttpClient, you don't need to stringify your object (see POST example from official doc). In the same way, for a GET request, HttpClient parse json data for you.
Try this :
login() {
const user = { email: this.email, password: this.password };
const headers = new HttpHeaders({
'Authorization': 'my-auth-token',
'Content-Type': 'application/json'
});
this.http.post('http://localhost:3000/signin', user, {
headers: headers
}).subscribe(data => {});
console.log(`email: ${this.email} password: ${this.password}`) }
user= {
email: aka#gmail.com,
password: 123,
}
$http({
method: "POST",
url: http://localhost:3000/signin,
data: JSON.stringify(user),
headers: headers
}).success(function(data) {
// you can print data hera
}
}).error(function() {
});
First i thought you using an object for the user, than a saw it's a string.
Your data is not with correct json format.
Try to put quotes on the fields name
var user = `{ "email": ${this.email}, "password": ${this.password} }`
WRONG!
You should stringify the data - JSON.stringify(user)
this.http.post('http://localhost:3000/signin', JSON.stringify(user), {
headers: headers
}).subscribe(data => {
});

Mailchimp: The API key provided is linked to a different datacenter

I am trying to update a Mailchimp list but receive the following error:
{
"type":"http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/",
"title":"Wrong Datacenter",
"status":403,
"detail":"The API key provided is linked to a different datacenter",
"instance":""
}
However, the data-center referenced in my request URL is the same (us14) as the one suffixing my API key.
request.put({
url: 'https://us14.api.mailchimp.com/3.0/lists/xxxxxxxxx/members/',
auth: {
user: 'apikey:xxxxxxxxxxxxxxxxxxxxx-us14'
},
data: {
email_address: email,
status_if_new: 'subscribed',
email_type: 'html'
}
}
I have tried generating new API keys to no avail (they're all in us14).
Ok I was able to get this to work by first passing your API Key via the headers object. Second, I wrapped my data in JSON.stringify to ensure MailChimp was receiving a proper JSON Object on post. See below for sample code, hope this helps:
request.post({
url: 'https://usXX.api.mailchimp.com/3.0/lists/xxxxxxx/members',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Basic xxxxxxxxxxxxxxxxxxxxxxxxx-usXX'
},
form: JSON.stringify({
email_address: req.body.email,
status: 'subscribed',
interests: { 'xxxxxxx': true } // Interest Group
})
}, function(err, httpResponse, body) {
res.send(body);
});
const options = {
method: "POST",
auth: "uname:apikey656a******d2dfdb37c071a7cc-us19" //Should not give a space after a colon after uname
}
I had given a Space after the colon of uname. Now the API is working fine

Resources