Showing posts with label PHP. Show all posts
Showing posts with label PHP. Show all posts

Tuesday, May 6, 2014

FuseDesk API Integration

FuseDesk PHP API Integration Class Wrapper.
Use the cases method to add, find and update cases.
see full documentation: https://fusedesk.com/help/api/cases/

Source Code:
<?php
class fusedesk_api
{
 public $fusedeskAppName = 'XXXXXXXX'; // Your fusedesk app name
 public $fusedeskApiKey  = 'XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX'; // Your fusedesk api key
 
 function _newcase($params)
 {
  $err = array();
  
  $args['repid']  = (!empty($params['repid']) ? $params['repid'] : ''); 
  $args['contactid']  = (!empty($params['contactid']) ? $params['contactid']: '');
  $args['status']  = (!empty($params['status']) ? $params['status']: '');
  $args['companyid']  = (!empty($params['companyid']) ? $params['companyid']: '');
  $args['date_assigned']  = (!empty($params['date_assigned']) ? $params['date_assigned']: '');
  $args['date_opened']  = (!empty($params['date_opened']) ? $params['date_opened']: '');
  $args['companyid']  = (!empty($params['companyid']) ? $params['companyid']: '');
  
  date_default_timezone_set('Australia/Sydney');
  $args['date_updated']  = date('Y-m-d H:i:s',time());  
  
  if(!empty($params['email'])){
   $args['email']      = $params['email']; 
  }
  
  if(!empty($params['depid'])){
   $args['depid']   = $params['depid'];   
  }else{
   $err[] = 'depid';
  }
  
  if(!empty($params['summary'])){
   $args['summary']  = $params['summary'];    
  }else{
   $err[] = 'summary';
  }

  if(!empty($params['details'])){
   $args['details']  = $params['details'];  
  }else{
   $err[] = 'details';
  }
  
  if(!empty($params['openedby'])){
   $args['openedby']  = $params['openedby']; 
  }else{
   $err[] = 'openedby';
  }

  if(empty($err)){
   $results =  json_encode($this->_apicall("/cases/", $args, 'POST'));
  }else{
   $results = json_encode(array('error' => 'Invalid submission! Please refresh the page and try again.'));
  }
  
  return $results;
 }
 
 function _apicall( $url, $args = array(), $type = 'GET' )
 {
     $fullurl = 'https://'.$this->fusedeskAppName.'.fusedesk.com/api/v1'.$url; 
     $ch = curl_init();
     curl_setopt($ch, CURLOPT_URL, $fullurl);
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-FuseDesk-API-Key: '.$this->fusedeskApiKey));

     if($type == 'POST') {
         curl_setopt($ch, CURLOPT_POST, true);
         curl_setopt($ch, CURLOPT_POSTFIELDS, $args);
     } else {
         curl_setopt($ch, CURLOPT_URL, $fullurl.'?'.http_build_query($args));
     }
 
  $result = json_decode(curl_exec($ch));
  curl_close($ch);
  
     return $result;
 }
}
?>

Sample Code:

<?php
$params['repid']   = (int) 1;
$params['depid']   = (int) 001;
$params['summary'] = 'Test API summary';
$params['details'] = 'Test API details';
$params['openedby'] = 'Juan Dela Cruz';

$payload = new fusedesk_api();
$cases = $payload->_newcase($params);
print_r($cases);

?>

Wednesday, April 30, 2014

Google AdSense API PHP Integration

Get More Money/Income from AdSense and Increase your Google Ads Revenue by Integrating and Customizing Ads using Google AdSense API. A sample GenerateAdCode method integration using NuSoap Client for Google AdSense API.

Source Code
<?php

require_once 'soapclient/nusoap.php';
require_once 'common.php';

$live  = FALSE;

define('EMAIL', '<YOUR-GOOGLE-DEVELOPER-EMAIL>');
define('PASSWORD', '<YOUR-GOOGLE-DEVELOPER-PASSWORD>');
define('CLIENT_ID', '<YOUR-GOOGLE-CLIENT-ID>');

if($live){
        $server = 'https://www.google.com';
    }else{
        $server = 'https://sandbox.google.com';
}

$namespace = 'http://www.google.com/api/adsense/v3';

/* Authentication Headers */

$header     = EMAIL . PASSWORD . CLIENT_ID;

/* Creating Soap Client Request */

$wsdl   = $server . '/api/adsense/v3/AccountService?wsdl';
$client = new soapclient($wsdl, true);
$err    = $client->getError();

if ($err) {
  showSoapClientError($err);
  return;
}
$client->soap_defencoding = 'UTF-8';

/* Set the headers; they are needed for authentication */
$client->setHeaders($header);
if ($client->fault) {
  showMyErrors($client);
  return;
}
$err = $client->getError();
if ($err) {
  showSoapClientError($err);
  return;
}

/* setting the parameter */
$param = "<ns1:getSyndicationService xmlns:ns1=\"$namespace\"><synServiceType><value>ContentAds</value></synServiceType></ns1:getSyndicationService>";

/* invoke web service */
showCall('getSyndicationService', $param);
$response = $client->call('getSyndicationService', $param, $namespace);
if ($client->fault) {
  showMyErrors($client);
  return;
}
$err = $client->getError();
if ($err) {
  showSoapClientError($err);
  return;
}

/* get back the response */
$response = $response['return'];
$synServiceId = $response['id'];
showSynServiceId($synServiceId);


/* showing the soap */
showRequestResponse($client);


// setup client soap for another webservice
$wsdl = $server . '/api/adsense/v3/AdSenseForContentService?wsdl';
$client = new soapclient($wsdl, true);
$err = $client->getError();
if ($err) {
  showSoapClientError($err);
  return;
}
$client->soap_defencoding = 'UTF-8';

/* Set the headers; they are needed for authentication */
$client->setHeaders($header);
if ($client->fault) {
  showMyErrors($client);
  return;
}
$err = $client->getError();
if ($err) {
  showSoapClientError($err);
  return;
}

/* setting up adstyle parameter */
$ads_param = '<adStyle>';
$ads_param .= "<name>demoStyle</name>";
$ads_param .= '<borderColor>#0000FF</borderColor>';
$ads_param .= '<backgroundColor>#FFFFFF</backgroundColor>';
$ads_param .= '<titleColor>#FF0000</titleColor>';
$ads_param .= '<textColor>#00FF00</textColor>';
$ads_param .= '<urlColor>#FFFF00</urlColor>';
$ads_param .= '</adStyle>';

/* setting up parameter */
$param = '<synServiceId>'.$synServiceId.'</synServiceId>';
$param .= $ads_param;
$param .= '<adUnitType><value>TextOnly</value></adUnitType>';
$param .= '<layout><value>728x90</value></layout>';
$param .= '<alternate>#FFFFFF</alternate>';
$param .= '<isFramedPage type="xsd:boolean">false</isFramedPage>';
$param .= '<channelName xsi:nil="true"/>';
$param .= '<cornerStyles><value>DEFAULT</value></cornerStyles>';

$param = "<ns1:generateAdCode xmlns:ns1=\"$namespace\">" . $param . "</ns1:generateAdCode>";

/* invoke the web service */
showCall('generateAdCode', $param);
$response = $client->call('generateAdCode', $param, $namespace);
if ($client->fault) {
  showMyErrors($client);
  return;
}
$err = $client->getError();
if ($err) {
  showSoapClientError($err);
  return;
}

$response = $response['return'];
$snippet = $response;
showSnippet($snippet);

/* showing the soap */
showRequestResponse($client);

?>


Posting Status in your Facebook Page with PHP API Class Wrapper

Post your Status in Facebook Page with PHP API Class Wrapper

Get Your App Id and App Secret 
http://developers.facebook.com

Facebook PHP SDK (v.3.2.2)
https://github.com/facebook/facebook-php-sdk

Source Code

<?php

/* Post your Status in your Facebook Page with PHP API Integration */

require 'src/facebook.php';

/* Configure Facebook Apps Settings */

define('APP_ID', '<YOUR-APP-ID>');
define('APP_SECRET', '<YOUR-APP-SECRET>');
define('APP_PERMISSION', 'publish_stream, manage_pages');
define('FILE_UPLAOD', FALSE);


/* Configure Facebook */

$facebook = new Facebook(
                array(
                    'appId'         => APP_ID,
                    'secret'        => APP_SECRET,
                    'fileUpload'    => FILE_UPLAOD
                )
        );

try {
    
    $user = $facebook->getUser();

    if ($user) {
        
        $page_id = '<YOUR-PAGE-ID>';
        $page_info = $facebook->api("/$page_id?fields=access_token");
        
        if( !empty($page_info['access_token']) ) {
            $data = array(
                            'access_token'  => $page_info['access_token'],
                            'message'       => '<YOUR-POST-MESSAGE>', 
                            'picture'       => '<YOUR-PICTURE-URL-LINK>', 
                            'link'          => '<YOUR-WEBSITE-URL-LINK>',
                            'description'   => '<YOUR-POST-DESCRIPTION>', 
                            'name'          => '<YOUR-POST-NAME>'

                        );
            $post_id = $facebook->api("/$page_id/feed","post",$data);
       } else {
        $permissions = $facebook->api("/me/permissions");
        if( !array_key_exists('publish_stream', $permissions['data'][0]) || !array_key_exists('manage_pages', $permissions['data'][0])) {
            echo("<script>top.location.href='" . $facebook->getLoginUrl(array( 'scope' => APP_PERMISSION )) . "'</script>");
        }

    }
        
    }else{
        echo("<script>top.location.href='" . $facebook->getLoginUrl(array( 'scope' => APP_PERMISSION )) . "'</script>");
    }

} catch (FacebookApiException $e) {
    echo $e->getMessage();
    $user = null;
}

PHP Twitter OAuth Login Dialog Implementation

This simple code is used for authentication in twitter. It is an OAuth Login using PHP SDK Codebird Adapter.

Get Your Twitter Developer Account ( Consumer Key & Consumer Secret )
https://dev.twitter.com/

Source Code
<?php session_start();

require_once 'codebird.php';

define('CONSUMER_KEY', '<YOUR-CONSUMER-KEY>');
define('COMSUMER_SECRET', '<YOUR-CONSUMER-SECRET>');

Codebird::setConsumerKey(CONSUMER_KEY, COMSUMER_SECRET);
$tweet = Codebird::getInstance();

if (!isset($_REQUEST['oauth_verifier'])) {

        $response = $tweet->oauth_requestToken(array('oauth_callback' => 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']));
        $tweet->setToken($response->oauth_token, $response->oauth_token_secret);

        $_SESSION['OAUTH_TOKEN']        = $response->oauth_token;
        $_SESSION['OAUTH_TOKEN_SECRET'] = $response->oauth_token_secret;

        $auth_url = $tweet->oauth_authorize();
        header('Location: ' . $auth_url);
        exit;
    
    } else {
    
        $tweet->setToken($_SESSION['OAUTH_TOKEN'], $_SESSION['OAUTH_TOKEN_SECRET']);
        $response = $twitt->oauth_accessToken(array('oauth_verifier' => $_REQUEST['oauth_verifier']));

        $_SESSION['OAUTH_TOKEN']        = $response->oauth_token;
        $_SESSION['OAUTH_TOKEN_SECRET'] = $response->oauth_token_secret;
}

/* Get your account details.*/

$tweet->setReturnFormat(CODEBIRD_RETURNFORMAT_ARRAY);
$acct_info = $tweet->account_verifyCredentials();
var_dump($acct_info);




Send SMS PHP Integration Using Twilio API

This sample source code is a simple PHP Integration which uses Twilio API.

Get Your API ACCOUNT SID and AUTH TOKEN 
http://www.twilio.com/user/account/

Source Code
<?php

   require_once 'Services/Twilio.php';

   define('ACCOUNT_SID', '<YOUR-ACCOUNT-SID>');  
   define('AUTH_TOKEN', '<YOUR-AUTH-TOKEN>');  
   
   $client = new Services_Twilio(ACCOUNT_SID, AUTH_TOKEN);
   
   /* Send an SMS */
   
   $twilioNumber = "XXX-XXX-XXXX";  /* Twilio number that you've purchased*/
   $mobilePhoneNumber = "+63XXXXXXXXXXX"; /* the number you are sending */
   
   $artist = "Juan Dela Cruz";
   $message = "Rock N Roll!. - {$artist}";
   
   $sendSMS = $client->account->sms_messages->create($twilioNumber , $mobilePhoneNumber , $message );
   
   /* Response */
   echo $sendSMS->sid;
   
  
?>
   

Simple Facebook API PHP Integration

This is a PHP Integration using Facebook PHP SDK (v.3.2.2) This sample code will help you on how to post messages, pictures, links, descriptions,names and captions into your wall.

 Get Your App Id and App Secret 
http://developers.facebook.com

Facebook PHP SDK (v.3.2.2)
https://github.com/facebook/facebook-php-sdk

Source Code


<?php
/**
 * Name         : Simple Facebook API PHP Integration
 * Description  : Post message, picture, link, description, name, caption to your wall!. 
 * Author       : Ryan Tipones
 * Version      : 0.1
 * Author URI   : wpmigrator.wordpress.com
 *  
 */

require 'src/facebook.php';

/* Configure Facebook Apps Settings */

define('APP_ID', '<YOUR_APP_ID>');
define('APP_SECRET', '<YOUR_APP_SECRET>');
define('APP_PERMISSION', 'publish_stream,read_stream');
define('FILE_UPLAOD', FALSE);

$facebook = new Facebook(
                array(
                    'appId'         => APP_ID,
                    'secret'        => APP_SECRET,
                    'fileUpload'    => FILE_UPLAOD
                )
        );

try {
    
    $user = $facebook->getUser();

    if ($user) {
        
        $user_info = $facebook->api('/me'); 
        
        if ($user_info) { 
            
            /* Your basic profile information */

            $id           = $user_info['id'];
            $name         = $user_info['name'];
            $first_nam    = $user_info['first_nam'];
            $last_name    = $user_info['last_name'];
            $username     = $user_info['username'];
            $birthday     = $user_info['birthday'];
            $hometown     = $user_info['hometown']['name'];
            $gender       = $user_info['gender'];
            $email        = $user_info['email'];

        }
        
        $privacy = array(
                'value'     => 'ALL_FRIENDS', // EVERYONE, ALL_FRIENDS, NETWORKS_FRIENDS, FRIENDS_OF_FRIENDS, CUSTOM
                'friends'   => '', //FRIENDS_OF_FRIENDS, ALL_FRIENDS, SOME_FRIENDS, SELF, or NO_FRIENDS
                'allow'     => '', // Change this to your friends ids
                'deny'      => '' // Change this to your friends ids 
            );
                    
        $post_id = $facebook->api('/me/feed', 'post', 
                array(
                        'message'   => 'Simple Facebook API PHP Integration', 
                        'picture'   => '<YOUR-IMAGE-LINK-URL>', 
                        'link'      => 'http://bikolexpressonline.com',
                        'description'   =>'Simple PHP Integration using Facebook PHP SDK (v.3.2.2)', 
                        'name'          => 'Test API Facebook SDK', 
                        'privacy'       => json_encode($privacy),
                        'caption'       => 'BikolExpress Online Free Source Code for life!'
                    )
             );
        
        /* Debug */
        print_r($post_id);
        
    }else{
        echo("<script>top.location.href='" . $facebook->getLoginUrl(array( 'scope' => APP_PERMISSION )) . "'</script>");
    }

} catch (FacebookApiException $e) {
    echo $e->getMessage();
    $user = null;
}

Salesforce AddLead and Task API Webservice

Salesforce Webservice API Integration using PHP SOAP Client library.
 Method AddLead and Create Task for Leads.
 Get Salesforce developer account to.

http://developer.force.com

Source Code
<?php

/**
 * Name         : Salesforce - AddLead and Task API Webservice
 * Description  : Salesforce Webservice API Integration using PHP SOAP Client library. 
 * Author       : Ryan Tipones
 * Version      : 0.1
 * Author URI   : wpmigrator.wordpress.com
 * Salesforce Developer : http://developer.force.com/
 *  
 */


ini_set("soap.wsdl_cache_enabled", "0");

require_once 'soapclient/SforcePartnerClient.php';
require_once 'soapclient/SforceHeaderOptions.php';

$wsdl       = 'soapclient/partner.wsdl.xml';
$userName   = "YOUR_SALES_FORCE_USERNAME";
$password   = "YOUR_SALES_FORCE_PASSWORD";

$client     = new SforcePartnerClient();
$client->createConnection($wsdl);
$client->login($userName, $password);

/* Salesforce Create New Lead */ 

$lead = new sObject();
$lead->type = 'Lead';
$lead->fields = array(
    'FirstName'     => '',
    'LastName'      => '',
    'Company'       => '',
    'Email'         => '',
    'Country'       => '',
    'MobilePhone'   => ''
);

/* Submitting the Lead to Salesforce */

$result = $client->create(array($lead), 'Lead');

/* Debug */

 print_r($response); 


/* Salesforce Create Task */

/* Check Lead Email if Exist*/

$response  = $client->query("SELECT Id,Email from Lead WHERE Email='{$email}'");

if(!empty($response->records)){
    
     $data      = (array) $response->records;
     $LeadId    = $data[0]->Id;
     $fields    = array (
                    'Status'        => '', // Not Started , In Progress , Completed
                    'Description'   => '',
                    'Subject'       => '',
                    'WhoId'         => $LeadId,
                    'ActivityDate'  => date('c')
    );
     
    $sObject            = new SObject();
    $sObject->fields    = $fields;
    $sObject->type      = 'Task';
    $response           = $client->create(array($sObject));
    
    /* Debug */
    
    print_r($response); 
}
        
       


StorMan Webservice API PHP Integration

StorMan WS_AddContact Webservice API Integration using PHP NuSoap wsdl client library.

StorMan WS_AddContact Method Documentation.
http://www.storman.com/api/WS_AddContact.pdf

StorMan API documents
http://my.storman.com/support/knowledgebase/onlineservices/api.php

PHP NuSoap Library
http://sourceforge.net/projects/nusoap/ 

Source Code

<?php
/**
 * Name         : StorMan - WS_AddContact Webservice
 * Description  : StorMan Webservice API Integration using PHP NuSoap wsdl client library. 
 * Author       : Ryan Tipones
 * Version      : 0.1
 * Author URI   : http://wpmigrator.wordpress.com
 * StorMan Reference Docs : http://www.storman.com/api/WS_AddContact.pdf
 *  
 */
require_once 'lib/nusoap.php';
 
/* Your StorMan Endpoint Server Url*/
$endPointUrl = "http://ipaddressofStorMancomputer:19812/4dwsdl"; $client = new nusoap_client( $endPointUrl, true); $err = $client->getError();
if ($err) {
    echo '<h2>Constructor error</h2>' . $err;
}
$result = $client->call("WS_AddContact", 
        array(
                'WS_CTFacility'     => '', 
                'WS_CTContactName'  => '', 
                'WS_CTTitle'        => '', 
                'WS_CTFirstName'    => '', 
                'WS_CTUserName'     => '', 
                'WS_CTMailAddress'  => '', 
                'WS_CTMailCity'     => '', 
                'WS_CTMailState'    => '', 
                'WS_CTMailZIPCode'  => '', 
                'WS_CTMailCountry'  => '', 
                'WS_CTContactPhone' => '', 
                'WS_CTPhoneBus'     => '', 
                'WS_CTMobilePhone'  => '', 
                'WS_CTEmailAddress' => '', 
                'WS_CTOrganization' => '',                 
                'WS_CTMarketSrce'   => '', 
                'WS_CTCustType'     => '', 
                'WS_CTCategory'     => '', 
                'WS_CTStoredBefore' => '', 
                'WS_CTStoredGoods'  => '', 
                'WS_CTWhenRequired' => '', 
                'WS_CTExpDuration'  => '', 
                'WS_asQTAnalysisCode' => array(), 
                'WS_asQTSize'           => array(), 
                'WS_asQTUnitTypeCode'   => array(), 
                'WS_asQTNote'           => array(), 
                'WS_asQTPrice'          => array(), 
                'WS_CTOldContactNo'     => '', 
                'WS_WebServicePassword' => '' 
            )
        );
/* Debug */
if ($client->fault) {
    echo '<h2>Fault</h2>';
        print_r($result);
} else {
    // Check for errors
    $err = $client->getError();
    if ($err) {
        // Display the error
        echo '<h2>Error</h2>' . $err . '';
    } else {
        // Display the result
        echo '<h2>Result</h2>';
        print_r($result);
  
    }
}



Simple Google URL Shortener PHP Class Wrapper

This is a simple PHP Class Wrapper using Google API URL

<?php

class GoogleUrlShortener 
{
        public $endPoint = 'https://www.googleapis.com/urlshortener/v1/url';
        public $key      = 'YOUR_GOOGLE_API_KEY';
        
        /* Shorten a long URL */
        function shorten($url)
        {
            $data = $this->execute($url,1);
            
            if(isset($data['id'])){
                    $result = $data['id'];
                }else{
                    $result = FALSE;
            }
            
            return $result;
        }
        
        /* Expand a short URL */
        function expand($url) 
        {
            $data = $this->execute($url,0);
            
            if(isset($data['longUrl'])){
                    $result = $data['longUrl'];
                }else{
                    $result = FALSE;
            }
            
            return $result;
        }
        
        /* Send Request to Google */
        function execute($url,$status) 
        {
            $curl           = curl_init();
            $googleApiUrl   = $this->endPoint.'?key='.$this->key;
            
            if($status == 1) {
                    curl_setopt($curl,CURLOPT_URL,$googleApiUrl);
                    curl_setopt($curl,CURLOPT_POST,1);
                    curl_setopt($curl,CURLOPT_POSTFIELDS,json_encode(array("longUrl"=>$url)));
                    curl_setopt($curl,CURLOPT_HTTPHEADER,array("Content-Type: application/json"));
                }else {
                    curl_setopt($curl,CURLOPT_URL,$googleApiUrl.'&shortUrl='.$url);
            }
            
            curl_setopt($curl,CURLOPT_RETURNTRANSFER,1);
            $res = curl_exec($curl);
            curl_close($curl);
            
            return json_decode($res,true);
        }    
}

Examples
  • Shorten URL
<?php

$shorten_my_url = new GoogleUrlShortener();
echo $shorten_my_url->shorten("http://wpmigrator.wordpress.com");
output : http://goo.gl/MZ4bW
  • Expand URL
<?php

$expand_my_url = new GoogleUrlShortener();
echo $expand_my_url->expand("http://goo.gl/MZ4bW");
output : http://wpmigrator.wordpress.com
Genesis Framework for WordPress