I want to know how to get WHMCS Price via WHMCS API.
I have created a little script to get price via API which is working fine but when I update the script on my external WHMCS pages it is taking a lot more time to update the function on each page my simple question is to get price via API without defining the first array see example below.
Array
(
[result] => success
[totalresults] => xxx
[products] => Array
(
[product] => Array
(
[0] => Array // how can I call it dynamically
(
[pid] => 1
[gid] => 1
[type] => hostingaccount
[name] => Plan Name
[description] => Plan Description
[module] => cpanel
[paytype] => recurring
[pricing] => Array
(
[USD] => Array
(
[prefix] => $
[suffix] => USD
[msetupfee] => 0.00
[qsetupfee] => 0.00
[ssetupfee] => 0.00
[asetupfee] => 0.00
[bsetupfee] => 0.00
[tsetupfee] => 0.00
[monthly] => 0.14
[quarterly] => 0.39
[semiannually] => 0.73
[annually] => 1.32
[biennially] => 2.39
[triennially] => 3.20
)
)
)
)
)
)
I just want to get price after I define [pid] and then I will create a function like
GetPrice($pid, $billingcycle); // to get produce price according to tenure
My Script:
$identifier = "IDENTIFIER";
$secret = "SECRET";
$APIURL = "mydomain/whmcs_directory/includes/api.php"; // it is with HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
and then I want to use function to get price according product id & tenure as defined earlier but complete function looks like this.
function GetPrice($pid, $billingcycle){
// $pid will be product ID
// $billingcycle will be 1,3,6,12,24,36 accordingly.
/**
* It would be great if I could just remove "["products"]["product"]"
* But I understand to call API I have define them so it's Okay.
*/
$monthly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][$pid]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo $monthly;
}
if( $billingcycle == "3" ){
echo $quarterly;
}
if( $billingcycle == "6" ){
echo $semiannually;
}
if( $billingcycle == "12" ){
echo $annually;
}
if( $billingcycle == "24" ){
echo $biennially;
}
if( $billingcycle == "36" ){
echo $triennially;
}
}
I got help from WHMCS API Reference
This has done with php, please improve my code if require.
I have achieved this with the following code which work dynamically and works with product id.
PHP Function
function GetPrice($product_id, $billingcycle){
$identifier = "WHMCS_IDENTIFIER";
$secret = "WHMCS_SECRET";
$APIURL = "YOURDOMAIN.com/WHMCS_DIRECTORY/includes/api.php"; // use HTTPS
$postfields = array(
'username' => $identifier,
'password' => $secret,
'action' => 'GetProducts',
'pid' => $product_id, // Product id
'responsetype' => 'json',
);
// Call the API
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $APIURL);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1); // SET to 0 for non SSL
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($postfields));
$response = curl_exec($ch);
if (curl_error($ch)) {
//die('Unable to connect: ' . curl_errno($ch) . ' - ' . curl_error($ch));
die("Out of Stock");
}
curl_close($ch);
// Decode response
$jsonData = json_decode($response, true);
$monthly = $jsonData["products"]["product"][0]["pricing"]["USD"]["monthly"];
$quarterly = $jsonData["products"]["product"][0]["pricing"]["USD"]["quarterly"];
$semiannually = $jsonData["products"]["product"][0]["pricing"]["USD"]["semiannually"];
$annually = $jsonData["products"]["product"][0]["pricing"]["USD"]["annually"];
$biennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["biennially"];
$triennially = $jsonData["products"]["product"][0]["pricing"]["USD"]["triennially"];
if( $billingcycle == "1" ){
echo round( str_replace('.00', '', $monthly), 2 );
}
if( $billingcycle == "3" ){
echo round( str_replace('.00', '', $quarterly) / 3, 2 );
}
if( $billingcycle == "6" ){
echo round( str_replace('.00', '', $semiannually) / 6, 2 );
}
if( $billingcycle == "12" ){
echo round( str_replace('.00', '', $annually) / 12, 2 );
}
if( $billingcycle == "24" ){
echo round( str_replace('.00', '', $biennially) / 24, 2 );
}
if( $billingcycle == "36" ){
echo round( str_replace('.00', '', $triennially) / 36, 2 );
}
}
Using Function
echo GetPrice( 1 , 1 );
Output
1.99
Related
I'm using a cURL request to grab data from a website and adding them to properties within a loop later. However, I'm stuck on making the data adjustable enough where I can add them directly within the objects.
I have a cURL request that I'm calling that grabbing all the content that I need as below:
public function request()
{
$resource = curl_init();
curl_setopt(
$resource,
CURLOPT_URL,
'lorem ipsum'
);
curl_setopt(
$resource,
CURLOPT_HTTPHEADER,
['API Auth']
);
curl_setopt(
$resource,
CURLOPT_REFERER,
'http://' . $_SERVER['SERVER_NAME'] . '/'
);
curl_setopt(
$resource,
CURLOPT_USERAGENT,
'F'
);
curl_setopt(
$resource,
CURLOPT_RETURNTRANSFER,
1
);
$response = json_decode(curl_exec($resource), true);
if (!curl_errno($resource)) {
$info = curl_getinfo($resource);
echo 'Took ', $info['total_time'], ' seconds to send a request to ', $info['url'], "\n";
};
return $response;
}
When I call the following execution $offices_array = $this->request(); print_r2($offices_array);, this is the return that I receive:
Array
(
[paginator] => Array
(
[total] => 131
[per_page] => 500
[current_page] => 1
[last_page] => 1
[prev_page] =>
[next_page] =>
)
[data] => Array
(
[0] => Array
(
[id] => 1
[name] => Atlanta
)
I'm using this function _csv_to_array:
private function _csv_to_array($filepath) {
$data_array = array();
if(is_readable($filepath)) {
$fp = fopen($filepath, 'r');
while(($data_item = fgetcsv($fp, 1000, "\t")) !== false) {
$data_array[] = array_map('utf8_encode', $data_item);
}
fclose($fp);
}
return $data_array;
}
to print out data as this:
Array
(
[0] => Array
(
[0] => ABU DHABI
[1] => FHI
)
How could I do something similar with the cURL request?
<?php
error_reporting(E_ALL);
$ch = curl_init();
ini_set('max_execution_time', 0); ini_set('set_time_limit', 0);
curl_setopt($ch, CURLOPT_URL, "https://security.voluum.com/login");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "GET");
$headers = array();
$headers[] = "Authorization: Basic username:password";
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
$result = curl_exec($ch);
if (curl_errno($ch)) {
echo 'Error:' . curl_error($ch);
}
$res_decoded = json_decode($result);
$tok = $res_decoded->token;
$id = 'asdafewfcs';
$karon = date("Y-m-d");
$datetime = new DateTime('tomorrow');
$sh = curl_init();
curl_setopt($sh, CURLOPT_URL, "https://portal.voluum.com/report?from=" .$karon. "T00:00:00Z&to=" . $datetime->format('Y-m-d') . "T00:00:00Z&tz=Etc%2FGMT&sort=revenue&direction=desc&columns=offerName&columns=visits&columns=clicks&columns=conversions&columns=revenue&columns=cost&columns=profit&columns=cpv&columns=ctr&columns=cr&columns=cv&columns=roi&columns=epv&columns=epc&columns=ap&columns=affiliateNetworkName&groupBy=offer&offset=0&limit=100&include=active&filter1=campaign&filter1Value=" . $id);
curl_setopt($sh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($sh, CURLOPT_CUSTOMREQUEST, "GET");
$header = array();
$header[] = "Cwauth-Token: " . $tok;
curl_setopt($sh, CURLOPT_HTTPHEADER, $header);
$results = curl_exec($sh);
if (curl_errno($sh)) {
echo 'Error:' . curl_error($sh);
}
$user = json_decode($results, true);
echo '<pre>' . print_r($user, TRUE) . '</pre>';
foreach($user['rows'] as $mydata)
{
$visit = $mydata['visits'] ;
echo $visit . "\n<br>";
if($visit >= 10){
$wh = curl_init();
curl_setopt($wh, CURLOPT_URL, "https://core.voluum.com/campaigns/" . $id);
curl_setopt($wh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($wh, CURLOPT_CUSTOMREQUEST, "GET");
$head = array();
$head[] = "Cwauth-Token: " . $tok;
curl_setopt($wh, CURLOPT_HTTPHEADER, $head);
$resulta = curl_exec($wh);
if (curl_errno($wh)) {
echo 'Error:' . curl_error($wh);
}
echo "Request:" . "<br>";
$campinfo = json_decode($resulta, true);
echo '<pre>' . print_r($campinfo, TRUE) . '</pre>';
foreach($campinfo['pathsGroups'] as $datacamp){
echo $datacamp['active'];
$xh = curl_init();//starts not working when i add codes from here to end
curl_setopt($xh, CURLOPT_URL, "https://core.voluum.com/campaigns/" . $id);
curl_setopt($xh, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($xh, CURLOPT_POSTFIELDS,http_build_query(array($datacamp['active']),'','&');
curl_setopt($xh, CURLOPT_CUSTOMREQUEST, "PUT");
$header = array();
$header[] = "Cwauth-Token: " . $tok;
curl_setopt($xh, CURLOPT_HTTPHEADER, $header);
$result = curl_exec($xh);
if (curl_errno($xh)) {
echo 'Error:' . curl_error($xh);
}
}
}
}
curl_close ($ch);
curl_close ($sh);
curl_close ($wh);
curl_close ($xh);
?>
can someone please check my syntax i don't know whats wrong with it when i run it it says page isn’t workinq. ive already have ini_set('max_execution_time', 0); ini_set('set_time_limit', 0); in my code but there are no error message everything was running well until i add the PUT as what ive mentioned in the comment iam trying to replace value of [active] => false
here is a short the structure of data:
Array
(
[pathsGroups] => Array
(
[0] => Array
(
[paths] => Array
(
[0] => Array
(
[weight] => 100
[active] => 1
[landers] => Array
(
[0] => Array
(
[lander] => Array
(
[id] =>
[namePostfix] =>
[name] =>
)
[weight] => 100
)
)
[offers] => Array
(
[0] => Array
(
[offer] => Array
(
[id] =>
[name] =>
[namePostfix] =>
)
[weight] => 100
)
)
)
)
[active] => 1 //this is what i'am trying to replace
)
)
)
Below is my code, I am trying to get particular api response (msg,amt) in php string.
........................................................................................................................................
$key = "XXXXX";
$mykey = "XXXXX";
$command = "Check";
$value = "5454355435";
$r = array('key' => $key , 'value' => $value, 'command' => $command);
$qs= http_build_query($r);
$wsUrl = "https://info.service-provider.com";
$c = curl_init();
curl_setopt($c, CURLOPT_URL, $wsUrl);
curl_setopt($c, CURLOPT_POST, 1);
curl_setopt($c, CURLOPT_POSTFIELDS, $qs);
curl_setopt($c, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($c, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($c, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($c, CURLOPT_SSL_VERIFYPEER, 0);
$o = curl_exec($c);
if (curl_errno($c)) {
$sad = curl_error($c);
throw new Exception($sad);
}
curl_close($c);
$valueSerialized = #unserialize($o);
if($o === 'b:0;' || $valueSerialized !== false) {
print_r($valueSerialized);
}
print_r($o);
RESPONSE:
{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}
Your string is in json format. To get value from it, you should convert it into an array like this:
$json = '{"status":1,"msg":"1 out of 1 Transactions Fetched Successfully","transaction_details":{"2767712494": {"mihpayid":"268999084","request_id":"","ref_num":"020814301298","amt":"1.00","txnid":"5454355435","additional_charges":"0.00","productinfo":"SHIRT"}}}';
$array = json_decode($json, true);
echo '<pre>'; print_r($array);
Your array will look like this:
Array
(
[status] => 1
[msg] => 1 out of 1 Transactions Fetched Successfully
[transaction_details] => Array
(
[2767712494] => Array
(
[mihpayid] => 268999084
[request_id] =>
[ref_num] => 020814301298
[amt] => 1.00
[txnid] => 5454355435
[additional_charges] => 0.00
[productinfo] => SHIRT
)
)
)
To get msg you should write like this:
echo $array['msg'];
You can get more information from json_decode
Let me know for more help.
This response looks like JSON format.
Pass this response string to php method json_decode like:
$response = json_decode($yourResponseString,true);
and then you should be able to access it's properties like a regular associative array:
$msg = $response['msg'];
I'm working on a project and trying to find a way to add my api results to mysql.
Here is the page were you can find the results.
Here is the code of the page:
<?php
///PLOT PROJECT USER REQUEST
//HELPER FUNCTION TO PRINT TO CONSOLE
function debug_to_console( $data ) {
if ( is_array( $data ) )
$output = "<script>console.log( 'Debug Objects: " . implode( ',', $data) . "' );</script>";
else
$output = "<script>console.log( 'Debug Objects: " . $data . "' );</script>";
echo $output;
}
//PLOT PROJECT REQUEST
$appId = '9fed0c75ca624e86a411b48ab27b3d5a';
$private_token = 'VGjPehPNBa5henSa';
$qry_str = "/api/v1/account/";
$ch = curl_init();
$headers = array(
'Content-Type:application/json',
'Authorization: Basic '. base64_encode($appId.":".$private_token) // <---
);
$geofenceId = '736cb24a1dae442e943f2edcf353ccc7';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
curl_setopt($ch, CURLOPT_URL, 'https://admin.plotprojects.com/api/v1/notification/?geofenceId=' . $geofenceId);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, '3');
curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
$content = trim(curl_exec($ch));
curl_close($ch);
print $content;
?>
You can use json_decode() to decode your JSON string and take the values that you need to make your query. Read more at:
http://php.net/manual/en/function.json-decode.php
<?php
//The response from http://www.jobsinsac.com/api/api_notification.php
$json = '{ "success": true, "result": { "data": [{ "placeId": "736cb24a1dae442e943f2edcf353ccc7", "cooldownDays": 0, "triggerTimes": "inherit", "state": "published", "cooldownSeconds": 1, "data": "http://www.illuminatimc.com", "enabled": true, "geofenceId": "736cb24a1dae442e943f2edcf353ccc7", "id": "0cad6b54d225459e85cd8c27567f8b0b", "message": "Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.", "created": "2015-03-17T18:54:41Z", "timespans": [], "handlerType": "landingPage", "trigger": "enter" }], "total": 1 } }';
$data = json_decode($json, true);
print_r($data);
?>
Output:
Array
(
[success] => 1
[result] => Array
(
[data] => Array
(
[0] => Array
(
[placeId] => 736cb24a1dae442e943f2edcf353ccc7
[cooldownDays] => 0
[triggerTimes] => inherit
[state] => published
[cooldownSeconds] => 1
[data] => http://www.illuminatimc.com
[enabled] => 1
[geofenceId] => 736cb24a1dae442e943f2edcf353ccc7
[id] => 0cad6b54d225459e85cd8c27567f8b0b
[message] => Get a cold beer, for $2.00, shots for $4.00, come inside, up stairs.
[created] => 2015-03-17T18:54:41Z
[timespans] => Array
(
)
[handlerType] => landingPage
[trigger] => enter
)
)
[total] => 1
)
)
Myself and a few friends are trying to use WHMCS to offer services in a virtual world. Issue is WHMCS does not provide a simple way to search for a specific client record without already having the client id, which wouldn't be stored anywhere besides the WHMCS database. the api function getclients returns results in an XML format, issue is when you search for a client using this method you can only search for firstname, lastname, or email address. Now we have tried passing the variables for firstname and lastname(they have to be passed separately) This unfortunatly returns the client records for all clients that X firstname OR Y Lastname, instead of narrowing down the one client with both X and Y.
What I want to know is how to search PHP array generated from an XML result to try and grab the client records for only the client we are looking for.
The results are posted as such:
Array ( [WHMCSAPI] => Array ( [ACTION] => getclients [RESULT] => success [TOTALRESULTS] => 2 [STARTNUMBER] => 0 [NUMRETURNED] => 2 [CLIENTS] => Array ( [CLIENT] => Array ( [ID] => 9 [FIRSTNAME] => Test1 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test1#test.com [DATECREATED] => 2013-04-24 [GROUPID] => 1 [STATUS] => Active ) [CLIENT1] => Array ( [ID] => 20 [FIRSTNAME] => Test3 [LASTNAME] => Test2 [COMPANYNAME] => [EMAIL] => test#test.com [DATECREATED] => 2014-01-20 [GROUPID] => 0 [STATUS] => Active ) ) ) )
The code we try using to search is:
$postfields["action"] = "getclients";
$postfields["search"] = $firstname;
$postfields["search"] = $lastname;
$postfields["responsetype"] = "xml";
$query_string = "";
foreach ($postfields AS $k=>$v) $query_string .= "$k=".urlencode($v)."&";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, 30);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $query_string);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 0);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 0);
$xml = curl_exec($ch);
if (curl_error($ch) || !$xml) $xml = '<whmcsapi><result>error</result>'.
'<message>Connection Error</message><curlerror>'.
curl_errno($ch).' - '.curl_error($ch).'</curlerror></whmcsapi>';
curl_close($ch);
$arr = whmcsapi_xml_parser($xml); # Parse XML
$client = searchClient($firstname, $lastname, $arr);
print_r($client); # Output XML Response as Array
/*
Debug Output - Uncomment if needed to troubleshoot problems
echo "<textarea rows=50 cols=100>Request: ".print_r($postfields,true);
echo "\nResponse: ".htmlentities($xml)."\n\nArray: ".print_r($arr,true);
echo "</textarea>";
*/
function whmcsapi_xml_parser($rawxml) {
$xml_parser = xml_parser_create();
xml_parse_into_struct($xml_parser, $rawxml, $vals, $index);
xml_parser_free($xml_parser);
$params = array();
$level = array();
$alreadyused = array();
$x=0;
foreach ($vals as $xml_elem) {
if ($xml_elem['type'] == 'open') {
if (in_array($xml_elem['tag'],$alreadyused)) {
$x++;
$xml_elem['tag'] = $xml_elem['tag'].$x;
}
$level[$xml_elem['level']] = $xml_elem['tag'];
$alreadyused[] = $xml_elem['tag'];
}
if ($xml_elem['type'] == 'complete') {
$start_level = 1;
$php_stmt = '$params';
while($start_level < $xml_elem['level']) {
$php_stmt .= '[$level['.$start_level.']]';
$start_level++;
}
$php_stmt .= '[$xml_elem[\'tag\']] = $xml_elem[\'value\'];';
#eval($php_stmt);
}
}
return($params);
}
function searchClient($first, $last, $array)
{
foreach ($array as $key => $val)
{
if($val['FIRSTNAME'] == $first && $val['LASTNAME'] == $last)
{
return $key;
}
}
return null;
}
?>
This returns a blank result. I will admit I am not entirely sure how to do this so any pointers will help.
You are able to "search for a specific client record" via email address utilizing their api and they now support json format for responsetype
"Please note either the clientid or email is required."
http://docs.whmcs.com/API:Get_Clients_Details