I have defined the following custom endpoint for woocommerce:
add_action( 'rest_api_init', 'custom_endpoint' );
function custom_endpoint() {
register_rest_route( 'wc/v3', 'my_custom_endpoint', array(
'methods' => 'GET',
'callback' => 'return_value',
) );
}
function return_value() {
return "this is my custom endpoint!";
}
However, this endpoint is also accessible if I'm not authenticated using the ck and cs.
How can I protect it the same way all other, default endpoints of the WooCommerce API are protected? (I would prefer not needing another auth plugin for this to work, but to access it with the standard WooCommerce auth keys instead).
Thanks!
Hello use permission_callback with JWT Authentication for WP REST API plugin so it will work fine.
Steps :
1) Install JWT Authentication for WP REST API plugin
2) Set permission_callback
Below code will work well after JWT Authentication for WP REST API plugin installation
add_action('rest_api_init', 'custom_endpoint');
function custom_endpoint(){
register_rest_route('wc/v3', 'my_custom_endpoint', array(
'methods' => 'GET',
'callback' => 'return_value',
'permission_callback' => function($request){
return is_user_logged_in();
}
));
}
function return_value(){
return "this is my custom endpoint!";
}
for more information please check JWT Authentication for WP REST API documentation.
Checked and works well.
Cookie authentication is the standard authentication method included with WordPress. When you log in to your dashboard, this sets up the cookies correctly for you, so plugin and theme developers need only to have a logged-in user.
As an example, this is how the built-in Javascript client creates the nonce:
<?php
wp_localize_script( 'wp-api', 'wpApiSettings', array(
'root' => esc_url_raw( rest_url() ),
'nonce' => wp_create_nonce( 'wp_rest' )
) );
This is then used in the base model:
options.beforeSend = function(xhr) {
xhr.setRequestHeader('X-WP-Nonce', wpApiSettings.nonce);
if (beforeSend) {
return beforeSend.apply(this, arguments);
}
};
Here is an example of editing the title of a post, using jQuery AJAX:
$.ajax( {
url: wpApiSettings.root + 'wp/v2/posts/1',
method: 'POST',
beforeSend: function ( xhr ) {
xhr.setRequestHeader( 'X-WP-Nonce', wpApiSettings.nonce );
},
data:{
'title' : 'Hello Moon'
}
} ).done( function ( response ) {
console.log( response );
} );
Note that you do not need to verify that the nonce is valid inside your custom end point. This is automatically done for you in
rest_cookie_check_errors()
Woocommerce API
https://woocommerce.github.io/woocommerce-rest-api-docs/?php#authentication-over-https
While cookie authentication is the only authentication mechanism
available natively within WordPress, plugins may be added to support
alternative modes of authentication that will work from remote
applications.
As Per Official Document : https://developer.wordpress.org/rest-api/using-the-rest-api/authentication/#authentication-plugins
Related
I started creating an ajax post form that takes name and email as inputs. The idea is to have the anonymous, un-logged user to fill out the fields, and when the forms posting succeeds on the API, the user gets access to download an eBook.
The admin wants to be able to view the data of all the users that have filled out the form on the backend, so what I did is create a new custom post type labeled "ebook-user".
From the researching that I've done online, it seems that a user could only post on post comments to the rest api. Is there a way to enable anonymous posting on a custom post type?
Right now, when I post with my current code, I get a 401 error:
{
"code": "rest_cannot_create",
"message": "Sorry, you are not allowed to create posts as this user.",
"data": {
"status": 401
}
}
Here's my js code:
fetch(`${site_url}/wp-json/wp/v2/ebook-user`, {
credentials: 'same-origin',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-WP-Nonce': ajax_nonce,
},
body: JSON.stringify(credentials)
})
.then((res) => res.json())
.then((res) => {
console.log(res)
if(res.data.status == 403) {
formMsg.textContent = `Error`
}
console.log('success');
})
.catch((err) => {
console.error(err);
})
Note that I did add this line in my functions.php, which enables comment posting as guest user
add_filter( 'rest_allow_anonymous_comments', '__return_true' );
Since you want to POST with an un-authenticated user, I'd create a custom endpoint to do it.
Something like:
/wp-json/mytld/v1/ebook
Allow POST to the end point but nothing else.
Validate the input VERY CAREFULLY and I'd go so far as to do things like make sure you don't already know the email address before allowing the post to succeed.
This requires a little more code but gives you a lot more control.
=C=
add_action( 'rest_api_init', function () {
register_rest_route( 'getdata/v1', '/author/(?id)', array(
'methods' => 'GET',
'callback' => 'my_bookdata_func',
) );
} );
function my_bookdata_func( $data ) {
$posts = get_posts( array(
'author' => $data['id'],
) );
if ( empty( $posts ) ) {
return null;
}
return $posts[0]->post_title;
}
Url to access
wp-json/getdata/v1/author/(?id).
How can I post a post on WordPress through a post request without using the UI?
If possible I would also like to have guidance on how I can implement this with ACF fields.
You could create a child theme or a plugin to write your custom functionality.
You can handle AJAX requests with a specific action, and call wp_insert_post() to create posts.
Example to get you started:
add_action( 'wp_ajax_create_post', 'create_post_ajax_handler' );
/**
* Handle the create post ajax request
*/
function create_post_ajax_handler() {
// Get the post title from the ajax request
// You can get whatever you have passed here
// Also, perform any validations you might want
$post_title = $_POST['post_title'];
// Create the post
$post_id = wp_insert_post( array(
'post_title' => $post_title,
'post_status' => 'publish'
// you could also specify the 'post_type', 'meta_input' etc
), true );
// Error handling
if ( is_wp_error( $post_id ) ) {
// Send error response
wp_send_json_error( $post_id->get_error_message() );
}
// Send success response
wp_send_json_success( $post_id );
}
add_action( 'wp_enqueue_scripts', 'enqueue_ajax_script' );
/**
* Enqueue the ajax script
*/
function enqueue_ajax_script() {
// Enqueue your JavaScript file with 'jquery' as a dependency
wp_enqueue_script(
'ajax-script',
plugin_dir_url( __FILE__ ) . 'ajax-script.js',
array( 'jquery' )
);
// Expose the url to admin-ajax.php as `ajax_object.ajaxurl`
wp_localize_script(
'ajax-script',
'ajax_object',
array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) )
);
}
// Set the url as `ajax_object.ajaxurl` which is the url to admin-ajax.php
$.ajax(ajax_object.ajaxurl, {
method: 'POST',
data: {
// Your action should match the name of your 'wp_ajax_{action}' hook
action: 'create_post',
// Pass any data you want
post_title: 'Example post title'
}
})
.done((response) => {
// Do whatever you want with the response (in this example, this would be the post id)
console.log(response);
})
.fail((error) => {
// Handle the errors
console.error(error);
});
You might also want to look into Nonces, which help protect against Cross-Site Request Forgery (CSRF).
Disclaimer: I haven't tested this code, but I hope you get the idea.
Edit: Since you mentioned that you use Advanced Custom Fields:
$post_id = wp_insert_post( array(
'post_title' => $post_title,
'post_status' => 'publish',
// You can set ACF fields in the 'meta_input' array
'meta_input' => array(
'acf_custom_field_name' => 'an example value'
)
), true );
Edit #2: Please read more about AJAX in WordPress on the Codex.
Replying to your comment:
to which URL should I make the ajax request in order for it to trigger?
On the Codex, under AJAX in Plugins > Ajax on the Viewer-Facing Side
You might also use wp_localize_script() to make the URL available to your script, and generate it using this expression: admin_url( 'admin-ajax.php' )
how do I insert the action "wp_ajax_create_post" in my post request?
On the Codex, AJAX in Plugins > Ajax on the Administration Side
Notice how the 'action' key's value 'my_action', defined in our JavaScript above, matches the latter half of the action 'wp_ajax_my_action' in our AJAX handler below.
Based on a quick research, WordPress REST API should be enabled after v4.7 (https://v2.wp-api.org/), however, I cannot access the REST API for my existing or new user by simply appending {name}.wordpress.com/wp-json, ie. https://steventsaotest.wordpress.com/wp-json does not return the expected JSON. Whereas sites like http://www.tribunemedia.com/wp-json works exactly as I wish, as well as my WordPress instance on Digital Ocean.
How can a user whose blog is registered with wordpress.com enable their REST API?
add_action( 'rest_api_init', function () {
$namespace = 'aroma_api';
register_rest_route( $namespace, '/get_signin', array (
'methods' => 'POST',
'callback' => 'get_singnin_data',
));
} );
function get_singnin_data($data)
{
global $wpdb;
$resultdata = array();
$resultdata['message'] = 'Login SuccessFull';
return $resultdata;
}
I have created a custom WooCommerce API endpoint (in a custom WP plugin) for that creates a new order in WooCommerce. I usually use HTTPS and basic auth with consumer key and consumer secret.
This customer API was designed to be accessed by another platform that does not have the ability to enter consumer key and secret in request header. So I would like to disable WooCommerce authentication for this plugin only. I will be authenticating using a field in the original request by comparing a key.
Does anyone know how to do this?
I found the solution:
// To disable authentication, hook into this filter at a later priority and return a valid WP_User
add_filter( 'woocommerce_api_check_authentication', array( $this, 'authenticate' ), 0 );
Comment below lines in file woocommerce/includes/class-wc-rest-authentication.php
if ( !hash_equals( $signature, $consumer_signature ) ) { #codingStandardsIgnoreLine
return new WP_Error( 'woocommerce_rest_authentication_error', __( 'Invalid signature - provided signature does not matchh.', 'woocommerce' ), array( 'status' => 401 ) );
}
If you want to disable authentication for v3, then disable line 152, 153 in plugins/woocommerce/incoudes/api/legacy/v3/class-wc-api-authentication.php
//$this->check_oauth_signature( $keys, $params );
//$this->check_oauth_timestamp_and_nonce( $keys, $params['oauth_timestamp'], $params['oauth_nonce'] );
i created my app on fb with permissions ready to publish on users behalf, the thing is, a regular post has Like and Comment links, like buttons on bottom of the post, i want to add my custom link : VOTE NOW, its a poll post
how can i do that?
someone gave an answer but for js sdk not php, n i cant find it on facebook dev documentation
some gave a close enough solution, but ddnt seem to work on php with modifications
FB.ui({
method: "feed",
link: "LINK_URL",
...
actions: [
{ name: "Read Now", link: "URL TO THE READ NOW " }
]
}, function(response) { console.log(response); });
It seems it's working with /me/feed but with my custom /me/xxxxxx:submitted_a_poll/ its not working
When you make a call with the PHP SDK, you also pass a similar set of parameters:
$attachment = array(
'link' => 'http://your-cool-site.com',
'description' => 'This is the description',
...
'actions' => array(
array(
'name' => 'Vote Now!',
'link' => 'http://your-cool-site.com/vote.php'
)
)
);
$result = $facebook->api('/me/feed/', 'post', $attachment);
All you really have to do is add the relevant action settings to your parameters.