Category: WHMCS

27 Jan

How to know WHMCS Admin Username for local API call?

For calling WHMCS API’s internally from the WHMCS, we have a function named
localAPI. To call this function we have to pass
1)command; What api you would like to call.
2)data
3)admin user name of the WHMCS.

A sample API command UpdateClientProduct can be called as shown below.

        $command = 'UpdateClientProduct';
        $postData = array(
            'serviceid' => 11, // your service id
            'recurringamount' => 17,// recurring amount
        );
        //if WHMCS admin name is admin
        $adminUsername = "admin"; 
        $results = localAPI(
                       $command,
                       $postData, 
                       $adminUsername
        );

We hard coded the admin user name in the above code.
But hard coding the admin user name is a bad way of coding.
The code won’t work if admin username is changed or the code is uploaded
to another WHMCS where admin username is different.

So we can use below function to get the admin name.

use Illuminate\Database\Capsule\Manager as Capsule;
function getAdminUserName() {
    $adminData = Capsule::table('tbladmins')
            ->where('disabled', '=', 0)
            ->first();
    if (!empty($adminData))
        return $adminData->username;
    else
        die('No admin exist. Why So?');
}

So the API can be called as below.

  $command = 'UpdateClientProduct';
  $postData = array(
            'serviceid' => $product['service_id'],
            'recurringamount' => $deducted_amount,
  );
  $adminUsername = getAdminUserName();
  $results = localAPI(
                 $command, 
                 $postData, 
                $adminUsername
  );
16 Jan

Calling worldsteram.nl APIs from WHMCS

Calling worldsteram.nl APIs from WHMCS.

worldsteram.nl Provides API ID, and that must be used with API Calls.
So first of all create a file named worldstream.php and it must be
uploaded to the folder /modules/servers/worldstream.

<?php
function worldstream_ConfigOptions() {
    return array(
        'API ID' => array(
            'Type' => 'text',
            'Size' => '30',
            'Default' => '_API-ID_',
            'Description' => 'REplace _API-ID_ with your API ID',
        )
    );
}

/**
 The content that we will display on the page
[server.com]/clientarea.php?action=productdetails&id=[SERVICE_ID]
**/
function worldstream_ClientArea($vars) {
    //store your api id in config option and fetch it.
    $api_id = $vars['configoption2'];
    //create a custom field to store your server id 
    //and fetch it
    if(!empty($vars['customfields']['Server ID'])){
       $server_id = $vars['customfields']['Server ID'];
    } 
    
    
      if (empty($server_id)) {
        $return_array['status'] = 0;
        return array(
            'templatefile' => 'no_serverid',
            'vars' => array(
                'response' => $return_array
            )
        );
      }

      /*
          Call the function getMyServer to get
          server details.
      */
      $result_array = getMyServer($api_id, $server_id);
      return array(
                'templatefile' => 'clientarea',
                'vars' => array(
                    'response' => $result_array
                ),
      );
}

/**
 Let's call the API get_dedicated_list 
**/
function getMyServer($api_id, $server_id) {
    $url = 'https://www.customerpanel.nl/api.php';
    $data = array(
        "api_id" => $api_id,
        "method" => "get_dedicated_list"
    );

    $options = array(
        'CURLOPT_TIMEOUT' => '300',
    );
    $response = curlCall($url, $data, $options);
    $return = array();
    $result_array = json_decode($response);
    if ($result_array->StatusCode == 1) {
        unset($result_array->StatusCode);
        unset($result_array->StatusMessage);
        foreach ($result_array as $k => $value) {
            if ($value->Server_Id == $server_id) {
                $return['Status'] = 1;
                $return['Default_Password'] =
                    $value->Default_Password;
                $return['Main_IP'] = $value->Main_IP;
                $return['IPv6'] = isset($value->IPv6)
                    ? $value->IPv6 : "None";
                $return['Max_Datatraffic'] = 
                    $value->Max_Datatraffic;
                $return['Status'] = $value->Status;
                return $return;
            } else {
                continue;
            }
        }
    }
    $return['Status'] = 0;
    return $return;
}

Create a folder named templates in the path /modules/servers/worldstream.
Within that folder create a file named clientarea.tpl.
Then store the below contents to that file.

<div class="row">
    
    <div class="col-sm-12">
        <strong class="text-center">
               Server Details:
        </strong>
    </div>
</div>

<div class="row">
    
    <div class="col-sm-5 text-right">
        IPv4 Addresses:
    </div>
    <div class="col-sm-7 text-left">
       {$response['Main_IP']}
    </div>

</div>
<div class="row">
    
    <div class="col-sm-5 text-right">
       IPv6 Addresses:
    </div>
    <div class="col-sm-7 text-left">
      {$response['IPv6']}
    </div>
</div>

<div class="row">
    
    <div class="col-sm-5 text-right">
           Max. Datatraffic:
    </div>
    <div class="col-sm-7 text-left">
       {$response['Max_Datatraffic']}GB
    </div>
</div>

<div class="row">
    
    <div class="col-sm-5 text-right">
          Default Password:
    </div>
    <div class="col-sm-7 text-left">
          {$response['Default_Password']}
    </div>
</div>

<div class="row">
    
    <div class="col-sm-5 text-right">
          Status:
    </div>
    <div class="col-sm-7 text-left">
       {$response['Status']}
    </div>
</div>
5 Dec

WHMCS Database Queries

WHMCS use Laravel framework’s database component.
So Insert, Select, Update and Delete queries should be written in
Laravel style.

If you are planning to do the database query from a custom WHMCS page, add the below code
at the top of the page.

require_once("init.php");
use Illuminate\Database\Capsule\Manager as Capsule;

If you are going to do query from a module page, just the below code is enough.

use Illuminate\Database\Capsule\Manager as Capsule;

Select rows

In order to select all rows from the table tblinvoices,
we can use the below code.

//get all rows
try {
    $data = Capsule::table('tblinvoices')
        ->get();
    echo "<pre>"; print_r($data);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

To select just paid invoices, we can use the below query.

//get all rows
try {
    $data = Capsule::table('tblinvoices')
        ->where("status", "=", "Paid") // we can add multiple where conditions
        ->get();
    echo "<pre>"; print_r($data);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Select a single row

To select a single row, we can use the function first instead of the function get as shown below.

//get a single row, note we added a where condition too
try {
    $data = Capsule::table('tblinvoices')
        ->where("id", "=", 3)
        ->first();
    echo "<pre>"; print_r($data);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Get value of a single field.

Assume that we just need to know paymentmethod of an invoice with id=3,
we can use the below query. Note that we used ->value(‘paymentmethod’) instead of first().

try {
    $data = Capsule::table('tblinvoices')
        ->where("id", "=", 3)
        ->value('paymentmethod');
    echo $data;
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Add a row

Now let’s add a row to the table tblconfiguration.

//insert a row
try {
    //key value pair.
    $insert_array = [
        "setting" => "Discount",
        "value" => "60",
        "created_at" => date("Y-m-d H:i:s", time()),
        "updated_at" => date("Y-m-d H:i:s", time()),
    ];
    Capsule::table('tblconfiguration')
        ->insert($insert_array);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Add a row and get the last insert id.

To get the last insert id, we have to use insertGetId function instead of the insert.

//get insert id
try {
    $insert_array = [
        "date" => date("Y-m-d H:i:s", time()),
        "description" => "Testing insert id stuff",
        "user" => "test",
        "userid" => 1,
        "ipaddr" => "127.0.0.1"
    ];
    $new_log_id = Capsule::table('tblactivitylog')
        ->insertGetId($insert_array);
    echo $new_log_id;
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Update a table

To update a table, we can write the query as given below.

//update a table
try {
    $update_data =  [
        'status' => 'Paid',
        'paymentmethod' => 'paypal'
    ];
    Capsule::table('tblinvoices')
       ->where('id', '=', 9)
       ->update($update_data);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Delete from a table

#delete from a table
try {
    Capsule::table('tblactivitylog')
        ->where('id', '=', 12)
        ->delete();
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

Sample Join Query

If we have to join two tables tblinvoices and tblinvoiceitems on a condition tblinvoices.id = tblinvoiceitems.invoiceid, then we can write the join query as written below. For any select query we can just select interested field’s values. In the below query we are just selecting three field values, they are tblinvoices.id, tblinvoiceitems.description, and tblinvoiceitems.amount.

    //Join query
try {
    $invoice_details = Capsule::table('tblinvoices')
         ->join(
             'tblinvoiceitems',
             'tblinvoices.id',
                  '=', 'tblinvoiceitems.invoiceid'
         )
         ->select(
               'tblinvoices.id',
               'tblinvoiceitems.description',
               'tblinvoiceitems.amount'
        )
        ->get();
        echo "<pre>"; print_r($invoice_details);
} catch(\Illuminate\Database\QueryException $ex){
    echo $ex->getMessage();
} catch (Exception $e) {
    echo $e->getMessage();
}

To know more about the query,
Go to Laravel Query Tutorial

24 Nov

Simplify Commerce Basics Using PHP SDK

Simplify Commerce is a payment gateway brought to you by MasterCard.
They have SDK for most of the programming languages. Here i am going to explain about PHP SDK of the Simplify Commerce. Using Simplify Commerce we can do payments using token. With this approach we don’t have to pass card number and also we are not storing the cc number in the database.

First of all you have to download the SDK and include it in your code as shown below. Link to download the SDK is
https://www.simplify.com/commerce/sdk/php/simplifycommerce-sdk-php-1.6.0.tgz

require_once 'Simplify.php'

In your Simplify account, you will have public key and private key for both live and sandbox. For testing use sandbox keys and when you go live have to use the live keys.

        require_once 'Simplify.php'
        if($is_test_mode){
                $pub_key = $sandbox_pubkey;
                $prive_key $sandbox_privkey;
        } else {
                $pub_key = $live_pubkey;
                $prive_key = $live_privkey;
        }
        try{
                Simplify::$publicKey = $pub_key;
                Simplify::$privateKey = $prive_key;
        }catch (Simplify_ApiException $e) {
                die($e->getMessage());
        }


How to get Simplify token?

You can create a token that can be used only once using the below code. You won’t be able to use the token more than once.

  $card = array(
      'addressState' => $state,
      'expMonth' => $exp_m,
      'expYear' => $exp_y,
      'addressCity' => $city,
      'cvc' => $cvc,
      'number' => $card_num
  );
  try {
        $cardToken =  Simplify_CardToken::createCardToken(
          array(
              'card' => $card 
          )
        );
        $token = $cardToken->id;
  } catch (Simplify_ApiException $e) {
        die( $e->getMessage());
  }

How to create a customer using the simplify token?
You can create a customer using the below code. You can see that we are using the token created. The below API will return a customer id
and we can use that for multiple transactions. Even though the token id can be used only once, the customer id can be used many times.

  
try {
    $data = array(
        'token' => $token,
        'email' => $email,
        'name' =>  $name,
        'reference' => $reference
    );
    $customer = Simplify_Customer::createCustomer(
        $data
    );
    $customer_id = $customer->id;
}catch (Simplify_ApiException $e){
    die( $e->getMessage());
}

How to make a payment using the simplify customer id?
The sample payment code is below. One important point to remember is, if you want to make a payment of $10, then we have to pass amount as
10 * 100, not 10. So for $10, we have pass amount as 1000 and currency as USD. We have to pass the $customer_id we generated in the previous step. We can pass anything as reference. Normally we pass order id or invoice id as reference.

  
$payment_data = array(
    'amount' =>  $amount * 100,
    'customer' => $customer_id,
    'description' => $description,
    'currency' => 'USD',
    'reference' => $invoice_id
);
try {
   $payment = Simplify_Payment::createPayment(
       $payment_data
   );
} catch (Simplify_ApiException $e) {
   die( $e->getMessage());
}

How to add a monthly subscription for the simplify customer id?
You can add a recurring payment from a customer as below.
amount and customer id, we already discussed in the above step.
If the customer will pay monthly, we have to set frequency as MONTHLY and frequencyPeriod as 1. If the customer will pay bimonthly then frequency should be MONTHLY and frequencyPeriod should be 2.
For semiannual payments set frequency=MONTHLY, frequencyPeriod=6.

Possible values for frequency are DAILY, WEEKLY, MONTHLY and YEARLY.

  
$subscription_data = array(
   'amount' =>  $amount * 100,
   'customer' => $customer_id,
   'frequency' => $frequency,
   'name' => $name,
   'frequencyPeriod' => $frequencyPeriod
);
try {
   $subscription  = Simplify_Subscription::createSubscription(
      $subscription_data
   );
} catch (Simplify_ApiException $e) {
   die( $e->getMessage());
}

Developed a WHMCS payment gateway module using the Simplify Commerce PHP SDK. Please contact me if you need it.

16 Nov

Is Single Page Checkout Possible With WHMCS?

In WHMCS, when you try to order for a product.Assume that you are a logged in customer.How many steps are there now?

1)First you have to go to products display page.
Url will be http://[mysite.com]/cart.php

2)If you click on “Order Now” Button of a Hosting product, You will be taken to a product configuration page. Url will be: http://[mysite.com]/cart.php?a=confproduct&i=[x]

3)Then on clicking “Continue” You will be taken to a Review & Checkout Page.

4)On clicking Checkout Button, you will be taken to payment method selection page.

5)After selecting payment, you can click on the ‘Complete Order’ Button. That will place an order.

So total 5 steps are there.

Is it possible to do it in a single step? In other words, is one page checkout possible in WHMCS? Yes, it is possible. We have to use a hook for the purpose. In addition to that we have to make some changes for the template.

The hook should have some ajax post code. Sample code is below. The code will add the product to the cart before submitting the order form.

$('#completeOrder').click(function(){
     $.post('cart.php', 'ajax=1&amp;a=confproduct&amp;' +
         $('#configProduct').serialize(),
         function(data) {
           if (!data) {
               $('#orderform').submit();
           }
         }
     });
});

We have a ready made single page checkout order form, with one time cost of $120.

To view a demo, please go to the video
We are adding more features and making the no #1 single page checkout module for WHMCS.

If you purchase this module
1) Free support for 6 months
2) Free bug fixes
3) Future updates for free of cost
4) Discount for any WHMCS module development and WHMCS customizations.

please Contact Us by filling the form. We will get back to you asap.

10 Nov

Why no transaction data for a WHMCS order? Why the refund failing?

Even though order is complete, from Billing => Transactions List you might not see any transaction data related to the order.

If you go to admin/configgeneral.php, there is an option Auto Redirect on Checkout. Is the option ‘Automatically forward the user to the payment gateway’ selected? Then during the order, customer must have gone through the payment gateway module code. Even then why no transaction id and other data?

Go to ‘Manage Orders’ from admin side. Is the payment status of the order is complete? Is your refund failing for the invoice of the order? Are you getting the error ‘The refund attempt has failed. Please check the Gateway Log for more information’ when you try to refund?

It’s happening because the customer have some credit balance. The amount is deducted from that for the order.

If you are a developer and would like to test a refund for the payment gateway,you can simply reset the credit balance as zero for the customer.

Then place a new order and refund for that order will work.
To know credit balance of a customer with id [x],
go to the page clientssummary.php?userid=[x]
and search for Credit Balance.

5 Nov

How to hide a field from WHMCS register.php?

If you have to remove a form field from the WHMCS register file, How you can do it?

It can be done using a hook named ClientAreaFooterOutput.

Assume that the field’s id is  myfield. Then you can create a file named hook_register_hide.php and place it in include/hooks folder.

<?php
add_hook('ClientAreaFooterOutput', 1, function ($vars)
{
$filename = $vars['filename'];
if($filename == "register") {
$string = "<script type='text/javascript'>";
$string .=  "        $(function() {  ";
$string .= "$('#myfield').addClass('hidden')";
$string .=  "});";
$string .= "</script> ";
return $string;
}
});