Wordpress nonce token failing - woocommerce

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 ?

Related

Weird 401 and 403 with wordpress REST API (wp-json)

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.

How to create Forgot password user endpoint API in WordPress?

How can we use custom code to generate a password for the forgot password user endpoint API?
I used this plugin: bdvs password reset
You can simply reset password and set new password. I put example some code:
Reset Password:
$.ajax({
url: '/wp-json/bdpwr/v1/reset-password',
method: 'POST',
data: {
email: 'example#example.com',
},
success: function( response ) {
console.log( response );
},
error: function( response ) {
console.log( response );
},
});
Set New Password:
$.ajax({
url: '/wp-json/bdpwr/v1/set-password',
method: 'POST',
data: {
email: 'example#example.com',
code: '1234',
password: 'Pa$$word1',
},
success: function( response ) {
console.log( response );
},
error: function( response ) {
console.log( response );
},
});
Wordpress generates passwords by function wp_generate_password() - documentation
At the end of the function there is hook random_password, so if you wnat to use your custom code to generate a password instead of native WP function, you need to add filter and in function you can write your custom code for generating password. This function will be called always at the end of wp_generate_password().
function custom_random_password( $password ) {
// here you make your password generation
$password = 'your-password';
return $password;
}
add_filter( 'random_password', 'custom_random_password' );

Fetching resources from google analytics services using HTTPS by Wix fetch function

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));
});

angular2 wait for error http response

I have a problem with angular2 http response.
I want to catch the error in my component.
How does my app work.
In my Component, I Call a function in a personal service :
var response = this.apiUser.login(username, password);
alert(response);
In my Service, I try to auth :
this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.subscribe(
response => {
localStorage.setItem('id_token', response.json().token);
this.router.navigate(['home']);
},
error => {
return error.json();
},
() => { }
);
When the auth is ok, all work fine. But when the Auth fail, i can't catch the response in my Component.
(Its undefinied because the alert is executed before the http call...)
Can u help me please !!! (It was working when all the code was only in my Component, but I wanted to slip my code...)
Ty.
Return the observable by using map() instead of subscribe()
return this.http.post(this.httpApiAdress + '/' + this.httpUserAutenticate, body, { headers: contentHeaders })
.map(
response => {
localStorage.setItem('id_token', response.json().token);
this.router.navigate(['home']);
},
);
and then use subscribe where you want to execute code when the response or error arrives
var response = this.apiUser.login(username, password)
.subscribe(
response => alert(response),
error => alert(error),
);

$http.post not working with JSON data

I am building an application using AngularJS and I have a login form from which I want to send JSON data as request body.
In my controller;
$scope.credentials = {userid: $scope.userid, password: $scope.password};
$scope.login = function () {
$http({
method : 'POST',
url : 'http://localhost/login.json',
data : $scope.credentials,
headers: {'Content-Type': 'application/json'}
}).success(function (data) {
// code
}).error(function (data, status, headers, config) {
$scope.status = status + ' ' + headers;
console.log($scope.status);
});
};
But when I am submitting the form POST request is not performing and I am getting a message in the console like;
0 function (name) {
"use strict";
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
}
What am I doing wrong here?
If I changed the line
headers: {'Content-Type': 'application/json'}
to
headers: {'Content-Type': 'application/x-www-form-urlencoded'}
the POST request is making. But I don't want to send it as form values instead I want to send the request as JSON.
You should encode javascript object to corresponding mime-type data in order to post data. If you are using jQuery, try to use $.param($scope.credentials) instead of just $scope.credentials.
I think the problem is that you're POSTing to http://localhost/login.json which is not any script that is able to receive POSTrequests with form data.

Resources