E-Commerce Solutions and Third-Party Integration Options within Drupal Ecosystem

Drupal has several options and solutions to develop different types of websites including e-commerce portals. Drupalers have redefined the way e-commerce sites used to operate by developing a range of plugins and modules for high-end security, tailored web content, third-party integration, and other utilities. These modules primarily aim at enhancing end users experience, providing a user-friendly interface, flexibility, and reliability.

There are several e-commerce options within Drupal along with options to integrate third-party APIs, which I’ll discuss in a later section. Let’s first discuss the options available within Drupal - Ubercart,  Drupal Commerce, and Magento-Integrated Drupal.

Ubercart

Ubercart is an open source e-commerce solution that comes with a set of modules, designed for running multiple stores on your Drupal site in multiple countries. Driven by two major emphases of flexibility and usability, it has various options like product catalog, shopping cart, and checkout, order, shipping, etc. that can be extended to meet all store requirements.

Drupal Commerce

Drupal Commerce empowers online stores of different sizes with easy configuration and better management, allowing retailers to enhance their customer interaction. The latest version - Drupal Commerce 2.X - comes with a range of new features and contributed modules. It is well suited for online stores targeting niche market where product attributes need tailored content to bolster their business.

Magento Integrated with Drupal

The integration of Magento with Drupal and Acquia’s Acquia Commerce Manager can be used to create a full user commerce experience for your customers. This will not only deliver highly personalized, content-rich experiences across every touchpoint but will allow marketers to collaborate with merchandisers.

Third-Party API Integration at each stage using Drupal

Every enterprise has their own unique need. We need to know that one solution cannot work for all size and types of company. To overcome this, we need a solution that can be easily integrated with other solutions. Given below are a host of such integration options in the Drupal ecosystem:
 

Enterprise Search

Apache Solr: Apache Solr Search module can be used as a replacement for core content search and boosts features as well as performance. Additional features can be added as per the project requirement by extending the module. Valuebound contributed two modules in the process - Multisite Solr Search and Custom Solr Search. 

Ankiro: Ankiro - a search solution - provides user-friendly search tools by using a unique combination of language databases and enabling users to find exactly what they are looking for. Ankiro Enterprise Search Integration module help s with the integration with Drupal.

Sajari Search: Sajari Search is a highly customizable search engine for complex web applications. Search API Sajari module helps to integrate Sajari with Drupal for enabling its use from PHP.

Inventory management 

Commerce Brightpearl module integrates Brightpearl to Commerce Stock and Drupal Commerce allowing retailers to manage orders, inventory, customer data and accounting in a single, reliable retail management system.

Oracle Integration module is used to connect to Oracle databases using Drupal's familiar database functions and classes. Oracle Driver, another module, also allows Drupal to use an Oracle Database as the primary backend.

Stitch Labs API module provides API integration with StitchLabs.com which is an inventory and order tracking platform.

Payment Gateway

Paypal: Commerce PayPal module integrates Paypal into Drupal Commerce payment and checkout system. It supports both off-site and on-site payment systems.

Braintree: Commerce Braintree module is used to add Braintree payment functionality to Drupal Commerce for payments and to store customer data in the Braintree vault for future processing.

Cashpresso: Commerce Cashpresso integrated with Drupal Commerce gives users an option for easy payment in installments.

Amazon Pay: Amazon Pay makes it easy to log-in and pay through your Amazon account in an E-Commerce site based on Drupal. Commerce Amazon Pay module integrates Amazon Pay and lets you log into Amazon with Drupal Commerce.

Paytm: Commerce Paytm module integrates Paytm with Drupal Commerce payment system, for hassle-free e-commerce payments in India.

Order Fulfilment Services

Order Management Systems (OMS): Commerce Fulfilment via OMS module integrates Drupal Commerce with OMS and is being used for production. It currently provides web services like ExportOrders, GetStockOrders, and CreateSalesOrder.

Shipwire: UC Shipwire module allows shipping integration of Ubercart and Shipwire with various API methods like order placement, real-time stock update, and status tracking.

Shipping Gateway

FedEx: By extending Commerce Shipping API, Commerce FedEx module adds FedEx shipping calculations functionality with  Drupal Commerce. 

ShipEngine: Commerce ShipEngine provides the rates for services configured for ShipEngine. It also delivers labels that are visible on order page.

United Parcel Service (UPS): Requiring a UPS.com account, the Commerce UPS module allocates  UPS shipping estimates in conjunction with the Commerce Shipping and Commerce Physical modules.

DPD Shipping: If you are looking for France-based parcel delivery service, Commerce DPD shipping module will enable the most common DPD shipping services to your Drupal Commerce Site. It includes sub-modules like "commerce dpd shop delivery"  and "commerce dpd classic predict”. 

E-mail marketing

MailChimp: Commerce MailChimp module adds the e-commerce 360 feature to Drupal Commerce in order to track store statistics for marketing emails sent via MailChimp. Also, MailChimp E-Commerce helps to merge MailChimp with both Drupal Commerce and Ubercart.  

Marketo: Marketo module provides integration between various Drupal components and the Marketo email marketing system. Marketo MA, another module helps your website track marketing automation and capture user data during registration and form submission.

Analytics & Personalization Service

Google Analytics Integration: Personalize Google Analytics Integration module provides integration of the Personalize module with Google Analytics. It can be used to report the activities of Personalize module and Visitor Actions module to Google Analytics as custom events.

SharpSpring: SharpSpring Personalize module makes SharpSpring user data available to the Personalize module for conditional rules. It depends upon the SharpSpring module for tracking data that helps to add sharpspring tracking to your webpage. API credentials can be stored here to be used for other advanced integrations.

Acquia Lift: Acquia Lift Connector module helps firms to bridge content and customer data in order to deliver a tailored experience to customers. This module integrates with the Acquia Lift Service for an enhanced optimization experience on the front-end of your website.

Web Notification

Urban Airship: Urban Airship Web Push Notifications module connects your Drupal site to Urban Airship to deliver live notifications to your site visitors.

Firebase Notification: Firebase Push Notification module implements Google's Firebase Cloud Messaging to deliver notifications to Web and mobile devices. Relying on the Firebase Platform, another module called Google Firebase Push Notification delivers a feature set to send out push notifications to Chrome and other browsers as well as IOS & Android devices.

iZooto: Izooto Integration module adds iZooto Integrations for Web Push Notifications. Izooto allows businesses to create and send personalized notifications to their customers and web users using their mobile devices and desktops.

Integrations with Amazon / eBay: 

Various modules of Drupal that provide integration with eBay and Amazon are:

Amazon Module: Amazon Module helps to achieve product advertising API functionality for Drupal using advertisement API. Its central “Pure API” components interact with Amazon and optional modules to handle expanded data for other features like wishlists, customer reviews, etc.

Amazon Store Module: Amazon Store helps you to have an Amazon Associates Store along with an Associates ID. It provides a window to search content, product pages and also manages a shopping cart.

eBay Integration: eBay Integration bridges Drupal E-Commerce module and eBay. It allows you to create a special type of product, which will be listed on eBay automatically.

Commerce eBay: Commerce eBay module lists Drupal Commerce products on eBay along with automated stock management. 

Drupal has a number of powerful tools to develop e-commerce sites, as we discussed above. It provides integration with various third-party tools at each stage to make your e-commerce site user-friendly. We at Valuebound help developing commerce solutions by combining various sorting options, delivery modes, payment gateways, tax calculations, etc. to best accomplish your tasks.

Need assistance in building an e-commerce site? Get in touch with our Drupal developers today to enhance your site’s user engagement.

How to integrate Google Assistant with Drupal 8

The demand for Voice technology is rising and it is likely to revolutionize the way publishing websites engage with their audience. The Internet-connected virtual assistant is seeing a significant rise, but the question is how publishers can use this tech to grow their audience base and ultimately increase revenue? Here, we will explore how to use Actions on Google for a new project and an existing one followed up by an integration with Drupal 8 website.

Let’s have a look.

Integrating Actions on Google with a device

Integrating Actions on Google with an electronic gadget or smart speakers allow us to trigger voice command to control various Drupal commands such as:

  • Clearing cache
  • Count number of node 
  • Sending an email
  • Run external as well as internal cron
  • Control Drupal application to respond or insite defined action
  • Integrating Google voice assistance with Drupal 8

1->Go to https://console.actions.google.com

  •     Create new Add/import project.
  •     Enter your project name and Country /region. 

Google Assistant app

 

  • Add a new project

Add project on Google Assistant

Create actions on Dialog Flow 

  • Build a Dialog Flow, you will land to given page as per below screenshot.

Google Assistant - Dialogflow

  • Now create a new intent and enter the following details as shown in the screenshot      

Google Assistant - Dialogflow2

Fill below field

  1. User says
  2. Response → Default → “voice control text which can speak”
  3. Select the field of Fulfillment and then save.
  • Now click on Fulfillment.
  • Enable Webhook
  • Enter URL of your controller and save 

Google Assistant_webhook

Module development in Drupal 8

We are creating this module to hit '/ok-google-test’ page and return test reply setup after performing the process.

Create a custom module and a routing file:

Create Controller:

Now go to your bot.
console.dialogflow.com/api-client/#/agent/a128xxxx-711a-4c7f-b6b6-dxxxxxxxxxxx/integrations

You will see the similar screen where you can say clear caches.

Google Assistant_Console dialog flow

With this integration,  we can interact with our voice-enabled devices to use various Drupal functionalities, like cache clear, external cron run, sending mail, and others. Hope now you can integrate Actions on Google with your Drupal website. If you have any suggestions or queries please do comment below.

Below given is the presentation on "Integration of Google Assistant with Drupal".

How Blockchain can help the Media Industry

There is a lot of fuss all around regarding Blockchain Technology - I myself have heard of it a number of times! Even big companies like Google have already started inclining towards building a related technology. It has brought in quite a stir for media and entertainment industry who today are mostly concerned about how it would impact them. 

The Blockchain isn’t a new idea. We’ve already heard of cryptocurrencies like Bitcoin and Ethereum which are both based on the Blockchain model. It is a safer approach to store information, make transactions, perform various functions, and to establish trust. This idea for which a “mystery” designer named Satoshi Nakamoto is credited, surely has the potential to overturn or enhance the growth of any industry.

Still wondering how Blockchain will impact media industry? Have patience, we’ll discuss it later. First, let’s get to know the advantages of a Blockchain-based industry:

  • A quick payment model, which requires the details to be entered only once and later can be distributed over nodes if required.
  • Reducing transaction costs by removing third parties from managing transactions and keeping records.
  • Data Security and Integrity as it is a chain technology where the transfer of data is carried out by a network of servers, making it highly secure.
  • Open source platform which allows anyone with a record on Blockchain to make live interactions.

Impact of Blockchain on Media Industry:

By 2020, Blockchain shall reduce many enterprise security efforts of validation and verification for all sectors including the media industry. It will provide a digital decentralized ledger system for them which is tamper-resistant and encrypted - so transactions can’t be faked. This makes it a great choice for the media industry in many ways:

  • Crowdfunding with ICOs: Blockchain based sectors are generally funded with Initial Coin Offerings (ICOs) which use cryptocurrencies like Bitcoin. ICOs can also be employed by creative sectors like media for crowdfunding. These ICOs when used for crowdfunding, can help keep a record of all funding transactions that can be utilized later in real-time.
     
  • Digital Advertising: Digital advertising can be enhanced as this ledger system is transparent and highly encrypted, there are no chances for ad frauds. This technology will ensure that the consumer data is better protected because of the added security that it comes with, making it trustworthy. Earlier, knowing the consumer details such as age, earnings, and other details required a lot of time, but with the implementation of Blockchain technology, marketers can directly build customer profile based on the details entered.
     
  • Distribution Mechanism: Digital rights expression is a major target for all media industries. So, to tackle the problem of piracy in digital marketing, Blockchain provides frictionless monetization of content. This helps to establish a legal distribution mechanism.
     
  • Real-Time Sales Data Analytics: With a database of all transactions carried out within an institution, Blockchain can provide a way for media industries to keep a track of all affairs carried out in real-time.
     
  • Payment Royalties: Blockchain is proving itself to be a foundational technology that will help to achieve sales transparency for all folks related to media. Rather than passing through a number of intermediaries, royalty payment mechanisms can now become instantaneous.
     
  • Monetization of Micro-Contents: An advantage of Blockchain technology is that payments can be divided into smaller parts. This means that the customers can divide their payments according to the size of content they want to interact with. Example, buying a single track instead of the whole song album in Apple’s iTunes.

How Drupal comes into the picture?

Just like Drupal, Blockchain is an Internet-based, open source platform for digital assets, supported by a large community. This ledger technology helps to implement an additional trust layer to the use of payment over internet whereas Drupal can provide an identity and recognition to all user groups. It can also implement enterprise level workflows required for document signing, asset tracking, etc.

The implementation of Blockchain technology can surely help with secured payments across various websites. Here Drupal acts as a mediator, bridging the gap between end-user communities.

Integrating Ethereum with Drupal

Ethereum is a Blockchain-based technology that allows you to write decentralized applications using smart contracts and the Ethereum Virtual Machine. It is a ledger system that requires the use of service or setting up one’s own network node. The codes used in Ethereum are deployed to Blockchain.

Drupal’s Ethereum Module helps to enable integration between Ethereum blockchain and Drupal. This module intends to be a repository, where various modules that help in integration between Drupal and Ethereum Blockchain can be added. It also includes submodules like Ethereum User connector, which allows Drupal users to verify an Ethereum account address.

Ethereum module will configure applications with Smart Contracts along with connected Drupal functionality. Drupal and Ethereum are planning to implement the JSON RPC Ethereum API which is developed next to this module as an Ethereum PHP library.

In this era of digitalization, it has become a necessity to provide customers an encrypted and secure ledger platform like Blockchain to ensure their trust. And, this technology is not just a new digital currency system but also a revolution in many industries like media, where major flaws in the management system like piracy can mean considerable losses. Although this technology will need time to gain full support and trust, it surely has the potential to bring in a major transformation in the whole economy.

By leveraging our extensive experience in the Drupal framework, we at Valuebound provide you with the best solutions for web development. Contact us to know more!

Visualising Drupal Security Advisory Data

Drupalgeddon 2.0 brought a lot of focus on the Drupal security initiative and its practices. The way the security team disclosed this vulnerability and communicated to developers, community and press were proactive and commendable. Further, the communication was continuous.

The vulnerability, which started off with a risk score of 21/25 on 28th March, was upgraded to 22/25 on 13th April and was finally marked as 24/25 on 14th April. If you are interested to know what was changed during this interval - you can check out the revisions and compare them yourself here.

One thing we observed, recently, that in spite of all these disclosure and announcements not many Drupalers were aware of the details and terminology. Though security risk levels were well defined on Security Risk Level Definitions Page, it looked like not many are reading it in detail. This intuition is based on a sample survey of around 100 developers from three different cities in India. While it may not be an actual representation it still highlights a problem that needs to be addressed. It would be great if Drupal Association adds this question on one of their surveys. 

“Have you read defined security risk levels” with options of Yes and No. 

This may give us more insights. If developers themselves are not aware of these details then I believe it is too much to expect from site-builders to take corrective actions. So we created a crude static file that can make it easy for humans to understand - what the security string like 24∕25 AC:None/A:None/CI:All/II:All/E:Exploit/TD:Default means. While the security score is pretty much self-explanatory it is the second part that generally stumps many people.

You can check it out on https://nkgokul.github.io/drupalsecurity/. Once you enter the security string like “24∕25 AC:None/A:None/CI:All/II:All/E:Exploit/TD:Default” it will give a description that humans can easily understand. It is a very crude version without any validations. Would be great if anybody can clean it up.

Once this was done we wanted to do a basic analysis to figure out - how Security Advisories have been released till date? and what were the security scores of each of these advisories? Though official Security track record has some details, it was not up to date and was not in detail. So we set out to gather the data. Though there were various API endpoints like

https://www.drupal.org/api-d7/node.json?type=sa&status=1
https://www.drupal.org/api-d7/node.json?taxonomy_forums=1852  
https://www.drupal.org/api-d7/node.json?taxonomy_forums=1856

We felt it was too much of work to normalize the data from these endpoints. So we took a different approach to scrape the data from security advisories. Just to let you know it was not a straightforward job and was not as easy as we initially thought it would be. We scraped the advisories using our good old Google docs and some queries.

Since the data was inconsistent we had to use different queries based on the different time windows during which these announcements were made. After doing an initial round of scraping we did some data manipulations to get all the relevant data in the format we required.

The next challenge was that two different formats were used while sharing the security advisories. Post 6th August 2014 NIST Common Misuse Scoring System (NISTIR 7864) mechanism was used for categorizing the vulnerabilities and scoring them so that the data should be structured properly. Before that Drupal team had its own way of classifying the vulnerabilities.

You can read about security risk levels at Drupal.org 

In order to have meaningful insights, we gave the security risk score for vulnerabilities that were reported prior to 6th August 2014. So based on the new guidelines and the security risk level assigned to the vulnerabilities, announced before the date, we did a reverse mapping.

For highly critical we gave a rating of 22.5, Critical - 17, Moderately Critical - 12, Less Critical - 7 and Not Critical - 2.

Though these numbers were not accurate, they gave us a broad sense. To have an exact scoring we need to have a rating for each of the six risk metrics defined in NISTIR 7864. This can be time-consuming. Hence we put it on hold for now. It would be great if somebody can rate the old SAs as per the new guidelines. If you would like to take a dig at it you are free to do it here - Drupal core vulnerability analysis. All users have edit access. So please go ahead and update the Columns H to M that are marked in orange color and have the text “Details not available”. Once you are done with it you can also update the column G and you can use these values in https://security.drupal.org/riskcalc to find out the Risk Score.

With the data currently available, we made some visualizations. Have a look.

Drupal Risk Score vs Date

This was created using Google spreadsheet. As you can see the number of SAs have reduced over the time and it is especially interesting to note that vulnerabilities with the score less than 10 have minimized drastically post January 2010. I am not sure if this could be attributed to automation tools that were around that time.

Using the data from Google spreadsheets, we created a couple of interactive maps in PowerBI.

Drupal security analysis 1Drupal security analysis 2

You can check out these interactive maps here.

Special thanks to Gokul for contributions to this blog post.

Highlights from DrupalCamp Mumbai 2018

DrupalCamp Mumbai 2018 is just around the corner and we are all set for it. This year we are excited to support DrupalCamp in Mumbai as both Gold sponsors and attendees. The camp is returning to Indian Institute of Technology Bombay. The three-day camp consists of Drupal 8 workshop on Friday 27th April, keynote session as well as various talks on 28th April. The 2018 Camp will conclude with sessions, code sprints followed by a vote of thanks and closing ceremony. 

During the camp, you can catch the Valuebound team presenting the following sessions:

Drupal 8 Plugin API

We all know that Drupal 8 introduced many new APIs. The Plugins API is used to extend Drupal and add new functionality that allows modules to define new plugin types. In this session “Drupal 8 Plugin API”, Drupal consultant Manoj K will discuss on various agendas like:

  • Things you need to know before creating Plugin
  • When to use Plugin or Service
  • Plugin vs Info Hooks
  • Example of pluggable components
  • Plugin discovery types
  • How to create your own Plugin Manager

Package Your Solution Using Drupal Distributions

In this session, Drupal consultant Girish V and Pavan B S will talk about the powerful Drupal distributions or installation profiles. They will also cover how distribution can reduce the development hours by giving you a head-start for your project.

The session will cover the topics around building a distribution:

  •   What is a Distribution or Installation Profile
  •   What can be packaged inside a Distro
  •   How it is beneficial as a starting point
  •   When do we need to think about architecting an installation profile
  •   Popular Distributions present in the market

The session will be followed by a brief demo of creating a basic installation profile using Drupal 8. 

Too Many Project Methodology Can Spoil Drupal Projects

What happens when you start working on a project which turns your way of working upside down? How do you keep your sanity and support your team while keeping your client happy? Everything is different, from deployments and workflows to conflicting Scrum methodology. Many people try to wear a Project Manager hat, however, few deliver the project successfully on deadline. Here the bottleneck is a timebox. 

In this session, Scrum Master  Nikhil Anant will share his first-hand experience how he and the development team fixed the clients woes and what worked for them. The various agendas of this session are:

  • Project Decision Tree
  • Choosing the right team members
  • Tradition Vs Agile approach
  • Plan-Do-Check-Act
  • Retrospective
  • Where are we going? 
  • Take a break
  • Bounceback

So how can you connect with the Valuebound team 

Well, the easiest way is to stop by our booth in the exhibition area. Join the Valuebound team and fellow Drupalists to learn about our open positions and grab some goodies!

Drupal highly critical vulnerability - DrupalGeddon 2 - We've got you covered

This blog post attempts to focus on the highly critical vulnerability that was announced by Drupal on 28th March tagged as SA-CORE-2018–002, Drupalgeddon 2.

Recently, Drupal core announced a security advisory rated as highly vulnerable - dubbed DrupalGeddon 2 (SA-CORE-2018-002 / CVE-2018-7600) - that has the potential to affect the vast majority of Drupal 6, 7 and 8 websites.

According to BuiltWith, around 9% of websites are running on Drupal and hence had a high probability of being affected by the vulnerability as the score is 24/25.

SA-CORE-2018-002 potentially allow attackers to take full control of any affected Drupal site that could result in the site being completely compromised. The vulnerability was initially scored 22/25 but was later raised to 24/25 as there were proofs of automated attacks in the wild.

The risk metrics for this vulnerability are as follows AC:None / A:None/ CI:All / II:All / E:Exploit / TD:Default. You can read the article about security risk levels to know more about the details of the risk metrics. In short, SA-CORE-2018-002 means:

  • AC (Access Complexity): None - It is very easy for the attacker to leverage the vulnerability.
  • A (Authentication): None - No privilege level was required for the exploit to be successful. Meaning even anonymous users could exploit the vulnerability.
  • CI (Confidentiality impact): All - All non-public data was accessible because of the vulnerability.
  • II (Integrity impact): All - The data could have been easily modified or deleted.
  • E (Exploit) - An exploit is known to exist or is documented.
  • TD (Target distribution): Default - The default configurations were likely to be affected.

If you are curious to know how the score (24/25) was obtained you can take a look at Risk Calculator. This calculator takes six different metrics, which can have three different values. This gives an objective sense of the risk of different issues. While the numeric value gives you a sense of how critical the issue is. The security risk string, for example, “AC:None/A:None/CI:All/II:All/E:Exploit/TD:Default”, gives you a sense of six different risk factors that are considered in this case. This provides a better sense of how vulnerable your site is. Also, you are the right person to evaluate since you know how your website is structured and built, and how vulnerable it is to these specific risk factors. 

FYI, SA-CORE-2018–002 is as critical as “DrupalGeddon” episode which came to light in October 2014. To put things in perspective since 6th August 2014 (the date when NIST Common Misuse Scoring System - NISTIR 7864 was used by Drupal) there have been only three highly critical issues that have had a score of more than 23. 

Our approach

In response to this latest vulnerability, we gathered our development team to make sure we can deploy patches to this vulnerability for all our clients’ websites. We implemented a standard plan to notify all clients about the security update and to execute it across all of our supported sites immediately.

So when the patch - 8.5.1 / 8.4.6 / 8.3.9 / 7.58 - was available, our team knew exactly what to do. Just to let you know, the security update was carried out successfully as quickly as possible. Thanks to our team, at Valuebound, who worked tirelessly to ensure that all our clients’ websites were patched within hours.

If you are interested to know more how Valuebound can help you with security and maintenance of your Drupal website, do explore our services.

Read more at FAQ on SA-CORE-2018-002.

Creating a list of Steemit Profiles from steem handles

This is the third tutorial in the series Learning to play with SteemJS. In this tutorial we will learn how to fetch the profile details of the users from Steem blockchain once we have their steem handles.

preview-steemit-profile-listing-using-steemjs.png

What will you learn?

In this tutorial you will learn

  • How to use SteemJS
  • How to use steem.api.getAccounts(usernames, function(err, result) { function to fetch the details of steem user.
  • Create a basic HTML that will list the steem users' profile details in a list.
  • How to use the browsers copy to clipboard feature in Javascript.

Requirements

These are good to have requirements. Even if you don't know these you can still read the tutorial and make sense out of it.

  • Basics of HTML
  • Basics of Javascript

Difficulty

  • Basic. You can take a look at the code even if you are not from a development background. I will be happy to answer any queries you have in the comments section.

Create a HTML skeleton

    <div class="container">
      <h1>Steem Profile List Builder</h1>
      <div class="row">
        <div class="col-xs-18 col-md-9 left-region">
          <div class="row">
            <div>
                  Enter the list of user accounts whose profile details you need to fetch.
            </div>
            <textarea id="handles" rows="4" style="min-width: 100%">@gokulnk, @dragosroua, @barrydutton, @lexiconical</textarea>
            <div class="btn-group">
              <button type="button" class="btn btn-primary" id="fetch-profile">Fetch Profile Details</button>
              <button type="button" class="btn btn-primary" id="copy-html">Copy HTML</button>
            </div>
          </div>
          <div class="row" id="profile-details-html"></div>
          <div class="row" id="profile-details"></div>
        </div>
        <div class="col-xs-6 col-md-3 right-region">
          Follow <a href="https://www.steemit.com/@gokulnk" target="_blank">@gokulnk</a> for further updates.
        </div>
      </div>
    </div>
  </body>

We have created a basic layout using the Twitter Bootstrap library. You can learn more about the Bootstrap layouts and grids from here. We have created a text area input field along with two buttons one from generating the html and the other for copying the html.

We have also created two empty divs <div class="row" id="profile-details-html"></div> <div class="row" id="profile-details"></div>which will store the sample perview and the html code once the user clickcs on the button.

Add relevant javascript files

In your head tag add the following scripts

    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.2/js/bootstrap.min.js" integrity="sha384-vZ2WRJMwsjRMW/8U7i6PWi6AlO1L79snBrmgiDpgIWJ82z8eA5lenwvxbMV1PAh7" crossorigin="anonymous"></script>
    <script src="https://cdn.steemjs.com/lib/latest/steem.min.js"></script>

The first script is the jQuery library file which simplifies DOM manipulations and saves time in performing the frequently used actions in javascript. We will use these two files in all the browser based tutorials going forward.

The second script is the minified version of Bootstrap library which will help created the basic grids and makes sure that we can reuse the css elements from bootstrap library. In this case we have used this for creating grid, create button groups and making the input fields full width. We can do most of this by adding relevant classes to the html elements that we already use.

The third script is the minified version of SteemJS library which will help us interact with the steem blockchain direction from the javascript/browser.

Getting the inputs and sanitising the data

    $('#fetch-profile').click(function(){
      $('#profile-details').text("Fetching the details from Steem Blockchain");
      $('#profile-details-html-textarea').text();
      markDownHolder = "";
      handles = $('#handles').val();
      usernames = handles.replace(new RegExp("@", "g"),"").replace(new RegExp(" ", "g"),"").split(",");

In the above code on click of the submit button we are clearing the contents of our placeholder divs and adding relevant messages. We are doing this to make sure that even if the user clicks on submit button after fetching the output, it should still work as expected. We are cleaning up the input from the text area to remove unnecessary spaces and converting it into an array of steem handles that can be passed to the next function.

Understanding steem.api.getAccounts function

The takeaway from this tutorial will be how to use steem.api.getAccounts function. We pass the array of usernames to the function as the first parameter and second parameter is the handling function. If there is an error we are printing it to the console. If there is no error then we are processing it to display the output.

        steem.api.getAccounts(usernames, function(err, result) {
          if (err) {
            console.log(err);
          }else{
            $('#profile-details').text("");
            $('#profile-details-html').html('<textarea id="profile-details-html-textarea" rows="4" style="min-width: 100%">Filling HTML</textarea>');
            result.forEach(function(userAccount, i){
              console.log(getProfileHTML(userAccount));
              profileDetails = getProfileHTML(userAccount, i);
              markDownHolder += profileDetails;
            });
          $('#profile-details-html-textarea').html(markDownHolder);
         $('#profile-details').html('<h4>Preview (Looks much better in Steemit)</h3>' + markDownHolder);
}

In this code we are doing a couple of things. We are calling the function steem.api.getAccounts and once we have the details of the users we are looping through the results and concatenating the processed output of the users. Then we are populating the Preview and code text area with the processed output.

The processing function

The processing function generates the html output for each of the user. I have just used some crude string concatenations to generate the output. It can definitely be improved.

function getProfileHTML(userAccount, i){
  profile = JSON.parse(userAccount.json_metadata).profile;
  divBgColor = i % 2 == 0 ? "#FEFEFE" : "EDEDED";
  console.log(userAccount);
  console.log(profile);
  profileImage = profile.profile_image || defaultImage;
  profileTargetUrl = steemAuthorFullurl(userAccount.name);
  profileHTML = `<div style="clear:left"></div><div style="width:100%;height: 100%;border:red 1px;background-color=${divBgColor};padding=2px"><div class="profile-image" style="float:left;display:inline-block;width: 100px;height: 100%;"><a href="/%24%7BprofileTargetUrl%7D"><img width = "90px" height = "90px" src="/%24%7BprofileImage%7D"></a></div><div class="profile-details" style="float:left;display:inline-block;width: -moz-calc(100% - 100px);width: -webkit-calc(100% - 100px);width: calc(100% - 100px);height: 100%;">${profile.name || ""}(${userAccount.name || ""})<br/>${profile.about || ""}</div></div>`;
  //divPullClass = i % 2 == 0 ? "pull-right" : "pull-left";
  divPullClass = "pull-left";
  profileSteemHTML = `<div class="${divPullClass}"><a href="/%24%7BprofileTargetUrl%7D" target="_blank"><img src="https://steemitimages.com/100x100/${profileImage}"></a></div><b>${profile.name || ""} (<a href="/%24%7BprofileTargetUrl%7D" target="_blank">${userAccount.name}</a>)</b><br/>${profile.about || ""}<hr/>\n\n`;
  return profileSteemHTML;
}

Following Helper functions are used to generate links to the authors and blogs.

  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemBlogFullurl(author, permlink) {
      return BASEURL + '@' + author + '/' + permlink;
  }
  function steemAuthorFullurl(author) {
      return BASEURL + '@' + author;
  }
  function steemAuthorLink(author) {
    return getLink('@' + author, steemAuthorFullurl(author));
  }
  function getLink(linkText, targetLink) {
    if (typeof linkText == "undefined" || linkText == ''){
      linkText = targetLink;
    }else if (typeof targetLink === "undefined") {
      targetLink = linkText;
    }
    return `<a href = ${targetLink} target="_blank">${linkText}</a>`;
  }

Final notes.

You can checkout the final code and the demo to see what you have created with the help of this tutorial.

Originally published on https://steemit.com/utopian-io/@gokulnk/creating-a-list-of-steemit-prof…

Download the Drupal Guide
Enter your email address to receive the guide.
get in touch