Magento API / web service work

piaoling  2011-06-30 11:26:41

Magento has strong web service features. I can say Magento’s web service is one step ahead than others e-commerce. Magneto has soap, v2_soap(soap 2) and xmlrpc adapter facilities. Using magento web services you can synchronize customer, categories, products, orders etc data with existing stores. Here I am going to describe magento’s web service deals step by step.

Setup API: At first create api user and api key from Magento’s admin. Follow below steps.
1. Create api user from admin->system->web services-> Users->Add New User->User Info. See picture.

Api user create with api key

Api user create with api key

2. Create role to set permission on api method under admin->system->web services-> Roles->Add New Role.
3. Define “Role Resources” for created role. See picture.

Set api permission on role

Set api permission on role

4. Set “User Role” from admin->system->web services-> Users->choose user->User Role.

Call API:
API user and key is created. Now we can call api methods in two ways.
1. Soap call
2. V2_Soap call

Here I am going to discuss both ways.

Soap call:
Magento wiki and help center have described this method. So who are beginner in web service work they can call magento api using this soap method. You get all api documentations in Magento site. Here is an example.

//create soap object
$proxy = new SoapClient('http://127.0.0.1/magento/api/soap/?wsdl');

// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('m4u_admin', '12345678');

 // Get customer info for customer id = 1
$customerinfo = $proxy->call($sessionId, 'customer.info', 1);

print_r($customerinfo);


V2_Soap call:
V2_soap call is for advance user. Who are expert in web service work they can easily use this method to call any magento api method from remote place. Whose magento knowledge is zero they also can use this soap method to work with magento web service. But about this method you will not get any api documentation in Magento wiki. But I think it will easy for you.

Here I am going to describe a-z about v2_soap method as any beginner also can use this soap calling method.

//create soap object
$proxy = new SoapClient('http://127.0.0.1/magento/api/v2_soap/?wsdl');

// create authorized session id using api user name and api key
// $sessionId = $proxy->login('apiUser', 'apiKey');
$sessionId = $proxy->login('m4u_admin', '12345678');

 // Get customer info for customer id = 1
$customerinfo = $proxy->customerCustomerInfo($sessionId,1);

print_r($customerinfo);

Which method you need to call?

At first decide which method you need to call of api. Suppose you want to retrieve customer info from Magento store. So you should call customer related api method to get customer info. But you donot know which method exactly you need. To view all available methods in your magento api please run http://127.0.0.1/magento/api/v2_soap/?wsdl. Now pick appropriate api method from wsdl operation list. Suppose I pick “customerCustomerInfo” method to get customer info.

<operation name="customerCustomerInfo">
   <documentation>Retrieve customer data</documentation>
   <input message="typens:customerCustomerInfoRequest"/>
   <output message="typens:customerCustomerInfoResponse"/>
</operation>

What is request parameter?

From wsdl you get a clear concept about api request/input parameter. For “customerCustomerInfo” operation input message is “customerCustomerInfoRequest”. So you will get all input/request parameter info (name and type) to call customerCustomerInfo method in message “customerCustomerInfoRequest”. customerCustomerInfo has three request parameter such sessionid(string), customerid(int) and atribuates(Array).

<message name="customerCustomerInfoRequest">
    <part name="sessionId" type="xsd:string"/>
    <part name="customerId" type="xsd:int"/>
    <part name="attributes" type="typens:ArrayOfString"/>
</message>

So we can request customerCustomerInfo method as below.

// Get customer info for customer id = 1 and attribute is optional
$attribute = array(‘firstname’, ‘lastname’, ‘email’, ‘store_id’);
$customerinfo = $proxy->call($sessionId, ‘customer.info’, 1, $attribute);

see picture for details-

API v2_soap wsdl request and response message.

API v2_soap wsdl request and response message.

What is return/response data?

From wsdl you also get idea about api response/return/output. For “customerCustomerInfo” operation output message is “customerCustomerInfoResponse”. So you will get output/result info (name and type) of customerCustomerInfo method in message “customerCustomerInfoResponse”. customerCustomerInfo will return customerCustomerEntity object as data. Please see what the format of customerCustomerEntity object in wsdl.

<message name="customerCustomerInfoResponse">
    <part name="customerInfo" type="typens:customerCustomerEntity"/>
</message>

That’s it!!

 
7 Votes
One blogger likes this post.

43 Responses to Magento API / web service work

  1. Good article.

  2. Goog Job. This article is very interesting for my project.
    I’ve a doubt. Do you know if I can “addtocart” a product using the webservice methods?? I was looking for that issue in the API Doc , but I didn’t find anything.

    Thanks in advance.

  3. Hi moinul,

    I have followed the above steps but i have not get the perfect output by using API,so plz explain me how to use API. I am not getting the “customerCustominformation” method in the XML sheet in the browser page.

    • Hello Raj,

      To retrieve user information you have to write code like below.

      //create soap object
      $proxy = new SoapClient(‘http://127.0.0.1/magento/api/v2_soap/?wsdl‘);

      // create authorized api sessionid using api user name and api key
      // $sessionId = $proxy->login(‘apiUser’, ‘apiKey’);
      $sessionId = $proxy->login(‘m4u_admin’, ’12345678′); // replace this using your own apikey and user id

      // Get customer info for customer id = 1
      $customerinfo = $proxy->customerCustomerInfo($sessionId,1);

      print_r($customerinfo);

  4. THANKS A LOT ISLAM. I WANT THE STORE NAME THROUGH API. WE ARE GETTING STORE ID IN THE PLACE OF STORE ID WE SHOULD PUT STORE NAME. IS IT POSSIBLE TO GET THE STORE NAME THROUGH CUSTOMER INFO?

    • Raj, You have to modify customer Info api method to get STORE NAME. You have store id in customer info. Use store id to get STORE Name and embed in api method.

  5. Is it possible to login and logout a user via the API? I’m trying to do this as part of an integration with another cms. How can this be achieved? Thanks for the great article!

    • Alex, It is not possible to destroy cookie/session through API. It is not a Magento limitation. It is matter of web service technology. Actually web service does not support session/cookie deletion. So you have to do this in alternate way. Suppose, you can manage a usertoken in magento db to track a user login and logout. Then You can create new api method to verify that token. I have used this usertoken technique in click2mail.com site to do same work.

  6. Hi Moinul Islam,

    Can you please guide me how to create the orders by using custom API. I have already create dthe two functions for creating the orders. It was working fine with saving customer data perfectly. But i am unable to save the product cost. It was saving as zero in the database. so plz share with me how to do perfectly the creating order API?

    • Hello Raj, did you get any solution? I have seen your code and it seems all are ok. But you are getting problem with order price. I think your product is virtual product. For virtual product you have to change code like below. Because a virtual product have no shipping address.

      $convertQuoteObj=Mage::getSingleton('sales/convert_quote');
      $orderObj = $convertQuoteObj->addressToOrder($quoteObj->getBillingAddress());
      $orderPaymentObj=$convertQuoteObj->paymentToOrderPayment($quotePaymentObj);
      $orderObj->setBillingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getBillingAddress()));
      //$orderObj->setShippingAddress($convertQuoteObj->addressToOrderAddress($quoteObj->getShippingAddress()));
      $orderObj->setPayment($convertQuoteObj->paymentToOrderPayment($quoteObj->getPayment()));
      

      If you have further any query then let me know.
      Thanks and sorry for late

  7. Is it possible to update a customer password for an existing customer using Magento API soap V2? I have had no success… tried using password, password_hash, both, salted hash, no luck. Others have posted similar failure with no successful solution posted anywhere I have seen. You are much more responsive than Magento forum so I thought my question would get help faster here :)
    thank you

    • Alex, goto Mage_Customer_Model_Customer_Api model and modify update method as below

      $customer->setPassword($customerData['password']);
      $customer->save();
      return true;
      
  8. Thank you!
    Can I override this API method the same way I have overridden the regular customer model session methods (like login)? I’m writing a module to fully integrate SMF and Magento and don’t want to change the core files. Also when I upgrade the file I modify might be updated and my changes will be lost. It seems like Magento checks the md5 sum of it’s files when it upgrades and replaces any that aren’t correct. The Magento Wiki on customizing the API is a disaster as you probably know. If I can just get this password update function to work I’ll be done :)
    Varian should hire you to write Magento documentation because you do a better job than anyone there :D

  9. Here’s what I am trying to do:

    in app/etc/modules/Magentobridge.xml I have:

    <?xml version="1.0"?>
    <!--
    /*
    * Magento bridge files
    * for integrating SMF and Magento
    */
    -->
    <config>
        <modules>
            <Magentobridge_Apioverride>
    		    <active>true</active>
    		    <codePool>local</codePool>
            </Magentobridge_Apioverride>
        </modules>
    </config>
    

    in app/code/local/Magentobridge/Apioverride/etc/config.xml I have:

    <?xml version="1.0"?>
    <config>
      <modules>
        <Magentobridge_Apioverride>
          <version>0.1.0</version>
        </Magentobridge_Apioverride>
      </modules>
      <global>
        <models>
          <customer>
            <rewrite>
              <api_v2>Magentobridge_Apioverride_Model_Customer_Api_V2</api_v2>
            </rewrite>
          </customer>
        </models>
      </global>
    </config>
    

    and in app/code/local/Magentobridge/Apioverride/Api/v2.php I have:

    <?php
    
    class Magentobridge_Apioverride_Model_Customer_Api_V2 extends Mage_Customer_Model_Customer_Api_V2
    {
        public function update($customerId, $customerData)
        {
            $customer = Mage::getModel('customer/customer')->load($customerId);
    
            if (!$customer->getId()) {
                $this->_fault('not_exists');
            }
    
            foreach ($this->getAllowedAttributes($customer) as $attributeCode=>$attribute) {
                if (isset($customerData->$attributeCode)) {
                    $customer->setData($attributeCode, $customerData->$attributeCode);
                }
            }
    //big thanks to you for finding this!
            if(isset($customerData['password'])){
             $customer->setPassword($customerData['password']);}
            $customer->save();
            return true;
        }
    
    }
    

    Is that the correct way to do this?
    Thanks!!!

  10. Hello Alex,
    change your model rewrite code in config xml as like below

    <models>
      <customer>
            <rewrite>
                  <customer_api_v2>Magentobridge_Apioverride_Model_Customer_Api_V2</customer_api_v2>
            </rewrite>
       </customer>
    </models>
    

    Thanks

  11. I’m getting closer. There is a response now :)
    Unfortunately with your code I get

     1="error:" 2="Uncaught" 3="SoapFault" 4="exception:" 5="Fatal"] Resource path is not callable

    when using ANY soap functions

    • Alex, i have checked and run that code in my pc. Please check your api calling url. Or if you can give access of your server then i can check the problem.

  12. Hi Moinul, I emailed you api and ftp logins for my site. The soapfault error I posted above is using my code. When I upload the code you emailed me I get another error, ‘SoapFault exception: [SOAP-ENV:Server] Cannot use object of type stdClass as array’.
    It looks like I’m getting closer :)
    Thanks!

  13. hi i’m trying to use the magento’s sales order api but my code is not connecting to the soap client can you give the solution.

    The error occured during my testing.

    Warning: SoapClient::SoapClient(http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl) [soapclient.soapclient]: failed to open stream: HTTP request failed! HTTP/1.1 500 Internal Service Error in D:xampphtdocsmetny1dreamminingcake_1_2appwebrootsoaptest.php on line 37

    Warning: SoapClient::SoapClient() [soapclient.soapclient]: I/O warning : failed to load external entity “http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl” in D:xampphtdocsmetny1dreamminingcake_1_2appwebrootsoaptest.php on line 37

    Fatal error: Uncaught SoapFault exception: [WSDL] SOAP-ERROR: Parsing WSDL: Couldn’t load from ‘http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl‘ : failed to load external entity “http://192.168.1.80/metny1/dreammining/cake_1_2/app/webroot/magento/api/v2_soap/?wsdl” in D:xampphtdocsmetny1dreamminingcake_1_2appwebrootsoaptest.php:37 Stack trace: #0 D:xampphtdocsmetny1dreamminingcake_1_2appwebrootsoaptest.php(37): SoapClient->SoapClient(‘http://192.168….‘) #1 {main} thrown in D:xampphtdocsmetny1dreamminingcake_1_2appwebrootsoaptest.php on line 37

  14. thanx for the grat info

  15. Assalamo alikum,
    I know i m writing this in wrong category but still i m writing because i need your help.I made one website multiple stores and currencies and languages but it is not working as i did all the settings.I don’t know where it is going wrong, i tried all the solutions but ca’t get it done.If you can help me please drop me a mail.
    My website is http://magento.copiaclassica.com
    and if you want admin details i will PM you if you can give me your mail id.

    Thanks & Regards
    Naved M Pasha

  16. Indianic Orange

    Hello guys,

    I am new to using web services. I wants to use soap api to transfer data of contact us form to some other system like OTRS ticket system .

    I have code below to use.. but in magento where we have to place this code and how can we call it i can’t understand:

    error_reporting(E_ALL);

    # Please define the connection information here:
    $url = “http://example.com/otrs/rpc.pl”;
    $username = “some_user”;
    $password = “some_pass”;
    $title = “My Test Ticket via SOAP and PHP”;
    $from = “me@example.com”;

    # Set up a new SOAP connection:
    $client = new SoapClient(null, array(‘location’ =>
    $url,
    ‘uri’ => “Core”,
    ‘trace’ => 1,
    ‘login’ => $username,
    ‘password’ => $password,
    ‘style’ => SOAP_RPC,
    ‘use’ => SOAP_ENCODED));

    # Create a new ticket. The function returns the Ticket ID.
    $TicketID = $client->__soapCall(“Dispatch”, array($username, $password,
    “TicketObject”, “TicketCreate”,
    “Title”, $title,
    “Queue”, “Postmaster”,
    “Lock”, “Unlock”,
    “PriorityID”, 2,
    “State”, “new”,
    “CustomerUser”, $from,
    “OwnerID”, 1,
    “UserID”, 1,
    ));

    # A ticket is not usefull without at least one article. The function
    # returns an Article ID.
    $ArticleID = $client->__soapCall(“Dispatch”,
    array($username, $password,
    “TicketObject”, “ArticleCreate”,
    “TicketID”, $TicketID,
    “ArticleType”, “webrequest”,
    “SenderType”, “customer”,
    “HistoryType”, “WebRequestCustomer”,
    “HistoryComment”, “created from PHP”,
    “From”, $from,
    “Subject”, $title,
    “ContentType”, “text/plain; charset=ISO-8859-1″,
    “Body”, “This is the body”,
    “UserID”, 1,
    ));

    # Use the Ticket ID to retrieve the Ticket Number.
    $TicketNr = $client->__soapCall(“Dispatch”,
    array($username, $password,
    “TicketObject”, “TicketNumberLookup”,
    “TicketID”, $TicketID,
    ));

    But dont know how can i deal with this code..

    Please help me if you have some idea..

    Thanks,

    Bijal :)

    • Hi Bijal,

      Have you find a standard way to call the Web-services using magento?
      I will appropriate any help regarding this. Waiting for response !!

      Thanks,
      Darshana

      • Moinul Al-Mamun

        Hi Darshana, I have described it in post so far. Please can you check again? Actually what do you need? If it is not satisfy your requirements please can you write details?
        I will try to make it clear.

        Thanks

  17. Hi,i followed the insturction but was getting error on gettting product information so i removed the permission on catalog and just given on customers section and it worked.I hope it will help others.

  18. Thank you for this nice intro, though I have one question about the wsdl file.
    I have created my own API with my own models and methods, but what kind of function will wsdl file have? Why would I create it in my module?
    For example I created new module and have the config.xml and api.xml in my etc folder, is it necessary to put wsdl.xml file too?

  19. Could you give us a post about ‘How to make a magento bridge?’. Please

    • Moinul Al-Mamun

      Hi Key, to make a bridge with magento you can use magento api. If magento api don’t fulfill your requirements then to extend magento api. I am not sure actually what you need. For more details you have to explain your requirements.

      Thanks

  20. Hi,
    I have done all the settings suggested in this article but I don’t know where i have to keep the web service code, in which file copy the above code and how it will work. Please suggest.

  21. Pingback: Customer Export API, Product Export API,Order Export API ,Product Inventory Export, Product Inventory Update API in PHP and XML Tested in Magento 1.5.1.0 | Open Source Rocks

  22. Hi, and thanks
    After adding Role, I want to add user. But the API key and API key confirmation has *(astriks) and I don’t know where to get it.
    best regards
    Emil

  23. how to get the store id of a by magento web service , to retrieve the product.list data specific to store only. please help me im searching and trying for this from whole day but not got the result. :(

  24. acutlay my requirement is , i have retrieve the products list specific to one store by magento web service , for that store id or store view code is needed but iam not able to find it, and after finding that the store id has to pass as to the magento api function available product.list but i dont know how to pass the store id to the argument of that funtion, please help me :(

    like ..
    $storeproduct_array=$client->call($session, 'product.list', 'storeid or storeview id >/b>');

    please tell me how to pass the storeid or storeview code in that function call…

    with best regards,
    yaba

    • Moinul Al-Mamun

      Hello Yaba, for storeId or code contact with your magento administrator or if you have magento admin access then go to System->Manage store. There you will get the store info.
      Thanks !

      • Hi Moinul Al-Mamun, thanks for your reply,

        i have the store id code, but please tell me how to retrieve the products to particular store by store id, how to pass this as argument to the product.list web service function

        i have done like below but dont have luck…

        $storeproduct_array=$client->call($session, 'product.list', 'storeid or storeview id >');

        but didnot get products related to particular store, instead getting all the products of all the store of website.

        please check the code and let me know..

        thanks and regards
        yaba

  25. Aslkm, dear all any body please help me ..iam waiting for the reply for the above post ..

    plaase admin bhai Moinul Al-Mamun, help me regarding this..

  26. Hi Moinul,
    i am new to magento, ur article is good and i want to retrieve user information but i dont know where can i place that code which u hav provided, i mean can u plz tell me the path whr wil i write that code..

    Thanks in advance.

  27. Thank you!! you make Web service & API integration easy @Magento.
    I also love http://www.php-example.com where i am learning Oracle.

    Kelly Blue
    Web Developer, Sydney, Australia

  28. Hello All,
    Is there any one have done Integration With POS?
    Please guide me? How can I achieve the Integration With POS.

    Thanks
    Saleem

类别 :  magento(258)  |  浏览(9398)  |  评论(0)
发表评论(评论将通过邮件发给作者):

Email: