Using WordPress as API for Laravel (2)

Connecting Laravel to WordPress

Leonie Derendorp
PLint-sites
4 min readMay 8, 2019

--

Many custom-made applications require an interface to let admins control the content of their application. There are several options for the content management part of the application. You can develop it yourself, use an admin package, or use a full open source CMS. The latter is particularly interesting if the content mainly consists of text, like blog posts and pages.

Nowadays, we use Laravel to develop custom websites, webshops and web apps, because this framework has a lot of flexibility. In the past, we mainly developed our websites using WordPress. Although WordPress is no longer our default framework of choice, the admin panel lends itself perfectly to create pages and posts, keep track of revisions, structure posts using categories and tags, manage media like file uploads and handle comments.

Recently, we combined Laravel and WordPress in a project where we re-developed our personal cycling blog. This blog was originally built in WordPress, hence all posts were stored in the WordPress database. We liked to keep using the content management features of WordPress, but wanted to build the blog itself in Laravel (mainly because we are planinng to add more custom features in the future). Therefore, we decided to use WordPress as API for our Laravel app.

In part 1 we described how to setup and configure WordPress as API. In this post we will setup up the authentication and let the Laravel app communicate with the WordPress app. The actual retrieval of data via the WordPress API will be the subject of the next post.

Setup

We assume you have a working Laravel installation, otherwise create a new Laravel project. How to setup Laravel is beyond the scope of this post, but detailed instructions can be found in the documentation (https://laravel.com/docs/5.8/installation). Additionally, basic knowledge on OAuth authentication is required.

In our WordPress app, we installed the WP OAuth server plugin as described in our previous post. Before we can actually retrieve data from WordPress via the API, we need an access token. Go to the admin panel of WordPress app, navigate to the WP OAuth server section and register the Laravel app. Choose a name and fill in the redirect URI (in the next section we will explain what this URI should be), and you will get a client secret and a client id.

Navigate to the WP OAuth server in the WordPress app and go to ‘create client’. You will see this screen where you can set the client name and redirect URI.

Also check the settings section of the OAuth Server plugin. Here you can specify the token lifetime, token length and some other settings.

Next, add the client_id and client_secret to the .env file of the Laravel app and add the WordPress app as a service:

.env file

WP_API_BASE_URL=https://api.domainname.com WP_API_CLIENT_ID=client_id 
WP_API_CLIENT_SECRET=client_secret

config/services.php

'wp_api' => [ 
'url' => env('WP_API_BASE_URL'),
'client_id' => env('WP_API_CLIENT_ID'),
'client_secret' => env('WP_API_CLIENT_SECRET'),
],

Get an accesstoken

We create a dedicated WordPress authentication controller to get access tokens. Two routes are added to the routes/web.php file of the Laravel app that are only accessible for authenticated users. This means that you first have to login to the Laravel app before you can retrieve the access token for the WordPress API. We use the authentication scaffolding of Laravel to easily setup auth routes.

Below are the authentication routes. The second route is the URI that you’ll use in WordPress, when creating the client for the OAuth Server plugin.

Route::group(['middleware' => 'auth'], function(){ 
Route::get('get-token', 'WP\AuthController@getToken');
Route::get('process-token', 'WP\AuthController@processToken'); });

Next, we create the WP/AuthController and add these two methods.

Get a token

public function getToken() { 
$url = config('services.wp_api.url').'/oauth/authorize/?client_id='.config('services.wp_api.client_id').'&response_type=code';
return redirect()->away($url);
}

This route simply redirects to the endpoint of the WordPress app that returns an authorization code. This code can be used in the next method to retrieve the access token, which is required to retrieve posts from the API.

Process token

public function processToken(Request $request) 
{
$client = new \GuzzleHttp\Client();
$url = config('services.wp_api.url').'/oauth/token';
$data = [
'grant_type' => 'authorization_code',
'code' => $request->code,
'client_id' => config('services.wp_api.client_id'),
'client_secret' => config('services.wp_api.client_secret')
];
$params = [
'form_params' => $data,
'headers' => [
'Accept' => 'application/json'
]
];
try {
$response = $client->request('POST', $url, $params);
$decodedBody = json_decode($response->getBody()->getContents(), true);
$accessToken = $decodedBody['access_token']; if ($accessToken) {
DB::table('WpAuth')->truncate();
DB::table('WpAuth')->insert([
'access_token' => $accessToken,
'updated_at' => Carbon::now()
]);
}
return redirect('dashboard')->with('message', 'Access token has been updated');
}
catch (\GuzzleHttp\Exception\RequestException $e) {
$errors = $e->getResponse()->getBody();
return response($errors,$e->getCode());
}
}

Some notes on this piece of code:

  • The Guzzle http library is used to perform requests to the WordPress API.
  • We store the access token in our Laravel database. Alternatively, you can add the token to the .env file.
  • After storing the access token, we redirect to the dashboard page, but you can do whatever you like. The most important thing is that you get the access token and store it somewhere where you can easily re-use it.

Refresh token

Ideally, access tokens have a short lifetime for security considerations. You have to refresh this access token at regular times using the refresh token. However, the OAuth plugin used in WordPress requires a premium (not free) license for this functionality. If you would like to automate the process of refreshing access tokens, purchase a license and follow the instructions. Otherwise, use a somewhat longer lifetime for the access token, and refresh it manually.

Summary

This is the second post on using the WordPress as API for a Laravel application. We described how to setup the authentication, so the Laravel app is ready to communicate with the WordPress app via its API. The next step is actual retrieval of posts and pages created in WordPress. This will be the subject of the next blog post.

Originally published at https://www.blog.plint-sites.nl on May 8, 2019.

--

--

Leonie Derendorp
PLint-sites

Development of modern websites, webshops and web apps using Laravel. Owner of PLint-sites.