Making POST request from ReactJS app built on WordPress - javascript

I'm building a ReactJS app on top of a WordPress backend. The React App is running on the same domain, embedded in the WordPress site. Most of the tutorials I've been following cover how to get data from WordPress to React. I've been successful at this, but need to figure out how to submit data from my React app to WordPress (preferably via the REST API).
This will be a custom admin page for logged in editors, either available in the admin panel or from the front-end.
As an example to create a post, I'm naively trying the following function:
saveGrid() {
const url = "/wp-json/wp/v2/posts";
const body = JSON.stringify({
"title":"internet",
"content":"teapot"
});
fetch(url, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body:body
});
}
I get back a 401 unauthorized response. What is the easiest way to authorize myself for a POST submission (secure solution preferred)?

It looks like you're on the right track.
A quick read of this: https://apppresser.com/wp-api-post-submission/
shows me that all you're missing is a "nonce" in order for the WP API to recognise and validate your request successfully.
In the guide above, the dev created a JS written in JQuery that sends XHR/AJAX requests to the WP API and in their plugin.php they enqueue and localize the script with some variables from WP to help with the request inside the JS.
The takeaway here is that they used wp_create_nonce('wp_rest')and assigned this to a localized variable nonce so they could easily reference that later inside the JS and assign nonce to their X-WP-Nonce header inside the request!
If you look into this further you might find a suitable alternative for you that will work as I'm not entirely sure how you're loading your JSX files but this guide may come in handy for you to enqueue your JSX scripts/files: http://blog.milandinic.com/2015/12/01/using-react-jsx-in-wordpress/
More information
https://codex.wordpress.org/Function_Reference/wp_localize_script
https://developer.wordpress.org/reference/functions/wp_enqueue_script/

I was able to solve this problem by, instead of having a straight post request from React, using a Jquery AJAX submission outside of React that uses data from a form inside React. This caused the request to contain the necessary cookies (I don't understand exactly why this is the case)

Related

How to define Netlify function endpoint as POST?

I am new to serverless and am trying to get my head around it. So I've created a function on netlify using GET and it works fine.
Then I wanted a POST endpoint so I followed the same format and created a similar function. But then I sent a POST request to this new function. On checking the console.log on the server I realise that it's being read as a request with a GET method (httpMethod:'GET'). And then I realised that I have not defined the endpoint method which I would have done on a normal server.
But I have no idea how to do that.
Question
Is there a different way to do a GET function and POST function on netlify or serverless?
If the answer is Yes, then please guide me on this.
If the answer is No, and the functions are written in the same way, then can someone advise me why my POST request is being read as GET by netlify?
Here's the code from the function on codesandbox .. https://codesandbox.io/s/serverless-function-2xebuf?file=/src/index.js
Posting the answer to this so that it serves as a reminder to me and if it helps someone in the future who has a similar issues
Thanks to #alessiopremoli for sharing that one can't explicitly define to what verb the function handler should respond to .. that answered my first question : Is there a different way to do a GET function and POST function on netlify or serverless?
The second issue that I faced was that my POST request was being read by netlify as GET.. I realised what the issue was.. there's a setting for redirect rules in the netlify.toml file that simplifies the URL to the api.. so you can type "site.com/api/functionName.js" instead of "site.com/.netlify/functions/functionName.js"
[[redirects]]
from = "/*"
to = "/blog/:splat"
and I was using this for my api routes as
[[redirects]]
from="/api/*"
to="/.netlify/functions/:splat"
to simplify the access to my api route.. but I didn't realise that that by default the status code for this redirect is 301 which changes the method to GET and this was also changing the method of my request. So for those who face this issue, I hope this helps.
If it's a POST request and you are using a redirect option then ensure that you add the status of 200 or just call the function using the default path that you've set eg "site.com/.netlify/functions/functionName.js"
So changing the redirect rule to the one as below fixed the issue for me
[[redirects]]
from="/api/*"
to="/.netlify/functions/:splat"
status=200
Here's the link to the netlify support team that helped resolve this issue that explains it better (https://answers.netlify.com/t/does-using-the-redirects-route-to-a-function-call-change-the-method-of-the-request-from-post-to-get/55760/5)
For my experience, you can't explicitly define to what verb the function handler should respond to, I usually set a check on the event verb:
if (event.httpMethod !== 'POST') {
return {
statusCode: 501,
body: JSON.stringify({ message: "Not Implemented" }),
headers: { 'content-type': 'application/json' }
}

Can I send a Stripe charge request directly from the frontend?

I am wondering if I can send a Stripe request directly from my front-end, because I don't have a back-end. Please note that security isn't an issue, because I won't deploy the project or even use it in any way shape or form.
I am thinking of using axios instead of curl, and it should look like something like this:
On the Stripe official doc, they use curl on the back-end
I am also wondering if there's any other key I need to pass. There's a secret key and a publishable key. I am thinking the publishable key is not needed. Also, do I need to activate my account in order for it to work? I don't plan to use it outside of pet projects.
axios({
method: 'post',
url: 'https://api.stripe.com/v1/charges',
header: {
Authorization: 'sk_test_IvnLvlpEpskxJA8u7eEsAOBr00e7fmPyMZ'
},
data: {
amount: '999',
currency: 'cad',
description: '',
source: 'tok_visa'
}
});
I want the same result a curl request would yield.
You should not be making this call client-side, both for Security reasons obviously but also because you'd have to make the raw request and handle error handling and such.
Instead, you should use one of Stripe's official client libraries. Those run server-side, but it doesn't mean you need a separate server. You can just run the code locally on your computer for example by building a PHP script that interacts with your client-side code in the browser.
Another alternative would be to use Checkout as there's a client-side-only integration that only requires some javascript. See the docs here.

How to get around auth level when testing API on laravel project?

I am using the basic Auth from laravel that you get from running the following command.
php artisan make:auth
I have an API written so that the backend on the server can update/create services and statuses. The issue i'm running into is that the Admin also has a UI on the web app and can create a service, or update its status manually. Therefore, I have an Auth level on the methods where you have to be logged in to use them.
Now when I call the method in postman it redirects me to the login page, I was wondering if there was a way around this Auth level strictly for an API?
I was told of a way to do pre-request scripts directly in postman but i'm fairly lost when it comes to the whole java script part of that and feel like there is an easier way to do it. I also already tried to do 'basic auth' with the username and password, it didnt seem to work though.
Thank you for the help in advance!
Edit: Here is the screenshot from my header.
I am presuming if you have the API in place you have an api_token set for the specific user. You can use that inside Postman in one of two ways.
You will goto the Headers tab and add:
Key: Authorization
Value: Bearer API_TOKEN_VALUE
Edited: Added the screenshot of postman
You can amend the url for the request and add the token:
url_to_api_endpoint?api_token=API_TOKEN_VALUE
On the api routes if you have ->middleware('auth:api') Laravel will read the authorization token from the header or using the query parameter and check it to the database value.
Adding the api_token to the user table
If you don't have an api_token field in your user table then add one. It is not the same as remember_token, they are different. So add to your user migration the following:
$table->string('api_token', 60)->unique();
You will need to update the users api_token using something like the following:
$user = User::find(1);
$user->update(['api_token' => str_random(60)]);
That 60 character string you will use where I put VALUE_OF_TOKEN_FROM_DB

How to get twitter oAuth token of a logged in user

I'm trying to set up a javascript function to post a status to a twitter account using POST statuses/update, details here: https://dev.twitter.com/docs/api/1/post/statuses/update. The goal is a Twitter post similar to the open graph actions on Facebook.
I'm using jQuery ajax to make the post request, here's what I have so far:
$.ajax
({
type: "POST",
url: "https://api.twitter.com/1/statuses/update.json",
headers: jsonData,
data: {},
dataType: "jsonp",
success: function( data )
{
}
});
I believe that I need to generate a header something like this for security:
Authorization: OAuth oauth_consumer_key=consumerKey, oauth_nonce=nonce,
oauth_signature=signature, oauth_signature_method="HMAC-SHA1",
oauth_timestamp=timestamp, oauth_token=userToken, oauth_version="1.0"
I have the consumer key for my app, I can generate a nonce, I'm generating the signature and timestamp using the methods from this question Twitter OAuth authentication in javascript. The only thing I have left is th oauth_token, which I believe is the token of the user whose feed I wish to post to. Please correct me if I'm wrong about that.
The problem is, I have absolutely no idea how to get this token from the user in order to post to their feed. I've spent the last 2 hours running around in circles through Twitter's oAuth documention without finding anything that looked useful; everything I've found was either flowcharts with no code examples or predicated on my code already having the user's oAuth token.
My question is this: how can I get the logged in user's oAuth token using javascript?
If that is not possible, I have another page where I am currently storing the user's twitter id in the database with their permission, getting their token and databasing it in PHP would also be satisfactory, assuming it doesn't change very frequently.
In order to obtain the oauth_token you need to follow the authentication process. Your application needs to be authorized to act on the behalf of the user.
I would recomend to take some time first and learn how OAuth exactly works (there is a lot of information available) and then implement it in your app. (http://hueniverse.com/oauth/)
You could also benefit from a library which will make your life easier. (in your case, look at: https://dev.twitter.com/docs/twitter-libraries#php).
Hope this has been useful.
Here is example for get twitter oauth token and post tweet in twitter .
Code sample is in php .
http://www.phpgang.com/how-to-post-tweet-on-twitter-with-php_414.html
1) to obtain the oauth token you need to follow the authentication process.
2) and your application needs to be authorized to act on the behalf of the user.
you can also see this twitter example for better understanding how it works
In this use can see the process of authorized user and post and get json result.
https://dev.twitter.com/rest/tools/console
I hope this will help you.
thanks

How to post Facebook Score using JS SDK, without hardcoding the app access token?

I'm trying to post a score using the JS SDK. Here's the code that I'm using:
FB.api("/[USER_ID]/scores", 'post', {score:score, access_token:"APP_ACCESS_TOKEN"}, function(response){
if (!response || response.error) {
log(response);
} else {
log(response);
}
});
However, I need to do this without hardcoding the APP_ACCESS_TOKEN. Any idea on how to do it using the JS SDK?
/me/ refers to the current user - when using the app access token there is no 'current' user - you're acting as the app - make the request to /[USER ID]/scores using the app access token
You can grab access_token through JS by using FB.getLoginStatus. More can be found in the doc.
.
There is no way, that I know of.
And, nor should there be, when you consider that the App will only have one app access_token.
Think of it like your app secret, keep it safe!
Especially when you consider how you get the access_token to start with, just by making a formatted request to FB with your ID and App Secret.
If you put that client side, then ANYONE could grab it and do stuff on behalf of your app!!
I would suggest one of two things:
Try making a call to /me/scores, and use the normal access token.
Even though the API docs don't suggest this being possible, you never know.
OR
2. Encapsulate it as an AJAX call to your server, and make the Graph call from there.
Sucks, but there seems to be a few things that aren't quite designed to work on the client side yet. :-/

Categories

Resources