Tuesday 20 June 2017

Bitcoin Coinbase API for PHP - Example

Bitcoin Coinbase API for PHP - Example

Bitcoin is an innovative payment network and a new kind of money. Bitcoin is the world's most widely used alternative currency with a total market cap of approximately $10 billion. The bitcoin network is made up of thousands of computers run by individuals all over the world.
Here i am going to present a small example to send money with Coinbase API. You can create a new payment button with Coinbase api. Let see step by step how it will work.

Step 1: Create a payment.php file


<?phprequire __DIR__ . '/vendor/autoload.php';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Value\Money;
use Coinbase\Wallet\Resource\Checkout;
use Coinbase\Wallet\Resource\Order;
    
$apiKey = 'API KEY';
$apiSecret = 'API SECRET';

$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);

$amount = 0.1;
$orderId = "YOUR ORDER ID";

$params = array(
    'name'          => 'Site order ID: '.$orderId,
    'amount'        => new Money($amount, 'USD'),
    'metadata'      => array('order_id' => $orderId),
    'auto_redirect' => true
);

$checkout = new Checkout($params);
$client->createCheckout($checkout);
$code = $checkout->getEmbedCode();

$redirect_url = "https://www.coinbase.com/checkouts/$code";
?>

Step 2: Create a notification.php file


<?php require __DIR__ . '/vendor/autoload.php';
use Coinbase\Wallet\Client;
use Coinbase\Wallet\Configuration;
use Coinbase\Wallet\Value\Money;
use Coinbase\Wallet\Resource\Checkout;
use Coinbase\Wallet\Resource\Order;

$apiKey = 'API KEY';
$apiSecret = 'API SECRET';
$configuration = Configuration::apiKey($apiKey, $apiSecret);
$client = Client::create($configuration);

$raw_body = file_get_contents('php://input');
$signature = $_SERVER['HTTP_CB_SIGNATURE'];
$authenticity = $client->verifyCallback($raw_body, $signature); // boolean
if($authenticity){
 $order = json_decode($raw_body, true);
    mail("YOUR EMAIL ID","Coinbase Patment Notifications",print_r($order, true));
}
?>

Step 3: Create a success.php file


<?php
$order = $_GET['order'];
var_dump($order);
?>

Note: You need to set these all files url in your coinbase merchant account

Friday 28 April 2017

Consuming REST API in PHP Using Guzzle

If you are familiar with Rest API, you must know about HTTP calls created for getting and posting data from the client to the server. What if you wish to create a REST API client in PHP? Your answer would be to go with CURL. CURL is the most widely used method to make HTTP calls but it contains several complicated steps.
Let’s see a simple CURL request in PHP:
$url = “https://api.cloudways.com/api/v1
$resource = curl_init($url);
curl_setopt($ch, CURLOPT_HTTPHEADER, [‘Accept:application/json, Content-Type:application/json’]);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, ‘GET’);
You need to call the curl_setopt() method to define the header and the particular HTTP verb like GET, POST, PUT, etc. It does look pretty complicated. So, what is a better and robust alternative?
Here comes Guzzle.
Let’s see how Guzzle creates a request:
$client = new GuzzleHttp\Client();
$res = $client->request(‘GET’, ‘https://api.cloudways.com/api/v1’, [
‘headers’ => [
‘Accept’ => ‘application/json’,
‘Content-type’ => ‘application/json’
]])
You could see that it is simple. You just need to initialize the Guzzle client and give HTTP verbs and a URL. After that, pass the array of headers and other options.

Understand the Guzzle Client

Guzzle is a simple PHP HTTP client that provide an easy method of creating calls and integration with web services. It is the standard abstraction layer used by the API to send messages over the server. Several prominent features of Guzzle are:
  1. Guzzle can send both synchronous and asynchronous requests.
  2. It provides a simple interface for building query strings, POST requests, streaming large uploads & downloads, uploading JSON data, etc.
  3. Allows the use of other PSR7 compatible libraries with Guzzle.
  4. Allows you to write environment and transport agnostic code.
  5. Middleware system allows you to augment and compose client behavior.

Install Guzzle In PHP

The preferred way of installing Guzzle is Composer. If you haven’t installed Composer yet, download it from here
Now to install Guzzle, run the following command in SSH terminal:
composer require guzzlehttp/guzzle
This command will install the latest version of Guzzle in your PHP project. Alternatively you can also define it as a dependency in the composer.json file and add the following code in it.
{
 “require”: {
 “guzzlehttp/guzzle”: “~6.0”
 }
}
After that, run the composer install command. Finally you need to require the autoloader and added some more files to use Guzzle:
require ‘vendor/autoload.php’;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use GuzzleHttp\Psr7\Request;
The installation process is over and now it’s time to work with a real example of creating HTTP calls with an API. For the purpose of this article, I will work with Cloudways API.

What You Can Do With the Cloudways API

Cloudways is a managed hosting provider for PHP, Magento, WordPress and many other frameworks and CMS. It has an API that you could use for performing CRUD operations on servers and applications. Check out popular use cases of the Cloudways API to see how you could integrate it into your projects.
In this article, I am going to create HTTP calls to perform specific operations with Guzzle on Cloudways server.

Create the HTTP Requests In Guzzle

As I mentioned earlier, creating HTTP requests in Guzzle is very easy; you only need to pass the base URI, HTTP verb and headers. If there is an authentication layer in the external API, you can also pass these parameters in Guzzle. Similarly, Cloudways API needs email and API key to authenticate users and send the response. You need to sign up for a Cloudways account to get your API credentials.
Let’s start by creating a CloudwaysAPIClient.php file to set up Guzzle for making HTTP calls. I will also create a class and several methods using HTTP calls in them.
The URL of the API does not change so I will use const datatype for it. Later on, I will concatenate it with other URL suffixes to get the response. Additionally, I have declared variables $auth_key,$auth_email which will hold the authentication email and the API key. $accessToken will hold the temporary token which will be renewed every time.
Class CloudwaysAPIClient
{
private $client = null;
const API_URL = “https://api.cloudways.com/api/v1";
var $auth_key;
var $auth_email;
var $accessToken;
public function __construct($email,$key)
{
$this->auth_email = $email;
$this->auth_key = $key;
$this->client = new Client();
}
}

Create a Post Request to get Access Token

The access token will be generated from this URL: https://api.cloudways.com/api/v1/oauth/access_token every time I access the API. This will be set in $url with additional data array which holds auth credentials. Later on, I created a POST request with the base URL and query string. The response will be decoded and access token is saved to be used within the methods.
public function prepare_access_token()
{
try
{
$url = self::API_URL . “/oauth/access_token”;
$data = [‘email’ => $this->auth_email,’api_key’ => $this->auth_key];
$response = $this->client->post($url, [‘query’ => $data]);
$result = json_decode($response->getBody()->getContents());
$this->accessToken = $result->access_token;
}
catch (RequestException $e)
{
$response = $this->StatusCodeHandling($e);
return $response;
}
}
Here the POST request for getting access token is completed. Additionally, If you observed in the exception handling, I declared a method StatusCodeHandling($e), which will take care of the response codes (HTTP codes like 404, 401, 200 etc), and throw a related exception.
public function StatusCodeHandling($e)
{
if ($e->getResponse()->getStatusCode() == ‘400’)
{
$this->prepare_access_token();
}
elseif ($e->getResponse()->getStatusCode() == ‘422’)
{
$response = json_decode($e->getResponse()->getBody(true)->getContents());
return $response;
}
elseif ($e->getResponse()->getStatusCode() == ‘500’)
{
$response = json_decode($e->getResponse()->getBody(true)->getContents());
return $response;
}
elseif ($e->getResponse()->getStatusCode() == ‘401’)
{
$response = json_decode($e->getResponse()->getBody(true)->getContents());
return $response;
}
elseif ($e->getResponse()->getStatusCode() == ‘403’)
{
$response = json_decode($e->getResponse()->getBody(true)->getContents());
return $response;
}
else
{
$response = json_decode($e->getResponse()->getBody(true)->getContents());
return $response;
}
}
The main client class is now completed. I will extend it to create more HTTP requests for different cases.

Create a GET Request to Fetch All Servers

Once the User is authenticated, I can fetch all my servers and applications from Cloudways. /server is the suffix concatenated with the base URI. This time, I will attach the accessToken with Authorization string in Guzzle header to fetch all servers in JSON response. To do this, create a new method:
Public function get_servers()
{
try
{
$url = self::API_URL . “/server”;
$option = array(‘exceptions’ => false);
$header = array(‘Authorization’=>’Bearer ‘ . $this->accessToken);
$response = $this->client->get($url, array(‘headers’ => $header));
$result = $response->getBody()->getContents();
return $result;
}
catch (RequestException $e)
{
$response = $this->StatusCodeHandling($e);
return $response;
}
}
Now create index.php file and include CloudwaysAPIClient.php at the top. Next, I will declare my API key and email, passing it to the class constructor to finally get the servers.
include ‘CloudwaysAPIClient.php’;
$api_key = ‘W9bqKxxxxxxxxxxxxxxxxxxxjEfY0’;
$email = ‘shahroze.nawaz@cloudways.com’;
$cw_api = new CloudwaysAPIClient($email,$api_key);
$servers = $cw_api->get_servers();
echo ‘<pre>’;
var_dump($servers);
echo ‘</pre>’;
Let’s test it in Postman to verify that the information and right response codes are being fetched.
So all my servers hosted on the Cloudways Platforms are being fetched. Similarly, you can create new methods with HTTP calls to get applications, server settings, services and etc.
Let’s create a PUT call to change the label of the server which is cloned-php applications at the moment. But first, I need to get the server ID & label because this information will be used as an argument. To get the server ID, create a foreach loop in the index.php file:
foreach($servers->servers as $server){
echo $server->id;
echo $server->label;
}
Now, if I hit the API, it will fetch the server id and label.

Create a PUT Request to Change Server Label

Now to change the server label, I need to create a PUT call in Guzzle. I will extend the class with a new method. Remember that server id and label are two necessary parameters that will be passed in the method.
public function changelabel($serverid,$label)
{
try
{
$url = self::API_URL . “/server/$serverid”;
$data = [‘server_id’ => $serverid,’label’ => $label];
$header = array(‘Authorization’=>’Bearer ‘ . $this->accessToken);
$response = $this->client->put($url, array(‘query’ => $data,’headers’ => $header));
return json_decode($response->getBody()->getContents());
}
catch (RequestException $e)
{
$response = $this->StatusCodeHandling($e);
return $response;
}
}
Now in the index.php, put this condition beneath the foreach loop.
if($server->id == ‘71265’ && $server->label == ‘Cloned-php applications’){
$label = ‘Cloudways Server’;
$changelabel = $cw_api->changelabel($server->id,$label);
}
When testing this in Postman, I will get the updated server label.

Create a Delete Request to Remove a Server

To delete a server using Cloudways API, I need to create a Delete request in Guzzle through the following method. This is pretty similar to the above method, because it also requires two parameters, server id and label.
public function deleteServer($serverid,$label)
{
try
{
$url = self::API_URL . “/server/$serverid”;
$data = [‘server_id’ => $serverid,’label’ => $label];
$header = array(‘Authorization’=>’Bearer ‘ . $this->accessToken);
$response = $this->client->delete($url, array(‘query’ => $data,’headers’ => $header));
return json_decode($response->getBody()->getContents());
}
catch (RequestException $e)
{
$response = $this->StatusCodeHandling($e);
return $response;
}
}
Try this in Postman or just refresh the page. The server will be deleted.

Final Words

Guzzle is a flexible HTTP client that you could extend as per your requirements. You can also try out new ideas with uploading data, form fields, cookies, redirects and exceptions. You can also create middleware for authentication layer (if needed). All in all, Guzzle is a great option for creating REST API in PHP, without using any frameworks.
If you have any questions or query you can comment below.

Sunday 16 April 2017

What is WebGL and how does it work?

WebGL 

Web Graphics Library (WebGL) is a javaScript API for rendering 2D and 3D graphics within web browser without the use any plug-ins. It is derived from OpenGL's Embedded Systems (ES) 2.0 library which is a low-level 3D API for phones and other mobile devices. WebGL provides similar functionality of ES 2.0 and uses the HTML5 canvas element to performs well on modern 3D graphics hardware.

WebGL is written in a mix of JavaScript and shader code that is written in OpenGL Shading Language, a language similar to C or C++, and is executed on a computer's GPU.

In 2007, Vladimir Vukicevic, an American-Serbian software engineer started working on an OpenGL prototype for Canvas element of the HTML document. By the end of 2007, both Mozilla and Opera had made their own separate implementations. In early 2009, the non-profit technology consortium Khronos Group started the WebGL Working Group, with initial participation from Apple, Google, Mozilla, Opera, and others.

Version 1.0 was released in March 2011 and some early adopters and users of WebGL including Google Maps and Zygote Body. Autodesk also ported many of their applications to the cloud, running on local WebGL systems. Some of the browsers that support WebGL include Google Chrome, Mozilla Firefox, Internet Explorer, Opera, and Safari. It is also supported by a number of mobile browsers including Opera Mobile, WebOS, and MeeGo.


How does it work?

WebGL is slightly more complicated than your typical web technologies because it’s designed to work directly with your graphics card. To access WebGL content you need to have a browser that supports it. Also, having a good graphics card will likely improve WebGL performance on your computer. This is what allows it to rapidly do complex 3D rendering involving lots of calculations.

When programming in WebGL, you are usually aiming to render a scene of some kind. This usually includes multiple subsequent draw jobs or calls, each of which is carried out in the GPU through a process called the rendering pipeline.

In WebGL, like in most real-time 3D graphics, the triangle is the basic element with which models are drawn. Therefore, the process of drawing in WebGL involves using JavaScript to generate the information that specifies where and how these triangles will be created, and how they will look like; colour, shades, textures, etc. This information is then fed to the GPU, which processes it, and returns a view of the scene.

The key metaphor here is that of a pipeline. GPUs are massively parallel processors, consisting of a large number of computation units designed to work in parallel with each other, and in parallel with the CPU. That is true even in mobile devices. With that in mind, graphics APIs such as WebGL are designed to be inherently friendly to such parallel architectures. On typical work loads, and when correctly used, WebGL allows the GPU to execute graphics commands in parallel with any CPU-side work, i.e. the GPU and the CPU should not have to wait for each other, and WebGL allows the GPU to max out its parallel processing power. It is in order to allow running on the GPU that these shaders are written in a dedicated GPU-friendly language rather than in JavaScript. It is in order to allow the GPU to run many shaders simultaneously that shaders are just callbacks handling one vertex or one pixel each - so that the GPU is free to run shaders on whichever GPU execution unit and in whichever order it pleases.

Conclusion

In the recent years WebGL bring lot of change the world wide web with 3D graphics and browser games. Even bring the 3D world map in our browser, and with the latest stable release of WebGL 2 it put one step ahead. In future we will able to see some more interesting implement in WebGL.

REST API and how does it work

REST API
REST or Representational state transfer API defines a set of functions which developers can perform requests and receive responses via HTTP protocol such as GET and POST. It providing interoperability between computer systems on the Internet. REST-compliant Web services allow requesting systems to access and manipulate textual representations of Web resources using a uniform and predefined set of stateless operations. Other forms of Web service exist, which expose their own arbitrary sets of operations such as WSDL and SOAP.
The REST used by browsers. REST technology is generally preferred to the more robust SOAP technology because REST leverages less bandwidth, making it more suitable for internet usage. An API for a website is code that allows two software programs to communicate with each another. With cloud use on the rise, APIs are emerging to expose web services. REST is a logical choice for building APIs that allow users to connect and interact with cloud services. This APIs are commonly used by popular sites like Amazon, Google, LinkedIn and Twitter.
The REST architectural style describes six constraints. The six constraints are: 

  • Uniform Interface - The uniform constraint interface is fundamental to the design of any REST service. It simplifies and decouples the architecture, which enables each part to evolve independently.
  • Client-server - Separation of concerns is the principle behind the client-server constraints. By separating the user interface concerns from the data storage concerns, it improves the portability of the user interface across multiple platforms and improve scalability by simplifying the server components.
  • Stateless - The client–server communication is constrained by no client context being stored on the server between requests. Each request from any client contains all the information necessary to service the request, and session state is held in the client. The session state can be transferred by the server to another service such as a database to maintain a persistent state for a period and allow authentication. The client begins sending requests when it is ready to make the transition to a new state.
  • Cacheable - As on the World Wide Web, clients and intermediaries can cache responses. Responses must therefore, implicitly or explicitly, define themselves as cacheable or not to prevent clients from reusing stale or inappropriate data in response to further requests.
  • Layered system - A client cannot ordinarily tell whether it is connected directly to the end server, or to an intermediary along the way. Intermediary servers may improve system scalability by enabling load balancing and by providing shared caches. They may also enforce security policies.
  • Code on demand - Servers can temporarily extend or customize the functionality of a client by transfering executable code.

How does it work? 

A REST API breaks down a transaction to create a series of small modules. Each module addresses a particular underlying part of the transaction. This modularity provides developers with a lot of flexibility.

A REST API explicitly takes advantage of HTTP methodologies defined by the RFC 2616 protocol. They use GET to retrieve a resource; PUT to change the state of or update a resource, which can be an object, file or block; POST to create that resource; and DELETE to remove it.


With REST, networked components are a resource you request access to a black box. The presumption is that all calls are stateless. Because the calls are stateless, REST is useful in cloud applications. Stateless components can be freely redeployed if something fails, and they can scale to accommodate load changes. This is because any request can be directed to any instance of a component; there can be nothing saved that has to be remembered by the next transaction. That makes REST preferred for web use, but the RESTful model is also helpful in cloud services.

Wednesday 15 March 2017

Login With Yahoo PHP API

Yahoo is one of the network giant.I remember now once upon a time when i was learning class 3rd(2004) I have accessed Yahoo home page from my school internet and and many websites too.btw i Dont know that was internet and Web browser. and This is just a simple post for login with yahoo API for fetching users detail for our web application and authentication.This is basic for fetching users data such as Contacts/Basic Profile and used for posting status and whatever API.We could use general API too. such as Whether forecast,Business Stocks,news headlines.however this is old API familiar to every one,I'm gonna add this and integrate with invite by email script with Google!

Installation : 

Yahoo provides a Library for their Oauth service with many inbuilt functions such as checking session and fetching users data.I have Included it in Demo File.use the Resource.



  • First of all create a developer account and login Yahoo.click here to create. 
  • Create New Application[project] for Web Oauth2 Authentication and Fetching Users Data
  • register your app

    • In Scope choose private data -> contacts and ur preferred options for your application

Choose private data -> contacts -> preferred read or write
  • After Final Step is to verify your Domain by uploading a file to root of the website.
  • Get your Application ID, Consumer Key,Consumer Secret and Note your Domain is verified
    and you can add details about your app in Detail section too.
  • final app registered


    Configuration :

    Under index.php just we are adding our Application details and defining ,They are used to authenticate your application and provide you the user data.
    define('OAUTH_CONSUMER_KEY', 'ZZZZZZZZAAAAA');
    define('OAUTH_CONSUMER_SECRET', 'AAAAAAAAA');
    define('OAUTH_DOMAIN', 'mydomain.com');
    define('OAUTH_APP_ID', 'APP_ID');

    Authenticate The User :

    Include the Yahoo library and lets make authenticate URL,we just need to pass a callback URL alone which can be defined ourself.And to maintain the Authentication flow A Javascript is introduced for User convenience , A popup for authentication and loading the page once again for API calls and fetching user data.So , We have user in_popup in our Callback url to know that the user has authenticated and to reload the page

    YahooSession is a predefined class with member function to create authurlfor our application by passing our key,secret and callback url

      $callback = "http://bulbon.freeiz.com/shivasurya/invite/yahoo/sample/sampleapp.php?in_popup";

      // this URL will be used for the pop-up.

      $auth_url = YahooSession::createAuthorizationUrl(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, $callback);

    place the $auth_url in the form of Login with Yahoo link button.

    Checking for Session : 

    There are two type of function to easily manage session in our application.
    1. hasSession method is used to check the web app has previous any session and this is used to determine to login once again with a popup.
    2. requireSession method is to generate a session for us/fetch session existing one and our session data consist of the profile of the user.

    $hasSession = YahooSession::hasSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

    $session_new = YahooSession::requireSession(OAUTH_CONSUMER_KEY, OAUTH_CONSUMER_SECRET, OAUTH_APP_ID);

    Loading user Data and Displaying Details :

    So,by using the above methods we could check the existing session or request to create new session and we could load the user profile data in our web application.


    if($session_check) {
        $user = $session->getSessionedUser();
      // Load the profile for the current user.
        $profile = $user->getProfile();
      }
    try to var_dump the $profile array to see whole data of User who logined in to web application.For full code download and have a try in your Domain.i am leaving in your part for exception handling and checking sessions and showing login button to the users in your application.

    Note : For using Yahoo API , Your domain must be verified[file upload in root directory] and above code runs in popup for authentication purpose ,enable your popups!