Firebase custom functions POST 3rd party API - javascript

i'm trying to create a custom function in Firebase custom functions to invoke a POST req to 3rd API. I was able to get together the syntax from frontend but I have no idea how to do it via firebase functions.
I need to rewrite this code - any help greatly appreciated
axios
.post(
URL,
{
order: {
category_id: 7,
status_id: 1,
aff_source_id: 1,
},
person: {
name: "n-a",
surname: "n-a",
phone: phone,
email: email,
},
extend: {
amount: maxMorgageBudget,
repayment_time: 30,
fixation: 5,
house_value: maxMorgageBudget * 1.1,
mortgage_purpose_id: mortPurpose,
income: income,
},
organization: 2,
},
{
headers: { "Content-Type": "application/json" },
auth: {
username: username,
password: password,
},
}
)
.then(async (response) => {
console.log(response.data);
})
.catch((error) => {
if (error.response) {
console.log(error.response.data); // => the response payload
}
});

Related

How to update component in user collection Strapi v4

[details="System Information"]
Strapi Version: 4.5.5
Operating System: Windows
Database: MySQL
Node Version: 14.20
NPM Version: 8.18.0
Yarn Version: 1.22.19
[/details]
Hi there, I'm trying to updata a component called "billingAddress" within my user collection. I have set up a route to be able to enable a user to update their own data based on this video: Updating Your Own User Info in Strapi - YouTube
I'm able to update user data but once I need to update data in the component I'm not able to update any data.
This is what my extension looks like on the strapi backend:
module.exports = (plugin) => {
plugin.controllers.user.updateMe = async (ctx) => {
if (!ctx.state.user || !ctx.state.user.id) {
return ctx.response.status = 401;
}
await strapi.query('plugin::users-permissions.user').update({
where: { id: ctx.state.user.id },
data: ctx.request.body,
}).then((res) => {
ctx.response.status = 200;
})
}
plugin.routes['content-api'].routes.push(
{
method: "PUT",
path: "/user/me",
handler: "user.updateMe",
config: {
prefix: "",
policies: []
}
}
)
return plugin;
}
This is the Axios put request I'm using to update the user data from the frontend:
const handleUpdateBillingAddress = () => {
axios.put('http://localhost:1337/api/user/me', {
billingAddress: {
zipCode: "2840",
id: 1,
firstName: "Tim",
lastName: "kerrem",
company: "mycompany",
address1: "mystreet 42",
address2: null,
city: null,
country: "Belgium",
provinceOrState: null,
zipCode: null,
phone: "+31412412412",
email: null
}
},
{
headers: {
'authorization': `Bearer ${jwt}`,
'Content-Type': 'application/json'
},
},
)
.then(response => {
console.log(response)
notification.open({
type: 'success',
message: 'Success!',
description:'Your user information has been updated',
});
})
.catch(error => {
console.log(error);
console.log('An error occurred:', error.response);
notification.open({
type: 'error',
message: 'Something went wrong',
description:'Some of your credentials are not valid',
});
});
}
Would be really helpful if someone could advise me on how to update the component
Hi you wanna try doing this via entityService strapi doc's states:
The Entity Service API is the recommended API to interact with your application's database. The Entity Service is the layer that handles Strapi's complex data structures like components and dynamic zones, which the lower-level layers are not aware of.
reference
so try:
await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {data: ctx.request.body })
By using entityService and doing some tweaking with data and populate parameters I was able to get this working with following code:
module.exports = (plugin) => {
plugin.controllers.user.updateMe = async (ctx) => {
if (!ctx.state.user || !ctx.state.user.id) {
return ctx.response.status = 401;
}
const billingData = ctx.request.body.billingAddress;
await strapi.entityService.update('plugin::users-permissions.user', ctx.state.user.id, {
data: {
billingAddress: {
firstName: billingData.firstName,
lastName: billingData.lastName,
company: billingData.company,
address1: billingData.address1,
city: billingData.city,
country: billingData.country,
provinceOrState: billingData.provinceOrState,
zipCode: billingData.zipCode,
phone: billingData.phone,
email: billingData.email,
},
},
populate: ["billingAddress"],
}).then((res) => {
ctx.response.status = 200;
})
}
plugin.routes['content-api'].routes.push(
{
method: "PUT",
path: "/user/me",
handler: "user.updateMe",
config: {
prefix: "",
policies: []
}
}
)
return plugin;
}

Mailchimp post request in react giving error

I am making my web using React no backend. I want to integrate MailChimp to my app but it's giving me the following error:
ContactUs.jsx:40 POST http://localhost:3000/3.0/lists/{api-key} 404 (Not Found)
function sendData(event) {
const { name, email, subject } = state;
const userData = {
members: [
{
"email_address": email,
status: "subscribed",
merge_fields: {
"FNAME": name,
"MESSAGE": subject,
}
}
]
}
console.log(userData)
fetch('/3.0/lists/{api-key}', {
method: 'POST',
headers: {
'auth': "saad:153b-us12",
'Content-Type': 'application/json',
},
body: JSON.stringify(
userData
)
}).then(response => console.log(response))
.catch(error => console.error(error))
event.preventDefault();
}
You are sending the request to the localhost, which is your app url on your machine. According to the Mailchnimp docs you should send the request to https://<dc>.api.mailchimp.com url. Just set the correct url in the fetch function.

React Router Adds URL Query Params on POST Request

Hello my fellow nerds,
I am running into an issue where when I make a POST request (using Axios library inside of React function), it automatically appends all of the data from the "Create a User" form into search parameters in the URL of the page upon submission. I don't like this because I'd rather this stay hidden within the POST request, not flung out onto the page URL.
Image: URL after user was created
This is a direct result of React Router adding the data sent in the request of the body being appended to the location.search of react router's history object. So, naturally, since the react router history object is mutable, I tried adding this to the response of the submission:
this.props.location.search.replace({*some random parameter stuff here*});
This was in hopes it would remove all of that stuff from the URL and redirect to the page without search parameters. Anyways, I have seen a few other posts similar in nature but they don't seem to answer this exact question.
TL;DR: I am trying to send a POST request without React Router adding my req.body data to the params in my URL and the location.search object.
MY CODE:
Users.js: (front end)
handleSubmit (e) {
Axios.post(`${server}/s/admin/users/create`, {
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}
users.js: (back end)
app.post("/s/admin/users/create", (req, res) => {
let rb = req.body.data;
let newUser = new User({
_id: uid.time(),
orgID: req.session.orgID,
email: rb.email,
username: rb.username,
password: bcrypt.hashSync(rb.password, hashRate),
firstName: rb.firstName,
lastName: rb.lastName,
data: { exist: "true" },
settings: { exist: "true" }
});
// Save new owner to db
newUser.save((err, data) => {
if (err) return console.error(err);
res.json({info: `A new user, ${newUser.firstName} ${newUser.lastName}, has been created successfully.`});
});
});
Thank you!
P.S. This is my first post, thank you for your patience. I've tried searching and solving this issue for about a day now.
Can you try rewriting it this way? cause axios.post expect
axios({
method: 'post',
url: `${server}/s/admin/users/create`,
headers: {
'Content-Type': 'application/json'
},
data: {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
Axios.post method expect the second argument as data but you have passed config, another way is to pass data and config in the third argument.
handleSubmit(e) {
Axios.post(`${server}/s/admin/users/create`, {
firstName: this.state.firstName,
lastName: this.state.lastName,
username: this.state.username,
password: this.state.password,
email: this.state.email
}, {
headers: {
'Content-Type': 'application/json'
}
}
}).then((res) => {
console.log(res);
}).catch(err => console.log(err));
}

React Stripe Payment Create Customer and Order / Shipping Address etc

I created stripe payment page using gatsby react and aws lambda. But this code not create customer data like ( shipping address, email etc. )
Lamdba Code
const stripe = require("stripe")(process.env.STRIPE_SECRET_KEY);
module.exports.handler = (event, context, callback) => {
console.log("creating charge...");
// Pull out the amount and id for the charge from the POST
console.log(event);
const requestData = JSON.parse(event.body);
console.log(requestData);
const amount = requestData.amount;
const token = requestData.token.id;
// Headers to prevent CORS issues
const headers = {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Headers": "Content-Type"
};
return stripe.charges
.create({
// Create Stripe charge with token
amount,
source: token,
currency: "usd",
description: "Tshirt"
})
.then(charge => {
// Success response
console.log(charge);
const response = {
headers,
statusCode: 200,
body: JSON.stringify({
message: `Charge processed!`,
charge
})
};
callback(null, response);
})
.catch(err => {
// Error response
console.log(err);
const response = {
headers,
statusCode: 500,
body: JSON.stringify({
error: err.message
})
};
callback(null, response);
});
};
Gatsby Payment Code
Code is working , payment is working. but shipping details not working.
openStripeCheckout(event) {
event.preventDefault();
this.setState({ disabled: true, buttonText: "WAITING..." });
this.stripeHandler.open({
name: "Demo Product",
amount: amount,
shippingAddress: true,
billingAddress: true,
description: "",
token: (token, args) => {
fetch(`AWS_LAMBDA_URL`, {
method: "POST",
body: JSON.stringify({
token,
args,
amount,
}),
headers: new Headers({
"Content-Type": "application/json",
}),
})
.then(res => {
console.log("Transaction processed successfully");
this.resetButton();
this.setState({ paymentMessage: "Payment Successful!" });
return res.json();
})
.catch(error => {
console.error("Error:", error);
this.setState({ paymentMessage: "Payment Failed" });
});
},
});
}
I want to see customer data , shipping address etc.
Thanks for helping.
The billing and shipping address are both available in the args-argument of the token callback you're collecting.
https://jsfiddle.net/qh7g9f8w/
var handler = StripeCheckout.configure({
key: 'pk_test_xxx',
locale: 'auto',
token: function(token, args) {
// Print the token response
$('#tokenResponse').html(JSON.stringify(token, null, '\t'));
// There will only be args returned if you include shipping address in your config
$('#argsResponse').html(JSON.stringify(args, null, '\t'));
}
});

Getting values from response

I am getting the response from an external api like the given below screenshot.
How can i get the value of id i.e., 3991938
Here is how i do the request.
$http.post('http://api.quickblox.com/users.json', {
token: quickbloxapitoken,
user: {
email: email,
login: email,
password: password
}
}, {
'Content-Type': 'application/x-www-form-urlencoded'
})
.then(function(results) {
console.log('1');
console.log(results);
console.log('2');
})
.catch(function(response) {
console.log('Error', response.status, response.data.errors);
});
I tried to do console.log(results.id); and console.log(results.data.id) but i am getting only undefined as the result.
How can i get it.
Your JSON is:
{
data: {
user: {
id: 65
}
}
}
You can acces to user data with results.data.user, eg: results.data.user.id
you id is in user object,
so what you need is :-
results.data.user.id

Categories