Calling Apex methods in Salesforce Lightning web components

[Originally published as ¿Cómo Llamar Apex en Lightning Web Component?]

One of the features that Salesforce gives us is the ability to call Apex methods in Lightning web components. This can be done by importing the method and calling it with the decorator wire service or imperatively.

How to import an Apex method in a Lightning web component?

We can import methods from Apex classes into a component using the import form in ES6 (ECMAScript v6). This way:

  • apexMethodName: Symbol to identify the Apex method.
  • apexMethodReference: Name of the Apex method that we are going to import.
  • Classname: Name of the Apex class in Salesforce.
  • Namespace: If the Apex class is in the same namespace as the component, do not specify a Namespace. If the class is in a managed package, specify the namespace of the managed package.

How to expose an Apex method in Lightning web components?

To expose a method of an Apex class in a component, the method must be static and global or public. Also, we need to add the @AuraEnabled annotation to it.

In the following example, we expose a method called getContactList in the component, which returns a list of contacts.

How to call an Apex method with React Wire?

To read data from Salesforce, the Lightning web component can use the Reactive Wire service. The wire decorator is used to call an Apex method.

In the following example, we call an Apex method using the wire decorator.

How to call an Apex method imperatively?

In the next example, we call an Apex method, which returns a list of contacts, imperatively. The imported function returns a promise.

If you are looking for Salesforce technical content in Spanish written by experts, we recommend visiting Snake on Code, where you will find more information regarding Lightning web components, Apex, and more. 

If you enjoyed this article, here are some more that you might enjoy:

How to set a tamper-proof Salesforce session cookie with Apex

Imagine we have a website in which we want the user session to persist for a specific period, even when the user closes and reopens the browser. 

Our goal is to have operations/logic for a particular user persist on the website. Whenever the user returns to the site within a given amount of time using a session cookie.

There are a multitude of ways to store the session data. In this article, we are focusing on client-side storage (cookies). Cookies are small pieces of data that are transmitted from the server to the client (generally done once.) Then when the user comes back to the site, the cookies are sent back to the server. This allows us to track a single user across multiple connections to our site. 

Why should I care about the expiration?

Being able to easily expire user sessions allows for extra security measures. In our case, if we wanted to add a new feature that allows us to sign out of all sessions in other locations (machines where the user has logged in), this (expire session cookie) would force those other locations to re-authenticate before gaining access to the account.

This is a good security approach for when a user’s cookie is stolen or his credentials are compromised. Upon changing his password all his sessions are invalidated. An attack using an old cookie cannot continue to wreak havoc on the user’s account.

Signing your session cookie

As we know, all data stored on the client-side could potentially be compromised as a user can maliciously tamper with it. And since we are not able to avoid it, we might provide the server with the feature to recognize this manipulation. 

This feature consists of a cryptographically signed cookie. Upon receiving the cookie from the client, verify that the signature matches what you are expecting. 

HMAC (Hash-based message authentication code) is a cryptographic construct that uses a hashing algorithm (SHA-1, SHA-256, SHA-3) to create a MAC (message authentication code) with a secret key. Salesforce provides us with a class named Crypto that contains methods for creating digests, message authentication codes, and signatures, as well as encrypting and decrypting information. Click here to see more about Crypto.

Let’s code!

We are going to create a global helper class for signing session cookies. That we will be able to re-use in any part of our project.

Session-Cookies-with-apex-1

Within this class, we are using other Salesforce helper classes such as Blob (Contains methods for the Blob primitive data type) and EncodingUtil (to encode and decode URL strings, and convert strings to hexadecimal format).

This allows us to do the following:

Session-Cookies-with-apex-2

We can then send that to the client that requested the page. Once the client visits the next page, their browser will send that same cookie back to use. 

Assuming we need to store the ‘session ID’, we would get this as result:

Session-Cookies-with-apex-3
Session-Cookies-with-apex-4

Note: 

All cookies created from Salesforce contain ‘apex__’ as a prefix and are encoded before being set for the page.  Learn more about cookies here

To retrieve and verify the data was not tampered with, we could do the following:

retrieve-and-verify-data-apex

If the MAC is verified, it means that the data was not tampered with by the user and we can continue our business logic. 

Real Secret Key

For extra security measures, we might set an auxiliary CustomSetting for storing AES secret keys. We will create a Secret__c CustomSetting with a field named Base64HmacKey__c.

Now, we are going to refactor our code to include this new approach:

  • Add a new variable to our helper class
new-variable-helper-class
  • Add a new function to get the secret key from the CustomSetting
CustomSetting
  • Lastly, modify the private variable named SECRET_KEY
secret-key

Now we have better handling of our secret key.

Encryption

When using client-side storage, it may be beneficial to encrypt the data to add an extra layer of security. Even when encrypting the data, you need to continue using a MAC.

Using just encryption will not protect you against decrypting bad data because an attacker decided to provide invalid data. Signing the cookie data with a MAC makes sure that the attacker is not able to mess with the ciphertext.

If you’ve made it this far, thanks for reading! Also, if you are interested in Salesforce development go and check our latest articles here.

App Development with Salesforce Technologies

Working together with our partners to bring ideas to life is one of the driving forces behind everything we do here at Oktana. That’s why when Huge approached us to help them with app development for Stanley Security; we leaped at the chance.

Stanley is a large security company specializing in commercial security systems. They needed a tool for their field sales team to use on the go that showcased their current product offerings. Also, they preferred to manage the process through the app, on either computers or tablets.

Huge has excellent skills in front-end development and was planning to develop the app and the UI/UX elements internally. But they needed a partner to help complete the backend work and sync everything up with Stanley’s Salesforce instance. That’s where the team at Oktana came in. Huge was able to focus on designing a front-end experience that would satisfy Stanley’s sales team. Meanwhile, Oktana could focus on a seamless experience on the back end.

How do the front and the back of this application work, and what did it take to make them play nicely? The front-end app was built utilizing React and Node.JS, managed with a Postgres database that Huge hosted on Heroku. For our backend development, we needed to make sure everything tied into the Postgres database correctly. To do that we utilized Heroku Connect to transfer between the front-end database and Salesforce. Additionally, we mapped all the data so that everything was stored where it needed to be on both ends of the application process. This application’s design was for interfacing with Stanley’s Salesforce organization, and it required a Salesforce login to access the app and all of its features. The login ensured that anyone using that app is a part of the sales team at Stanley. 

Now, beyond the basic connective functionality, we needed to complete all aspects of the sales cycle through this app. This included allowing the sales team to send emails for clients with sales details and other information. To make that happen, we built an email tool using Apex and Visualforce. Stanley also wanted to close sales within the app, so we built in Adobe Sign functionality. Sales contracts could be signed digitally, and Zuora payment systems facilitated immediate payment. The final step was to synch the new data with the Salesforce organization.

The key technologies used in this project include:

  • Salesforce
  • Heroku
  • Postgres
  • React
  • Node.JS
  • Heroku Connect
  • Apex
  • Visualforce
  • Adobe Sign
  • Zuora

This project allowed us to work collaboratively with another development team to build different parts of an app. We’ve been able to successfully demonstrate our skill and ability to understand other’s work and apply it to our goals.

We’re looking forward to working with both Huge and Stanley again in the future. If you have a project that we can help you with, please be sure to let us know!

Learn more from our team here, or check out our custom development services.

Connecting Salesforce and Slack

We’re always looking for new challenges here at Oktana. One recent challenge that presented itself to us came from our partners, a leading investment firm. This investment firm out of California works with growth-stage companies in a wide variety of industries. They approached Oktana to help them find a solution to an efficiency problem within their organization. The primary tool that they used within the organization for work was Slack, and several different apps designed to interface with it. Their employees had to switch between Salesforce and Slack to manage updates and new tasks that would populate through Salesforce.

That’s where Oktana came in; the firm wanted a way to integrate Salesforce into their Slack experience to help save everyone at their company time and energy while they’re working. What could we do to bring these two platforms together? We started by exploring what tools might already exist within Slack that would make this integration quick and easy and found Incoming Webhooks. With Incoming Webhooks, we were about to take any new notifications from the Salesforce org about new task assignments and send them to users within the Slack instance.

This implementation was a success, and users were receiving notifications, but it was apparent that it wasn’t going to be the right solution for the long term. There were severe limitations to what we could do with Incoming Webhooks. While it could bring in notifications from Salesforce, it wasn’t able to limit those notifications to those directly involved with the task and instead sent them indiscriminately to the entire team. Additionally, there was no way to talk back to Salesforce after you received a notification in Slack, Incoming Webhooks is a one-way street. As such, we decided that we would need to take a different approach to solve this problem.

Thankfully, our partners at the firm were receptive to these concerns and were open to our recommendation for another option that might better suit their long-term needs. Since Incoming Webhooks did not fit our needs, there was only one course of action to take at this point. We needed to build a bespoke app to do the job. We created a small application in Node.js hosted on Heroku that would handle everything the investment firm required and more.

First, the app would replicate the functionality of the old implementation and take any task notifications from Salesforce and send them to Slack. Next, the app acts as a chatbot on Slack that can receive messages from Slack and send them back to Salesforce to update and create new tasks. Additionally, we built this app to be as lightweight and efficient as possible. At its core, the app is always listening to both sides, and when it detects something relevant, it translates the message and sends it from one application to the other. Oktana development process is about creating the most value possible for our clients. The lightweight nature of the app means it has space to grow and take on other functions so that the link between Salesforce and Slack can be expanded later on if needed. The app also can interface with applications beyond Salesforce if the need were ever to present itself.

The Critical technologies from this project:

  • Salesforce
  • Slack
  • Node.js
  • Heroku
  • Apex
  • Incoming Webhooks

This project was about seeing disfunction in how employees at the investment firm were working and finding a way to make it more streamlined. We saw that our client needed a solution for fixing their workflow, and we were able to accurately identify the problems as well as the best way to solve them. Now, they don’t have to move between Salesforce and Slack every time they want to update tasks, and we were able to face a new challenge head-on and solve it creatively.


Gathering Leads with Royal Caribbean

At Oktana, we’re heavily invested in the world of mobile app development. We believe that building new mobile tools that let our customers interact with their Salesforce instance out in the field is essential to the future of the platform. One of the most recent projects that allowed us to utilize our Mobile development skills is our project with Royal Caribbean for their Celebrity Cruises premium brand.

Celebrity Cruises participates in a number of large conferences and expos every year where their sales team is out in the field talking to potential clients and customers. They needed a way to easily gather data from the people they met for giveaways and potential sales leads. Additionally, this needed to be a tool that would allow them to gather the data while offline and then sync with Salesforce when they reconnected later because while moving around at conferences they can’t count on network connectivity.

Oktana was brought in to build an iPad app that would accomplish these goals. The app was built and designed internally by us. We designed an app that was slick and would be impressive looking so that when potential customers saw it on the floor it would look like something you would expect from a premium brand like Celebrity Cruises. We needed to make sure it met all of the client’s needs from beginning to end which included both the technical aspects and the app’s appearance.

What tools did we use to accomplish this task? We built the app using Salesforce DX along with Forcereact and the Salesforce Mobile SDK. The app also talks directly to the Salesforce Sales and Marketing Clouds. When a member of the sales team at Celebrity Cruises is preparing to go out to the floor of a show or conference they simply need to launch the app and select the Salesforce campaign the leads will be entered into. Then when they disconnect from the network the app will store all their leads locally and when they reconnect to the network at the end of the day it will sync them with the proper campaign. Additionally, when leads are entered the team member has the option to edit them for errors or even delete them before they sync to keep their campaign list clean.

This project was a perfect fit for us because it allowed us to utilize our experience in mobile development and Salesforce to make a unique tool for our client. The key elements to highlight for this project include:

  • Salesforce DX
  • React Native
  • Salesforce Mobile SDK
  • Apex
  • Sales Cloud
  • Marketing Cloud
  • iOS
  • UI/UX Design

While we have been working on this project for Celebrity Cruises we have also been helping Royal Caribbean with ensuring their tools meet GDPR requirements in the EU. We created tools to ensure collected data could be anonymized upon request. Royal Caribbean has been a great partner for us at Oktana and we believe this app was a great showcase of our skills in both Salesforce and Mobile development.

If you are a Salesforce partner looking to partner with experts to help you provide the best custom app development solutions to your clients Contact us. Our team will give you more information about these services. 

Okta and Oktana: Working Together

At Oktana, we’re proud of the work we’ve done and the companies we’ve had the opportunity to work with. Our goal with this blog is to share some of the work we’ve been doing and in turn highlight the things that make us good partners for those that may need help in the Salesforce space. One of our most recent partners -Okta- is one we’d like to highlight. Okta fast-growing technology company with a strong emphasis on enterprise security. Its focus is on the development of single sign-on systems for enterprise clients that allow users to log in to a number of services, including Gmail, Salesforce, and Slack all with one username and password. The success Okta has been experiencing has led to our partners so that we can assist them in their growth and capture key processes needed for such growth to be as smooth as possible.

Okta needed a partner to supplement its internal development team to achieve greater bandwidth, higher quality, and faster development cycles. In the process, we’ve become a part of Okta’s team and integrated ourselves into their workflow acting almost as an extension of the existing engineering team. Working together on projects with a goal of acting like one team even in an environment where everyone is collocated is something we’ve been doing for a long time. We can do it and we can do it really well. One of the key factors in the decision-making process that gravitated Okta to Oktana was the appreciation for transparency, honesty, and integrity when critically examining the work to be done and recognizing as a team the challenges we may face along the way as well as their solutions.

With that goal in mind, we have been working closely on a number of different projects. The biggest being an important refactoring exercise of their entire codebase. As mentioned earlier, growth is occurring so fast that they need to improve logic and code across the board is imperative to their ability scale. Oktana has become the face of this effort by spearheading improvements and encouraging the adoption of best practice principles that will lower maintenance costs and leverage Salesforce release improvements better.

This type of customer engagement is one that fits perfectly into our wheelhouse. The key elements of this project that we want to highlight are:

  • Apex/Visualforce
  • Salesforce Lightning and Lightning Components
  • Salesforce CPQ
  • Agile
  • Velocity
  • Quality
  • Transparency
  • Integrity
  • Honesty

Beyond our specific project described in this blog post, we’re also supporting Okta by helping improve its internal development processes. With the refactoring exercise, we’ve been slowly and subtly making the development process smoother and more streamlined for their team and helping them improve their scrum process as well. We are honored to get the chance to help an amazing organization such as Okta and hope we continue helping others in this same capacity.

If you are a Salesforce partner looking to partner with experts to help you provide the best custom app development solutions to your clients Contact us. Our team will give you more information about these services.