Node.js应用中使用DocuSign AccessToken发送信封及从开发者账户自动获取AccessToken的实现方案问询
Hey there! Let's tackle your two DocuSign + Node.js questions clearly and practically—this is a common workflow I've helped implement multiple times.
First, let's assume you already have a valid AccessToken (from any DocuSign auth flow), your DocuSign account ID, and the correct environment base path (demo: account-d.docusign.com, production: account.docusign.com). Here's the step-by-step implementation:
Prerequisites
- Install the DocuSign Node.js SDK:
npm install docusign-esign
Full Implementation Code
const docusign = require('docusign-esign'); const fs = require('fs'); async function sendEnvelopeWithAccessToken() { // Replace these with your actual values const accessToken = 'YOUR_VALID_ACCESS_TOKEN'; const accountId = 'YOUR_DOCUSIGN_ACCOUNT_ID'; const basePath = 'https://account-d.docusign.com/restapi'; // Demo environment // Initialize the DocuSign API client const apiClient = new docusign.ApiClient(); apiClient.setBasePath(basePath); apiClient.addDefaultHeader('Authorization', `Bearer ${accessToken}`); // Read and encode your document to base64 const documentBytes = fs.readFileSync('./path/to/your/document.pdf'); const documentBase64 = Buffer.from(documentBytes).toString('base64'); // Build the envelope definition const envelopeDefinition = new docusign.EnvelopeDefinition(); envelopeDefinition.emailSubject = 'Please sign this important document'; envelopeDefinition.status = 'sent'; // Set to 'draft' if you want to save instead of send // Add the document to the envelope const document = new docusign.Document(); document.documentBase64 = documentBase64; document.name = 'Agreement.pdf'; document.documentId = '1'; envelopeDefinition.documents = [document]; // Add a signer and their signature tab const signer = new docusign.Signer(); signer.email = 'recipient@example.com'; signer.name = 'Recipient Full Name'; signer.recipientId = '1'; const signHereTab = new docusign.SignHere(); signHereTab.documentId = '1'; signHereTab.recipientId = '1'; signHereTab.xPosition = '150'; // Adjust based on your document layout signHereTab.yPosition = '250'; const tabs = new docusign.Tabs(); tabs.signHereTabs = [signHereTab]; signer.tabs = tabs; const recipients = new docusign.Recipients(); recipients.signers = [signer]; envelopeDefinition.recipients = recipients; // Send the envelope const envelopesApi = new docusign.EnvelopesApi(apiClient); try { const response = await envelopesApi.createEnvelope(accountId, { envelopeDefinition }); console.log(`Envelope sent successfully! Envelope ID: ${response.envelopeId}`); return response; } catch (error) { console.error('Error sending envelope:', error.response?.body || error.message); throw error; } } // Execute the function sendEnvelopeWithAccessToken();
Key Notes
- Ensure your AccessToken has the
signaturescope (andimpersonationif acting on behalf of another user). - Double-check document paths and recipient details to avoid failures.
Yes! The JWT Authorization Flow is designed exactly for this scenario—it lets server-side apps get AccessTokens automatically without requiring manual user login. This is ideal for sending envelopes on behalf of a user (or your own developer account) in a fully automated way.
Prerequisites
- A DocuSign developer/production account.
- An Integrator Key (your app's ID in DocuSign) with JWT enabled.
- An RSA key pair (you'll need the private key for signing the JWT request).
- A one-time user consent (for acting on behalf of a user; skip if using your own account).
Full Implementation Code
First, get the JWT token, then use it to send the envelope:
const docusign = require('docusign-esign'); const fs = require('fs'); async function getJwtAccessToken() { // Replace these with your actual values const clientId = 'YOUR_INTEGRATOR_KEY'; const userId = 'YOUR_DOCUSIGN_USER_ID'; // Found in your DocuSign account settings const privateKeyPath = './path/to/your/private.key'; const oauthBasePath = 'https://account-d.docusign.com/oauth'; // Demo environment const scopes = ['signature', 'impersonation']; // Required scopes const apiClient = new docusign.ApiClient(); apiClient.setOAuthBasePath(oauthBasePath); // Load your private key const privateKey = fs.readFileSync(privateKeyPath, 'utf8'); // Request the JWT token try { const jwtResponse = await apiClient.requestJWTUserToken( clientId, userId, scopes, privateKey, 3600 // Token expires in 1 hour (max allowed) ); // Extract key values from the response const accessToken = jwtResponse.body.access_token; const accountId = jwtResponse.body.accounts[0].account_id; const basePath = jwtResponse.body.accounts[0].base_uri + '/restapi'; return { accessToken, accountId, basePath }; } catch (error) { console.error('Error fetching JWT token:', error.response?.body || error.message); throw error; } } // Combine JWT token fetch with envelope sending async function sendEnvelopeAutomatically() { const { accessToken, accountId, basePath } = await getJwtAccessToken(); // Reuse the envelope sending logic from the first example here const apiClient = new docusign.ApiClient(); apiClient.setBasePath(basePath); apiClient.addDefaultHeader('Authorization', `Bearer ${accessToken}`); // ... [Insert envelope building/sending code from question 1 here] ... } // Execute the automated workflow sendEnvelopeAutomatically();
Key Notes
- One-Time Consent: Before your first run, generate a consent URL using
apiClient.getJWTUri(clientId, scopes, redirectUri)and have the user visit it to grant permissions. After that, no more manual steps are needed. - Token Refresh: Since JWT tokens expire after 1 hour, call
getJwtAccessToken()every time you need to send an envelope (it's a fast, stateless request). - Private Key Security: Store your private key securely (never commit it to version control) and set file permissions to read-only (e.g.,
chmod 600 private.key).
内容的提问来源于stack exchange,提问作者Rafras PL

