grayscale key hovering before a keyhole

Creating a cron job to generate an API key with cPanel for your Dhru Fusion GSM cell phone unlock server would be great. Business is good. Many are signing up with you to become unlock code resellers. However, the manual API key creation process is getting old.

When you receive the notification that someone has signed up and activated their account with your Dhru Fusion GSM server, they will most likely request an API key from you.

How to Generate an API Key

In order to generate an API key for them, you have to:

  • Log into your Dhru Fusion GSM server
  • Find the new user’s profile
  • Edit the profile
  • Enable API access
  • Generate an API Access Key
  • Save the profile and send the API Access details

Some Dhru Fusion GSM direct source suppliers prefer the manual API key generation process. Manual activation gives them time to examine every detail regarding the potential reseller. The supplier can then decide whether or not to generate an API key for the user profile under consideration.

For those who would prefer an automated API key generation solution, creating a cron job with cPanel is the way to go. The cron job can be customized to run on a regular schedule, freeing up your time.

NOTE: The automated API key generation process works even better when you have the REGISTRATION MODE set to Automatic in the General Settings of your Dhru Fusion GSM server. If your server is not already enabled for this, follow the [How to Enable Automatic user registration mode for Dhru Fusion GSM] tutorial to see how it’s done.

When creating a cron job with cPanel to automatically generate an API key, you’ll need to use cPanel in order to:

  • Access the File Manager in your web hosting environment
  • Create a cron script .php file in your Dhru Fusion GSM server’s directory
  • Add the new cron job to the schedule

Create the .php Script File for the Cron Job

cpanel files main headerStep 1: Log into your cPanel account and go to the section with the heading FILES

cpanel file manager selected

Step 2: Click on File Manager

cpanel file manager includes folder

Step 3: Navigate to your Dhru Fusion GSM installation directory and select the includes sub-directory or folder

 cpanel file manager add file buttonStep 4: Click on +File at the top to create a file in the includes directory

cpanel file manager add new file dialogType the new file name in the text box. In our example, we’ll call this file: ‘cron_apikey_generate.php’. Of course, you may name it whatever you’d like.

Verify that the new file will be created in the  … /includes directory and click the Create New File button.

cpanel add new file refreshing view

cron file created to generate an api key

The web page will refresh and you see the newly created file appear in the directory.

Editing the .php Script File for the Cron Job

NOTE: This tutorial is not intended to be an in-depth explanation of [PHP] or [SQL]. In an effort to keep things as simple as possible, very brief explanations will accompany the code found below showing how to generate an API key.

Step 1: Select the ‘cron_apikey_generate.php’ file and click ‘Edit’ at the top

Step 2: Add the following text to the file:

date_default_timezone_set('America/Los_Angeles');
$servername = "localhost";
$username = "your_mysql_db_username";
$password = "your_mysql_db_password";
$dbname = "your_mysql_db_name";
// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
// prepare the subject and message for API details
$sql = "SELECT subject, message FROM tbl_emailtemplates WHERE name='API Access Details'";
$from_name = 'your_name';
$from_email = 'your_email@yourdomain.com';
$headers = 'From: '. $from_name .' <'. $from_email .'>';
$subject = '';
$message = '';
$signature = 'Best Regards' . chr(10) . 'The Development Team.';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$subject = $row["subject"];
$message = $row["message"];
}
} else {
// echo "0 results";
}
// collect all of the newly registered users with no API key
// userstatus = 2 (newly registered) OR 0 (fully activated)
$sql = "SELECT id, username, email FROM tblUsers WHERE api_key='' AND userstatus=0";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
// output data of each row
while($row = mysqli_fetch_assoc($result)) {
$id = $row["id"];
$username = $row["username"];
$to = $row["email"];
$api_key = suwp_uuid_make();
$sqlUpdate = "UPDATE tblUsers SET api_key='" . $api_key . "' WHERE id=" . $id;
$replace = array(
‘{$companyname}’ => ‘Your Company Name',
);
$subject = html_entity_decode( strip_tags( suwp_string_replace_assoc( $replace, $subject ) ) );
$replace = array(
'{$username}' => $username,
'{$apiaccesskey}' => $api_key,
'{$adminsignature}' => $signature,
);
$message = html_entity_decode( strip_tags( suwp_string_replace_assoc( $replace, $message ) ) );
if (mysqli_query($conn, $sqlUpdate)) {
// echo "Record updated successfully";
// send an email with details ...
mail($to, $subject, $message, $headers);
} else {
echo "Error updating record: " . mysqli_error($conn);
}
}
} else {
// echo "0 results";
}
// creates unique id for general use
function suwp_uuid_make(){
$string = substr( strtoupper( md5( date('dmYHisu') ) ),0,24 );
$string = substr($string, 0, 3 ) .'-'.
substr($string, 3, 3) .'-'.
substr($string, 6, 3) .'-'.
substr($string, 9, 3) .'-'.
substr($string, 12, 3) .'-'.
substr($string, 15, 3) .'-'.
substr($string, 18, 3) .'-'.
substr($string, 21);
return $string;
}
// replace variables with values
function suwp_string_replace_assoc(array $replace, $target) {
return str_replace(array_keys($replace), array_values($replace), $target);
}
mysqli_close($conn);

Explaining the .php Script File

date_default_timezone_set

Sets the default timezone used by all date/time functions in the script. Some scripts will behave strangely if the designated timezone is missing.

$servername = "localhost";

$username = "your_mysql_db_username";

$password = "your_mysql_db_password";

$dbname = “your_mysql_db_name”;

Replace these values with those for your web hosting environment.

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

 

Create the connection to the mySQL database that holds all of the data for your Dhru Fusion GSM server.

// prepare the subject and message for API details

$sql = "SELECT subject, message FROM tbl_emailtemplates WHERE name='API Access Details'";
$from_name = 'your_name';
$from_email = 'your_email@yourdomain.com';
$headers = 'From: '. $from_name .' <'. $from_email .'>';
$subject = '';
$message = '';
$signature = 'Best Regards' . chr(10) . 'The Development Team.';
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $subject = $row["subject"];
        $message = $row["message"];
    }
} else {
    // echo "0 results";
}

 

Access the Dhru Fusion GSM default API Access Details email template and extract the subject and message values. Also creates the header and a basic signature to add to the message.

// collect all of the newly registered users with no API key
// userstatus = 2 (newly registered) OR 0 (fully activated)
$sql = "SELECT id, username, email FROM tblUsers WHERE api_key='' AND userstatus=0";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    // output data of each row
    while($row = mysqli_fetch_assoc($result)) {
        $id = $row["id"];
        $username = $row["username"];
        $to = $row["email"];
        $api_key = suwp_uuid_make();
        $sqlUpdate = "UPDATE tblUsers SET api_key='" . $api_key . "' WHERE id=" . $id;
        $replace = array(
          ‘{$companyname}’ => ‘Your Company Name',
        );
        $subject = html_entity_decode( strip_tags( suwp_string_replace_assoc( $replace, $subject ) ) );
        $replace = array(
          '{$username}' => $username,
          '{$apiaccesskey}' => $api_key,
          '{$adminsignature}' => $signature,
        );
        $message = html_entity_decode( strip_tags( suwp_string_replace_assoc( $replace, $message ) ) );
        if (mysqli_query($conn, $sqlUpdate)) {
            // echo "Record updated successfully";
            // send an email with details ...
            mail($to, $subject, $message, $headers);
        } else {
            echo "Error updating record: " . mysqli_error($conn);
        }
    }
} else {
    // echo "0 results";
}

 

Collects all fully activated, registered resellers and:

1. Generates an API key and adds it to the reseller’s profile.

2. Emails the reseller with the API key using the message values from the API Access Details email template.

// creates unique id for general use
function suwp_uuid_make(){
    $string = substr( strtoupper( md5( date('dmYHisu') ) ),0,24 );
    $string = substr($string, 0, 3 ) .'-'.
    substr($string, 3, 3) .'-'.
    substr($string, 6, 3) .'-'.
    substr($string, 9, 3) .'-'.
    substr($string, 12, 3) .'-'.
    substr($string, 15, 3) .'-'.
    substr($string, 18, 3) .'-'.
    substr($string, 21);
    return $string;
}

 

Generates a unique string to be used as the API key. The string will be created using the following format:

XXX-XXX-XXX-XXX-XXX-XXX-XXX-XXX

// replace variables with values
function suwp_string_replace_assoc(array $replace, $target) {
    return str_replace(array_keys($replace), array_values($replace), $target);

}

Replaces variables that appear in the API Access Details email template with actual text values. This function receives two text parameters: $replace and $target.

For example, the $replace value = ‘{$apiaccesskey}’ and the $target value = ‘XXX-XXX-XXX-XXX-XXX-XXX-XXX-XXX’, which represents the actual API key.

‘{$apiaccesskey}’ will be replaced with ‘XXX-XXX-XXX-XXX-XXX-XXX-XXX-XXX’ wherever it appears in the email message.

mysqli_close($conn);

Closes the connection to the mySQL database.

Step 3: Click the Save Changes button to save the .php script to be used for the cron job

Step 4: Click the Close button to close the page and return to the directory

Now that you’ve created the .php script file, it’s time to add the scheduled Cron Job that will reference this file.

Add a New Scheduled Cron Job

cpanel advanced heading to create cron jobStep 1: Navigate back to the cPanel Home page and find the section labeled ADVANCED.

cpanel cron jobs icon selectedStep 2: Click on Cron Jobs to open the page

Step 3: Select the appropriate schedule for running the cron job under the Common Settings drop-down list in the ‘Add New Cron Job’ section

Be careful when choosing a schedule to run the cron job. If it runs too often, the job can degrade the server performance.

cpanel cron job common settings schedule selectionSince this cron job will be generating API keys, a setting like Once Per Five Minutes(*/5****) should be appropriate.

cpanel cron job settings to generate an api keyStep 4: Type the PHP command and location of the .php script file in the Command: text field

cpanel cron command line to generate an api keyFor example:

php -q /home/yourserverdirectory/public_html/yourdomain.com/includes/cron_apikey_generate.php

cpanel adding new cron job to generate an api keyStep 5: Click theAdd New Cron Job button to add the .php script to the schedule with the other cron jobs

On a Final Note

Creating a cron job to generate an API key with cPanel can save you a lot of time. Additionally, your resellers won’t have to wait long before they can start importing remote unlock services into their website.

When a new user registers with your Dhru Fusion GSM server and their user profile is fully activated, the cron job that you created will:

  • Find the new user’s fully activated profile
  • Generate an API Access Key and add it to the user profile
  • Save the profile and send the API Access details to the user

If your unlock code resellers use the StockUnlocks plugin for WordPress, then they will be able to configure their website to:

1. Securely connect with your Dhru Fusion GSM server

2. Use the API from Dhru Fusion to automatically place orders with you

3. Improve customer satisfaction by speeding up the unlock code delivery process

What other functionality would you like to see explained regarding the Dhru Fusion GSM unlock server? Let us know!

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.