Laravel E-Signature using Docusign API Tutorial

By Hardik Savani January 7, 2023 Category : Laravel

Hi,

I am going to explain to you example of laravel docusign integration. I explained simply about how to integrate docusign in laravel. you will learn laravel docusign api example. I explained simply about laravel electronic signature docusign.

DocuSign is used for electronic signature for your pdf document. DocuSign is a popular and trusted e-signature website. DocuSign also provides API to integrate embedded digital signs with your website.

In this example, we will simply create a developer account with DocuSign. Then we will integrate the embedded signing document process with laravel. we will create routes and controllers to implement DocuSign API. we will add one sample pdf file with two signature options. you need to follow the below step to do a simple example.

You can integrate electronic signature in laravel 6, laravel 7, laravel 8 and laravel 9 versions with DocuSign.

Step 1: Install Laravel

This is optional; however, if you have not created the laravel app, then you may go ahead and execute the below command:

composer create-project laravel/laravel example-app

Step 2: Install Docusign Package

Here, we need to install docusign/esign-client package provides a quick way to use DocuSign api. run the below command:

composer require docusign/esign-client

Step 3: Set Docusign API and Secret

In this step, we need DOCUSIGN_BASE_URL, DOCUSIGN_ACCOUNT_ID, DOCUSIGN_CLIENT_ID and DOCUSIGN_CLIENT_SECRET to access docusign api.

So, first we need to create developer account in Docusign Website.

Let's Click Here to create developer account.

After creating successfully account, go to setting page and copy API Account ID, that we need to paste in .env file.

next, create application to click on "Add App and Integrate Key" button. then create new app.

After creating application then you need to copy Integration Key and Secret Key.

Note: You must have to add callback URL in your docusign, so they can redirect on back to laravel app.

Next, you need to add app key and secret add on .env file as like the below:

.env

DOCUSIGN_BASE_URL=https://demo.docusign.net/restapi

DOCUSIGN_ACCOUNT_ID=2f178ddb...

DOCUSIGN_CLIENT_ID=083f0167...

DOCUSIGN_CLIENT_SECRET=674f6d3d...

Step 4: Create Routes

In this step, we will create new routes for docusign process. you can see the below routes:

routes/web.php

<?php

use Illuminate\Support\Facades\Route;

use App\Http\Controllers\DocusignController;

/*

|--------------------------------------------------------------------------

| Web Routes

|--------------------------------------------------------------------------

|

| Here is where you can register web routes for your application. These

| routes are loaded by the RouteServiceProvider within a group which

| contains the "web" middleware group. Now create something great!

|

*/

Route::get('/', function () {

return view('welcome');

});

Route::get('docusign',[DocusignController::class, 'index'])->name('docusign');

Route::get('connect-docusign',[DocusignController::class, 'connectDocusign'])->name('connect.docusign');

Route::get('docusign/callback',[DocusignController::class,'callback'])->name('docusign.callback');

Route::get('sign-document',[DocusignController::class,'signDocument'])->name('docusign.sign');

Step 5: Create Controller

Here, we will create DocusignController with all the methods.

Then you need to download sample PDF file from Here and add on public/doc folder.

so let's copy the below code and add to controller file:

app/Http/Controllers/DocusignController.php

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;

use DocuSign\eSign\Configuration;

use DocuSign\eSign\Api\EnvelopesApi;

use DocuSign\eSign\Client\ApiClient;

use Illuminate\Support\Facades\Http;

use Exception;

use Session;

class DocusignController extends Controller

{

private $config, $args, $signer_client_id = 1000;

/**

* Show the html page

*

* @return render

*/

public function index()

{

return view('docusign');

}

/**

* Connect your application to docusign

*

* @return url

*/

public function connectDocusign()

{

try {

$params = [

'response_type' => 'code',

'scope' => 'signature',

'client_id' => env('DOCUSIGN_CLIENT_ID'),

'state' => 'a39fh23hnf23',

'redirect_uri' => route('docusign.callback'),

];

$queryBuild = http_build_query($params);

$url = "https://account-d.docusign.com/oauth/auth?";

$botUrl = $url . $queryBuild;

return redirect()->to($botUrl);

} catch (Exception $e) {

return redirect()->back()->with('error', 'Something Went wrong !');

}

}

/**

* This function called when you auth your application with docusign

*

* @return url

*/

public function callback(Request $request)

{

$response = Http::withBasicAuth(env('DOCUSIGN_CLIENT_ID'), env('DOCUSIGN_CLIENT_SECRET'))

->post('https://account-d.docusign.com/oauth/token', [

'grant_type' => 'authorization_code',

'code' => $request->code,

]);

$result = $response->json();

$request->session()->put('docusign_auth_code', $result['access_token']);

return redirect()->route('docusign')->with('success', 'Docusign Successfully Connected');

}

/**

* Write code on Method

*

* @return response()

*/

public function signDocument()

{

try{

$this->args = $this->getTemplateArgs();

$args = $this->args;

$envelope_args = $args["envelope_args"];

/* Create the envelope request object */

$envelope_definition = $this->makeEnvelopeFileObject($args["envelope_args"]);

$envelope_api = $this->getEnvelopeApi();

$api_client = new \DocuSign\eSign\client\ApiClient($this->config);

$envelope_api = new \DocuSign\eSign\Api\EnvelopesApi($api_client);

$results = $envelope_api->createEnvelope($args['account_id'], $envelope_definition);

$envelopeId = $results->getEnvelopeId();

$authentication_method = 'None';

$recipient_view_request = new \DocuSign\eSign\Model\RecipientViewRequest([

'authentication_method' => $authentication_method,

'client_user_id' => $envelope_args['signer_client_id'],

'recipient_id' => '1',

'return_url' => $envelope_args['ds_return_url'],

'user_name' => 'savani', 'email' => 'savani@gmail.com'

]);

$results = $envelope_api->createRecipientView($args['account_id'], $envelopeId, $recipient_view_request);

return redirect()->to($results['url']);

} catch (Exception $e) {

dd($e->getMessage());

}

}

/**

* Write code on Method

*

* @return response()

*/

private function makeEnvelopeFileObject($args)

{

$docsFilePath = public_path('doc/demo_pdf_new.pdf');

$arrContextOptions=array(

"ssl"=>array(

"verify_peer"=>false,

"verify_peer_name"=>false,

),

);

$contentBytes = file_get_contents($docsFilePath, false, stream_context_create($arrContextOptions));

/* Create the document model */

$document = new \DocuSign\eSign\Model\Document([

'document_base64' => base64_encode($contentBytes),

'name' => 'Example Document File',

'file_extension' => 'pdf',

'document_id' => 1

]);

/* Create the signer recipient model */

$signer = new \DocuSign\eSign\Model\Signer([

'email' => 'savani@gmail.com',

'name' => 'savani',

'recipient_id' => '1',

'routing_order' => '1',

'client_user_id' => $args['signer_client_id']

]);

/* Create a signHere tab (field on the document) */

$signHere = new \DocuSign\eSign\Model\SignHere([

'anchor_string' => '/sn1/',

'anchor_units' => 'pixels',

'anchor_y_offset' => '10',

'anchor_x_offset' => '20'

]);

/* Create a signHere 2 tab (field on the document) */

$signHere2 = new \DocuSign\eSign\Model\SignHere([

'anchor_string' => '/sn2/',

'anchor_units' => 'pixels',

'anchor_y_offset' => '40',

'anchor_x_offset' => '40'

]);

$signer->settabs(new \DocuSign\eSign\Model\Tabs(['sign_here_tabs' => [$signHere, $signHere2]]));

$envelopeDefinition = new \DocuSign\eSign\Model\EnvelopeDefinition([

'email_subject' => "Please sign this document sent from the ItSlutionStuff.com",

'documents' => [$document],

'recipients' => new \DocuSign\eSign\Model\Recipients(['signers' => [$signer]]),

'status' => "sent",

]);

return $envelopeDefinition;

}

/**

* Write code on Method

*

* @return response()

*/

public function getEnvelopeApi(): EnvelopesApi

{

$this->config = new Configuration();

$this->config->setHost($this->args['base_path']);

$this->config->addDefaultHeader('Authorization', 'Bearer ' . $this->args['ds_access_token']);

$this->apiClient = new ApiClient($this->config);

return new EnvelopesApi($this->apiClient);

}

/**

* Write code on Method

*

* @return response()

*/

private function getTemplateArgs()

{

$args = [

'account_id' => env('DOCUSIGN_ACCOUNT_ID'),

'base_path' => env('DOCUSIGN_BASE_URL'),

'ds_access_token' => Session::get('docusign_auth_code'),

'envelope_args' => [

'signer_client_id' => $this->signer_client_id,

'ds_return_url' => route('docusign')

]

];

return $args;

}

}

Step 6: Create Blade File

In this step, we will create new blade file call docusign.blade.php. so let's update following file:

resources/views/docusign.blade.php

<!DOCTYPE html>

<html lang="en">

<head>

<title>Laravel Docusign Integration Example - ItSlutionStuff.com</title>

<meta charset="utf-8">

<meta name="viewport" content="width=device-width, initial-scale=1">

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/css/bootstrap.min.css">

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.16.0/umd/popper.min.js"></script>

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.5.2/js/bootstrap.min.js"></script>

</head>

<body>

<div class="container">

@if ($message = Session::get('success'))

<div class="alert alert-success alert-block">

<button type="button" class="close" data-dismiss="alert">×</button>

<strong>{{ $message }}</strong>

</div>

@endif

<div class="card">

<div class="card-header">

<h5 class="card-title">Laravel Docusign Integration Example - ItSlutionStuff.com</h5>

</div>

<div class="card-body">

<h5 class="card-title">Docusign Tutorial</h5>

<p class="card-text">Click the button below to connect your application with Docusign</p>

@if ($message = Session::get('success'))

<a href="{{ route('docusign.sign') }}" class="btn btn-primary">Click to Sign Document</a>

@else

<a href="{{ route('connect.docusign') }}" class="btn btn-primary">Connect Docusign</a>

@endif

</div>

</div>

</div>

</body>

</html>

Run Laravel App:

All the required steps have been done, now you have to type the given below command and hit enter to run the Laravel app:

php artisan serve

Now, Go to your web browser, type the given URL and view the app output:

http://localhost:8000/docusign

Output:

Then, you need to click on Connect DocuSign and authenticate your docusign account.

After authenticate you will redirect back with following screen:

Then, you need to click on Click to Sign Document and you will able to sign your pdf file as like the below screen.

Then in end, you will redirect back and you will receive email with signed pdf file.

You can see all the above screens as output.

I hope it can help you...

Tags :