Chat with us, powered by LiveChat

This website uses cookies

Our website, platform and/or any sub domains use cookies to understand how you use our services, and to improve both your experience and our marketing relevance.

How to Install Let’s Encrypt SSL Through Cloudways API

October 27, 2016

5 Min Read
Reading Time: 5 minutes

Cloudways API has been released to all developers and re-sellers with some excellent third-party solutions. To educate the developers, I have written this tutorial which explains the installation of Let’s-Encrypt to Cloudways application.

Installation Of Lets Encrypt

Guzzle Installation

I have used Guzzle to handle all HTTP requests that will be sent to the API. To install Guzzle, run the following command:

composer require guzzlehttp/guzzle

command line

Once the installation is complete, create a class which interacts with the API.

Class To Connect Cloudways API

Create a file named CloudwaysAPIClient.php which involve vendor/autoload and define the Guzzle classes. Constructor class gets the client email as well as API Key which creates a token using prepare_access_token(). This function sends the request to Cloudways API for a token. Once the token is received, it is saved in the variable $accessToken. Next, I have created StatusCodeHandling() function for handling all the status codes generated by the API.

<?php
require 'vendor/autoload.php';
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
Class CloudwaysAPI
{
	private $client = null;
	const API_URL = "https://api.cloudways.com/api/v1";
	var $auth_key;
	var $auth_email;
	var $accessToken;
	public function __construct($email,$key)
	{
		$this->auth_email = $email;
		$this->auth_key = $key;
		$this->client = new Client();
		$this->prepare_access_token();
	}
	public function prepare_access_token()
	{
		try
		{
			$url = self::API_URL . "/oauth/access_token";
			$data = ['email' => $this->auth_email,'api_key' => $this->auth_key];
			$response = $this->client->post($url, ['query' => $data]);
			$result = json_decode($response->getBody()->getContents());
			$this->accessToken = $result->access_token;
		}
		catch (RequestException $e)
		{
			$response = $this->StatusCodeHandling($e);
			return $response;
		}
	}
	public function StatusCodeHandling($e)
	{
		if ($e->getResponse()->getStatusCode() == '400')
		{
			$this->prepare_access_token();
		}
		elseif ($e->getResponse()->getStatusCode() == '422')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '500')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '401')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $response;
		}
		elseif ($e->getResponse()->getStatusCode() == '403')
		{
			$response = json_decode($e->getResponse()->getBody(true)->getContents());
			return $e->getResponse()->getStatusCode();
		}
	}
	public function get_servers()
	{
		try
		{
			$url = self::API_URL . "/server";
			$option = array('exceptions' => false);
			$header = array('Authorization'=>'Bearer ' . $this->accessToken);
			$response = $this->client->get($url, array('headers' => $header));
			$result = json_decode($response->getBody()->getContents());
			return $result;
		}
		catch (RequestException $e)
		{
			$response = $this->StatusCodeHandling($e);
			return $response;
		}
	}
	public function AddApplication($server_id,$app_id,$ssl_domain,$ssl_domain_alias,$ssl_email)
	{
		try
		{
			$url = self::API_URL . "/security/lets_encrypt_install";
			$data = ['server_id' => $server_id,'app_id' => $app_id,'ssl_domain' => $ssl_domain,'ssl_domain_alias' => $ssl_domain_alias, 'ssl_email'=> $ssl_email];
			$header = array('Authorization'=>'Bearer ' . $this->accessToken);
			$response = $this->client->post($url, array('query' => $data,'headers' => $header));
			return json_decode($response->getBody()->getContents());
		}
		catch (RequestException $e)
		{
            $response = $this->StatusCodeHandling($e);
			return $response;
		}
	}
}
?>

get_servers() is the function that gets servers and applications using Cloudways API.

public function get_servers()
	{
		try
		{
			$url = self::API_URL . "/server";
			$option = array('exceptions' => false);
			$header = array('Authorization'=>'Bearer ' . $this->accessToken);
			$response = $this->client->get($url, array('headers' => $header));
			$result = json_decode($response->getBody()->getContents());
			return $result;
		}
		catch (RequestException $e)
		{
			$response = $this->StatusCodeHandling($e);
			return $response;
		}
	}

Now Calling AddApplication() which required parameters

  • Server ID
  • Application ID
  • SSL Domain
  • SSL Domain Alias
  • SSL Email
public function AddApplication($server_id,$app_id,$ssl_domain,$ssl_domain_alias,$ssl_email)
	{
		try
		{
			$url = self::API_URL . "/security/lets_encrypt_install";
			$data = ['server_id' => $server_id,'app_id' => $app_id,'ssl_domain' => $ssl_domain,'ssl_domain_alias' => $ssl_domain_alias, 'ssl_email'=> $ssl_email];
			$header = array('Authorization'=>'Bearer ' . $this->accessToken);
			$response = $this->client->post($url, array('query' => $data,'headers' => $header));
			return json_decode($response->getBody()->getContents());
		}
		catch (RequestException $e)
		{
            $response = $this->StatusCodeHandling($e);
			return $response;
		}
	}

In above code API_URL . “/security/lets_encrypt_install” is the URL of installing Let’s-Encrypt

After that, create a new file index.php for the application. Through this, get 

$server_id,$app_id,$ssl_domain,$ssl_domain_alias,$ssl_email
<?php
include 'CloudwaysAPIClient.php';
$api_key = 'Your API Key';
$email = 'owais.alam@cloudways.com';
$cw_api = new CloudwaysAPI($email, $api_key);
$servers = $cw_api->get_servers();
$success = null;
if (!empty($_POST)) {
    $server_id = $_POST['server_id'];
    $app_id = $_POST['app_id'];
    $ssl_domain = $_POST['ssl_domain'];
    $ssl_domain_alias = $_POST['ssl_domain_alias'];
    $ssl_email = $_POST['ssl_email'];

    $result = $cw_api->AddApplication($server_id, $app_id, $ssl_domain, $ssl_domain_alias,$ssl_email);
    $error = null;
    //echo '<pre>';print_r($result);echo '</pre>';
     if (isset($result->operation_id)) {
        $success["message"] = "Congragulation You have Done";
    } else {
        foreach ($result as $key => $value) {
            foreach ($value as $keys => $values) {
                if ($values->message) {
                    $success["$key"] = $values->message;
                }
            }
        }
        $success["message"] = "Installation Of Lets-Encrypt";
    }
}
?>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Application</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"
          integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap-theme.min.css"
          integrity="sha384-rHyoN1iRsVXV4nD0JutlnGaslCJuC7uwjduW9SVrLvRYooPp2bWYgmgJQIXwl/Sp" crossorigin="anonymous">
    <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"
            integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa"
            crossorigin="anonymous"></script>
</head>
<body>
<div class="container-fluid">
    <div class="row">
        <div class="col-md-10">
            <form class="form-horizontal" method="POST"
                  action=" ">
                <fieldset>

                    <legend>Installation Of Lets-Encrypt</legend>
                    <!-- Text input-->
                    <!--first input start-->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="label">Server ID</label>
                         <div class="col-md-4">
                            <input id="server_id" name="server_id" type="text" placeholder="Server ID" class="form-control input-md" required>
                         </div>
                    </div>
                    <!--first input end-->
                    <!--second input start-->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="label">APP ID</label>

                        <div class="col-md-4">
                            <input id="app_id" name="app_id" type="text" placeholder="APP ID" class="form-control input-md" required>
                         </div>
                    </div>
                    <!--second input end-->
                    <!--Third input start-->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="label">SSL Domain</label>

                        <div class="col-md-4">
                            <input id="ssl_domain" name="ssl_domain" type="text" placeholder="SSL Domain" class="form-control input-md" required>
                        </div>
                    </div>
                    <!--Third input end-->
                    <!--Fourth input start-->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="label">SSL Domain Alias</label>

                        <div class="col-md-4">
                            <input id="ssl_domain_alias" name="ssl_domain_alias" type="text" placeholder="SSL Domain Alias" class="form-control input-md" required>

                        </div>
                    </div>
                    <!--Fourth input end-->
                    <!--Fifth input start -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="label">SSL Email</label>

                        <div class="col-md-4">
                            <input id="ssl_email" name="ssl_email" type="text" placeholder="SSL Email" class="form-control input-md" required>
                        </div>
                    </div>
                    <!--Fifth input end -->
                   <!-- Button -->
                    <div class="form-group">
                        <label class="col-md-4 control-label" for="add"></label>

                        <div class="col-md-4">
                            <button id="add" class="btn btn-primary">Add Application</button>
                            <span class="bg-success"><?php  echo $success["message"]   ?> </span>
                        </div>
                    </div>
                </fieldset>
            </form>
        </div>
    </div>
</div>
</body>
</html>

Empty Form

You can get server ID from the following screen:

Server_id

Also, you can get all these values by using var_dump function. Once you put all the fields you can get this:

Success Message

 

Check your new certificate

Once the Let’s Encrypt SSL certificate deploys on your application, you can check and verify it by using any free online SSL checker such as https://www.sslshopper.com/ssl-checker.html. You should see something like this:

Verification Check

Conclusion

Through this tutorial, you should be able to install Let’s-Encrypt. However, follow these steps, and you will be able to see that the code works in a proper manner. Leave a comment below if you wish to add to the conversation or have a question in mind!

Share your opinion in the comment section. COMMENT NOW

Share This Article

Start Growing with Cloudways Today.

Our Clients Love us because we never compromise on these

Owais Alam

is the WordPress Community Manager at Cloudways - A Managed WooCommerce Hosting Platform and a seasoned PHP developer. He loves to develop all sorts of websites on WordPress and is in love with WooCommerce in particular. You can email him at owais.alam@cloudways.com

Get Our Newsletter
Be the first to get the latest updates and tutorials.

Do you like what you read?

Get the Latest Updates

Share Your Feedback

Please insert Content

Thank you for your feedback!

BFCM 2019