Categories
php Plugin wordpress

WP REST with JWT

Last updated on November 1st, 2020 at 15:20

Using the WordPress REST API with JWT authentication

Step 1. Install this plugin => https://wordpress.org/plugins/advanced-access-manager/. The free version will suffice. This goes on the site you will be xtracting data from. The REST API must be enabled in the WordPress settings.

Step 2. Configure the plugin and on it’s Settings tab add the Secret as per this page => https://aamplugin.com/article/how-to-authenticate-wordpress-user-with-jwt-token

On the Page pulling the data from the above server, use the following PHP code :

function getToken()
{
	$token="";
	$html="<div>";
	
	$postRequest = array(
		'username' => 'ANY_ADMIN_USERNAME',
		'password' => 'THE_PASSWORD_FOR_SAID_USER'
	);
	$h=http_build_query($postRequest);
	$ch = curl_init("https://YOUR_SERVER_NAME.COM/wp-json/aam/v1/authenticate");
	curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS,$h);
	curl_setopt($ch, CURLOPT_FAILONERROR, true);
	curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
	curl_setopt($ch, CURLOPT_VERBOSE, true);
	
    $server_output = curl_exec ($ch);
	$info = curl_getinfo($ch);
	//$html="<pre>".print_r($info,true)."</pre>";
	//echo $html;
    if ($server_output === false)
	{
        die('Error getting JWT token on WordPress for API integration.');
    }
    $server_output = json_decode($server_output);

    if ($server_output === null && json_last_error() !== JSON_ERROR_NONE)
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    if (!empty($server_output->token))
	{
        $token = $server_output->token; # Token is here
        curl_close ($ch);
        return $token;
    }
	else
	{
        die('Invalid response getting JWT token on WordPress for API integration.');
    }
    return false;
}

The when you need the token, call it like such :

$mytoken=getToken();

And that’s about it…..

Categories
php Plugin wordpress

WordPress Basic Plugin

Last updated on November 1st, 2020 at 15:59

Below is a very simple working example of a plugin. Create a directory in your plugins directory, create a php file and copy the below into it.

Then from the wordpress plugins menu simply activate it.

Just know that this plugin does absolutely nothing other than to show the basic setup, including public and protected variables.

<?php
/*
	Plugin Name: Plugin Demo
	Plugin URI: https://southcoasthosting.com/
	Description: Just a plugin demo to show how to set up the class
	Author: Gavin Simpson
	Version: 1.0
	Author URI: https://southcoasthosting.com
*/

class plugindemo
{
	protected $namespace;
	public $posttype="plugindemo";
	public static function init()
	{
		$class = __CLASS__;
		new $class;
	}
	public function __construct()
	{
		$this->namespace=test;
	}
	public function test_function($namespace)
	{
		$this->namespace=$namespace;
	}
}

add_action('init',array('plugindemo','init'));
?>