Salesforce How-To Guides, Automating Salesforce, Improving Customer Experiences, Integrating Salesforce, Salesforce Admin, Salesforce Customization

Salesforce QR Code Generator: Formula Field & Apex Guide

Updated · first published 11 min read
Generated QR code displayed on a Salesforce Contact record
Salesforce Contact Details page for Mr. Arrify Test displaying the generated Account Website QR Code field

You can generate QR codes directly on Salesforce records — no AppExchange package required. This guide walks through two working methods: a formula field that creates QR codes with zero code, and an Apex class for more control over size, format, and error correction. Both approaches work on any standard or custom object.

Whether you need QR codes on contact records for networking, on assets for field service tracking, or on cases for quick customer lookup — the setup takes about five minutes with the formula approach and under thirty minutes with Apex.

Why Generate QR Codes in Salesforce?

Most teams generate QR codes outside Salesforce — in a separate tool, on a different website — and then manually paste images back into records. That’s slow, error-prone, and the QR codes go stale the moment the underlying data changes.

Building QR code generation inside Salesforce fixes all three problems:

  • Always current: A formula-based QR code recalculates every time the record loads. Change the URL or phone number, and the QR code updates automatically — no manual regeneration.
  • No extra cost: Both methods in this guide use free, public QR code APIs. No AppExchange license fees, no per-scan charges.
  • Works everywhere Salesforce does: QR codes render on record pages, in generated PDFs, in list views, and even in automated email templates. Your field technicians, sales reps, and support agents all see them without extra setup.

If your team uses Salesforce to manage contacts, assets, inventory, or events, adding a QR code field takes one formula and about five minutes. Here’s how.

Generate a QR Code for a Contact in Salesforce

Curious about setting up a QR code for a contact in Salesforce? Follow our step-by-step guide, and you’ll be a pro in just 5 minutes:

Total Time: 5 minutes

Go to Setup Menu

Navigating to Setup menu from the gear icon in Salesforce org

From the top-right corner of Salesforce, click the gear icon and select Setup.
In the left-hand panel, click on Object Manager.
In the search bar at the top of Object Manager, type Contact and click on it.

Navigate to Fields & Relationships

Salesforce Object Manager Contact Fields and Relationships page showing the New button to create a custom field

Once you’re inside the Contact object, click on Fields & Relationships in the left menu. Then click the New button on the top right.

Select Formula as the Data Type

Salesforce New Custom Field Step 1 screen on Contact with the Formula data type selected

You’ll see a list of field types. Choose Formula and click Next.

Name The Field and Set Return Type

Salesforce New Custom Field Step 2 screen configuring Account Website QR Code with Text formula return type

Give the field a label. Then set the Formula Return Type to Text and click Next.

Insert the QR Code Formula

Salesforce Step 3 formula editor showing the IMAGE and qrserver.com QR code formula with zero syntax errors

Paste the following formula into the formula editor. This uses the free QR Server API to generate a dynamic QR code containing the contact’s details:
IMAGE(
"https://api.qrserver.com/v1/create-qr-code/?size=150x150&data=" &
SUBSTITUTE(
SUBSTITUTE(
"https://arrify.com/contact/" & TRIM(FirstName & " " & LastName) & " | Phone: " & Phone & " | Email: " & Email,
" ", "%20"
),
"|", "%7C"
),
"QR Code for " & TRIM(FirstName & " " & LastName),
150,
150
)

How it works:
IMAGE() — Salesforce function that renders an image from a URL on the record page (syntax: IMAGE(image_url, alternate_text, height, width)).
api.qrserver.com — Free QR code API. The size parameter controls width × height in pixels, and data contains the string encoded into the QR code.
SUBSTITUTE() — Replaces spaces (%20) and pipe symbols (%7C) to URL-encode the payload (Salesforce’s URLENCODE() function cannot be used inside custom formula fields).
TRIM(FirstName & " " & LastName) — Combines the contact’s first and last name safely, as the compound Name field is not supported in Contact formula fields.
Click Check Syntax to verify, then click Next.
Tip: Replace the "https://arrify.com/contact/" payload with whatever data you want the QR code to hold—such as a direct record URL, a vCard contact card (MECARD:...), or plain text.

Set Field Level Security

Salesforce Step 4 field-level security table for Account Website QR Code showing Visible and Read-Only profile checkboxes

Choose which user profiles should be able to see this field. For most setups, you can grant access to all internal profiles. Click Next.
Add the field to the desired page layout, Click Save

Create a Contact Record

Salesforce New Contact creation modal with Salutation, First Name, and Last Name fields filled in

Go to the Contacts tab
Click on new
Fill out details
Click on save

Verify the QR Code

Salesforce Contact Details page for Mr. Arrify Test displaying the generated Account Website QR Code field

Open any contact record and scroll to the formula field you created. You should see a 150×150 pixel QR code rendered directly on the page.
Test it by scanning with your phone’s camera — it should decode to the contact’s name, phone, and email. If the QR code doesn’t appear, check that your Salesforce org allows external image URLs (Setup → Security → CSP Trusted Sites — add api.qrserver.com).

⚠️ Note: The formula approach above works well for displaying QR codes on record pages. However, it depends on an external API — if api.qrserver.com ever goes down, the images won’t render. For a more resilient approach, or if you need to generate QR codes in bulk, use the Apex method below.

Generate QR Codes Using Apex

The formula field approach works well for displaying QR codes on record pages, but it depends on an external service being available at page-load time. If you need to store QR codes as images, generate them in bulk, or control error correction levels, use Apex instead.

The Apex method calls the same QR Server API used in the formula approach, but gives you full control over the HTTP request. Before writing the code, you need to add a Remote Site Setting.

Step 1: Add the Remote Site Setting

Salesforce blocks outbound HTTP callouts by default. You must whitelist the QR API domain first:

  1. Go to Setup → search Remote Site Settings
  2. Click New Remote Site
  3. Set Remote Site Name to QRServerAPI
  4. Set Remote Site URL to https://api.qrserver.com
  5. Check Active and click Save

Without this step, your Apex callout will throw a System.CalloutException: Unauthorized endpoint error.

Step 2: Create the Apex Class

public class QRCodeGeneratorService {

    /**
     * Returns the full URL for a QR code image.
     * Use this URL in an IMG tag, email template, or Visualforce page.
     *
     * @param data  The text to encode (URL, vCard, plain text, etc.)
     * @param size  Pixel dimensions, e.g. 200 for 200x200
     * @return      Direct image URL (PNG) — no callout needed to display it
     */
    public static String getQRCodeUrl(String data, Integer size) {
        String sizeParam = String.valueOf(size) + 'x' + String.valueOf(size);
        return 'https://api.qrserver.com/v1/create-qr-code/'
             + '?size=' + sizeParam
             + '&data=' + EncodingUtil.urlEncode(data, 'UTF-8');
    }

    /**
     * Downloads the QR code image as a Blob.
     * Use this when you need to save the image as a file
     * (e.g., attach to a record via ContentVersion).
     *
     * @param data  The text to encode
     * @param size  Pixel dimensions
     * @return      PNG image as a Blob, or null on failure
     */
    public static Blob getQRCodeImage(String data, Integer size) {
        HttpRequest req = new HttpRequest();
        req.setEndpoint(getQRCodeUrl(data, size));
        req.setMethod('GET');
        req.setTimeout(10000); // 10-second timeout

        HttpResponse res = new Http().send(req);

        if (res.getStatusCode() == 200) {
            return res.getBodyAsBlob(); // Binary PNG image data
        }

        System.debug('QR generation failed: ' + res.getStatusCode()
                     + ' ' + res.getStatus());
        return null;
    }
}

How to Use It

Option A — Display in a Visualforce page or LWC: Call getQRCodeUrl() to get the image URL, then render it in an <img> tag. No callout happens at display time — the browser fetches the image directly from the API.

// In a controller or LWC Apex method:
String qrUrl = QRCodeGeneratorService.getQRCodeUrl(
    'https://arrify.com/contact/' + con.Id,
    200
);
// Pass qrUrl to your component → <img src="{!qrUrl}" />

Option B — Save as a file on the record: Call getQRCodeImage() to download the PNG, then insert it as a ContentVersion. This is useful when you need the QR code to work offline or in PDFs where external URLs aren’t supported.

You can trigger either method from a Salesforce Flow (using an invocable Apex action), a trigger, or a custom button — whatever fits your workflow.

Formula Field vs Apex vs AppExchange: Which Should You Use?

Salesforce gives you multiple ways to implement QR codes depending on your technical requirements, security governance, and budget. While a formula field handles straightforward record display needs, high-volume automation and offline generation demand different architectural approaches.

Here is a side-by-side breakdown of the three primary methods:

FactorFormula Field (IMAGE)Apex Callout / Custom CodeAppExchange App
Setup ComplexityLow (No code, < 5 minutes)Medium (Apex class + Remote Site Setting)Low to Medium (Managed package install)
CostFree (Native formula + free public API)Free (Native Apex + free/paid API)Paid ($1–$5/user/month or flat org fee)
Offline / Stored ImageNo (Renders live in browser via URL)Yes (Saves binary as ContentVersion/Attachment)Yes (Pre-generates and attaches to records)
Bulk ProcessingNo (Individual record page loads)Yes (Queueable/Batch Apex callouts)Yes (Native bulk batch jobs)
Security & Data PrivacyRecord data sent in URL to external APIData sent via HTTPS callout or generated locallyVaries; top apps generate client-side or on-platform
MaintenanceDepends on third-party API uptimeRequires developer maintenance & unit testsSupported by vendor with regular updates

Our Recommendation

  • Use the Formula Field method if: You need a quick, zero-cost way to display static record links or vCards on standard Lightning record pages, and your data does not contain sensitive PII.
  • Use the Apex Callout method if: You need to generate QR code image files automatically via Salesforce Flow, email attachments, or embed them into custom PDF quotes and invoices.
  • Use an AppExchange App if: You require enterprise-grade QR code generation entirely on-platform without third-party API exposure, barcode scanning capabilities, or branded vector (SVG/EPS) downloads. Popular solutions include apps like QR Code Generator by Vicinity or document generation packages like Salesforce document generation tools.

Use Cases of Salesforce QR Code Generator

QR codes, with their ability to bridge the gap between the physical and digital realms, have found a myriad of applications in the Salesforce ecosystem. Let’s explore some of the most impactful use cases:

Event Management & Check-ins

Smartphone running an Event Tickets Scanner app showing a successful QR code check-in for General Admission

Badge Scanning

At conferences or trade shows, attendees can be given badges with QR codes. Scanning these codes can quickly check them into sessions or workshops, and the data can be instantly updated in Salesforce.

Lead Capture

Instead of typing visitor details after the event, staff can scan a visitor’s QR code and instantly create or update a Lead in Salesforce. It’s faster and more accurate.

Product Authentication & Warranty

Smartphone displaying a Product Warranty registration screen after scanning a QR code sticker on a product package

Verification

Companies that deal with high-value or branded products can place QR codes on packaging. Customers scan the code to confirm if the product is genuine. The verification can be recorded inside Salesforce.

Warranty Activation

Instead of filling long forms, customers scan a QR code to register their product. The warranty details are automatically saved in Salesforce. It keeps everything organized.

Customer Feedback and Surveys

Illustration of a customer scanning a QR code on a smartphone to submit star and emoji feedback

Instant Feedback

Add a QR code on receipts, bills, or store counters. Customers scan it and open a feedback form. Once submitted, the response gets stored in Salesforce.

Post-purchase Surveys

After buying something, customers can scan and share their experience. This helps businesses improve service and track satisfaction levels.

Marketing Campaigns and Promotions

Outdoor highway billboard displaying a large scannable QR code for marketing campaigns

Promotional Offers

Promotional Content: QR codes in print ads or posters can direct potential customers to promotional videos, product pages, or special offers, with interaction data tracked in Salesforce. Pair this with Web to Lead to capture scanned leads automatically.

Loyalty Programs

Customers can scan QR codes to earn loyalty points or redeem rewards, with their loyalty program data managed within Salesforce.

Field Service & Asset Tracking

Smartphone scanning a QR code on a physical asset box for field service asset tracking

Asset Tracking

Machines and equipment can have QR labels. When scanned, users can see service history, maintenance schedules, or related cases stored in Salesforce.

Field Service Efficiency

Technicians can scan a QR code on equipment to quickly pull up service manuals, parts lists, or log service activities in Salesforce.

Business Cards and Networking

Stacked business cards with printed QR codes next to contact name, role, and company placeholders

Digital Business Cards

Instead of traditional cards, professionals can use QR codes that, when scanned, add their contact details directly to Salesforce. See how this fits into the broader Salesforce product ecosystem.

Networking Events

At conferences, attendees can scan each other’s QR codes to exchange contact details quickly. This reduces errors and saves follow-up time.

By integrating QR codes into Salesforce, businesses can enhance data accuracy, improve operational efficiency, and provide enriched experiences for both employees and customers. As technology continues to evolve, the potential applications of QR codes within Salesforce are bound to expand even further.

Conclusion

Generating QR codes in Salesforce doesn’t require paid tools or complex integrations. A formula field with the IMAGE() function handles most use cases — contacts, assets, events, cases — in under five minutes. When you need more control over size, format, or batch generation, the Apex approach gives you that flexibility with only a few lines of code.

If your team is already using Salesforce automation for workflows, adding QR codes to records, emails, and documents is a natural next step. Start with the formula method on one object, verify it works for your use case, and expand from there.

Need help building custom QR code workflows, integrations, or automation in Salesforce? Get in touch with our team — we’ve built solutions like this for dozens of Salesforce orgs.

FAQs

Can you generate QR codes in Salesforce without writing code?

Yes. The simplest method is a formula field using the IMAGE() function paired with a free QR code API like api.qrserver.com. You paste the formula into a text formula field, and Salesforce renders the QR code directly on the record page. No Apex, no AppExchange installs — just a formula field that takes about five minutes to set up.

Does the QR code update automatically when the record changes?

If you use the formula field approach, yes — the QR code recalculates every time the record page loads. If you change a contact’s phone number or email, the QR code immediately reflects the new data. With the Apex approach, you’d need to re-trigger the generation (via a Flow, trigger, or button) since the image is stored statically.

Can I add a QR code to a Salesforce PDF or document?

It depends on your PDF generation method. If you use Visualforce-rendered PDFs, you can embed the QR code image URL directly into the template. For tools like Salesforce document generation apps on the AppExchange, check whether they support formula field rendering or dynamic image URLs. The Apex approach gives you more control here since you can pass the QR image URL as a merge field.

What size should a QR code be in Salesforce?

For on-screen display on record pages, 150×150 pixels is a good default — large enough to scan reliably, small enough to not dominate the layout. If the QR code encodes a lot of data (long URLs, vCard strings), increase the size to 200×200 or 250×250 so the modules stay scannable. For printed materials, generate at 300×300 or higher.

Are there AppExchange apps for QR codes in Salesforce?

Yes, several — including apps like “QR Code Generator for Salesforce” and “Appy QR.” These provide point-and-click configuration, bulk generation, and features like custom branding, logos, and color schemes. They’re worth considering if you need QR codes across many objects at scale or want advanced styling that the formula approach can’t provide. For most teams generating QR codes on one or two objects, the free formula method in this guide is more than enough.

Share

Got a Workflow Problem? Let’s Fix It.

We build custom tools, integrations, and automation for businesses that want things done right.