3

I am trying to connect docusign using java. Below code I am using.

public class DocuSignExample1 {

    private static final String Recipient = "xxx@gmail.com";
    private static final String SignTest1File = "/src/test/docs/SignTest1.pdf";
    private static final String BaseUrl = "https://demo.docusign.net/restapi";
    private static final String IntegratorKey = "xxxxx";
    private static final String UserId = "xxxxxx";
    private static final String privateKeyFullPath = System.getProperty("user.dir") + "/src/test/keys/docusign_private_key2.txt";
    public static void main(String[] args) {

        System.out.println("\nRequestASignatureTest:\n" + "===========================================");
        byte[] fileBytes = null;
        try {
            String currentDir = System.getProperty("user.dir");

            Path path = Paths.get(currentDir + SignTest1File);
            fileBytes = Files.readAllBytes(path);
        } catch (IOException ioExcp) {
            ioExcp.printStackTrace();
        }

        EnvelopeDefinition envDef = new EnvelopeDefinition();
        envDef.setEmailSubject("Please Sign My Sample Document");
        envDef.setEmailBlurb("Hello, Please Sign My Sample Document.");

        // add a document to the envelope
        Document doc = new Document();
        String base64Doc = Base64.encodeToString(fileBytes, false);
        doc.setDocumentBase64(base64Doc);
        doc.setName("TestFile.pdf");
        doc.setDocumentId("1");

        List<Document> docs = new ArrayList<Document>();
        docs.add(doc);
        envDef.setDocuments(docs);

        // Add a recipient to sign the document
        Signer signer = new Signer();
        signer.setEmail(Recipient);
        signer.setName("Sanjay");
        signer.setRecipientId("1");

        // Above causes issue
        envDef.setRecipients(new Recipients());
        envDef.getRecipients().setSigners(new ArrayList<Signer>());
        envDef.getRecipients().getSigners().add(signer);

        // send the envelope (otherwise it will be "created" in the Draft folder
        envDef.setStatus("sent");

        ApiClient apiClient = new ApiClient(BaseUrl);
        try {
            byte[] privateKeyBytes = null;
            try {
                privateKeyBytes = Files.readAllBytes(Paths.get(privateKeyFullPath));
            } catch (IOException ioExcp) {
                Assert.assertEquals(null, ioExcp);
            }
            if (privateKeyBytes == null)
                return;

            java.util.List<String> scopes = new ArrayList<String>();
            scopes.add(OAuth.Scope_SIGNATURE);

            OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes,
                    3600);
            Assert.assertNotSame(null, oAuthToken);
            // now that the API client has an OAuth token, let's use it in all
            // DocuSign APIs
            apiClient.setAccessToken(oAuthToken.getAccessToken(), oAuthToken.getExpiresIn());
            UserInfo userInfo = apiClient.getUserInfo(oAuthToken.getAccessToken());

            System.out.println("UserInfo: " + userInfo);

            apiClient.setBasePath(userInfo.getAccounts().get(0).getBaseUri() + "/restapi");
            Configuration.setDefaultApiClient(apiClient);
            String accountId = userInfo.getAccounts().get(0).getAccountId();

            EnvelopesApi envelopesApi = new EnvelopesApi();

            EnvelopeSummary envelopeSummary = envelopesApi.createEnvelope(accountId, envDef);
            System.out.println("EnvelopeSummary: " + envelopeSummary);
        } catch (ApiException ex) {
            ex.printStackTrace();
            System.out.println("Exception: " + ex);
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("Exception: " + e.getLocalizedMessage());
        }
    }
}

enter image description here

I am copying clientid and integratory key from given image.

Error : Error while requesting an access token: POST https://account-d.docusign.com/oauth/token returned a response status of 400 Bad Request

Sanjay
  • 2,481
  • 1
  • 13
  • 28

3 Answers3

1

Usually a 400 Bad Request response indicates something wrong with the request body you're sending or some other bad formatting about the request. To resolve I recommend you print your request body (i.e. the envelope definition) just before sending out so you can inspect its contents and make sure it's what you expect.

At a minimum, to send an envelope you need an email subject, a document, a recipient, and status (set to "sent").

When you print your request body in JSON it should look like this:

{
    "emailSubject": "API Signature Request",
    "documents": [{
        "documentId": "1",
        "name": "contract.pdf",
        "documentBase64": "<...base64 document bytes...>",
    }],
    "recipients": {
        "signers": [{
            "email": "bob.smith@docusign.com",
            "name": "Bob Smith",
            "recipientId": "1",
            "routingOrder": "1",
        }]
    },
    "status": "sent"
}
Ergin
  • 9,254
  • 1
  • 19
  • 28
  • 1
    Error is generating during requesting token.This line giving me error. OAuth.OAuthToken oAuthToken = apiClient.requestJWTUserToken(IntegratorKey, UserId, scopes, privateKeyBytes, 3600); – Sanjay Feb 14 '19 at 04:33
  • Above program perfectly working with https://github.com/docusign/docusign-java-client/blob/master/src/test/java/SdkUnitTests.java . As soon as I am adding my credentials,it is not working. – Sanjay Feb 14 '19 at 04:36
1

From your comment to Ergin's answer it sounds like you're not completing the JWT authentication flow.

I suggest that you start with the DocuSign JWT Grant code example for your language:

See the readme file for installation and configuration instructions.

Once you're able to generate an access token via the JWT flow, you can go on to implement your DocuSign API call itself.

Larry K
  • 47,808
  • 15
  • 87
  • 140
  • During generating token it is giving me error.Same code is working with userid and privatekey and integrator key of https://github.com/docusign/docusign-java-client/blob/master/src/test/java/SdkUnitTests.java – Sanjay Feb 14 '19 at 13:26
  • They have removed the code, I just clicked on "Java" (https://github.com/docusign/eg-01-java-jwt) link but it gives 404! – San4musa Jul 28 '20 at 17:19
  • Sorry about the 404 error. The JWT example has been folded into the larger [code-example-java](https://github.com/docusign/code-examples-java) – Larry K Jul 29 '20 at 12:03
0

I faced same problem after accepting consent 400 error gone. You can accept consent by typing this URL in a browser

https://account-d.docusign.com/oauth/auth?response_type=token&scope=signature&client_id=<integrator key>&state=<random number to avoid request forgery>&redirect_uri=http://example.com/callback/
Sanjiv
  • 11
  • 3