I am getting mad because as a lodded-in wordpress admin, on the front-end (not in the admin portal), I cannot make post/put requests.
A simple GET AJAX request works perfectly without any type of credentials:
axios.get(this.page.url + "/wp-json/wp/v2/posts").then((resp) => {
console.log(resp.data);
});
BUT, when I try to make post requests I always get 401 error if I do not include the nonce.
If I include the nonce, I get 403. Tried with both AXIOS and JQUERY:
// Axios:
axios.defaults.withCredentials = true;
axios.defaults.headers.post["X-WP-Nonce"] = MYSCRIPT.nonce; // for POST request
axios
.post(this.page.url + "/wp-json/wp/v2/posts", {
title: "title",
content: "content",
status: "publish",
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
// JQUERY
$.ajax({
url: this.page.url + "/wp-json/wp/v2/posts",
type: "post",
data: {
title: "title",
content: "content",
status: "publish",
},
headers: {
"X-WP-Nonce": MYSCRIPT.nonce, //If your header name has spaces or any other char not appropriate
},
dataType: "json",
success: function (data) {
console.info(data);
},
});
The nonce is simply generated with:
<script>
<?php echo 'const MYSCRIPT = ' . json_encode(
array('nonce' => wp_create_nonce('wp-rest'))
); ?>
</script>
I know this is not good practice, and I will include it properly as soon as I get it to work.
The nonce is perfectly retrieved by Javascript, but I get 403 from wordpress...
No idea on how to proceed!
The action specified in wp_create_nonce should be wp_rest (underscore), not wp-rest (hyphen).
https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/
For developers making manual Ajax requests, the nonce will need to be passed with each request. The API uses nonces with the action set to wp_rest
Replace wp-rest with wp_rest and it should work properly.
Related
i am creating a custom admin page to list all the current order is woocommerce.
First of all i place a fetch request to my php file that contains the function to receive a nonce token.
Content of file:
<?php
require '../wp-includes/pluggable.php';
$nonce = wp_create_nonce( 'wc_store_api' );
return $nonce;
?>
From there i take that response and perform another fetch to collect the orders list.
fetch('../cgi-bin/nonce.php',{
method: 'POST',
})
.then((response)=>{
console.log(response)
fetch('https://***********.com/wp-json/wc/v3/orders',{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': response,
}
})
.then((response)=>{
return response.json
})
.then((data)=> {
console.log(data)
})
})
I receive a status 500 on the first fetch call : Internal Server Error.
Am i doing something wrong or does anyone know how to fix this ?
I could not get the ugcPost of a post or comment, the urn looks like: urn:li:ugcPost:7023566176156811264,7023567581345140736
how to use this in the api rest/posts/{ugcPosts urn}
the API returns the error {
"message": "Could not find entity",
"status": 404,
"code": "NOT_FOUND"
}
I have also added the headers
{
Linkedin-Version: 202210,
X-RestLi-Protocol-Version: 2.0.0
}
but it is still returning the same error even though I have encoded the urn, example:
https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264?viewContext=Reader
You need to add a bearer token in the header. And viewContext=Reader params is not required as per my knowledge of the documentation. I am sharing a sample example.
var axios = require('axios');
var config = {
method: 'get',
url: 'https://api.linkedin.com/rest/posts/urn%3Ali%3AugcPost%3A7023566176156811264',
headers: {
'X-Restli-Protocol-Version': '2.0.0',
'LinkedIn-Version': '202208',
'Authorization': 'Bearer [your_bearer_token]',
}
};
axios(config)
.then(function (response) {
console.log(JSON.stringify(response.data));
})
.catch(function (error) {
console.log(error);
});
You can visit this link for more information.
How should I fetch data using Wix-fetch function?
I followed this google analytics API tutorial, this tutorial using post function for getting JSON data, I used WIX fetch function to get JSON file, but the return object is undefined.
What did I miss?
fetch( "https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body' : JSON.stringify({
'grant_type': 'authorization_code',
'code': URLCode,
'client_id': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx.apps.googleusercontent.com',
'client_secret': 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx',
'redirect_uri': 'https://www.mydomain.or/ga/oauth2callback'
})
} )
.then( (httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
} )
.then( (json) => console.log(json.someKey) )
.catch(err => console.log(err));
UPDATE
STEP 1
I used this URL to generate the CODE
wixLocation.to("https://accounts.google.or/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics%20https://www.googleapis.com/auth/userinfo.email&redirect_uri=https://www.mydomain.or/ga/oauth2callback/&access_type=offline&response_type=code&client_id=XXXXXXXXXXXXXXXXXX")
I get the CODE from the callback URL
Step 2
I used this code for the HTTP postman request
The redirect URI in step 1 and 2 is the following (the second one):
Step 1:
There needs to be an exact match between the redirect URI configured in the client id in the google developers console and the URL to get the code authorization.
The URL should be built as shown in the tutorial you linked (if you need a refresh token, you can add the access_type=offline)
https://accounts.google.com/o/oauth2/auth?scope=https://www.googleapis.com/auth/analytics&redirect_uri=<redirect_uri>&response_type=code&client_id=<client_id>
After you enter the URL, you will be provided with an authorization window. Once you authorize, you will be redirected to the <redirect_uri> you provided earlier. You will find the code as the first parameter in the URL query. e.g. <redirect_uri>/?code=<auth_code> ...
Since the access token is for one-time use only, if you will need it again, you will have to get a new <auth_code>.
Step 2 (Postman query example):
If you got the access_token correctly and you want to check now with WIX. Get a new <auth_code> (as said, the access token is given once) and set the code as follows:
import { fetch} from 'wix-fetch';
$w.onReady(function () {
const data = `grant_type=authorization_code&code=<your_authorization_code>&client_id=<your_client_id>&client_secret=<your_client_secret>&redirect_uri=<your_redirect_uri>`;
fetch("https://accounts.google.com/o/oauth2/token", {
"method": "post",
"headers": {
"Content-Type": 'application/x-www-form-urlencoded'
},
'body': data
})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
} else {
return Promise.reject("Fetch did not succeed");
}
})
.then((json) => console.log(json.access_token))
.catch(err => console.log(err));
});
In Google Cloud vision API documentation for the product search, the method for getting operation status is listed as CMD but there is no C# code example for it in order to check any long-running operation status.
I tried calling this method in postman but it didn't work as I cannot add the service account credentials
GET https://vision.googleapis.com/v1/locations/location-id/operations/operation-id
Would appreciate any guidance on this.
It turns out there are two solutions:
Using Google Cloud Vision REST APIKEY as a query parameter for (you will have to generate your own API key from the cloud console credentials)
GET https://vision.googleapis.com/v1/locations/location_id/operations/operation_id?key=value
Using AJAX with stringify to append the service account JSON key file with the request which is sent to the same URL above.
checkStatus: function() {
if (this.get('stop') || !this.getOperationUrl()) {
return;
}
$.ajax({
url: '/getOperation',
type: 'POST',
data: JSON.stringify({
operation_url: this.getOperationUrl(),
key: this.config_model.get('key'),
}),
cache: false,
contentType: 'application/json',
dataType: 'json',
}).done(function(response) {
const result = response.response;
if (!response.success || !result) {
console.log(response);
this.set('response', response);
} else {
if (result.done) {
this.set('response', response);
} else {
setTimeout(function() {
this.checkStatus();
}.bind(this), 5 * 1000);
}
}
}.bind(this));
I'm trying to create a webhook through the Trello API by using Meteor's HTTP.post method like this:
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
params: {
idModel: '...',
callbackURL: '...'
},
}, function(error, result) {...});
The request works but the response i get is "Invalid value for idModel". However, if i try the same request using jQuery:
$.ajax({
type: 'POST',
url: https://api.trello.com/1/webhooks?key=...&token=...,
data: {
idModel: '...',
callbackURL: '...'
},
});
Everything works fine (i.e. the webhook is created and data is returned). Somehow Meteor's method seems to make it impossible for Trello to parse the idModel field. Any ideas what might be behind this? Am i doing something wrong or is there a bug?
I solved it by setting the Content-Type header to application/x-www-form-urlencoded. It was sent as text/plain before.
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
params: {
idModel: '...',
callbackURL: '...'
},
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
}
}, function(error, result) {...});
Try using data instead of params:
HTTP.post('https://api.trello.com/1/webhooks?key=...&token=...', {
data: {
idModel: '...',
callbackURL: '...'
},
}, function(error, result) {...});
Supplementing this page because I had the same problem doing this in golang. I solve it by adding
req.Header.Add("Content-Type", "application/json")
It is confusing that the 400 message is about an invalid idModel.