Mailchimp Api is unable to get the email_address field I send - javascript

I am tryiong to use the mailchimp API in order to subscribe a user to an existing list.
Using the node https request, I send the following request to the mailchimp server:
const url = `https://us7.api.mailchimp.com/3.0/lists/<list_id>/members?skip_merge_validation=true'`;
const options = {
method: "POST",
auth: "<name>:<API Key>",
};
const request = https.request(url, options, (response) => {
response.on("data", (data) => {
console.log(JSON.parse(data));
if (data.status === 200) {
res.redirect("/sucess");
} else {
res.redirect("/failure");
}
});
});
request.write(JSON.stringify(user_data));
request.end();
});
Before making the request, I console.log the user data collected from the front-end.
console.log("USER DATA : " + JSON.stringify(user_data));
and this is the answer i am getting from the API server :
USER DATA : {"members":[{"email_address":"a.b#email.com","status":"subscribed","merge_fields":{"FNAME":"A","LNAME":"B"}}]}
{
type: 'http://developer.mailchimp.com/documentation/mailchimp/guides/error-glossary/',
title: 'Invalid Resource',
status: 400,
detail: "The resource submitted could not be validated. For field-specific details, see the 'errors' array.",
instance: 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
errors: [
{
field: 'email_address',
message: 'This value should not be blank.'
}
]
}
As you can see in the log, the email_address field is not blank.
Has anyone encountered this problem before ? any Ideas ?
Thanks in advance

I've found the problem, it was related to my user data structure. It is now working with the following code
const user_data = {
email_address: req.body.email,
status: "subscribed",
merge_fields: {
FNAME: req.body.fName,
LNAME: req.body.lName,
}
}

This works
{
"email_address": "real#gmail.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Name",
"LNAME": "Last Name"
}
}
Providing CURL
curl --location --request POST 'https://us10.api.mailchimp.com/3.0/lists/audience_id/members' \
--header 'Authorization: Bearer API_KEY' \
--header 'Content-Type: application/json' \
--data-raw '{
"email_address": "real#gmail.com",
"status": "subscribed",
"merge_fields": {
"FNAME": "Name",
"LNAME": "Last Name"
}
}'

Related

Can't create subscriptions on Stripe

I can't create stripe subscription due to Missing required param: items.. I request it with items although.
The error:
{
"error": {
"code": "parameter_missing",
"doc_url": "https://stripe.com/docs/error-codes/parameter-missing",
"message": "Missing required param: items.",
"param": "items",
"type": "invalid_request_error"
}
}
The code:
const stripeCustomer = await stripe.customers.create({
name: name,
email: email,
plan: basicPlan,
})
const stripeSubscription = await stripe.subscriptions.create({
items: [{ plan: basicPlan }],
customer: stripeCustomer.id,
})
Stripe Customer account was successfully added.
Got the same problem. I've found out I'm lacking some package details

Getting a 422 Error on Post request, but I think my request is being sent correclty

I have to make a POST request, to an API that was given to me.
I am supposed to send some data to it and get back an JWT token.
The data i have to send is an object called data like this:
{
"firstName": "Jane",
"address": "Lohmühlenstraße 65",
"numberOfChildren": 2,
"occupation": "EMPLOYED",
"email": "jane.doe#getpopsure.com"
}
And the API docu looks like this:
curl https://challenge-dot-popsure-204813.appspot.com/user \
-H 'Content-Type: application/json' \
-d '{"firstName":"Jane","address":"Lohmühlenstraße 65","numberOfChildren":2,"occupation":"EMPLOYED","email":"jane.doe#getpopsure.com"}' \
-X POST
I am sending with axios a POST request, with an object, but i get an 422 Error:
Failed to load resource: the server responded with a status of 422 ()
This is my POST request, where data is the object above:
axios.post('https://challenge-dot-popsure-204813.appspot.com/user', data)
.then(function (response) {
debugger
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Any ideas what can be the issue?
I was able to reproduce the 422 error by removing or invalidating the JSON data. For instance remove/rename the "firstName" property.
Example:
{
"name": "Jane",
"address": "Lohmühlenstraße 65",
"numberOfChildren": 2,
"occupation": "EMPLOYED",
"email": "jane.doe#getpopsure.com"
}
Resulted In: 422 Unprocessable Entity
{
"errors": {
"firstName": [
"Missing data for required field."
],
"name": [
"Unknown field."
]
}
}
Plunker
I think the issue you are facing is that the data you are expecting is not all there when you make the axios.post resulting in the error you are seeing. Make sure that the data sent in the request contains all valid fields and values beforehand.

Can I make a "Mailjet" API call using fetch?

I would like to make a request to "Mailjet" API from a react app. To do so, I would like to use fetch API.
According to the documentation, I can use curl :
curl -s \
-X POST \
--user "$MJ_APIKEY_PUBLIC:$MJ_APIKEY_PRIVATE" \
https://api.mailjet.com/v3.1/send \
-H 'Content-Type: application/json' \
-d '{
"Messages":[
{
"From": {
"Email": "toto#toto.fr",
"Name": "toto"
},
"To": [
{
"Email": "passenger1#example.com",
"Name": "passenger 1"
}
],
"TemplateID": 1074249,
"TemplateLanguage": true,
"Subject": "Hi there !",
"Variables": {}
}
]
}'
I tried with fetch the following code :
fetch('https://api.mailjet.com/v3.1/send',{
method : 'POST',
mode : 'no-cors',
headers : {
'Content-Type': 'application/json',
'client_id':'xxx111',
'client_secret':'xxx000'
},
body : {
"Messages":[
{
"From": {
"Email": "toto#toto.fr",
"Name": "Toto"
},
"To": [
{
"Email": "email#email.com"
}
],
"TemplateID": 1094249,
"TemplateLanguage": true,
"Subject": "Hi there",
"Variables": {
}
}
]
}
})
.then(resp=>resp.json())
.then(data => {
console.log('data mailjet', data);
})
.catch(err => err)
I always got a 401 error "not authorized". I am sure my API keys are not set properly, but I don't really know how I can set them with fetch.
Can I make this API call from my react-app or do I need to create my own API and request the resources with node?
Thanks a lot!!
Regarding Mailjet - use the node integration they provide ;)
import mailjet from 'node-mailjet';
Regarding fetch - add your token in your header, depending on what kind of token the API expects. This will differ whether with each API and wether your doing frontend or backend calls.
With Node, save the token as a environment variable and then inject into the Authorization header.
The API key & secret need to be added as a Basic auth header and base64-encoded (use any lib you'd like in Node)
const encoded = base64.encode(`${apiKey}:${apiSecret}`)
fetch('https://api.mailjet.com/v3.1/send', {
headers: {
Authorization: `Basic ${encoded}`
}
})
Docs: https://dev.mailjet.com/sms/reference/overview/authentication/

DocuSign: How can I update a specific user's permission set in using REST API?

First, I did read this post (Add permission profile through API) but do not find that it has helped me.
I would like to get a list of users who possess the permission set "DocuiSign Viewer" and set it to "DocuSign Sender".
I am able to connect to and get everything working EXCEPT this function. Below is some sample code.
var permissionSenderId = "123457";
var permissionSenderName = "DocuSign Sender";
data = UrlFetchApp.fetch(url, options);
users = JSON.parse(data).users;
numUsers = users.length;
for(var u = 0, szu = numUsers; u < szu; u++) {
var user = users[u];
if(user.isAdmin == "True") continue ;
if(user.userStatus != "Active") continue ;
if(user.permissionProfileId != permissionSenderId) {
user.permissionProfileId = permissionSenderId;
user.permissionProfileName = permissionSenderName;
body = JSON.stringify(user);
url = baseUrl + "/users/"+user.userId;
options = initializeRequest(url, "PUT", body, email, password, integratorKey);
data = UrlFetchApp.fetch(url, options);
}
}
The response I get from the server is:
{
"errorCode": "INVALID_REQUEST_BODY",
"message": "The request body is missing or improperly formatted."
}
The response to get the users is below:
{
"users": [
{
"userName": "TestUser",
"userId": "5b10fac4-5c68-4bee-b2ad-20z68715a8x6",
"userType": "CompanyUser",
"isAdmin": "False",
"userStatus": "Active",
"uri": "/users/5b10fac4-5c68-4bee-b2ad-20z68715a8x6",
"email": "do-not-reply#tmx.com",
"createdDateTime": "2018-05-18T19:04:06.6370000Z",
"firstName": "Test",
"lastName": "User",
"permissionProfileId": "123456",
"permissionProfileName": "DocuSign Sender",
"jobTitle": "Test User"
}
],
"resultSetSize": "1",
"totalSetSize": "1",
"startPosition": "0",
"endPosition": "1"
}
Variations that I have tried:
One:
user.permissionProfileId = permissionSenderId;
user.permissionProfileName = permissionSenderName;
body = JSON.stringify(user);
Two:
body = JSON.stringify({
"permissionProfileId": permissionSenderId,
"permissionProfileName": permissionSenderName
});
And other iterations that just feel more like hacking than actual programming. Anyway, I am always getting the same response (noted above). Any thoughts?
(IDs have been fudged to anonymize)
Further reading:
SDK API documentation for updating a user record
https://developers.docusign.com/esign-rest-api/reference/Users/Users/update
API Explorer - Under Users > Users, there is no update? :(
https://apiexplorer.docusign.com/
A few helper functions I'm using
//***********************************************************************************************
// --- HELPER FUNCTIONS ---
//***********************************************************************************************
function initializeRequest(url, method, body, email, password, integratorKey) {
var options = {
"method": method,
"uri": url,
"body": body,
"headers": {},
"accept": "application/json",
"contentType": "application/json",
"content-disposition": "form-data",
"muteHttpExceptions": true
};
addRequestHeaders(options, email, password, integratorKey);
return options;
}
///////////////////////////////////////////////////////////////////////////////////////////////
function addRequestHeaders(options, email, password, integratorKey) {
// JSON formatted authentication header (XML format allowed as well)
dsAuthHeader = JSON.stringify({
"Username": email,
"Password": password,
"IntegratorKey": integratorKey
});
// DocuSign authorization header
options.headers["X-DocuSign-Authentication"] = dsAuthHeader;
}

Send an email using Gmail API in Typescript/Javascript

I want to send an email on my application using my gmail account. I am using Ionic and followed https://www.sitepoint.com/sending-emails-gmail-javascript-api/ and https://developers.google.com/gmail/api/v1/reference/users/messages/send to send emails.
This is what I have for initializing client
client_id: gapiKeys.client_id,
discoveryDocs: ["https://www.googleapis.com/discovery/v1/apis/gmail/v1/rest"],
scope: [
"https://www.googleapis.com/auth/gmail.readonly",
"https://mail.google.com/",
"https://www.googleapis.com/auth/gmail.modify",
"https://www.googleapis.com/auth/gmail.compose",
"https://www.googleapis.com/auth/gmail.send"
].join(" ")
When I only put "https://www.googleapis.com/auth/gmail.readonly" under scope, I can get the list of labels of the user, but I get error 401 when I use mail.google.com, modify, compose, and send. Below is my code for sending an email.
sendEmail() {
let top = {
'To': 'someRecipient#gmail.com',
'Subject': 'Test'
}
var email = '';
for(var header in top) {
email += header += ": "+ top[header] + "\r\n";
}
email += "\r\n" + "this is a testing email message.";
var request = (gapi.client as any).gmail.users.messages.send({
'userId': 'me',
'resource': {
'raw': window.btoa(email).replace(/\+/g, '-').replace(/\//g, '_')
}
});
request.execute();
}
With this code, I get
POST https://content.googleapis.com/gmail/v1/users/me/messages/send?alt=json&key=someKey--M 401 ()
The address in the error shows the following:
{
"error": {
"errors": [
{
"domain": "global",
"reason": "required",
"message": "Login Required",
"locationType": "header",
"location": "Authorization"
}
],
"code": 401,
"message": "Login Required"
}
}
What should I do to send an email on application using Ionic (not email composer provided by Ionic)? I don't have to use Gmail API.
Your authorization to access the server is not existent.
Use basic trouble shooting to determine the problem.
Here is a link that tells you what is happening.
You will have to provide some sort of authentication in the header no matter how you send the email.
https://httpstatuses.com/401

Categories