Last active
March 18, 2022 16:04
-
-
Save krasenslavov/8952fe98781b783ff4beaa04e27dedd9 to your computer and use it in GitHub Desktop.
API server for our license key feature. Visit blog posts https://bit.ly/2Vwobsu
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Load up WordPress. | |
require_once '../wp-load.php'; | |
// Include license key funcitons that handle the options. | |
require_once 'options.php'; | |
// Include license key controller functions that handle the routes. | |
require_once 'controllers.php'; | |
// Autoloader for Composer with (all packages and dependencies). | |
require_once 'vendor/autoload.php'; | |
// Get all WordPress users of with role subscriber. | |
$users = array(); | |
$subscribers = get_users(['role__in' => ['subscriber']]); | |
foreach ($subscribers as $subscriber) { | |
$license_key = get_license_key($subscriber->user_login); | |
$users[$subscriber->user_login] = $license_key['password']; | |
} | |
// Instantiate Slim PHP framerwork. | |
$app = new Slim\App(); | |
// Basic authentication. | |
$app->add(new \Slim\Middleware\HttpBasicAuthentication(array( | |
'realm' => 'Protected', | |
// Restricted folder. | |
// For your setup may need to add `/api` as your restricted folder. | |
'path' => '/', | |
// Working over HTTPS for improved security. | |
'secure' => true, | |
// All register users (out of WordPress). | |
'authenticator' => function ($args) use($users) { | |
if (password_verify($args['password'], $users[$args['user']])) { | |
return true; | |
} | |
return false; | |
}, | |
// Use to return an error message if the auth fails. | |
'error' => function ($request, $response, $arguments) { | |
$data = []; | |
$data['status'] = 'error'; | |
$data['message'] = $arguments['message']; | |
$body = $response->getBody(); | |
$body->write(json_encode($data, JSON_UNESCAPED_SLASHES)); | |
return $response->withBody($body); | |
} | |
))); | |
// Grouping API routes. | |
// For your setup may need to add `/api` as you group top URL. | |
$app->group('/', function() use ($app) { | |
// Retrieve license key after authentication. | |
$app->post('/license', 'get_license'); | |
// Activate license key (+1) active_installs and add site URL. | |
$app->post('/license/activate', 'activate_license'); | |
// Deactivate license key (-1) for active installs. | |
$app->post('/license/deactivate', 'deactivate_license'); | |
// Development mode only. (remove these paths for production) | |
$app->get('/license', 'get_license'); | |
$app->get('/license/activate', 'activate_license'); | |
$app->get('/license/deactivate', 'deactivate_license'); | |
}); | |
// Run the server app. | |
$app->run(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment