Friday, August 5, 2016

FEDEX RATES API

Get FedEx Shipping Rates using FedEx Web Services

Steps involved:
1. go to fedex.com/developer, and create a test account, download the web services.
2. Create a production account (by putting all the credit card details) and go to test account, goto my profile-manage account.
 Add the details of  Production account to this account. An auth email will be sent to the admin of production account, if the admin authorizes, you will get an email, follow it and input the required details.  
login to fedex.com/developer nd request for app credentials, The password and some details will be displayed on the browser, save this for future use, the account number and other details will be sent to the email, you need these too for the web service call.

3. Open the 'RateWebServiceClient.php'  and check the require and wsdl paths
require_once('../../library/fedex-common.php');

//The WSDL is not included with the sample code. //Please include and reference in $path_to_wsdl variable.    
//$path_to_wsdl = "../../wsdl/RateService_v18.wsdl";
$path_to_wsdl = "RateService_v18.wsdl"; 

4. goto library/fedex-common.php and put the values (All Production Values) inside function getProperty()
if($var == 'key') Return 'XXXX'; 
if($var == 'password') Return 'XXXX'; 
if($var == 'shipaccount') Return 'account no';

if($var == 'billaccount') Return 'account no';
5. Now as we are running with production account (to get the correct shipping rates) modify the last line of wsdl file to: 

      <s1:address location="https://ws.fedex.com:443/web-services/rate"/>

Here are the 2 files: 
1. fedex-common.php:
<?php
// Copyright 2009, FedEx Corporation. All rights reserved.

/**
 *  Print SOAP request and response
 */
define('Newline',"<br />");

function printSuccess($client, $response) {
    printReply($client, $response);
}

function printReply($client, $response){
$highestSeverity=$response->HighestSeverity;
if($highestSeverity=="SUCCESS"){echo '<h2>The transaction was successful.</h2>';}
if($highestSeverity=="WARNING"){echo '<h2>The transaction returned a warning.</h2>';}
if($highestSeverity=="ERROR"){echo '<h2>The transaction returned an Error.</h2>';}
if($highestSeverity=="FAILURE"){echo '<h2>The transaction returned a Failure.</h2>';}
echo "\n";
printNotifications($response -> Notifications);
printRequestResponse($client, $response);
}

function printRequestResponse($client){
echo '<h2>Request</h2>' . "\n";
echo '<pre>' . htmlspecialchars($client->__getLastRequest()). '</pre>';  
echo "\n";
   
echo '<h2>Response</h2>'. "\n";
echo '<pre>' . htmlspecialchars($client->__getLastResponse()). '</pre>';
echo "\n";
}

/**
 *  Print SOAP Fault
 */  
function printFault($exception, $client) {
    echo '<h2>Fault</h2>' . "<br>\n";                        
    echo "<b>Code:</b>{$exception->faultcode}<br>\n";
    echo "<b>String:</b>{$exception->faultstring}<br>\n";
    writeToLog($client);
    
    echo '<h2>Request</h2>' . "\n";
echo '<pre>' . htmlspecialchars($client->__getLastRequest()). '</pre>';  
echo "\n";
}

/**
 * SOAP request/response logging to a file
 */                                  
function writeToLog($client){  
/**
* __DIR__ refers to the directory path of the library file.
* This location is not relative based on Include/Require.
*/
if (!$logfile = fopen(__DIR__.'/fedextransactions.log', "a"))
{
    error_func("Cannot open " . __DIR__.'/fedextransactions.log' . " file.\n", 0);
    exit(1);
}
fwrite($logfile, sprintf("\r%s:- %s",date("D M j G:i:s T Y"), $client->__getLastRequest(). "\r\n" . $client->__getLastResponse()."\r\n\r\n"));
}

/**
 * This section provides a convenient place to setup many commonly used variables
 * needed for the php sample code to function.
 */
function getProperty($var){
if($var == 'key') Return 'XXXX';
if($var == 'password') Return 'XXX'; 
if($var == 'shipaccount') Return 'acc no';
if($var == 'billaccount') Return 'acc no'; 
if($var == 'dutyaccount') Return 'XXX'; 
if($var == 'freightaccount') Return 'XXX';  
if($var == 'trackaccount') Return 'XXX'; 
if($var == 'dutiesaccount') Return 'XXX';
if($var == 'importeraccount') Return 'XXX';
if($var == 'brokeraccount') Return 'XXX';
if($var == 'distributionaccount') Return 'XXX';
if($var == 'locationid') Return 'PLBA';
if($var == 'printlabels') Return false;
if($var == 'printdocuments') Return true;
if($var == 'packagecount') Return '4';

if($var == 'meter') Return 'XXX';

if($var == 'shiptimestamp') Return mktime(10, 0, 0, date("m"), date("d")+1, date("Y"));

if($var == 'spodshipdate') Return '2014-07-21';
if($var == 'serviceshipdate') Return '2017-07-26';

if($var == 'readydate') Return '2014-07-09T08:44:07';
//if($var == 'closedate') Return date("Y-m-d");
if($var == 'closedate') Return '2014-07-17';
if($var == 'pickupdate') Return date("Y-m-d", mktime(8, 0, 0, date("m")  , date("d")+1, date("Y")));
if($var == 'pickuptimestamp') Return mktime(8, 0, 0, date("m")  , date("d")+1, date("Y"));
if($var == 'pickuplocationid') Return 'XXX';
if($var == 'pickupconfirmationnumber') Return '1';

if($var == 'dispatchdate') Return date("Y-m-d", mktime(8, 0, 0, date("m")  , date("d")+1, date("Y")));
if($var == 'dispatchlocationid') Return 'XXX';
if($var == 'dispatchconfirmationnumber') Return '1';

if($var == 'tag_readytimestamp') Return mktime(10, 0, 0, date("m"), date("d")+1, date("Y"));
if($var == 'tag_latesttimestamp') Return mktime(20, 0, 0, date("m"), date("d")+1, date("Y"));

if($var == 'expirationdate') Return date("Y-m-d", mktime(8, 0, 0, date("m"), date("d")+15, date("Y")));
if($var == 'begindate') Return '2014-07-22';
if($var == 'enddate') Return '2014-07-25';

if($var == 'trackingnumber') Return 'XXX';

if($var == 'hubid') Return '5531';

if($var == 'jobid') Return 'XXX';

if($var == 'searchlocationphonenumber') Return '5555555555';
if($var == 'customerreference') Return 'Cust_Reference';

if($var == 'shipper') Return array(
'Contact' => array(
'PersonName' => 'Sender Name',
'CompanyName' => 'Sender ABC Name',
'PhoneNumber' => '1234567890'
),
'Address' => array(
'StreetLines' => array('1202 Chalet Ln'),
'City' => 'Harrison',
'StateOrProvinceCode' => 'AR',
'PostalCode' => '72601',
'CountryCode' => 'US',
'Residential' => 1
)
);
if($var == 'recipient') Return array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'XYZ Recipient Company Name',
'PhoneNumber' => '1234567890'
),
'Address' => array(
'StreetLines' => array('2000 Freight LTL Testing'),
'City' => 'Harrison',
'StateOrProvinceCode' => 'AR',
'PostalCode' => '72601',
'CountryCode' => 'US',
'Residential' => 1
)
);

if($var == 'address1') Return array(
'StreetLines' => array('10 Fed Ex Pkwy'),
'City' => 'Memphis',
'StateOrProvinceCode' => 'TN',
'PostalCode' => '38115',
'CountryCode' => 'US'
    );
if($var == 'address2') Return array(
'StreetLines' => array('13450 Farmcrest Ct'),
'City' => 'Herndon',
'StateOrProvinceCode' => 'VA',
'PostalCode' => '20171',
'CountryCode' => 'US'
);  
if($var == 'searchlocationsaddress') Return array(
'StreetLines'=> array('240 Central Park S'),
'City'=>'Austin',
'StateOrProvinceCode'=>'TX',
'PostalCode'=>'78701',
'CountryCode'=>'US'
);
 
if($var == 'shippingchargespayment') Return array(
'PaymentType' => 'SENDER',
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'Contact' => null,
'Address' => array('CountryCode' => 'US')
)
)
);
if($var == 'freightbilling') Return array(
'Contact'=>array(
'ContactId' => 'freight1',
'PersonName' => 'Big Shipper',
'Title' => 'Manager',
'CompanyName' => 'Freight Shipper Co',
'PhoneNumber' => '1234567890'
),
'Address'=>array(
'StreetLines'=>array(
'1202 Chalet Ln', 
'Do Not Delete - Test Account'
),
'City' =>'Harrison',
'StateOrProvinceCode' => 'AR',
'PostalCode' => '72601-6353',
'CountryCode' => 'US'
)
);
}

function setEndpoint($var){
if($var == 'changeEndpoint') Return false;
if($var == 'endpoint') Return 'XXX';
}

function printNotifications($notes){
foreach($notes as $noteKey => $note){
if(is_string($note)){    
            echo $noteKey . ': ' . $note . Newline;
        }
        else{
        printNotifications($note);
        }
}
echo Newline;
}

function printError($client, $response){
    printReply($client, $response);
}

function trackDetails($details, $spacer){
foreach($details as $key => $value){
if(is_array($value) || is_object($value)){
        $newSpacer = $spacer. '&nbsp;&nbsp;&nbsp;&nbsp;';
    echo '<tr><td>'. $spacer . $key.'</td><td>&nbsp;</td></tr>';
    trackDetails($value, $newSpacer);
    }elseif(empty($value)){
    echo '<tr><td>'.$spacer. $key .'</td><td>'.$value.'</td></tr>';
    }else{
    echo '<tr><td>'.$spacer. $key .'</td><td>'.$value.'</td></tr>';
    }
    }
}

?>

getRates.php

<form action="" method="POST">
<table>
<tr><td>Packaging Type </td><td>
<select name="packagingType">
<option value="FEDEX_BOX">FEDEX BOX</option>
<option value="FEDEX_PAK">FEDEX PAK</option>
<option value="FEDEX_TUBE">FEDEX TUBE</option>
<option value="YOUR_PACKAGING">YOUR PACKAGING</option>
</select>
</td></tr>
<tr><td>Destination City: </td><td><input type="text" name="city"></td></tr>
<tr><td>Destination State: </td><td><input type="text" name="state"></td></tr>
<tr><td>Destination Zip Code: </td><td><input type="text" name="zip"></td></tr>
<tr><td>Weight (lbs): </td><td><input type="text" name="weight"></td></tr>
<tr><td>Length (inches): </td><td><input type="text" name="length"></td></tr>
<tr><td>Width (inches): </td><td><input type="text" name="width"></td></tr>
<tr><td>Height (inches): </td><td><input type="text" name="height"></td></tr>
<tr><td colspan="2"><input type="submit" name="submit" value="Submit"></td></tr>

</table>
</form>

<?php
// Copyright 2009, FedEx Corporation. All rights reserved.
// Version 12.0.0
function addShipper(){
$shipper = array(
'Contact' => array(
'PersonName' => 'Test',
'CompanyName' => 'Sender Company Name',
'PhoneNumber' => '9012638716'
),
'Address' => array(
'StreetLines' => array('7729 Lochlin Dr'),
'City' => 'Brighton',
'StateOrProvinceCode' => 'MI',
'PostalCode' => '48116',
'CountryCode' => 'US'
)
);
return $shipper;
}

function addRecipient($recipient){
$recipient = array(
'Contact' => array(
'PersonName' => 'Recipient Name',
'CompanyName' => 'Company Name',
'PhoneNumber' => '9012637906'
),
'Address' => array(
'StreetLines' => array('Address Line 1'),
'City' => $recipient['city'],
'StateOrProvinceCode' => $recipient['state'],
//'PostalCode' => 'V7C4V4',
'PostalCode' => $recipient['zip'],
'CountryCode' => 'US',
'Residential' => false
)
);
return $recipient;                                    
}
function addShippingChargesPayment(){
$shippingChargesPayment = array(
'PaymentType' => 'SENDER', // valid values RECIPIENT, SENDER and THIRD_PARTY
'Payor' => array(
'ResponsibleParty' => array(
'AccountNumber' => getProperty('billaccount'),
'CountryCode' => 'US'
)
)
);
return $shippingChargesPayment;
}
function addLabelSpecification(){
$labelSpecification = array(
'LabelFormatType' => 'COMMON2D', // valid values COMMON2D, LABEL_DATA_ONLY
'ImageType' => 'PDF',  // valid values DPL, EPL2, PDF, ZPLII and PNG
'LabelStockType' => 'PAPER_7X4.75'
);
return $labelSpecification;
}
function addSpecialServices(){
$specialServices = array(
'SpecialServiceTypes' => array('COD'),
'CodDetail' => array(
'CodCollectionAmount' => array(
'Currency' => 'USD', 
'Amount' => 150
),
'CollectionType' => 'ANY' // ANY, GUARANTEED_FUNDS
)
);
return $specialServices; 
}
function addPackageLineItem1($weight,$length,$width,$height){
$packageLineItem = array(
'SequenceNumber'=>1,
'GroupPackageCount'=>1,
'Weight' => array(
'Value' => $weight,
'Units' => 'LB'
),
'Dimensions' => array(
'Length' => $length,
'Width' => $width,
'Height' => $height,
'Units' => 'IN'
)
);
return $packageLineItem;
}

if(isset($_REQUEST['submit'])){
require_once('../../library/fedex-common.php');
echo '<pre>'; print_r($_REQUEST);
$packagingType = $_REQUEST['packagingType'];
$city = $_REQUEST['city'];
$state = $_REQUEST['state'];
$zip = $_REQUEST['zip'];
$weight = $_REQUEST['weight'];
$length = $_REQUEST['length'];
$width = $_REQUEST['width'];
$height = $_REQUEST['height'];
$recipient['city'] = $city;
$recipient['state'] = $state;
$recipient['zip'] = $zip;
/*
$weight = '2';
$length = '2';
$width = '2';
$height = '3';
*/
$newline = "<br />";

$path_to_wsdl = "RateService_v18.wsdl";
ini_set("soap.wsdl_cache_enabled", "0");
$client = new SoapClient($path_to_wsdl, array('trace' => 1)); // Refer to http://us3.php.net/manual/en/ref.soap.php for more information

$request['WebAuthenticationDetail'] = array(
'ParentCredential' => array(
'Key' => getProperty('parentkey'),
'Password' => getProperty('parentpassword')
),
'UserCredential' => array(
'Key' => getProperty('key'), 
'Password' => getProperty('password')
)
); 
$request['ClientDetail'] = array(
'AccountNumber' => getProperty('shipaccount'), 
'MeterNumber' => getProperty('meter')
);

$request['TransactionDetail'] = array('CustomerTransactionId' => ' *** Rate Request using PHP ***');
$request['Version'] = array(
'ServiceId' => 'crs', 
'Major' => '18', 
'Intermediate' => '0', 
'Minor' => '0'
);
$request['ReturnTransitAndCommit'] = true;
$request['RequestedShipment']['DropoffType'] = 'REGULAR_PICKUP'; // valid values REGULAR_PICKUP, REQUEST_COURIER, ...
$request['RequestedShipment']['ShipTimestamp'] = date('c');
//$request['RequestedShipment']['ServiceType'] = $serviceType;// SPECIFY IT IF YOU WANT A PARTICULAR SERVICETYPE eg'INTERNATIONAL_PRIORITY'; // valid values STANDARD_OVERNIGHT, PRIORITY_OVERNIGHT, FEDEX_GROUND, ...
$request['RequestedShipment']['PackagingType'] = $packagingType; // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
/*$request['RequestedShipment']['TotalInsuredValue']=array(
'Ammount'=>100,
'Currency'=>'USD'
);*/
$request['RequestedShipment']['Shipper'] = addShipper();
//$request['RequestedShipment']['Shipper'] = add();
$request['RequestedShipment']['Recipient'] = addRecipient($recipient);
$request['RequestedShipment']['ShippingChargesPayment'] = addShippingChargesPayment();
$request['RequestedShipment']['PackageCount'] = '1';
$request['RequestedShipment']['RequestedPackageLineItems'] = addPackageLineItem1($weight,$length,$width,$height);

try {
if(setEndpoint('changeEndpoint')){
$newLocation = $client->__setLocation(setEndpoint('endpoint'));
}

$response = $client -> getRates($request);


if ($response -> HighestSeverity != 'FAILURE' && $response -> HighestSeverity != 'ERROR'){  
$rateReplyArr = $response -> RateReplyDetails;
$count = count($rateReplyArr);
echo '<table border="1">';
echo '<tr><td>Service Type</td><td>Amount</td><td>Delivery Date</td></tr>';

for($i=0;$i<$count;$i++){
$rateReply = $rateReplyArr[$i];
//echo '<pre>'; print_r($rateReply);
$serviceType = '<tr><td>'.$rateReply -> ServiceType . '</td>';
if($rateReply->RatedShipmentDetails && is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails[0]->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}elseif($rateReply->RatedShipmentDetails && ! is_array($rateReply->RatedShipmentDetails)){
$amount = '<td>$' . number_format($rateReply->RatedShipmentDetails->ShipmentRateDetail->TotalNetCharge->Amount,2,".",",") . '</td>';
}
if(array_key_exists('DeliveryTimestamp',$rateReply)){  
$deliveryDate= '<td>' . $rateReply->DeliveryTimestamp . '</td>';
}else if(array_key_exists('TransitTime',$rateReply)){
$deliveryDate= '<td>' . $rateReply->TransitTime . '</td>';
}else {
$deliveryDate='<td>&nbsp;</td>';
}
echo $serviceType . $amount. $deliveryDate;
echo '</tr>';

}echo '</table>';//count ends
printSuccess($client, $response);
}else{
printError($client, $response);

writeToLog($client);    // Write to log file   
} catch (SoapFault $exception) {
  printFault($exception, $client);        
}
echo '<pre>';// print_r($request); 
print_r($response);// die("ABCD");

}

?>


Run the getRates.php, if you get any error message, just google it!

Monday, August 1, 2016

GET THE EMAIL IDs OF ALL MEMBERS THAT HAVE UNSUBSCRIBED TO MAILCHIMP IN THE LAST N DAYS AND UPDATE OUR DATABASE ACCORDINGLY

GET THE EMAIL IDs OF ALL MEMBERS THAT HAVE UNSUBSCRIBED TO MAILCHIMP IN THE LAST N DAYS AND UPDATE OUR DATABASE ACCORDINGLY

<?php
require_once("includes/db.php");
$db = new DB();
$database = "XXXX";
$list_id = 'XXX';


$unsubscribed_members = getList();
$json_array = getJson($unsubscribed_members);
$get_status = check_status($json_array);
echo '<pre>'; //print_r($json_array);
 print_r($get_status);

function check_status($array_resp){
//echo '<pre>'; print_r($array_resp);
$message[0] = 'Updated on: '.date("F j, Y, g:i a");
$message[1] = "Updates for Unsubscribed Members ";
$count = count($array_resp['members']);
for($i=0;$i<$count;$i++){
$member = $array_resp['members'][$i];
$email = $member['email_address'];
$status = $member['status'];
$last_changed = $member['last_changed'];

if($status=='unsubscribed'){
$unsubscription_status = 0;
$message[] = updateDatabase($email, $last_changed);
}

}
return $message;
}

function getList(){
global $list_id, $MCAPI;
$username = "XXX";
$password = "XXXX";
$api_key = 'XXXXXX-us3';
$dateSince= date('Y-m-d h:i:s',strtotime("-2 days"));
   
$api = array
(
'login' => $username,
'key'   => $api_key,
'url'   => 'https://us3.api.mailchimp.com/3.0/lists/'.$list_id.'/members/?count=50&status=unsubscribed&since_last_changed='.$dateSince
);
//echo '<pre>'; print_r($api);
    $result = mc_request( $api,'GET','','');    
return $result;  
}
function mc_request( $api, $type, $target, $data = false  ) {  
$ch = curl_init( $api['url'] . $target );
curl_setopt( $ch, CURLOPT_HTTPHEADER, array
(
'Content-Type: application/json',
'Authorization: ' . $api['login'] . ' ' . $api['key'],
)
);
curl_setopt($ch, CURLOPT_HEADER, 1);  
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $type );
curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $type );
if( $data )
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) );
$response = curl_exec( $ch );
//echo '<pre>'; var_dump($response);  die("TEST");
//$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close( $ch );
return $response;
}
function getJson($subscribed_members){
$resp = substr(strstr($subscribed_members, '{'), strlen('{'));
$js_result = '{'.$resp;
$jres = json_decode($js_result,true);
return $jres;
}

function updateDatabase($email, $timestamp_opt){
global $database, $db;

$sql_check_unsubscribers = "SELECT enabled FROM $database.subscribe_email WHERE email = '$email'";
$enabled = $db->Query($sql_check_unsubscribers);
if(isset($enabled)&&($enabled!='')){
if($enabled==0)
$message = "Member with email id '$email' is already Unsubscribed! ";
else{
$sql_update_unsubscribers = "UPDATE $database.subscribe_email SET enabled=0
WHERE email = '$email'";
$upd = $db->Command($sql_update_unsubscribers);
$message = "Member with email id '$email' Unsubscribed on: '$timestamp_opt', Updated in table '$upd'";
}
}else{
//echo "NOT IN TABLE"; echo '<br>';
$sql_add_subscribers = "INSERT INTO $database.subscribe_email
(`enabled`,`typeId`,`email`,`date`)
VALUES('0','5','$email',NOW())";
$enabled = $db->Query($sql_add_subscribers);
$message = "Added member with email id '$email' as Unsubscribed! ";
}
return $message;
}

?>

GET THE EMAIL IDs OF ALL MEMBERS THAT HAVE SUBSCRIBED TO MAILCHIMP IN THE LAST N DAYS AND UPDATE OUR DATABSE ACCORDINGLY

GET THE EMAIL IDs OF ALL MEMBERS THAT HAVE SUBSCRIBED TO MAILCHIMP IN THE LAST N DAYS AND UPDATE OUR DATABSE ACCORDINGLY

<?php
require_once("includes/db.php");
$db = new DB();
$database = "XXX";
$list_id = 'XXXXX';


$subscribed_members = getList();
$json_array = getJson($subscribed_members);
$get_status = check_status($json_array);
echo '<pre>'; print_r($get_status);  

function check_status($array_resp){
//echo '<pre>'; print_r($array_resp);
$message[0] = 'Updated on: '.date("F j, Y, g:i a");
$message[1] = "Updates for Subscribed Members ";
$count = count($array_resp['members']);
for($i=0;$i<$count;$i++){
$member = $array_resp['members'][$i];
$email = $member['email_address'];
$status = $member['status'];
$timestamp_opt = $member['timestamp_opt'];

if($status=='subscribed'){
$subscription_status = 1;
$message[] = updateDatabase($email,$subscription_status, $timestamp_opt);
}

}
return $message;
}

function getList(){
global $list_id, $MCAPI;
$username = "XXXX";
$password = "XXXXX";
$api_key = 'XXXXXX-us3';
$dateSince= date('Y-m-d h:i:s',strtotime("-2 days"));  
     
$api = array
(
'login' => $username, 
'key'   => $api_key,
'url'   => 'https://us3.api.mailchimp.com/3.0/lists/'.$list_id.'/members/?count=100&status=subscribed&since_timestamp_opt='.$dateSince
);     
//echo '<pre>'; print_r($api);
    $result = mc_request( $api,'GET','','');     
return $result;   
}
function mc_request( $api, $type, $target, $data = false  ) {   
$ch = curl_init( $api['url'] . $target ); 
curl_setopt( $ch, CURLOPT_HTTPHEADER, array

'Content-Type: application/json', 
'Authorization: ' . $api['login'] . ' ' . $api['key'],

);
curl_setopt($ch, CURLOPT_HEADER, 1);   
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $type );
curl_setopt( $ch, CURLOPT_TIMEOUT, 5 );
curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
curl_setopt( $ch, CURLOPT_USERAGENT, 'YOUR-USER-AGENT' );
curl_setopt( $ch, CURLOPT_CUSTOMREQUEST, $type );
if( $data )
curl_setopt( $ch, CURLOPT_POSTFIELDS, json_encode( $data ) );
$response = curl_exec( $ch );
//echo '<pre>'; var_dump($response);   
//$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close( $ch );
return $response;
}
function getJson($subscribed_members){
//echo $subscribed_members;
$resp = substr(strstr($subscribed_members, '{'), strlen('{'));
$js_result = '{'.$resp;
$jres = json_decode($js_result,true);
//echo '<pre>'; print_r($jres); die('AAA');
return $jres; 
}

function updateDatabase($email,$subscription_status, $timestamp_opt){
global $database, $db;

$sql_check_subscribers = "SELECT * FROM $database.subscribe_email WHERE email = '$email'";
$enabled = $db->getTable($sql_check_subscribers);

if(isset($enabled[0])&&($enabled[0]!='')){ 
$enabled_val = $enabled[0]['enabled'];
if($enabled_val==1)
$message = "Member with email id '$email'  with Opted In Date: '$timestamp_opt' is already Subscribed! ";
else{
$sql_update_subscribers = "UPDATE $database.subscribe_email SET enabled=1
WHERE email = '$email'";
$upd = $db->Command($sql_update_subscribers);
$message = "Updated '$email' with Opted In Date: '$timestamp_opt' in table '$upd' ";
}
}else{
//echo "NOT IN TABLE"; echo '<br>';
$sql_add_subscribers = "INSERT INTO $database.subscribe_email(`enabled`,`typeId`,`email`,`date`) 
VALUES('1','5','$email',NOW())";
$enabled = $db->Query($sql_add_subscribers);
$message = "Added member with email id '$email' as Subscribed! ";
}
return $message;


?>