Prolateral Consulting Ltd
Prolateral Consulting Ltd
Support
Knowledgebase Articles
Help
Setup examples
Support

Prolateral offers primary and backup domain (DNS) services, with servers in key geographic locations providing the best service possible.

Slider

Problem

How do I create an outMail service under a specified client using the Partner API?
Creating an outMail service using the RESTful Partner API?

Solution

The following example of code shows you how to create an outMail service under one of the partners clients. outMail is an outbound SMTP SmartHost service.

Notes

It is assumed that you already have the following.

  • Client ID - You need the client id (which could also be the partner id if your creating the service under your own account). Client ID can be found by using the /clients end point. See the examples on clients-list and clients-search.
  • Service Name - When creating a new service you need to know the name of the service you are trying to create. This information can be found from the end point /live_services/service_names, looking for the field name service_name. See the example liveservices-list-tariff.
  • Billing System ID (optional) - In the portal this is referred to as whmcs_service_id, however this field is simply a way of linking your own billing system to the portal.

Prerequisites

To use the Partner API you must meet the following criteria

  • Have a working development environment.
  • Have an active Partner account. If you need a partner account you can sign up here.
  • Enabled your account to use the API and set the access controls.
  • Have valid API Credentials.
  • Optional - Setup your development environment to initially use the Sandbox Testing Portal.

For Partner API reference documentation please see https://portal.my-engine.com/apidocs/index.html

Example Code

The examples below uses the sandbox. For a production environment remember to change the following:

  • API Url
  • Partner ID
  • Partner API Key

<?php
/**
 * outmail-add.php
 * 
 * This example will Add a new outmail service to a specified client.
 * 
 */
 
$apiPartnerId = "<PartnerID>";
$apiSecretKey = "___PartnerKey___";

$apiUrl       = "https://sandbox.my-engine.com/api-v1/outmails";

$crlf         = "<br />";

// Create the array for the new client data
$newOutmail = array();

$newOutmail["service_name"] = "Outmail500";     // Check the API Documentation for the service names /live_services/service_names
$newOutmail["whmcs_serviceid"] = "1324578";     // Optional, but used if linking to an external billing solution
$newOutmail["client_id"] = "9987606";           // Get this ID using examples like clients-list.php
$newOutmail["username"] = "myOutmail001";
$newOutmail["password"] = "myOutmailPassword";

// Init Curl
$curl = curl_init();

// API Authentication:
curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($curl, CURLOPT_USERPWD, "$apiPartnerId:$apiSecretKey");

// Set Curl Options
curl_setopt($curl, CURLOPT_URL, $apiUrl);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);

// API POST DATA
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($newOutmail));

// Tell it we're sending a JSON set of data in the POST
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
    'Content-Type: application/json',
    ));

// API POST
$jsonResult = curl_exec($curl);

// Check for a valid HTTP 200 success and process the returned result
// or handler the failure.
if (curl_getinfo($curl, CURLINFO_RESPONSE_CODE) == 201) {
    $result = json_decode($jsonResult, true);

    if (json_last_error() == JSON_ERROR_NONE)   {
        echo "status = " . $result["meta"]["success"] . $crlf;
        echo "new outMail id = " . $result["data"]["id"] . $crlf;
        echo "new outMail username = " . $result["data"]["username"] . $crlf;
        echo "new outMail password = " . $result["data"]["password"] . $crlf;
        echo "new outMail server = " . $result["data"]["outmail_server_id"] . $crlf;
        echo "Live Service ID = " . $result["data"]["live_service_id"] . "    (You will need this for /live_services/ID for Delete & Un/Suspend actions)" . $crlf;
    } else {
        print_r($result);
    }
    
} else {
    echo "Response Code = " . curl_getinfo($curl, CURLINFO_RESPONSE_CODE) . $crlf;
    
    $result = json_decode($jsonResult, true);
    if (json_last_error() == JSON_ERROR_NONE)   {
        echo "error = " . $result["error"]["name"] . $crlf;
        echo "url = " . $result["error"]["url"] . $crlf;
        echo "message = " . $result["error"]["message"] . $crlf;
    } else {
        echo $jsonResult;
    }
}

curl_close($curl);




/**
 * outmail-add.cs
 * 
 * This example will Add a new outmail service to a specified client.
 * 
 */

using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;

namespace outmail_add
{
    class Program
    {
        private const string apiPartnerId = "<PartnerID>";
        private const string apiSecretKey = "_PartnerKey_";

        private const string apiUrl = "https://sandbox.my-engine.com/api-v1/outmails";

        static void Main(string[] args)
        {
            // Create the new client data
            Dictionary<string, string> newOutmail = new Dictionary<string, string>();

            newOutmail.Add("service_name", "Outmail500");      // Check the API Documentation for the service names /live_services/service_names
            newOutmail.Add("whmcs_serviceid", "12234567");     // Optional, but used if linking to an external billing solution
            newOutmail.Add("client_id", "9987606");            // Get this ID using examples like clients-list
            newOutmail.Add("username", "myOutmail001");
            newOutmail.Add("password", "myOutmailPassword");

            // Convert the Dictionary to Json
            string newOutmailJsonStr = JsonConvert.SerializeObject(newOutmail, Formatting.Indented);

            // Create HTTP resource
            HttpClient outMail = new HttpClient();

            // Add an Accept header for JSON format.
            outMail.DefaultRequestHeaders.Add("ContentType", "application/json");

            // Set the Authorisation
            var authToken = System.Text.Encoding.UTF8.GetBytes(apiPartnerId + ":" + apiSecretKey);
            outMail.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(authToken));

            // Create the content
            var content = new StringContent(newOutmailJsonStr, Encoding.UTF8, "application/json");

            // Do the POST
            var response = outMail.PostAsync(apiUrl, content).Result;

            // Check the result for a valid HTTP 200 success and process the returned result
            // or handler the failure.
            if (response.IsSuccessStatusCode)
            {
                // Get the created ID
                var jsonResponseStr = response.Content.ReadAsStringAsync().Result;
                dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseStr);
                if (jsonResponse.ContainsKey("data"))
                {
                    Console.WriteLine("status = {0}", jsonResponse["meta"]["success"]);
                    Console.WriteLine("new outMail id = {0}", jsonResponse["data"]["id"]);
                    Console.WriteLine("new outMail username = {0}", jsonResponse["data"]["username"]);
                    Console.WriteLine("new outMail password = {0}", jsonResponse["data"]["password"]);
                    Console.WriteLine("new outMail server = {0}", jsonResponse["data"]["outmail_server_id"]);
                    Console.WriteLine("Live Service ID = {0}    (You will need this for /live_services/ID for Delete & Un/Suspend actions)", jsonResponse["data"]["live_service_id"]);
                }
                else
                {
                    Console.WriteLine("response = {0}", response);
                    Console.WriteLine("json response = {0}", jsonResponse);
                }

            }
            else
            {
                // Get the Json Error response and convert it
                var jsonResponseStr = response.Content.ReadAsStringAsync().Result;
                dynamic jsonResponse = JsonConvert.DeserializeObject(jsonResponseStr);
                Console.WriteLine("name = {0}", jsonResponse["error"]["name"]);
                Console.WriteLine("url = {0}", jsonResponse["error"]["url"]);
                Console.WriteLine("message = {0}", jsonResponse["error"]["message"]);
                Console.WriteLine("{0} ({1})", (int)response.StatusCode, response.ReasonPhrase);
            }

            //Dispose once all HttpClient calls are complete.
            outMail.Dispose();

        }
    }
}


'
' outmail-add.vb
' 
' This example will Add a new outmail service to a specified client.
' 
'

Imports Newtonsoft.Json
Imports System
Imports System.Collections.Generic
Imports System.Net.Http
Imports System.Net.Http.Headers
Imports System.Text

Module Program

    Private Const apiPartnerId As String = "<PartnerID>"
    Private Const apiSecretKey As String = "_PartnerKey_"

    Private Const apiUrl As String = "https://sandbox.my-engine.com/api-v1/outmails"

    Sub Main(args As String())

        ' Create the New client data
        Dim newOutmail As Dictionary(Of String, String) = New Dictionary(Of String, String)

        newOutmail.Add("service_name", "Outmail500")      ' Check the API Documentation For the service names /live_services/service_names
        newOutmail.Add("whmcs_serviceid", "12234567")         ' Optional, but used If linking To an external billing solution
        newOutmail.Add("client_id", "9987606")              ' Get this ID Using examples Like clients-list
        newOutmail.Add("username", "myOutmail001")
        newOutmail.Add("password", "myOutmailPassword")

        ' Convert the Dictionary to Json
        Dim newOutmailJsonStr As String = JsonConvert.SerializeObject(newOutmail, Formatting.Indented)

        ' Create HTTP resource
        Dim client As New HttpClient()

        ' Add an Accept header for JSON format.
        client.DefaultRequestHeaders.Add("ContentType", "application/json")

        ' Set the Authorisation
        Dim authToken = System.Text.Encoding.UTF8.GetBytes(apiPartnerId + ":" + apiSecretKey)
        client.DefaultRequestHeaders.Authorization = New AuthenticationHeaderValue("Basic", System.Convert.ToBase64String(authToken))

        ' Create the content
        Dim content = New StringContent(newOutmailJsonStr, Encoding.UTF8, "application/json")

        ' Do the POST
        Dim response As HttpResponseMessage = client.PostAsync(apiUrl, content).Result

        ' Check the result for a valid HTTP 200 success And process the returned result
        ' Or handler the failure.
        If (response.IsSuccessStatusCode) Then
            ' Get the created ID
            Dim jsonResponseStr = response.Content.ReadAsStringAsync().Result
            Dim jsonResponse As Object = JsonConvert.DeserializeObject(jsonResponseStr)
            If jsonResponse.ContainsKey("data") Then
                Console.WriteLine("status = {0}", jsonResponse("meta")("success"))
                Console.WriteLine("new outmail id = {0}", jsonResponse("data")("id"))
                Console.WriteLine("new outmail username = {0}", jsonResponse("data")("username"))
                Console.WriteLine("new outmail password = {0}", jsonResponse("data")("password"))
                Console.WriteLine("new outmail server = {0}", jsonResponse("data")("outmail_server_id"))
                Console.WriteLine("Live Service ID = {0}    (You will need this for /live_services/ID for Delete & Un/Suspend actions)", jsonResponse("data")("live_service_id"))
            Else
                Console.WriteLine("response = {0}", response)
                Console.WriteLine("json response = {0}", jsonResponse)
            End If
        Else
            ' Get the Json Error response And convert it
            Dim jsonResponseStr = response.Content.ReadAsStringAsync().Result
            Dim jsonResponse As Object = JsonConvert.DeserializeObject(jsonResponseStr)
            Console.WriteLine("name = {0}", jsonResponse("error")("name"))
            Console.WriteLine("url = {0}", jsonResponse("error")("url"))
            Console.WriteLine("message = {0}", jsonResponse("error")("message"))
            Console.WriteLine("{0} ({1})", response.StatusCode, response.ReasonPhrase)
        End If

        'Dispose once all HttpClient calls are complete.
        client.Dispose()

    End Sub


End Module




/**
 * outmail-add.js
 * 
 * This example will Add a new outmail service to a specified client.
 * 
 */

var apiPartnerId = "<PartnerID>";
var apiSecretKey = "_PartnerKey_";

var apiUrl = "https://sandbox.my-engine.com/api-v1/outmails";

var jsondata = {
    "service_name": "Outmail500",   // Check the API Documentation for the service names /live_services/service_names
    "whmcs_serviceid": "12345678",  // Optional, but used if linking to an external billing solution
    "client_id": "987606",          // Get this ID using examples like clients-list.js
    "username": "myOutmail1001",
    "password": "myOutmailPassword"
};

// Setup the Ajax request
var settings = {
    url: apiUrl,
    headers: {
        'Authorization': 'Basic ' + btoa(apiPartnerId + ":" + apiSecretKey),
        'cache-control': 'no-cache'
    },
    crossDomain: true,
    // Uncomment the lines below if you want to POST data as JSON.
    //   If so comment the "data: jsondata" out
    //     contentType: 'application/json',
    //     data: JSON.stringify(jsondata),
    // Comment the line below out, if you've uncomment the two line above.
    //   The "data: jsondata" method will POST data as application/x-www-form-urlencoded
    data: jsondata,
    dataType: 'json',
    async: true,
    method: "POST"
};

// API POST
$.ajax(settings)
    .done(function(response) {
        console.log("status = " + response.meta.success);
        console.log("new outMail id = " + response.data.id);
        console.log("new outMail username = " + response.data.username);
        console.log("new outMail password = " + response.data.password);
        console.log("new outMail server = " + response.data.outmail_server_id);
        console.log("Live Service ID = " + response.data.live_service_id + "    (You will need this for /live_services/ID for Delete & Un/Suspend actions)");
        console.log(" ");

    })
    .fail(function(request, textStatus, errorThrown) {
        try {
            var errObj = $.parseJSON(request.responseText);
            console.log("API Error - " + errObj.name);
            console.log("API Msg   - " + errObj.message);
            console.log("API url   - " + errObj.url);
        } catch (e) {
            console.log("Error - " + errorThrown);
            console.log("Status - " + request.status);
            console.log(request);
        }
    });

User Rating: 5 / 5   

like it, love it, then share it. Share this article on social media.

Did you enjoy this article?

Disclaimer

The Origin of this information may be internal or external to Prolateral Consulting Ltd. Prolateral makes all reasonable efforts to verify this information. However, the information provided in this document is for your information only. Prolateral makes no explicit or implied claims to the validity of this information. Any trademarks referenced in this document are the property of their respective owners.