Showing posts with label shopware. Show all posts
Showing posts with label shopware. Show all posts

Delete article and category using REST Api in Shopware

Q. How to delete article and category in Shopware using REST Api?

You have already read my last posts of Shopware. If not, Please read last posts to start shopware from beginning..

Delete article and category using REST Api in Shopware


Shopware Section:

    1. Rest API in Shopware PHP
    2. Create REST Api for Shopware using php and curl
    3. Retrieve Articles and Category using REST Api in Shopware
    4. Post Article, Category and Image using REST Api in Shopware

Now Lets start.

Follow these steps:

1. Create a page "deletedata.php"
2. Put following code under this page
     <?php
                 include 'config.php';
               $client->delete('articles/' . ArticleId);   //Delete Article
               $client->delete('categories/' . CategoryId);   //Delete Article
     ?>
3. If you are confused about the code of config.php. Must read 1st post of shopware section

4. Run this page. If you have write all correct coding. You will get success to delete data.

That's it.
    
Read More

Post Category using REST Api in Shopware

You have already read my last posts of Shopware Section. If not, Please read following posts first.

    1. Rest API in Shopware PHP
    2. Create REST Api for Shopware using php and curl
    3. Retrieve Articles and Category using REST Api in Shopware
    4. Post Article, Category and Image using REST Api in Shopware

Post Category using REST Api in Shopware

Post Category:



Follow these steps:

1. Create a page "postcategory.php" and put following code.

<?php
include 'config.php';     // Know more about config.php in last post. Must Read 
$s2parray = Array        (
                "id" => "A NEW CATEGORY ID",
                        "parent" => "PARENT ID",
                        "name" => "NAME",
"path" => "PATH",
"position" => "POSITION",
"metakeywords" => "META KEYWORDS",
"metadescription" =>"META DESCRIPTION",
"cmsheadline" => "CMS HEADLINE",
"cmstext" => "CMS TEXT",
"template" => "TEMPLATE",
"active" => TRUE OR FALSE,
"blog" => "BLOG",
"showfiltergroups" => "SHOW FILTER GROUPS",
"external" => "EXTERNAL",
"hidefilter" => "HIDE FILTER"
        );
$client->post('categories', $s2parray);
?>
2. Run this code.

Note: 

1. Please replace values of those fields, you don't want, to NULL.
2. You can remove "id". If you want to generate category automatically.
3. Don't remove parent. It is a required field. If you remove this field. You will get following error message:

                                             parent id is missing

Warning:

Don't delete a default row from category table. It has category id = 3 and parent id = 1
If you delete it. You will get above error message.







Read More

Post Article, Category and Image using REST Api in Shopware

In last post, I show you how to retrieve atricles and categories using REST Api. This time i am here with next step.

I will show you that how can you post data using REST Api.

Post article, category and image using REST Api in shopware
For Article:

Follow these steps:

1. Create a page "postarticle.php" and put following code.

<?php
include 'config.php';     // Know more about config.php in last post. Must Read 
            //create an array $s2parray here
$client->post('articles', $s2parray);
?>
2. Run this code.

Some questions created at this point:

1. What is "$s2parray"?

Ans.  Actually $s2parray is an array carrying all information to post into database.Such as article's name, title, description, category, ordernumber, price etc.

2. What would be the structure of this array?

Check following example:


$s2parray = array(
    'name' => "NAME",
'description' => "DESCRIPTION",
'descriptionLong' => "DESCRIPTION LONG",
    'active' => "TRUE",
    'tax' => "TAX",
    'supplier' => "SUPPLIER NAME",
    'categories' => array(
        array('id' => "CATEGORY ID"),
     
    ),
    'mainDetail' => array(
        'number' => "YOUR ORDER NUMBER",
        'prices' => array(
            array(
                'customerGroupKey' => 'EK',
                'price' => "PRICE",
            ),
        )
    ),
);

 3. Is this fix stucture for array to post article?

Ans: No, You can extend this according to your requirement.

4. How can i extend this array?

Ans: You can do some trick to make a full array.First post an test article using above array structure.
After that you retrieve this article by article id. You will get a JSON output like below:


{"data":
{
"id":307,
"mainDetailId":862,
"supplierId":24,
"taxId":1,
"priceGroupId":null,
"filterGroupId":null,
"configuratorSetId":null,
"name":"Zaunfeldpfosten Classic 42 x 1100x 1030 mm",
"description":"Zaunfeldpfosten Classic 42 x 1100x 1030 mm",
"descriptionLong":"","added":"2014-01-16T00:00:00+0100",
"active":true,
"pseudoSales":0,
"highlight":false,
"keywords":"1",
"changed":"2014-01-16T17:20:23+0100",
"priceGroupActive":false,
"lastStock":false,
"crossBundleLook":0,
"notification":false,
"template":"","mode":0,
"availableFrom":null,
"availableTo":null,
"configuratorSet":null,
"mainDetail":
{
"id":862,
"articleId":307,
"unitId":null,
"number":"BZSEZ71X1I",
"supplierNumber":null,
"kind":1,
"additionalText":null,
"active":0,
"inStock":null,
"stockMin":null,
"weight":null,
"width":null,
"len":null,
"height":null,
"ean":null,
"position":0,
"minPurchase":null,
"purchaseSteps":null,
"maxPurchase":null,
"purchaseUnit":null,
"referenceUnit":null,
"packUnit":null,
"shippingFree":false,
"releaseDate":null,
"shippingTime":null,
"prices":[
{
"id":1058,
"articleId":307,
"articleDetailsId":862,
"customerGroupKey":"EK",
"from":1,
"to":"beliebig",
"price":58.739495798319,
"pseudoPrice":0,
"basePrice":0,
"percent":0
}
],
"attribute":
{
"id":896,
"articleId":307,
"articleDetailId":862,
"attr1":null,
"attr2":null,
"attr3":null,
"attr4":null,
"attr5":null,
"attr6":null,
"attr7":null,
"attr8":null,
"attr9":null,
"attr10":null,
"attr11":null,
"attr12":null,
"attr13":null,
"attr14":null,
"attr15":null,
"attr16":null,
"attr17":null,
"attr18":null,
"attr19":null,
"attr20":null
}
},
"tax":
{
"id":1,
"tax":"19.00",
"name":"19%"
},
"categories":
{
"1":
{
"id":1,
"name":"Root"
}
},
"links":[],
"images":[],
"downloads":[],
"related":[],
"propertyValues":[],
"similar":[],
"customerGroups":[],
"supplier":
{
"id":24,
"name":"GAH Alberts",
"image":"",
"link":"",
"description":null
},
"details":[],
"propertyGroup":null
},
"success":true
}

What are you thinking? Your JSON output is not like this. Please copy your JSON data and paste into any editor like Notepad++ or Dreamweaver. Select language as Javascript.
Now rearrange manually.
Wow, you get a similar JSON.
Next work to convert this into your appropriate array. OK, I am helping you little bit. I am replacing some codes from this json and output is below.


$s2parray = array(


"mainDetailId":862,
"name":"Zaunfeldpfosten Classic 42 x 1100x 1030 mm",
"description":"Zaunfeldpfosten Classic 42 x 1100x 1030 mm",
"descriptionLong":"",
"active":true,
"pseudoSales":0,
"highlight":false,
"keywords":"1",

"priceGroupActive":false,
"lastStock":false,
"crossBundleLook":0,
"notification":false,
"template":"","mode":0,
"availableFrom":null,
"availableTo":null,
"configuratorSet":null,
"mainDetail":
{

"unitId":null,
"number":"BZSEZ71X1I",
"supplierNumber":null,
"kind":1,
"additionalText":null,
"active":0,
"inStock":null,
"stockMin":null,
"weight":null,
"width":null,
"len":null,
"height":null,
"ean":null,
"position":0,
"minPurchase":null,
"purchaseSteps":null,
"maxPurchase":null,
"purchaseUnit":null,
"referenceUnit":null,
"packUnit":null,
"shippingFree":false,
"releaseDate":null,
"shippingTime":null,
"prices":[
{

"customerGroupKey":"EK",
"from":1,
"to":"beliebig",
"price":58.739495798319,
"pseudoPrice":0,
"basePrice":0,
"percent":0
}
],
"attribute":
{

"attr1":null,
"attr2":null,
"attr3":null,
"attr4":null,
"attr5":null,
"attr6":null,
"attr7":null,
"attr8":null,
"attr9":null,
"attr10":null,
"attr11":null,
"attr12":null,
"attr13":null,
"attr14":null,
"attr15":null,
"attr16":null,
"attr17":null,
"attr18":null,
"attr19":null,
"attr20":null
}
},
"tax":
{

"tax":"19.00",
"name":"19%"
},
"categories":
{
"1":
{
"id":1,
"name":"Root"
}
},
"links":[],
"images":[],
"downloads":[],
"related":[],
"propertyValues":[],
"similar":[],
"customerGroups":[],
"supplier":
{

"name":"GAH Alberts",
"image":"",
"link":"",
"description":null
},
"details":[],
"propertyGroup":null
);


I did my work now your turn. Replace all colon (:) with => . I have removed all id attributes except unitid and category id.

Now this is your complete code to post article. If you face any problem. Don't hesitate to comment.



Read More

Retrieve Articles and Category using REST Api in Shopware

If you have api key and already create rest api. Then follow these steps to retrieve data using rest api.

Get articles and category using REST Api

  • Create a page getdata.php
  • put following code and run this code.
For Article:

If you want to search an article by Article Id:
<?php
include 'config.php';
$client->get('articles/ARTICLE_ID');  //Replace ARTICLE_ID with an article id for search
?>
If you want to search an article by Order Number:

<?php
include 'config.php';
$client->get('articles/ORDER_NUMBER?useNumberAsId=1');  //Replace ORDER_NUMBER with an article order number for search
?>
If you want to search all articles:

<?php
include 'config.php';
$client->get('articles'); 
?>
For Category:

If you want to search a category by category id:
<?php
include 'config.php';
$client->get('categories/CATEGORY_ID');  //Replace CATEGORY_ID with an article id for search
?>

If you want to search all categories:

<?php
include 'config.php';
$client->get('categories'); 
?>

  •  Thats it. Run this script and you will get your result.
Next Post: Update Data using REST Api in Shopware
Read More

Create REST Api for Shopware using php and curl

2 Comments
If you have already API key. Then read this post, otherwise read "http://s2ptech.blogspot.in/2014/02/rest-api-in-shopware-php.htm"  post to generate an api key.

Create REST API For Shopware


Follow these steps to create REST Api for shopware:
  • Create a page ApiClient.php
  • Paste following code and save.
<?php
class ApiClient {
    const METHODE_GET    = 'GET';
    const METHODE_PUT    = 'PUT';
    const METHODE_POST   = 'POST';
    const METHODE_DELETE = 'DELETE';
    protected $validMethods = array(
        self::METHODE_GET,
        self::METHODE_PUT,
        self::METHODE_POST,
        self::METHODE_DELETE
    );
    protected $apiUrl;
    protected $cURL;
    public $msg;
    public $ack = 1;

    public function __construct($apiUrl, $username, $apiKey) {
        $this->apiUrl = rtrim($apiUrl, '/') . '/';
         //Initializes the cURL instance
        $this->cURL = curl_init();
        curl_setopt($this->cURL, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($this->cURL, CURLOPT_FOLLOWLOCATION, false);
        curl_setopt($this->cURL, CURLOPT_HTTPAUTH, CURLAUTH_DIGEST);
        curl_setopt($this->cURL, CURLOPT_USERPWD, $username . ':' . $apiKey);
        curl_setopt($this->cURL, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json; charset=utf-8',
        ));
    }

    public function call($url, $method = self::METHODE_GET, $data = array(), $params = array()) {
        if (!in_array($method, $this->validMethods)) {
            throw new Exception('Invalid HTTP-Methode: ' . $method);
        }
        $queryString = '';
        if (!empty($params)) {
            $queryString = http_build_query($params);
        }
        $url = rtrim($url, '?') . '?';
        $url = $this->apiUrl . $url . $queryString;
        $dataString = json_encode($data);
        //set_time_limit(30);             
        curl_setopt($this->cURL, CURLOPT_URL, $url);
        curl_setopt($this->cURL, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($this->cURL, CURLOPT_POSTFIELDS, $dataString);
        $result   = curl_exec($this->cURL);
        $httpCode = curl_getinfo($this->cURL, CURLINFO_HTTP_CODE);

        return $this->prepareResponse($result, $httpCode);
    }

    public function get($url, $params = array()) {
        return $this->call($url, self::METHODE_GET, array(), $params);
    }

    public function post($url, $data = array(), $params = array()) {
        return $this->call($url, self::METHODE_POST, $data, $params);
    }

    public function put($url, $data = array(), $params = array()) {

            return $this->call($url, self::METHODE_PUT, $data, $params);
    }

    public function delete($url, $params = array()) {
        return $this->call($url, self::METHODE_DELETE, array(), $params);
    }
   
    public function setAck($x)
    {
        $this->ack = $x;
    }

    protected function prepareResponse($result, $httpCode) {



       
        if (null === $decodedResult = json_decode($result, true)) {
            echo "<h2>HTTP: $httpCode</h2>";
            $jsonErrors = array(
                JSON_ERROR_NONE => 'Es ist kein Fehler aufgetreten',
                JSON_ERROR_DEPTH => 'Die maximale Stacktiefe wurde erreicht',
                JSON_ERROR_CTRL_CHAR => 'Steuerzeichenfehler, möglicherweise fehlerhaft kodiert',
                JSON_ERROR_SYNTAX => 'Syntaxfehler',
            );
            echo "<h2>Could not decode json</h2>";
            echo "json_last_error: " . $jsonErrors[json_last_error()];
            echo "<br>Raw:<br>";
            print_r($result);
           
            error_log($jsonErrors[json_last_error()]);
           
            return;
        }
        if (!isset($decodedResult['success'])) {
            echo "<h2>HTTP: $httpCode</h2>";
            echo "Invalid Response";
            return;
        }
        if (!$decodedResult['success']) {
            if($this->ack == 1)
            {
                echo "<h2>HTTP: $httpCode</h2>";
            echo "<h2>No Success</h2>";
            echo "<p>" . $decodedResult['message'] . "</p>";
           
            error_log($decodedResult['message']);
           
            }
            return;
        }
        echo "<h2>HTTP: $httpCode</h2>";
       echo "<h2>Success</h2>";
        if (isset($decodedResult['data'])) {
            echo "<pre>" . print_r($decodedResult['data'], true) . "</pre>";
        }
       
        $this->msg = $decodedResult;
       return $decodedResult;
    }
}
?>
  • Create another page config.php and paste following code.
<?php
include "ApiClient.php";
$client = new ApiClient(
    //URL des Shopware Rest Servers
    'YOUR SHOPWARE SITE URL/api',
    //Benutzername
    'USERNAME',
    //API-Key des Benutzers
    'API KEY'
);

?>
 That's it. You have created REST Api successfully.
Now you are ready to do some action.

My next Post: Retrieve Data using Api
Read More

Rest API in Shopware PHP

There are few contents on web to use REST Api in Shopware. So, most of the users are unable to find their solutions.That's why, I am here to write some stuffs for you.

                         
Rest Api in shopware php


List of Contents:
  1. Generate Api Key.
  2. Create REST Api using php
  3. Retrieve Data using Api
  4. Post Data using Api
  5. Update Data using Api
  6. Delete Data using Api
Generate Api Key for REST Api in Shopware:
Follow these steps:
  • Login to Shopware Backend


  • When you logged in successfully. Go inside Configuration ----  User administration. See fig (below)
 Shopware user admin
  • Click Edit User:
Shopware Edit User

  •  Check Enabled checkbox under API access. An API key generated automatically. Please copy User name and API key for future use. Click Save button to enable api service.
Shopware Create API




 
Read More