DEV Community

Tejas Bal
Tejas Bal

Posted on

3 3

Integrating Cryptocurrency Prices in Salesforce using Lightning Web Component (LWC)

In this article I will integrate live cryptocurrency prices in Salesforce developer instance, so let’s get started !

I created a free account on CoinMarketCap to get an API key.

Image description

Complete documentation on how to use this api is provided here

I am using the latest listings api to get the prices.

URL
https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest

{
  "data": [{
     "name": "Bitcoin",
     "symbol": "BTC",
     "quote": {
        "USD": { 
           "price": 9283.92,
           "percent_change_24h": 0.518894
        }
     }
   }]
}
Enter fullscreen mode Exit fullscreen mode

Create a Free Salesforce Developer account.

Create new Remote Site Settings entry for CoinMarketCap site url.

Image description

Code to create the lightning web component

  • The html is used to show the table with cryptocurrency prices.
  • The javascript file is used to call the Apex class and store the prices for the view.
  • The Apex class calls the CoinMarketCap to get the latest prices.
<template>
<template if:true={coinPricesDefined}>
<lightning-card title="Crypto Currency Live Prices"
icon-name="custom:custom14">
<div style="height: 300px;">
<lightning-datatable
key-field="id"
data={coinPrices.data}
columns={columns}>
</lightning-datatable>
</div>
</lightning-card>
</template>
</template>
import { LightningElement, wire } from 'lwc';
import getLivePrices from '@salesforce/apex/CryptoPriceController.getLivePrices';
const columns = [
{ label: 'Name', fieldName: 'name' },
{ label: 'Symbol', fieldName: 'symbol'},
{ label: 'Price', fieldName: 'price'},
{ label: '24h Change', fieldName: 'percent_change_24h'}
];
export default class Crypto extends LightningElement {
columns = columns;
@wire(getLivePrices)
coinPrices;
get coinPricesDefined () {
return this.coinPrices !== undefined
&& this.coinPrices.data !== undefined
}
}
view raw cryptoPrice.js hosted with ❤ by GitHub
public with sharing class CryptoPriceController {
public CryptoPriceController() {
}
@AuraEnabled(cacheable=true)
public static List<Map<string, string>> getLivePrices() {
List<Map<string, string>> coinPrices = new List<Map<string, string>>();
HttpRequest req = new HttpRequest();
HttpResponse res = new HttpResponse();
Http http = new Http();
req.setEndpoint('https://pro-api.coinmarketcap.com/v1/cryptocurrency/listings/latest?start=1&limit=15&convert=USD');
req.setMethod('GET');
// Paste your API key here
req.setHeader('X-CMC_PRO_API_KEY', 'xxxxxxxx-xxxx-1111-2222-xxxxxxxxxxxx');
res = http.send(req);
Map<string, object> responseMap = (Map<string, object>) JSON.deserializeUntyped(res.getbody());
List<object> data = (List<object>) responseMap.get('data');
Map<string, string> coinData;
for(Integer i = 0; i < data.size(); i++) {
Map<String, object> coin = (Map<String, object>) data[i];
coinData = new Map<string, string>();
coinData.put('name', (string)coin.get('name'));
coinData.put('symbol', (string)coin.get('symbol'));
Map<string, object> quote = (Map<string, object>) coin.get('quote');
Map<string, object> usdQuote = (Map<string, object>) quote.get('USD');
coinData.put('price', '$' + Decimal.valueOf((double)usdQuote.get('price')).setScale(2));
coinData.put('percent_change_24h', Decimal.valueOf((double)usdQuote.get('percent_change_24h')).setScale(2) + '%');
coinPrices.add(coinData);
}
return coinPrices;
}
}

Deploy the code in your Salesforce Instance.

Please refer Create a Hello World Lightning Web Component trailhead for more details on how to write code and deploy it to Salesforce instance.

Let’s add our LWC component to the Contact Page.

Go to an existing contact record and Click Edit Page on the top right.

Image description

Drag the custom component to the layout above Activity section.

Image description

Save and Activate.

And all set, we have the Crypto Currency Live Prices in Salesforce !

Refresh the contact record page to get updated prices.

Image description

The code can be optimized for better performance. Github link to the repository in case you would like to reuse or contribute.

Thanks for reading !

Blog - https://tejasbal.in/
Medium - https://medium.com/@tejas.bal

Agent.ai Challenge image

Congrats to the Agent.ai Challenge Winners 🏆

The wait is over! We are excited to announce the winners of the Agent.ai Challenge.

From meal planners to fundraising automators to comprehensive stock analysts, our team of judges hung out with a lot of agents and had a lot to deliberate over. There were so many creative and innovative submissions, it is always so difficult to select our winners.

Read more →

Top comments (0)

👋 Kindness is contagious

Engage with a sea of insights in this enlightening article, highly esteemed within the encouraging DEV Community. Programmers of every skill level are invited to participate and enrich our shared knowledge.

A simple "thank you" can uplift someone's spirits. Express your appreciation in the comments section!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found this useful? A brief thank you to the author can mean a lot.

Okay