Java Docusign Аутентификация - PullRequest
       6

Java Docusign Аутентификация

0 голосов
/ 13 февраля 2019

Я пытаюсь подключить docusign, используя Java.Ниже код, который я использую.

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

Я копирую клиентский и интеграционный ключ из данного изображения.

Ошибка: ошибкапри запросе токена доступа: POST https://account -d.docusign.com / oauth / token вернул статус ответа 400 Bad Request

Ответы [ 2 ]

0 голосов
/ 14 февраля 2019

Из вашего комментария к ответу Эргина звучит, как будто вы не завершили процесс аутентификации JWT.

Я предлагаю вам начать с примера кода DocuSign JWT Grant для вашего языка:

Инструкции по установке и настройке см. В файле readme.

Как только вы сможете сгенерировать токен доступа через поток JWT, вы можете приступить к реализации самого вызова API DocuSign.

0 голосов
/ 13 февраля 2019

Обычно ответ 400 Bad Request указывает, что что-то не так с отправляемым телом запроса или другим неправильным форматированием запроса.Для разрешения я рекомендую распечатать тело запроса (то есть определение конверта) непосредственно перед отправкой, чтобы вы могли проверить его содержимое и убедиться, что вы ожидаете.

Как минимум, чтобы отправить конверт, вам нужентема электронного письма, документ, получатель и статус (установлено на "sent").

При печати тела запроса в формате JSON оно должно выглядеть следующим образом:

{
    "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"
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...