Wednesday, April 30, 2014

Pinterest Javascript and PHP Integration

Pinterest Sample Code Javascript and PHP Integration , Invite people to pin things from your website using Pin It button , Invite people to follow you on Pinterest from your site using Follow button.

  Source Code
<!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <script type="text/javascript">
                (function (d, buildThese) {
                    var homeScript, newScript, n = buildThese.length, i;
                    for (i = 0; i < n; i = i + 1) {
                        newScript = d.createElement('SCRIPT');
                        newScript.type = 'text/javascript';
                        newScript.async = true;
                        newScript.src = buildThese[i];
                        homeScript = d.getElementsByTagName('SCRIPT')[0];
                        homeScript.parentNode.insertBefore(newScript, homeScript);
                    }
                }(document, [
                    '//assets.pinterest.com/js/pinit.js'
                    /* load more third-party JavaScript here */
                ])
            );
        </script>
    </head>
    <body>
        <!-- Pin It button: Invite people to pin things from your website.-->
        
        <?php
            $url            = urlencode("<YOUR-URL>");
            $media          = urlencode("<YOUR-IMAGE-URL>");
            $description    = "<YOUR-DESCRIPTION>";
            $dataPinConfig  = "above"; /* above, beside, none */
            $buttonPin      = "buttonPin"; /* buttonPin, buttonFollow*/
        ?>
        
        <a 
           data-pin-config  ="<?=$dataPinConfig;?>" 
           href             ="//pinterest.com/pin/create/button/?url=<?=$url;?>&media=<?=$media;?>&description=<?=$description;?>" 
           data-pin-do      ="<?=$buttonPin;?>" >
            <img src="//assets.pinterest.com/images/pidgets/pin_it_button.png" />
        </a>
        
        <!-- Follow button: Invite people to follow you on Pinterest from your site.-->
        
        <?php
            $fullName       = "<YOUR-FULL-NAME>";
            $buttonPin      = "buttonFollow";
        ?>
        
        <a 
            data-pin-do="<?=$buttonPin;?>" 
            href="//pinterest.com/pinterest/"><?=$fullName;?>
        </a>
        
    </body>
</html>



BitPay Api Integration

Simple PHP Class Wrapper using BitPay Api Integration.

Source Code
<?php

class BitPay
{
    var $config = array();
    
    function __construct() {
        $this->config = array(
                'apiKey'            => '', /* bitpay.com Api key*/
                'verifyPos'         => 'true',
                'notificationEmail' => '',
                'notificationURL'   => '',
                'redirectURL'       => '',
                'currency'          => 'BTC',
                'physical'          => 'true',
                'fullNotifications' => 'true',
                'transactionSpeed'  => 'low'
         );
    }
    
    function execute ($url, $apiKey, $post = false){
        $curl   = curl_init($url);
        $length = 0;
        
        if ($post) {
            curl_setopt($curl, CURLOPT_POST, 1);
            curl_setopt($curl, CURLOPT_POSTFIELDS, $post);
            $length = strlen($post);
        }

        $uname = base64_encode($apiKey);
        $header = array(
            'Content-Type: application/json',
            "Content-Length: $length",
            "Authorization: Basic $uname",
        );

        curl_setopt($curl, CURLOPT_PORT, 443);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curl, CURLOPT_TIMEOUT, 10);
        curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 1); 
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2); 
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_FORBID_REUSE, 1);
        curl_setopt($curl, CURLOPT_FRESH_CONNECT, 1);

        $responseString = curl_exec($curl);

        if ($responseString == false) {
            $response = curl_error($curl);
        } else {
            $response = json_decode($responseString, true);
        }
        
        curl_close($curl);
        return $response;
    }
    
    function CreateInvoice($orderId, $price, $posData, $options = array()) {
        
        $options = array_merge($this->config, $options); 

        $options['posData'] = '{"posData": "' . $posData . '"';
        if ($this->config['verifyPos']) 
            $options['posData'].= ', "hash": "' . crypt($posData, $this->config['apiKey']) . '"';
        $options['posData'].= '}';

        $options['orderID'] = $orderId;
        $options['price'] = $price;

        $postOptions = array(   'orderID', 
                                'itemDesc', 
                                'itemCode', 
                                'notificationEmail', 
                                'notificationURL', 
                                'redirectURL',
                                'posData', 
                                'price', 
                                'currency', 
                                'physical', 
                                'fullNotifications', 
                                'transactionSpeed', 
                                'buyerName',
                                'buyerAddress1', 
                                'buyerAddress2', 
                                'buyerCity', 
                                'buyerState', 
                                'buyerZip', 
                                'buyerEmail', 
                                'buyerPhone'
                            );
        foreach ($postOptions as $o){
            if (array_key_exists($o, $options)){
                $post[$o] = $options[$o];
            }
        }
            
        $post       = json_encode($post);
        $response   = $this->execute('https://bitpay.com/api/invoice/', $this->config['apiKey'], $post);

        return $response;
    }
    
    function VerifyNotification($apiKey = false) {
        
        if (!$apiKey)
            $apiKey = $this->config['apiKey'];

        $post = file_get_contents("php://input");
        if (!$post)
            return 'No post data';

        $json = json_decode($post, true);

        if (is_string($json))
            return $json; // error

        if (!array_key_exists('posData', $json))
            return 'no posData';

        $posData = json_decode($json['posData'], true);
        if ($this->config['verifyPos'] and $posData['hash'] != crypt($posData['posData'], $apiKey))
            return 'authentication failed (bad hash)';
        $json['posData'] = $posData['posData'];

        return $json;
    }
    
    function GetInvoice($invoiceId, $apiKey = false) {
        
        if (!$apiKey)
            $apiKey = $this->config['apiKey'];

        $response = $this->execute('https://bitpay.com/api/invoice/' . $invoiceId, $apiKey);
        if (is_string($response))
            return $response; // error
        $response['posData'] = json_decode($response['posData'], true);
        return $response;
    }
            
}


?>


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;
}

Invite Friends In FACEBOOK with API Apprequest Method Implementation

This sample Code is a Facebook API method implementation which uses Javascript SDK. A simple source code that can invite your friends to use your Facebook Application.

Source Code


 <!DOCTYPE html>
<html>
    <head>
        <title></title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    </head>
    <body>
        <script type="text/javascript">
            window.fbAsyncInit = function() {
                FB.init({
                    appId: "<YOUR-APP-ID>",
                    status: true,
                    cookie: true
                });
            };
            
            // Load the SDK Asynchronously
            (function(d){
                var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
                if (d.getElementById(id)) {return;}
                js = d.createElement('script'); js.id = id; js.async = true;
                js.src = "//connect.facebook.net/en_US/all.js";
                ref.parentNode.insertBefore(js, ref);
            }(document));
            
            function invite_your_friends() {
                FB.ui({
                    method: "apprequests",
                    message: "Check out this Fantastic App!"
                }, invite_your_friends_callback);
            }
            
            function invite_your_friends_callback(response) {
                console.log(response);
            }

  </script>
  <center>
      <a href="javascript:;" onclick="invite_your_friends();">
          <h3>Invite Your Friends and Share this Fantastic App!</h3>
      </a>
  </center>
    </body>
</html>



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;
   
  
?>
   

Genesis Framework for WordPress