DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Setting Up CORS and Integration on AWS API Gateway Using CloudFormation
  • Navigating BNPL Integration: Key Steps and Best Practices for Developers
  • Optimizing API Lifecycles: A Comprehensive Guide for Product Managers
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication

Trending

  • Subtitles: The Good, the Bad, and the Resource-Heavy
  • Scaling Mobile App Performance: How We Cut Screen Load Time From 8s to 2s
  • How to Build Scalable Mobile Apps With React Native: A Step-by-Step Guide
  • Artificial Intelligence, Real Consequences: Balancing Good vs Evil AI [Infographic]
  1. DZone
  2. Software Design and Architecture
  3. Integration
  4. Securely Sign and Manage Documents Digitally With DocuSign and Ballerina

Securely Sign and Manage Documents Digitally With DocuSign and Ballerina

Integrate DocuSign with Ballerina, enabling straightforward interaction with DocuSign APIs to send envelopes, manage recipients, and track statuses.

By 
Nuvindu Hewapathirana user avatar
Nuvindu Hewapathirana
·
Jan. 08, 25 · Tutorial
Likes (3)
Comment
Save
Tweet
Share
5.1K Views

Join the DZone community and get the full member experience.

Join For Free

This article was written using Ballerina Swan Lake Update 10.0 (2201.10.0) but is expected to remain compatible with newer versions.

DocuSign is a leading digital transaction management platform that allows users to sign, send, and manage documents securely and efficiently. Ballerina, a cloud-native programming language designed for integration, simplifies interacting with the DocuSign API to sign and manage documents securely.

Use Case Overview

Imagine you’re selling a car and need the buyer to sign a sales agreement. Instead of printing the document, meeting in person, and collecting a physical signature, you can use DocuSign integrated with a Ballerina application. With a few clicks, you upload the agreement and send an email to the buyer, which they can sign online. The application then checks if the document is signed and notifies you, making the whole process quick and easy without even meeting in person. Additionally, this entire process is conducted over a secure connection, which ensures the privacy and integrity of this transaction.

Use case overview

Prerequisites

Before we begin, make sure you have the following.

1. Install Ballerina

If you are new to Ballerina, you can download it here. If you have already installed Ballerina, try to update its version by using this command.

Plain Text
 
bal dist update


2. Create a DocuSign Account

If you do not have a DocuSign developer account, sign up for a free account at the DocuSign Developer Center.

Getting Started

First, we need to obtain the credentials to integrate with DocuSign.

Step 1: Obtain DocuSign Credentials

To integrate with DocuSign, you need API credentials. Follow these steps to set them up:

  • Visit the DocuSign Authentication Guide to explore supported OAuth-based authentication mechanisms:
    • Confidential Authorization Code Grant: Requires a secret key and user presence at the start of the session; provides a refresh token for ongoing authentication; ideal for secure, server-side integrations
    • Public Authorization Code Grant: Similar to the Confidential Grant but does not require a secret key; also provides a refresh token
    • Implicit Grant: Designed for client-side apps with limited use cases; does not provide a refresh token
    • JWT Grant: Best for server-to-server integrations without user presence; enables single login for multiple users and supports large-scale applications

In this guide, we’ll use the Confidential Authorization Code Grant mechanism.

  • Follow the DocuSign Integration Key and Secret Key Guide to generate the necessary keys.

Note: The above steps enable DocuSign eSignature APIs in developer mode. When ready for production, follow the Go-Live Guidelines.

Now, we can dive into the implementation of the application.

Step 2: Initialize a Ballerina Project

Okay, now let’s start with creating a new Ballerina project.

Plain Text
 
bal new purchase_agreement


Once it is done, you will see Ballerina.toml and main.bal files inside the project directory.

Step 3: Create a New DocuSign Client

To get started, open the main.bal file in your Ballerina project and import the DocuSign module. Next, configure your DocuSign credentials as follows.

  • accountId: Provide the API Account ID associated with your DocuSign account.
  • clientId: Use the Integration Key you generated earlier.
  • clientSecret: Enter the Secret Key you obtained during setup.
  • refreshToken: Insert the refresh token you generated previously.
  • refreshUrl: If you’re using the developer mode, set this to https://account-d.docusign.com/oauth/token. For live mode, use https://account.docusign.com/oauth/token.
  • serviceUrl: Set this to https://demo.docusign.net/restapi. For live mode, use https://www.docusign.net/restapi.

Configurable variables in Ballerina allow you to define variables whose values can be provided at runtime via configuration files (e.g., Config.toml) or command-line arguments. This feature helps decouple sensitive or environment-specific data from your codebase, improving security and flexibility.

To learn more about configurable variables in Ballerina, refer to the following:

  • Configurable variables by example
  • Configuring via TOML
  • Configuring via CLI

This configuration will allow your Ballerina application to interact with the DocuSign API, enabling secure and authenticated communication for managing digital signatures.

Go
 
import ballerinax/docusign.dsesign;

configurable string accountId = ?;
configurable string clientId = ?;
configurable string clientSecret = ?;
configurable string refreshToken = ?;
configurable string refreshUrl = ?;
configurable string serviceUrl = ?;

public function main() returns error? {
    dsesign:Client docusign = check new (
        serviceUrl,
        {
            auth: {
                clientId,
                clientSecret,
                refreshToken,
                refreshUrl
            }
        }
    );
}


Step 04: Create a DocuSign Envelope

Next, create a DocuSign envelope, which is a container for the documents you want to send for signatures.

Go
 
string base64Encoded = array:toBase64(check io:fileReadBytes("./resources/README.pdf"));

dsesign:EnvelopeDefinition agreement = {
    documents: [
        {
            documentBase64: base64Encoded,
            documentId: documentId,
            fileExtension: "pdf",
            name: "document"
        }
    ]
};


This code reads a PDF document, encodes it in base64, and creates an envelope definition for it.

Step 5: Send the Envelope to Recipients

To send the envelope, you need to specify the recipients who will sign the document. Here you can add one or more recipients to the envelope and set a place where recipients can put their signatures.

Go
 
dsesign:EnvelopeDefinition agreement = {
    documents: [
        {
            documentBase64: base64Encoded,
            documentId: documentId,
            fileExtension: "pdf",
            name: "document"
        }
    ],
    emailSubject: "Vehicle Purchase Agreement - McLaren MP4/2",
    recipients: {
        signers: [
            {
                email: "add-recipient-email-here",
                name: "add-recipient-name",
                recipientId: "12",
                tabs: {
                    signHereTabs: [
                        {
                            xPosition: "300",
                            yPosition: "200",
                            documentId: documentId,
                            pageNumber: "1",
                            height: "10"
                        }
                    ]
                }
            }
        ]
    },
    status: "sent"
};

dsesign:EnvelopeSummary agreementResult = check docusign->/accounts/[accountId]/envelopes.post(agreement);

io:println("Agreement Status: ", agreementResult.status);


Step 6: Get the Document Status

We can get the status of the Document to check whether the recipient has signed by checking the status of that document.

Go
 
dsesign:Envelope agreementDocument = check docusignClient->/accounts/[accountId]/envelopes/[envelopeId];

io:println(agreementDocument.status);


This code retrieves the status of the envelope to confirm if the document has been signed. You can either check the status here or you will automatically receive a mail from DocuSign that the recipient(s) has completed signing the document.

The final version of the code will look as below.

Go
 
import ballerina/io;
import ballerina/lang.array;
import ballerinax/docusign.dsesign;

configurable string accountId = ?;
configurable string clientId = ?;
configurable string clientSecret = ?;
configurable string refreshToken = ?;
configurable string refreshUrl = ?;
configurable string serviceUrl = ?;

public function main() returns error? {
    dsesign:Client docusign = check new (
        serviceUrl,
        {
            auth: {
                clientId,
                clientSecret,
                refreshToken,
                refreshUrl
            }
        }
    );

    string base64Encoded = array:toBase64(check io:fileReadBytes("./resources/README.pdf"));
    string documentId = "1";

    dsesign:EnvelopeDefinition agreement = {
        documents: [
            {
                documentBase64: base64Encoded,
                documentId: documentId,
                fileExtension: "pdf",
                name: "document"
            }
        ],
        emailSubject: "Vehicle Purchase Agreement - McLaren MP4/2",
        recipients: {
            signers: [
                {
                    email: "add-recipient-email-here",
                    name: "add-recipient-name",
                    recipientId: "12",
                    tabs: {
                        signHereTabs: [
                            {
                                xPosition: "300",
                                yPosition: "200",
                                documentId: documentId,
                                pageNumber: "1",
                                height: "10"
                            }
                        ]
                    }
                }
            ]
        },
        status: "sent"
    };

    dsesign:EnvelopeSummary agreementResult = check docusign->/accounts/[accountId]/envelopes.post(agreement);
    io:println("Agreement Status: ", agreementResult.status);

    string? envelopeId = agreementResult.envelopeId;
    if envelopeId is () {
        return error("Envelope ID is not available");
    }
    io:println("Envelope ID", envelopeId);

    dsesign:Envelope agreementStatus = check docusign->/accounts/[accountId]/envelopes/[envelopeId];
    io:println("Current Status: ", agreementStatus.status);
}


Conclusion

This article demonstrated how to set up a DocuSign account, configure credentials, send documents for signatures, and finally track the status of the documents. By integrating DocuSign with Ballerina, you can eliminate the need for physical paperwork, saving time and resources while having secure digital transactions. With Ballerina’s integration-first approach, developers can easily connect to external APIs like DocuSign and deliver better solutions suitable for real-world business needs.

You can find the complete code for this tutorial here as well. If you encounter any issues, feel free to leave a comment.

API Document Ballerina (programming language) security Integration

Opinions expressed by DZone contributors are their own.

Related

  • Setting Up CORS and Integration on AWS API Gateway Using CloudFormation
  • Navigating BNPL Integration: Key Steps and Best Practices for Developers
  • Optimizing API Lifecycles: A Comprehensive Guide for Product Managers
  • Harnessing the Power of APIs: Shaping Product Roadmaps and Elevating User Experiences through Authentication

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!