Showing posts with label Web Service. Show all posts
Showing posts with label Web Service. Show all posts

Tuesday, August 13, 2019

ReactJs - Convert JSON Data using loadash

Hello,

Finally now I am going to post few blogs on React and ReactJs. In this blog we are going to learn how we can modify, manipulate or edit JSON data received from API according to your need.

This will be very useful when your backend developer refused to change API response. So not to worry, let it be as it is and convert data on your side before you use it.

For this we are going to use Lodash library, so first of all add it your ReactJs project using npm and import it in your class file.

import _ from "lodash";

Now create function for converting data.

const convertData = (data, key) =>{
  let result = _.chain(data)
    .get(key)
    .map(d => ({
      modified_key1: _.get(d, "original_key1"),
      modified_key2: _.get(d, "original_key2"),
      modified_key3: _.get(d, "original_key3"),
      modified_key4: _.get(d, "original_key4")
    }))
    .value();
    return result;
}

Now call this function in your API response.

let modifiedData = convertData(response.body, "data");

Here data is the root key of your JSON response. Change it according to your JSON response. That's it now you have modified data according to your requirements.

Thursday, March 30, 2017

PHP Debugging - Look for Case Sensitivity In Variable, File Names and Class Names

This blog is coming out of conversation with one of the developer in my team. He recently made some changes in API in local development and push code to test server. But on server it was throwing an error and API was not working. So after trying hard for sometime he came to me and asked for help. He showed me lines of code he has added and as an experienced person I immediately caught his error. The problem was, he declared variable in lowercase and was using variable with uppercase in next line and that's what breaking on server. Something like this

$var = new Class();
$VAR->prop = value;

Case sensitivity is one of the major reason for errors while you are working on local development environment with XAMPP, WAMP in Windows. At this time case sensitive is not applied and it will  treat

$var;
$VAR;
$Var;

as one and the same variables. But when you are working on server, you have unix / linux operating systems like Ubuntu, Fedora etc. At this time case sensitivity is applied and

$var;
$VAR;
$Var;

Are treated as three different variables. So by mistake if you declare it with lower case and try to use it upper case, it will give you an error. So if you are facing this issue that, code works on your local machine, but does not work on server look for the case sensitivity.

Same goes for the filenames and class names. If you have adde file with name

Myclass.php

and if you include it with

include 'MyClass.php';
require 'MyClass.php';

Then it will not be able to find file and it will throw warning or fatal error if you are using require. So make sure that you maintain case sensitivity while naming your class, variables and files in PHP because ultimately your code will be pushed to UNIX / LINUX server and it is case sensitive. 

Monday, August 31, 2015

Install and Configure PHP/Apache on Amazon EC 2 with Ubuntu (With SFTP)

Hello,

Recently for one of my project we moved our web application to Amazon EC 2. So we had to configure Aapche and setup SFTP there. I faced some difficulties in setting this up so here in blog I am going to explain you the process so it will help you.

First of all login to SSH on your Amazon EC 2 instance. For that first you have to download public key from your amazon EC 2 instance.  You can use public IP of your EC 2 instance to login to SSH.

Open your terminal and type following command.

ssh -i "YourKey.pem" ubuntu@your_ip_address

once you are logged in first of we have to install apache. For that run following command.

First we will install apache with PHP 7 and configure it.

sudo apt-get install apache2 php7.0 libapache2-mod-php7.0
Now verify it


a2query -m php7.0
Load PHP module.


sudo a2enmod php7.0

Restart apache.


sudo service apache2 restart

New version of ubuntu comes with PHP 7 but to access it you have to install php command lines. Run following command.


sudo apt-get install php7.0-cli

Now test it with

php -v

This will install apache, php with single command. Once installation is done type public ip in browser and it should show apache startup page. If you see this page that means apache installed. Now lets test PHP.

Go to your apache root directory with following command

cd /var/www/html

There will be one index.html file. We have to remove this and create new file for testing.

sudo rm index.html

sudo vim index.php

This will open vim editor, press i and now you can type in file. Let's create simple php file

<?php
     echo "Hello AWS";
?>


press esc and : and type wq this will save file. Now again type public IP in browser and it should show Hello AWS on browser.

Now let's create new SFTP user. But for that first we have to allow password authentication for SSH. Type following command.

cd /etc/ssh
sudo vim sshd_config

Find allowPasswordAuthetnciation. It will be set as no, make it yes and save the file and restart SSH service.


sudo service ssh restart

Now we can add user with password.

sudo adduser --home /var/www/html username

It will ask for password. Now user is created with same group name. Now we have to make this user, owner of /var/www/html so we can edit files via FileZilla. Now lets fist change ownership of folders and files.

sudo chown -R root:username /var/www/html
sudo find /var/www/html -type f -exec chmod 664 {} \;
sudo find /var/www/html -type d -exec chmod 775 {} \;
sudo find /var/www/html -type d -exec chmod g+s {} \;

That's it now you can use this username and password with SFTP in FileZilla. Hope this helps you.


Monday, August 24, 2015

PHP Parse SOAP XML Response

Recently in one of my project we were using SOAP service which was having XML response that we have to parse with PHP. For some reason PHP SOAP client was giving some because it XML response was using name namespaces and that was not parsed correctly with SOAP client. Here in this blog I am going to explain how to call XML web service without using SOAP client and parse response with PHP.

We will use PHP cURL. First lets create XML post data.

$postString = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"                 xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
  <soap:Body>
<GetProducts xmlns="http://ws.sourcingcity.co.uk/">
  <query>pen</query>
  <username>username</username>
  <password>password</password>
  <pageindex>1</pageindex>
  <pagesize>20</pagesize>
</GetProducts>
  </soap:Body>
</soap:Envelope>';

So that's our post data. Now lets create cURL request.

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'https://ws.sourcingcity.co.uk/ws3dpromo.asmx?op=GetProducts');
curl_setopt($ch, CURLOPT_POSTFIELDS, $postString);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
                                            'Content-Type: text/xml; charset=utf-8',
                                            'Connection: Keep-Alive',
                                            'SOAPAction: http://ws.sourcingcity.co.uk/GetProducts'
                                            ));    
$result = curl_exec($ch);
curl_close($ch);

Now you will get XML response in $result which is in string format. We will use SimpleXML class of PHP.

$soap = simplexml_load_string($result);

That will load SimpleXML object. Now we will register namespace.

$soap->registerXPathNamespace('ns1', 'http://ws.sourcingcity.co.uk/');

Now you can use XPATH to go to specific nodes.

$productsResult = $soap->xpath('//ns1:GetProductsResponse/ns1:GetProductsResult')[0]->Products;

for($i=0;$iProduct);$i++){
$product = $productsResult->Product[$i];
echo "Product ".$i;
echo "Name : ".$product->Name;
echo "SCRef : ".$product->SCRef;
echo "Description : ".$product->Description;
echo "PriceRange : ".$product->PriceRange;
echo "ProductType : ".$product->ProductType;
echo "ProductGroups : ".$product->ProductGroups;
echo "Colours : ".$product->Colours;
echo "ThumbImageURL : ".$product->ThumbImageURL;
echo "LargeImageURL : ".$product->LargeImageURL;
}

That's it. In the same way you can parse any other XML response.

Saturday, March 5, 2011

Working with Channel Advisor API with PHP

Hello Guys,

Recently I was working with Channel Advisor(CA) API in PHP script. Script was built to get product information from CA and  update product information in CA. First of all lets see what is Channel Advisor platform?

It's a SaaS(Software As A Service) provider which enables retailers to sell products online through various channels like eBay, Amazon etc. It has certain features like product inventory using which retailer can store product information. Those products can be synchronized in various e commerce channels. User can track sales through each channel. Detailed reports are also available.


This platform is built upon .Net Framework and it offers Asp.Net web services to use its API. Using those web service we can use that platform from the third party application. To use web services you have to register as a developer and get developer key and password. After this channel advisor admin will approve your developer account and provides a account ID and local id that developer can use in the scripts. 


Now as we all know that Asp.Net web services use SOAP protocol so we need some soap client in PHP. PHP 5.1 and above has soap pears available while for older version one need to install it separately.


Following is the code to use CA web service.

$developerKey = 'your developer key';
$password = 'password';
$localID = '1111111050';
$accountID = 'account id';


$client = new SoapClient("https://api.channeladvisor.com/ChannelAdvisorAPI/v3/InventoryService.asmx?WSDL");


$headersData = array('DeveloperKey' => $developerKey, 'Password' => $password);


$head = new SoapHeader("http://api.channeladvisor.com/webservices/","APICredentials",$headersData);
$client->__setSoapHeaders($head);


That's it and you have Soap client available now you can call any method which is provided by web service. See the example below.
$result = $client->GetInventoryItemQuantityInfo(array('accountID'=>$accountID,'sku' => $sku));
Above code gives quantity of product specified by sku. 


So this is how you can integrate channel advisor API in PHP. Above example is of inventory service. There are other services also available. Each method in services needs some input. Some are the required fields like product SKU etc. for example cosider following example of SynchInventoryItem method. This is the method used to add or update product in inventory. While working in PHP all the parameters need to be sent in format of an array.



$iteminfo = array('Sku'=>$sku,
                      'Title'=>$title,
                      'Subtitle'=>$title, 
                      'ShortDescription'=>$shortdescription,
                      'Description'=>$description,
                      'Weight'=>$weight,
                      'UPC'=>$upc,
                      'Manufacturer'=>$manufacturer,
                      'Brand'=>$brand,                      
                      
                      'QuantityInfo'=>array('UpdateType'=>'Absolute',
                                            'Total'=>$total
                                            ),
                      'PriceInfo'=>array('Cost'=>$cost,
                                         'RetailPrice'=>$price,
                                         'TakeItPrice'=>$special_price
                                         ),
                      'ImageList'=>array(
                                'ImageInfoSubmit'=>array(
                                'PlacementName'=>'ITEMIMAGEURL1',
                                'FilenameOrUrl'=>$imageurl)),                      
                      'Classification'=>$classification,
                      'AttributeList'=>array(
                                            'AttributeInfo'=>array(
                                                         array(
                                                              'Name'=>'Size',
                                                              'Value'=>$size
                                                           ),
                                                         array(
                                                              'Name'=>'Brand',
                                                              'Value'=>$brand)
                                                           )
                      ),
                      'VariationInfo'=>array('IsInRelationship'=>true,
                                             'RelationshipName'=>'Color',
                                             'IsParent'=>false,
                                             'ParentSku'=>$parent_sku
                                      ),   
                                      
                       );


Then we need to send above array as a parameter in the method.

$arrData = array(
'accountID'=>$accountID,
'item'=>$iteminfo,
);
                
$result=$client->SynchInventoryItem($arrData);
So this is how you can use CA API in PHP script.