Skip to main content

WooCommerce REST API with Ionic Framework

  • Step 1 : Enabling REST API


    • To enable the REST API within WooCommerce, visit the WooCommerce > Settings > API tab and tick the Enable REST API checkbox.


  • Step 2 : Generating API keys


    • The WooCommerce REST API works on a key system to control access. These keys are linked to WordPress users on your website.


    • To create or manage keys for a specific WordPress user, go to WooCommerce > Settings > API > Keys/Apps.


    • To get started, select Add Key.

    • Select the User you would like to generate a key for in the User field and add a Description. Choose the level of access for this API key, which can be Read access, Write access or Read/Write access. Then select the Generate API Key button and WooCommerce will generate API keys for that user.

    • Now that keys have been generated, you should see two new keys, a QRCode, and a Revoke API Key button. These two keys are your Consumer Key and Consumer Secret.

    • Place your consumer key and consumer secret in the application that uses the WooCommerce API (the application should request your URL as well).



Implementation in Ionic Framework


  1. Creating basic demo of Ionic framework.
  2. We required the some dependency to implement this assignment like as follows,
             Download the js files and place in your required directory and include in your index.html
        <script src="js/lib/hmac-sha1.js"></script>
        <script src="js/lib/enc-base64-min.js"></script>
        <script src="js/lib/oauth-1.0a.js"></script>
        <script src="js/lib/oauth-signature.js"></script>


  1. Here I am Creating  the service in angularjs to handle the calling of woocommerce api ,

angular.module(myapp.restservices', [])
.service("woocommerce",['$q','$http','errorHandler','$ionicLoading',
              function($q,$http,errorHandler,$ionicLoading){
               var self=this;

  //Request Url and method
              var request = {
                      url: 'http://www.example.com/wc-api/v3/products',
                      method: 'GET'
               };

 //OAuth Protocol authentication parameters
 var oauth = new OAuth({
                     consumer: {
    //Consumer Public Key
                                        public: 'ck_50xxxxxxxx',
    //Consumer Secrete Key
                                         secret: 'cs_b5xxxxx'
                       },
        //oauth1.0a protocol signature method
                     signature_method: 'HMAC-SHA1'
              });
//Service Function to get products

           this.products=function(){
$ionicLoading.show({
                                template: '<ion-spinner class="light"></ion-spinner>'
                     });

//OAuth Parameters to call woocommerce api      
var oauth_data = {
            oauth_consumer_key: oauth.consumer.public,
            oauth_nonce: oauth.getNonce(),
            oauth_signature_method: oauth.signature_method,
            oauth_timestamp: oauth.getTimeStamp()
          };

         //Oauth signature
         oauth_data.oauth_signature =  oauthSignature.generate(request.method,request.url,
                                                      oauth_data,oauth.consumer.secret );
         console.log("Params : "+ JSON.stringify(oauth_data));

         var deff=$q.defer();

          $http({
                     method:request.method,
                     url:request.url,
                     headers: {
                               "Content-Type":"application/JSON",
                       },
          params: oauth_data
           }).then(function(objS){
    $ionicLoading.hide();
               alert('Success :-    '+JSON.stringify(objS));
           },function(objE){
   $ionicLoading.hide();
               alert('error:-    '+JSON.stringify(objE));
               errorHandler.serverErrorhandler(objE);
               deff.reject("server Error");
           });
           return deff.promise;
       };
   }])

   .service('errorHandler',['$q',function($q){
       this.serverErrorhandler=function(error){
           alert("ERROR ::"+JSON.stringify(error));
           console.log("ERROR ::"+JSON.stringify(error));
       };
    }
])



  1. Write controller to call the service function as like follows,


angular.module(myapp.categorycontrollers, [])


.controller('MainCtrl', function($scope,woocommerce) {


       //Method to get all Products
         $scope.getAllProducts = function(){
               woocommerce.products().then(function(objS){
                },function(err){
               });
         }


        //calling to function
         $scope.getAllProducts();
}


Comments

  1. Hello, and can you please show the example of POST request to Woocommerce REST API to create an order: https://woothemes.github.io/woocommerce-rest-api-docs/?javascript#create-an-order ?
    I tried to use the same pattern but I get either 401 error or 404 error.

    ReplyDelete
  2. HI Santosh Shinde,

    I have compile this code but I have got some errors, can you please instruct me about html file for this app?
    please instruct me on dilipgenex132@gmail.com
    Thanks
    Dilip

    ReplyDelete
    Replies
    1. What type of error you are facing with html ?

      Delete
  3. can u instruct me on the final html file to this instructions
    instruct me on banphlet4@gmail.com

    ReplyDelete
  4. i create app in ionic but it shows blank white screen on product
    and category page

    ReplyDelete
    Replies
    1. Please check your console and any errors are there then please write here.

      Delete
  5. there is no error only it shows blank screen

    ReplyDelete

Post a Comment

Popular posts from this blog

What exactly means MVW design pattern ?

What is a MVW framework? The abbreviation stands for 'Model - View - Whatever'.  Well there are many different JavaScript frameworks available , all invented for the same purpose. They all try to separate the presentation logic from the business logic where JavaScript holds the model and logic, and html the presentation layer. Quick overview : You can change the model without changing the view and vice-versa Unit testing is easy These are the core benefits of using such a framework. By separating presentation and business logic changes to the code are easier to implement and take less time. Another benefit is that code can be reused from a controller thus saving more time. Angularjs makes the code also shorter in comparison to other frameworks, which improves code stability. Less code means minor potential for bugs. For several years +AngularJS was closer to MVC (or rather one of its client-side variants), but over time and thanks to many refactorings

File Upload & Download With ng-cordova File Transfer Plugin In Ionic Framework

Using the AngularJS extension set , ngCordova , with Ionic Framework and the Apache Cordova File Transfer plugin, you can easily upload files to a remote server and download files from a remote server. 1.Create the project ionic start Test blank cd Test ionic platform add android 2.Add Plugin org.apache.cordova.file-transfer https://github.com/apache/cordova-plugin-file-transfer This plugin allows you to upload and download files. This plugin defines global FileTransfer, FileUploadOptions Constructors. Although in the global scope, they are not available until after the deviceready event . Installation cordova plugin add cordova plugin add cordova-plugin-file-transfer     2.    org.apache.cordova.file             https://github.com/apache/cordova-plugin-file             This plugin implements a File API allowing read/write access to files residing on the    device.             Installation cordova plugin add cordova-pl

Steps To Create Cordova Plugin

Introduction A plugin is a package of injected code that allows the Cordova webview within which the app renders to communicate with the native platform on which it runs. Plugins comprise a single JavaScript interface along with corresponding native code libraries for each supported platform. Due to following reason, we will go for plugin development To get the native capabilities of the device in the cordova based app Build the common functionality across the number of Cordova application(Reusability) Prerequisites For the creation of plugin you need to install plugman . npm install -g plugman Plugin Structure Decide Plugin ID & Name The plugin ID should be unique Plugin name should follow the convention “cordova.plugin.[your.plugin.name]” Create the structure Use the following command to create the plugin with plugin ID “cordova.plugin.test” and name “Test”. plugman create --name Test --