How to manage woocommerce subscription with api? - woocommerce

I'm trying to get all subscriptions from php with this code:
<?php
require __DIR__ . '/vendor/autoload.php';
use Automattic\WooCommerce\Client;
$woocommerce = new Client(
'https://www.magazzinoperfetto.it', // Your store URL
'ck_c92b6b6452XXXXXXXXXXXXXXXXXX',
'cs_e3380e1c07XXXXXXXXXXXXXXXXXX',
[
'wp_api' => true, // Enable the WP REST API integration
'version' => 'wc/v2' // WooCommerce WP REST API version
]
);
print_r($woocommerce->get('subscriptions'));
?>
If I use the api with woocommerce product etc... it's functionally. But with the subscription I receive this error:
Fatal error: Uncaught exception 'Automattic\WooCommerce\HttpClient\HttpClientException' with message 'Error: Nessun percorso fornisce una corrispondenza tra l'URL e le modalità di richiesta [rest_no_route]' in /var/www/vhosts/magazzinoperfetto.it/httpdocs/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php:324 Stack trace: #0 /var/www/vhosts/magazzinoperfetto.it/httpdocs/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(349): Automattic\WooCommerce\HttpClient\HttpClient->lookForErrors(Array) #1 /var/www/vhosts/magazzinoperfetto.it/httpdocs/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php(385): Automattic\WooCommerce\HttpClient\HttpClient->processResponse() #2 /var/www/vhosts/magazzinoperfetto.it/httpdocs/vendor/automattic/woocommerce/src/WooCommerce/Client.php(82): Automattic\WooCommerce\HttpClient\HttpClient->request('subscriptions', 'GET', Array, Array) #3 /var/www/vhosts/magazzinoperfetto.it/httpdocs/change-sottoscrizione.php(22): Automattic\WooCommerce\ in /var/www/vhosts/magazzinoperfetto.it/httpdocs/vendor/automattic/woocommerce/src/WooCommerce/HttpClient/HttpClient.php on line 324

you have to create the new endpoint like get_subcription and create the once callback function with this function you can write your code for the get subscription and return it from the callback function.
add_action( 'rest_api_init', 'custom_api_endpoints' );
function custom_api_endpoints () {
register_rest_route( 'wc/v2', 'get_subcription', array(
'methods' => 'POST',
'callback' => 'custom_subscription_endpoint_handler'
) );
}
function custom_subscription_endpoint_handler () {
return $woocommerce->get('subscriptions');
}

Related

I can't access wp url parameter

I'm trying to add an url parameter to a custom wp rest api endpoint, but when I access the endpoint using this url: mysite.com/wp-json/booking/pris?name=carl, I get this error:
SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
Here is my code:
add_action( 'rest_api_init', 'my_register_route_for_price' );
function my_register_route_for_price() {
global $wp;
$wp->add_query_var( 'name' );
register_rest_route( 'booking', 'pris', array(
'methods' => 'GET',
'callback' => 'get_price_callback',
)
);
}
function get_price_callback() {
$param = $request->get_url_params( 'name' );
return rest_ensure_response($param);
}
That's a WordPress security feature.
Undefined WordPress query variable outside the scope of the WP_Query class need to be defined first.
WP::add_query_var( string $qv )
Adds a query variable to the list of public query variables.
Use Case Scenario
<?php
add_action( 'init','wp67408336' );
function wp67408336() {
global $wp;
$wp->add_query_var( 'name' );
};
In any case
<?php
$name = htmlspecialchars( $_GET["name"] );

How to generate API endpoints for my Products from Wordpress using Woocommerce REST API?

I have created a Shopping Cart Website with Wordpress and Woocommerce Plugin. Now I want to access these products from my Ionic App.
Now, whenever I try to access these endpoints using Woo REST API. It gives the following Errors.
http://localhost:8888/myshop/wp-json/wc/v3/products/
{
code: "rest_no_route",
message: "No route was found matching the URL and request method",
data: {
status: 404
}
}
Please check and verify WooCommerce REST API option is added under,
www.mydomain.com/wp-admin/admin.php?page=wc-settings&tab=advanced&section=keys
For making custom API end points, this snippet can be used.
add_action('rest_api_init', 'init_my_rest_api');
function init_my_rest_api() {
register_rest_route('myaction/v1', '/getdetails/', array(
'methods' => 'POST',
'callback' => 'gather_details',
));
}
http://localhost:8888/wp-json/wc/store/products
Try this endpoint for list products
My Solution,
Step 1:
Create a page:
<?php
/*
Template Name: Products API
*/
$productlist = array();
$vnfaster = new WP_Query(array(
'post_type'=>'product',
'post_status'=>'publish',
'orderby' => 'ID',
'order' => 'DESC',
));
while ($vnfaster->have_posts()) : $vnfaster->the_post();
$productlist[] = array( 'id' => $post->ID, 'title' => $post->post_title );
endwhile ; wp_reset_query();
echo json_encode( $productlist );
?>
Step 2:
I have a Page:
http://localhost:8888/myshop/products-api
Output:
{
id: "1",
title: "Product 1",
...
}

Wordpress | Writing custom APIs for ajax calls or reports

If I have to develop a simple custom API to be accessed directly say, to display "Hello World!", then what all steps I need to do?
Let's say the APIs reside in [/themes/my_theme/_apis/]
You need to go to functions.php of your theme file and then write this :
add_action('wp_ajax_my_theme_ajax_method', 'my_theme_ajax_method');
add_action('wp_ajax_nopriv_my_theme_ajax_method', 'my_theme_ajax_method');
function my_theme_ajax_method(){
return 'Hello World'
}
add_action( 'wp_enqueue_scripts', 'my_theme_frontend_custom_scripts' );
function my_theme_frontend_custom_scripts(){
wp_localize_script( 'ajax-script', 'MyTheme', array(
'ajaxurl' => admin_url( 'admin-ajax.php' ),
'action' => array (
'MyAjaxMethod' => 'my_theme_ajax_method',
)
) );
}
And then in your frontend consider index.php you can write this
jQuery(document).ready(function(){
jQuery.ajax ({
type : 'get',
url : MyTheme.ajaxurl,
data : {
action : MyTheme.action.MyAjaxMethod,
},
}).done(function(data){
console.log(data); // <-- prints hello world
})
});

Search all WP REST API Posts with angular

I using angular to display posts with the WP Rest Api. However the search will only filter through the first 99 posts since that is the max. Is there anyway to yield all results?
Create a custom endpoint that utilizes a custom query. Something like this:
add_action( 'rest_api_init', function () {
register_rest_route( 'search', '/all', array(
'methods' => 'GET',
'callback' => 'get_all_posts',
));
});
Endpoint: yoursite.com/wp-json/search/all
function get_all_posts() {
$query = new WP_Query(
array( 'posts_per_page' => -1 )
);
return json_encode( $query );
}
Remember to clear the permalinks when registering new endpoints!
Getting posts is capped at 100 per page, but each request returns the header X-WP-TotalPages which gives you the number of total pages in your request.
So do a request for the next pages...
var url = your-route.example/wp-json/wp/v2/posts?per_page=100
$http.get(url).
success(function(response) {
var pagesNum = response.headers('X-WP-TotalPages')
for (var i = 2; i <= pagesNum; i++) {
$http.get(url+'&page='+i)
.success(function(response){
// do something with the next page data
})
}
});
...and so on, until you've gone through all the available pages.
Source: REST API Handbook

Custom route endpoint for WP-REST API gives "code": "rest_no_route", error

I am following this tutorial to create custom end points to WP-API .
I am always getting this error on hitting /wp-json/custom-plugin/v2/get-all-post-ids/ on postman to test :
{
"code": "rest_no_route",
"message": "No route was found matching
the URL and request method ",
"data": {
"status": 404
}
}
I have created a custom-plugin.php file in /plugins/custom-plugin/ directory .
<?php
if ( ! defined( 'ABSPATH' ) ) exit;
add_action( 'rest_api_init', 'dt_register_api_hooks' );
function dt_register_api_hooks() {
register_rest_route( 'custom-plugin/v2', '/get-all-post-ids/', array(
'methods' => 'GET',
'callback' => 'dt_get_all_post_ids',
)
);
}
// Return all post IDs
function dt_get_all_post_ids() {
if ( false === ( $all_post_ids = get_transient( 'dt_all_post_ids' ) ) ) {
$all_post_ids = get_posts( array(
'numberposts' => -1,
'post_type' => 'post',
'fields' => 'ids',
) );
// cache for 2 hours
set_transient( 'dt_all_post_ids', $all_post_ids, 60*60*2 );
}
return $all_post_ids;
}
?>
Ensure your callback to add_action( 'rest_api_init', 'dt_register_api_hooks' ); is being run.
In my case, my callback was not being called because I was using add_action('rest_api_init', ...) too late; the action had already fired. As in, my call to register_rest_route() never even happened.
I hope my answer can be useful to some as well.
For a very similar problem, while I was designing an API in WordPress, I also got the same "code": "rest_no_route",... error on some websites and not on other ones. I traced it back to the fact that POST requests were transformed into GET requests so they weren't recognized by my plugin.
The conversion from POST to GET was made before WordPress even started. I was able to pinpoint the problem and solve it by adding the following header, as explained in details here:
headers: { 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8' }

Resources