How to get product using rakuten marketing api in PHP?

Share Me
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  
  •  

Today now in this post we will know about how we can use rakuten linkshare API in our php website. So at first we need to create a class for retrieve data from “https://pubhelp.rakutenmarketing.com/hc/en-us” website. Then now i will give you an example of product search, but if we use this class then we can easy to implement our other search like advance search etc. So now i will give you a class that will send a request to rakutenmarketing.com website and it will get data. But on this class we can also you for other site API use as like as CJ API.

Your php file :
public function getProduct()
{
	// Bearer token = 416b5350fcccf11f11826c25a058d6a88
	$token = 'Bearer token';  
    $client = new RakuteAPI($token);  
    $parameters = ['keyword'=>'test','max'=>50];  
    $products = $client->productSearch($parameters);  
    print_r($products);
}

RakuteAPI.php

class RakuteAPI {
    public $domain = "https://api.rakutenmarketing.com/%s/%s";

    /**
     * Curl handle
     *
     * @var resource
     */
    protected $curl;

    /**
     * API Key for authenticating requests
     *
     * @var string
     */
    protected $api_key;

    /**
     * The Commission Junction API Client is completely self contained with it's own API key.
     * The cURL resource used for the actual querying can be overidden in the contstructor for
     * testing or performance tweaks, or via the setCurl() method.
     *
     * @param string $api_key API Key
     * @param null|resource $curl Manually provided cURL handle
     */
    public function __construct($api_key, $curl = null) {
        $this->api_key = $api_key;
        if ($curl) $this->setCurl($curl);
    }
    
    /**
     * Convenience method to access Product Catalog Search Service
     * 
     * @param array $parameters GET request parameters to be appended to the url
     * @return array Commission Junction API response, converted to a PHP array
     * @throws Exception on cURL failure or http status code greater than or equal to 400
     */
    public function productSearch(array $parameters = array()) {
        return $this->api("productsearch", "productsearch", $parameters);
    }

    public function getToken()
    {
        return $this->apiToken("token", "token", $parameters = array());
    }
    
    /**
     * Convenience method to access Commission Detail Service
     * 
     * @param array $parameters GET request parameters to be appended to the url
     * @return array Commission Junction API response, converted to a PHP array
     * @throws Exception on cURL failure or http status code greater than or equal to 400
     */
    private function commissionDetailLookup(array $parameters = array()) {
        throw new Exception("Not implemented");
    }

    /**
     * Generic method to fire API requests at Commission Junctions servers
     * 
     * @param string $subdomain The subomdain portion of the REST API url
     * @param string $resource The resource portion of the REST API url (e.g. /v2/RESOURCE)
     * @param array $parameters GET request parameters to be appended to the url
     * @param string $version The version portion of the REST API url, defaults to v2
     * @return array Commission Junction API response, converted to a PHP array
     * @throws Exception on cURL failure or http status code greater than or equal to 400
     */
    public function api($subdomain, $resource, array $parameters = array(), $version = '1.0') {
        $ch = $this->getCurl();
        $url = sprintf($this->domain, $subdomain, $version, $resource);
        
        if (!empty($parameters))
            $url .= "?" . http_build_query($parameters);

        curl_setopt_array($ch, array(
            CURLOPT_URL  => $url,
            CURLOPT_HTTPHEADER => array(
                'Accept: application/xml',
                'authorization: ' . $this->api_key,
            )
        ));

        $body = curl_exec($ch);

        $errno = curl_errno($ch);
        if ($errno !== 0) {
            throw new Exception(sprintf("Error connecting to CommissionJunction: [%s] %s", $errno, curl_error($ch)), $errno);
        }
        
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_status >= 400) {
            throw new Exception(sprintf("CommissionJunction Error [%s] %s", $http_status, strip_tags($body)), $http_status);
        }
        
        return json_decode(json_encode((array)simplexml_load_string($body)), true);
    }

    public function apiToken($subdomain, $resource, array $parameters = array(), $version = '1.0') {

        $data = array("grant_type" => "password", "username" => "apiteam",'password'=>'apiteam2015','scope'=>'2373467');
        $data_string = json_encode($data);                                                                                   
                                                                                                                      
        $ch = curl_init('https://api.rakutenmarketing.com/token');                                                                      
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
        curl_setopt($ch, CURLOPT_POSTFIELDS, "grant_type=password&username=apiteam&password=apiteam2015&scope=2373467");
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                              
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                'Accept: */*',
                'Content-Type: application/x-www-form-urlencoded',
                'Authorization: '.$this->api_key,
            ));  

        $body = curl_exec($ch);

        $errno = curl_errno($ch);
        if ($errno !== 0) {
            throw new Exception(sprintf("Error connecting to CommissionJunction Token : [%s] %s", $errno, curl_error($ch)), $errno);
        }
        
        $http_status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        if ($http_status >= 400) {
            throw new Exception(sprintf("CommissionJunction Error Token  [%s] %s", $http_status, strip_tags($body)), $http_status);
        }
        return json_decode($body);
    }

    /**
     * @param resource $curl
     */
    public function setCurl($curl) {
        $this->curl = $curl;
    }

    /**
     * @return resource
     */
    public function getCurl() {
        if (!is_resource($this->curl)) {
            $this->curl = curl_init();

            curl_setopt_array($this->curl, array(
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => 2,
                CURLOPT_FOLLOWLOCATION => false,
                CURLOPT_MAXREDIRS      => 1,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_CONNECTTIMEOUT => 10,
                CURLOPT_TIMEOUT        => 30,
            ));
        }

        return $this->curl;
    }
}

Read Also : How to push item to 0 index or first of $scope object in AngularJS?

Thanks for read. I hope it help you. For more you can follow us on facebook.

About code chef

My name is Shahriar sagor. I'm a developer. I live in Bangladesh and I love to write tutorials and tips that will help to other Developer's. I am a big fan of PHP, Javascript, JQuery, Laravel, Codeigniter, VueJS, AngularJS and Bootstrap from the early stage.

View all posts by code chef →