Sunday, 23 April 2017

Get docusign recipient link in AEM

To generate the recipient signing URL call the EnvelopeViews: createRecipientmethod, using the same identifying recipient information - including the clientUserId - that was sent with envelope. To do this make an http POST request to the following endpoint:

POST /accounts/{accountId}/envelopes/{envelopeId}/views/recipient
With the following request body:
    "userName": "Kishore Polsani",
    "email": "[email protected]",
    "recipientId": "1",
    "clientUserId": "1111",
    "authenticationMethod": "email",
    "returnUrl": ""

The recipient information - userNameemailrecipientId, and clientUserId - must match the values that were provided when the recipient was first added to the envelope, otherwise an error will be returned. Also note we use the userNameproperty to reference the recipient's name instead of just name.
The authenticationMethod is an enumerated value that indicates the convention used to authenticate the signer. Since, with Embedding, you are telling Docusign that you are handling authentication this is your way of telling the platform how you authenticated the recipient. This information will also be included in the Certificate of Completion, a PDF that is automatically generated for every completed envelope. Lastly, the returnUrl is where the recipient will be re-directed to once signing is complete.
A successful response looks like:
    "uri": ""

Sample Code:

package com.kishore.docusign;

 * Docusign integration
 * Author: Kishore Polsani
import java.util.Dictionary;

import javax.servlet.ServletException;

import org.apache.commons.lang.StringUtils;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Component;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Service;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.params.ConnRoutePNames;
import org.apache.http.entity.ByteArrayEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.osgi.service.component.ComponentContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Component(name = "com.kishore.docusign.DocusignViewRecipientLink", label = "AEM Docusign - Integration", immediate = true, metatype = true)
@Properties({ @Property(name = "service.description", value = "AEM Docusign - Integration"),
        @Property(name = "service.vendor", value = "AEM Quickstart"),
        @Property(name = "docuservicebaseurl", value = ""),
        @Property(name = "docusignLoginUrl", value = ""),
        @Property(name = "docuusername", value = "[email protected]"),
        @Property(name = "docupassword", value = "XXXXX"), 
        @Property(name = "sling.servlet.paths", value = "/services/docusign/DocusignViewRecipientLink", propertyPrivate = true),
        @Property(name = "sling.servlet.methods", value = "POST"),
        @Property(name = "proxyurl", value = "xxxxxxxxxx"),
        @Property(name = "proxyport", value = "80"),
        @Property(name = "integratorkey", value = "XXXXX-XXXXX-XXXXX-XXXXX-XXXX") })
public class DocusignViewRecipientLink extends SlingAllMethodsServlet implements Serializable{
    /** The log. */
    private Logger log = LoggerFactory.getLogger(DocusignViewRecipientLink.class);

    private static final long serialVersionUID = 1L;

    private String loginServiceUrl;
    private String serviceBaseUrl;
    private String userName;
    private String password;
    private String integratorkey;
    private String proxyurl;
    private String proxyport;
    private String accountid;

    protected void doGet(SlingHttpServletRequest request,
               SlingHttpServletResponse response) throws ServletException
              doPost(request, response);
    public void doPost(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException {"loginServiceUrl :" + loginServiceUrl);"userName" + userName);"password " + password);"integratorkey:" + integratorkey);"serviceBaseUrl: "+serviceBaseUrl);
        JSONObject obj = new JSONObject();
        String recipientLink=null;
        try {
            obj.put("Username", userName);
            obj.put("Password", password);
            obj.put("IntegratorKey", integratorkey);
            HttpClient httpClient = new DefaultHttpClient();
            HttpGet getRequest = new HttpGet(loginServiceUrl);
            //If proxy is required, else avoid the below  two lines
            HttpHost proxy = new HttpHost(proxyurl, Integer.parseInt(proxyport));
            httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
            getRequest.addHeader("X-DocuSign-Authentication", obj.toString());
            HttpResponse responseHttp = httpClient.execute(getRequest);
            BufferedReader rd = new BufferedReader(new InputStreamReader(responseHttp.getEntity().getContent()));
            StringBuffer result = new StringBuffer();
            String line = "";
            int status = responseHttp.getStatusLine().getStatusCode();
  "Base Url Status :"+result);
            JSONObject resJsonObj = new JSONObject();
            if (status == 200) {
                while ((line = rd.readLine()) != null) {
      "result :"+result);
                if (!StringUtils.isEmpty(result.toString())) {
                    JSONObject resObj = new JSONObject(result.toString());
                    JSONArray quote = resObj.getJSONArray("loginAccounts");                 
                    String baseUrl = (String)quote.getJSONObject(0).get("baseUrl");
          "baseUrl :"+baseUrl);
                    String accountId = (String)quote.getJSONObject(0).get("accountId");
          "Account Id :"+accountId);
                    String envIdParam = request.getParameter("envelopeId");
          "userNameParam :"+envIdParam);
                    StringBuffer sb = new StringBuffer();
          "Envelope Url :"+sb.toString());
                    httpClient = new DefaultHttpClient();
                    HttpPost postReq = new HttpPost(sb.toString());
                    httpClient.getParams().setParameter(ConnRoutePNames.DEFAULT_PROXY, proxy);
                    postReq.addHeader("X-DocuSign-Authentication", obj.toString());
                    postReq.addHeader("Content-Type", "application/json");
                    postReq.addHeader("Accept", "application/json");
                    String userNameParam = request.getParameter("userName");
                    String emailParam = request.getParameter("email");
                    String clientUserIdParam = request.getParameter("clientUserId");
                    String docuSignReturnUrl = request.getParameter("docuSignReturnUrl");
          "userNameParam :"+userNameParam);
          "emailParam :"+emailParam);
          "clientUserIdParam :"+clientUserIdParam);
          "docuSignReturnUrl :"+docuSignReturnUrl);
                    JSONObject envJson = new JSONObject();
                    envJson.put("userName", userNameParam);
                    envJson.put("email", emailParam);
                    envJson.put("recipientId", 1);
                    envJson.put("routingOrder", 1);
                    envJson.put("clientUserId", clientUserIdParam);
                    envJson.put("authenticationMethod", "email");
                    envJson.put("returnUrl", docuSignReturnUrl);
                    HttpEntity entity = new ByteArrayEntity(envJson.toString().getBytes("UTF-8"));
                    HttpResponse envResponse = httpClient.execute(postReq);
          "Response Code" + envResponse.getStatusLine().getStatusCode());
                    int envStatus = envResponse.getStatusLine().getStatusCode();
           "Status :"+envStatus);
                    if(envStatus >= 200 &&  envStatus < 300) {
                     rd = new BufferedReader(new InputStreamReader(envResponse.getEntity().getContent()));
                      StringBuffer result1 = new StringBuffer();
                        String line1 = "";
                        while ((line1 = rd.readLine()) != null) {
                    JSONObject finalJsonObj = new JSONObject(result1.toString());
                     recipientLink = (String) finalJsonObj.get("url");  
                    if(!StringUtils.isEmpty(recipientLink)) {
                        resJsonObj.put("url", recipientLink);
              "recipientLink: "+recipientLink);
                        throw new Exception("Docusing status is "+envStatus);
            } else {
                resJsonObj.put("status", String.valueOf(status));

        } catch (JSONException e) {
            log.error("Json Exception details :"+ e.toString());
        } catch (Exception e) {
            log.error("Exception details :"+ e.toString());
        }"doPost Ended");


     * default activate method.
     * @param context
     *            the context
     * @throws Exception
     *             the exception
    protected void activate(ComponentContext context) throws Exception {
        Dictionary properties = context.getProperties();
        loginServiceUrl = (String) properties.get("docusignLoginUrl");
        serviceBaseUrl = (String) properties.get("docuservicebaseurl");     
        userName = (String) properties.get("docuusername");
        password = (String) properties.get("docupassword");
        integratorkey = (String) properties.get("integratorkey");
        proxyurl = (String) properties.get("proxyurl");
        proxyport = (String) properties.get("proxyport");

Sample Ajax Call

var signerName = "Kishore Polsani";
var  signerEmail= "[email protected]";
var envelopeId = "xxxxxxxxxxxxxxxxxxxxxxxx";
var clientUserId = "xxxxxxxxx";
var docuSignReturnUrl = "https://localhost:5433/content/kishore/docusign.html";
        type: "GET",
        async: true,
        url: "/services/salesforce/docusignViewRecipientLink ",
        data: {
        email :signerEmail,
        envelopeId :envelopeId,
        success: function(result) {
        console.log("result" +result);
        window.location.href = result;
        error: function(result) {
        console.log("Docusign Recipient Link" +result);        
Test this API

1 comment :

  1. Hi Kishore,

    Thank you for sharing this code snippet. will it be possible to share the POM file associated with this application. I'm having a hard time to do a maven build with my POM file.