Saturday, August 23, 2014

Magento Soap API call in Asp.net C#: Customer Module

The Customer module allows you to create, update, delete and retrieve customers and customer addresses. Click here to know more about Customer module.After the SOAP service added successfully to your project then get the reference of it in your class.

Add the namespace:

using MagentoRestApi.com.tejaprakash;

Here, com.tejaprakash is a service name which is given while creating web service. And add service reference like below.

MagentoService mservice = new MagentoService();

Before calling/consuming any Magento service module, you should call Magento service login with the details ApiUserName and ApiUserKey. On success,  you will get 32 bit string(SessionId) like 9b0f014c36868XXXX7dff1fe43fff1d. We have to use this in every call.

 var mlogin = mservice.login("YOURApiUserName", "YOURApiUserKey");

Create new Customer:

For creating/registering new customer using Magento api in C# is very first step in Customer Module. After creating customers, you can able to get the list of customers or customer details.
First, you need to create customer. If it successful then you will get back 'Customer Created ID'. Then you have to add address for the customer. Follow the below code to create new customer through Magento SOAP Api in C#.

      try
            {

            int newCustomerCreateID = 0;
            int createAddressID = 0;
            filters myfilter = new filters();
         
            // Create Customer
            customerCustomerEntityToCreate customerCreate = new customerCustomerEntityToCreate();
         
            //fill attributes
            customerCreate.email = "info@tejaprakash.com";
            customerCreate.password = "123456";
            customerCreate.firstname = "Teja";
            customerCreate.lastname = "Prakash";
            customerCreate.middlename = "";
            customerCreate.store_id = 1;
            customerCreate.store_idSpecified = true;
            customerCreate.website_id = 1;
            customerCreate.website_idSpecified = true;
            customerCreate.group_id = 1;
            customerCreate.group_idSpecified = true;
            customerCreate.suffix = "P";
            customerCreate.prefix = "Mr.";
            customerCreate.dob = "01/02/0101; //"DD/MM/YYYY";
            customerCreate.taxvat = "123456";
            customerCreate.gender = 1; //1-Male;2-Female
            customerCreate.genderSpecified = true;

      //Here, mlogin will be your Service token and Customer entity.
     newCustomerCreateID = mservice.customerCustomerCreate(mlogin, customerCreate);

         
            // If Customer added successfully then you will get back with value otherwise response will be zero.
            // Add Address
            if (newCustomerCreateID != 0)
            {
                customerAddressEntityCreate customerAddress = new customerAddressEntityCreate();

                customerAddress.city = "Hyderabad";
                customerAddress.company = "Prakash Blog";
                customerAddress.region_id = 2;   //CountryID
                customerAddress.region_idSpecified = true;
                customerAddress.country_id = "IN";

                string[] streettxt = { "123,Madhapur" };
                customerAddress.street = streettxt;

                customerAddress.fax = "986754321";
                customerAddress.firstname = "Teja";
                customerAddress.lastname = "Prakash";
                customerAddress.middlename = "";
                customerAddress.postcode = "500081";
                customerAddress.prefix = "Mr.";
                customerAddress.suffix = "P";
                customerAddress.telephone = "123456789";
                
               //If you specify 'true' for is_default_billing and is_default_shipping. Then this address will be your default shipping and billing. Otherwise none. 
                customerAddress.is_default_billing = true;
                customerAddress.is_default_shipping = true;
             

             
               createAddressID = mservice.customerAddressCreate(mlogin, newCustomerCreateID , customerAddress);
             
//If Customer Address added successfully then you will get back with value otherwise response will be zero.
                if (createAddressID != 0)
                {

                    Session["Customer_ID"] = newCustomerCreateID ;

                    Session["Customer_Address_ID"] = createAddressID;

                    mservice.endSession(mlogin);
                 

                }
                else
                {
                    mservice.customerCustomerDelete(mlogin, newCustomerCreateID );
                 
                    //lbl_MsgResult.Text = "Sorry, there was a problem saving your address information.";

                    mservice.endSession(mlogin);
                 
                }
            }

            else
            {
             
                //lbl_MsgResult.Text = "Sorry, there was a problem saving your information.";
             
                mservice.endSession(mlogin);
             
            }

            }
     catch (Exception ex)
            {
                //Unable to create account
            }

Retrieve customer:

Retrieve the customer details by using methods CustomerInfo and CustomerList. CustomerInfo method will provide you only single customer details. If you want list of customers then you use CustomerList method. Follow the below code to get the customer details.


filters myfilter = new filters();
customerCustomerEntity[] customers = mservice.customerCustomerList(mlogin, myfilter);

if (customers.Length > 0)
                {
               
                    foreach (var cust in customers)
                    {
                         var id = cust.customer_id;
                         string name = custome.firstname;
                         string pwdhash = cust.password_hash;
                    }
               }

Delete customer:

To delete the customer record, use CustomerDelete method. You should need SessionId and Customer created Id.

mservice.customerCustomerDelete(mlogin, newCustomerCreateID );

Customer Sign-in:

Magento doesn't providing you sign-in Api by default. If your are PHP developer then you can write your own Api call. But it was question for non-PHP's. I tried it using Customer Module Api's and with a small logic. It worked like a charm.
When customer use to login with their Username/Email and password. By using Email and Password, we need to validate it.
In Magento, CustomerInfo method provides you all the details regarding customer including password. But password is encrypted in a format HASH: SALT (3264b70e91268d8ecf59fffd47db675c:KSC2VzugdDdUbghTHoTouZeMLxk14TYU).  We have to separate and decrypt it. And match it with the customer password(typed). Matches, signed otherwise failed.


 protected void Magento_login()
        {
            try
            {
                mservice.Url = "";
             
                mlogin = mservice.login("ApiUserName", "ApiUserKey");
             
                filters filter = new filters();
                complexFilter[] cmxFilter = new complexFilter[1];
                complexFilter mcmxFilter = new complexFilter();
                mcmxFilter.key = "email";
                associativeEntity entity = new associativeEntity();
                entity.key = "in";
                entity.value = "info@tejaprakashp.com";
                mcmxFilter.value = entity;
                cmxFilter[0] = mcmxFilter;
                filter.complex_filter = cmxFilter;
                var filters = new filters();
                filters.complex_filter = cmxFilter;
                customerCustomerEntity[] customers = mservice.customerCustomerList(mlogin, filters);
             
                if (customers.Length > 0)
                {
                    //var data = mservice.customerCustomerList(mlogin);
                    foreach (var custome in customers)
                    {
                        var id = custome.customer_id;
                        string pwdhash = custome.password_hash;
                        var password = "12345678";
                        MD5 md5Hash = MD5.Create();
                        string[] hashh = pwdhash.Split(':');
                        string randomhash = hashh[1].ToString();
                        string bytehash = hashh[0].ToString();
                        string hash = GetMd5Hash(md5Hash, password, randomhash);

                        bool signed = VerifyMd5Hash(bytehash, hash);
                        if (signed)
                        {
                            //Do something after succesful login.

                            customerAddressEntityItem[] customers_address = mservice.customerAddressList(mlogin, id);
                         
                            customerAddressEntityItem shipping = new customerAddressEntityItem();

                            shipping = customers_address[0];

                        }
                        else
                        {
                            mservice.endSession(mlogin);
                            //Invalid Password
                      
                        }
                    }

                }
                else
                {
                    mservice.endSession(mlogin);
                    //Invalid UserName
                 
                }
            }
            catch(Exception ex)
            {
             
                // Do Something
            }
        }

     

 public static string GetMd5Hash(MD5 md5Hash, string input, string random)
        {

            // Convert the input string to a byte array and compute the hash.
            byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(random + input));

            // Create a new Stringbuilder to collect the bytes
            // and create a string.
            StringBuilder sBuilder = new StringBuilder();

            // Loop through each byte of the hashed data
            // and format each one as a hexadecimal string.
            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            // Return the hexadecimal string.
            return sBuilder.ToString();
        }


 public static bool VerifyMd5Hash(string input, string hash)
        {
            // Hash the input.
            //string hashOfInput = GetMd5Hash(md5Hash, input);

            // Create a StringComparer an compare the hashes.
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;

            if (0 == comparer.Compare(input, hash))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
     
Read More »

Saturday, August 9, 2014

Magento API soap call in C#: Integration

     I came up with a new task i.e Magento API SOAP calling in asp.net C# application. This platform is mostly used by the PHP developers. Interestingly, i got this task in the Dot net side. Magento basic topics looks like simple and easy to do but when we are going to the topic deeper and deeper then everything  will looks like a tough and tight. Required PHP framework installed server to install Magento platform i.e another part of work to install Magento into your server. To know more about Magento installation(click here) and Soap API(click here). 
    After successful Magento installation, you will be provided with your API details like serviceURL, ApiUserName, ApiUserKey and store details. I have used V2 SOAP version here.

Adding a Web Reference:

 First, create a new Asp.net C# web application. Then right click on the project and select 'Add service Reference'.






After selecting 'Add Service Reference'. You will get a new window called 'Add Service Reference'. Click on 'Advanced' button.



Then, you will another window called 'Service Reference Settings'. Click on 'Add Web Reference' button.


Give your Magento hosted URL.Then click on 'Go' button to get the Magento Service.
There are two SOAP version in Magento. I have used version 2 here.
EX:
SOAP v1 url: http://Hostname/api/soap/?wsdl=1
SOAP v2 url: http://Hostname/api/v2_soap/?wsdl=1


If URL access then you will get the service list as like below. And then click on 'Add Reference' button to complete the process.



On successful, you will get the reference in your project as like below.



CLICK HERE FOR ADD NEW CUSTOMER THROUGH MAGENTO SOAP API.
CLICK HERE FOR PLACE ORDER THROUGH MAGENTO SOAP API.

Have a nice day!!!





      
Read More »