I am fairly new to Wordpress/WooCommerce and I'm struggling to get a custom rest api endpoint registered. The following gives me a 404 when I try the endpoint :
class WC_FastSpring_Fulfillment_Integration extends WC_Integration {
public function __construct() {
$this->id = 'av-wc-fastspring';
$this->method_title = '';
$this->method_description = '';
// Method with all the options fields
$this->init_form_fields();
// Load the settings.
$this->init_settings();
// This action hook saves the settings
add_action( 'woocommerce_update_options_integration_' . $this->id, array( $this, 'process_admin_options' ) );
$namespace = 'test';
$endpoint = '/fs-fulfill-order';
add_action( 'rest_api_init', function () {
$logger = wc_get_logger();
$logger->debug("Registered API Endpoint");
register_rest_route( $namespace, $endpoint, array(
'methods' => 'GET',
'callback' => array($this, 'fulfill_fastspring_order'),
'permission_callback' => function() {
return true;
}
) );
} );
}
public function fulfill_fastspring_order() {
global $woocommerce;
$logger = wc_get_logger();
$logger->debug("Received request to fullfill FastSpring order via Rest API.");
return new WP_REST_Response('Damn !');
}
...
}
It does work if I register outside of the class, but not inside ! Any ideas ? I do see the debug log I've added in the WooCommerce log though, so that add_action does seem to be triggered.
Thanks !
CodePudding user response:
I have corrected your code and split code into functions and now it is working
/**
* Request URL: http://127.0.0.1/wordpress/wp-json/test/fs-fulfill-order
*/
class WC_FastSpring_Fulfillment_Integration extends WC_Integration{
function __construct(){
add_action( 'rest_api_init', array($this, 'rest_api_rest_init_fun'));
}
public function rest_api_rest_init_fun(){
$namespace = 'test';
$endpoint = '/fs-fulfill-order';
register_rest_route( $namespace, $endpoint, array(
'methods' => 'GET',
'callback' => array($this, 'fulfill_fastspring_order'),
'permission_callback' => function() {
return true;
}
));
}
public function fulfill_fastspring_order() {
global $woocommerce;
$logger = wc_get_logger();
$logger->debug("Received request to fullfill FastSpring order via Rest API.");
return new WP_REST_Response('Damn !');
}
}
//call class
new WC_FastSpring_Fulfillment_Integration;
Screenshot: https://prnt.sc/217fait