Skip to main content
Question

Envelope error USER_AUTHENTICATION_FAILED","message

  • 29 August 2024
  • 2 replies
  • 31 views

def get_docusign_client():
api_client = ApiClient()
api_client.set_base_path(DOCUSIGN_API_BASE_URL)
logging.info(f"Using API base path: {DOCUSIGN_API_BASE_URL}")

with open(DOCUSIGN_PRIVATE_KEY_FILE, 'rb') as private_key_file:
private_key_bytes = private_key_file.read()

try:
# Request JWT user token
oauth = api_client.request_jwt_user_token(
client_id=DOCUSIGN_CLIENT_ID,
user_id=DOCUSIGN_USER_ID,
oauth_host_name=DOCUSIGN_AUTH_SERVER,
private_key_bytes=private_key_bytes,
expires_in=3600,
scopes=['signature', 'impersonation']
)

logging.info("JWT token successfully obtained")

# Set the Authorization header
access_token = oauth.access_token
api_client.set_default_header('Authorization', f"Bearer {access_token}")

# Verify the token and get user info
user_info = api_client.get_user_info(access_token)
logging.info(f"Token verified for user: {user_info.name}")
logging.info(f"User email: {user_info.email}")

# Log account information
for account in user_info.accounts:
logging.info(f"Account ID: {account.account_id}, Name: {account.account_name}, Is Default: {account.is_default}")
if account.is_default:
logging.info(f"Default Account ID: {account.account_id}")
global DOCUSIGN_ACCOUNT_ID
DOCUSIGN_ACCOUNT_ID = account.account_id

# Verify that DOCUSIGN_ACCOUNT_ID is set and matches one of the user's accounts
if DOCUSIGN_ACCOUNT_ID not in [account.account_id for account in user_info.accounts]:
logging.error(f"DOCUSIGN_ACCOUNT_ID {DOCUSIGN_ACCOUNT_ID} does not match any of the user's accounts")
raise ValueError("Invalid DOCUSIGN_ACCOUNT_ID")

return api_client

except ApiException as e:
logging.error(f"DocuSign API exception: {e}")
logging.error(f"Error response: {e.body}")
raise

except Exception as e:
logging.error(f"Unexpected error: {e}")
raise

def create_envelope(docusign_client, recipient_email, recipient_name, pdf_file_path):
try:
with open(pdf_file_path, 'rb') as pdf_file:
pdf_bytes = pdf_file.read()
base64_file_content = base64.b64encode(pdf_bytes).decode('ascii')

# Create envelope definition
envelope_definition = EnvelopeDefinition(
email_subject="Please sign your Letter of Intent",
email_blurb=f"Dear {recipient_name},\n\nPlease sign your Letter of Intent.\n\nBest regards,\nAmazing Properties LLC",
documents=[
Document(
document_base64=base64_file_content,
name=f"{recipient_name}_Letter_of_Intent.pdf",
file_extension="pdf",
document_id="1"
)
],
recipients=Recipients(
signers=[
Signer(
email=recipient_email,
name=recipient_name,
recipient_id="1",
tabs=Tabs(
sign_here_tabs=[
SignHere(
document_id="1",
page_number="1",
x_position="100",
y_position="100"
)
]
)
)
]
),
status="sent" # Set to "created" if you want a draft
)

# Initialize the Envelopes API
envelopes_api = EnvelopesApi(docusign_client)

# Create the envelope
envelope_summary = envelopes_api.create_envelope(account_id=DOCUSIGN_ACCOUNT_ID, envelope_definition=envelope_definition)
logging.info(f"Envelope sent to {recipient_email}: {envelope_summary.envelope_id}")

except FileNotFoundError:
logging.error(f"No PDF found for {recipient_name} ({recipient_email})")
except ApiException as e:
logging.error(f"DocuSign API exception when sending to {recipient_email}: {e}")
logging.error(f"Error response: {e.body}")
except Exception as e:
logging.error(f"Unexpected error when sending to {recipient_email}: {e}")

the above is try to create and send an envelop but somehow I'm getting Authentication ```HTTP response body: b'{"errorCode":"USER_AUTHENTICATION_FAILED","message":"One or both of Username and Password are invalid. Invalid access token"}' ```
the token is generated and also verified from the log output but failing at the point of sending the envelope
Below is the log out
```
INFO:root:Using API base path: https://demo.docusign.net/restapi
INFO:root:JWT token successfully obtained
INFO:root:Token verified for user: User Name
INFO:root:User email: user@gmail.com
INFO:root:Account ID: 2a2eafca-xxxx-xxxx-xxxx-xxxxxxxxxxx, Name: Company Name, Is Default: True
INFO:root:Default Account ID: 2a2eafca-xxxx-xxxx-xxxx-xxxxxxxxxx
INFO:root:Using Account ID: 2a2eafca-xxxx-xxxx-xxxx-xxxxxxxxxx
ERROR:root:DocuSign API exception when sending to user@gmail.com: (401)
Reason: Unauthorized
Trace-Token: b2759cdc-xxxx-xxxx-xxxx-xxxxxxxxxxx
Timestamp: Thu, 29 Aug 2024 15:12:08 GMT
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache', 'Content-Length': '125', 'Content-Type': 'application/json; charset=utf-8', 'Vary': 'Origin', 'X-Content-Type-Options': 'nosniff', 'X-DocuSign-TraceToken': 'b2759cdc-xxxxx-xxxx-xxxx-xxxxxxxxxx', 'X-DocuSign-Node': 'SE3FE10', 'Date': 'Thu, 29 Aug 2024 15:12:08 GMT'})
HTTP response body: b'{"errorCode":"USER_AUTHENTICATION_FAILED","message":"One or both of Username and Password are invalid. Invalid access token"}'
```


I’ve spent days on this, and I will want a quick solution from anyone

@Neat_b 

The error message you're encountering, "USER_AUTHENTICATION_FAILED" with the message "One or both of Username and Password are invalid. Invalid access token", suggests that there may be an issue with the token's validity or the authentication process at the point where the envelope is being sent. 

The token might be expired by the time the envelope is being sent. Check the log timestamps to ensure that the token is still valid when you are making the API call to send the envelope. The token is set to expire after 3600 seconds (1 hour), so if there's a significant delay between token generation and the envelope creation, the token might no longer be valid.


could you provide full code?it seems you provide two function.  docusign_client is get by the function get_docusign_client? do you cache it ? 

 

FreeLink/甫连信息
🌍 DocuSign Partner | Partner Profile
🏆 2024 APAC Reseller Growth Partner of the Year
🔧 First globally to pass DocuSign eSignature Technical Consultant certification
🚀 Expertise in DocuSign integrations with in-house systems for leading enterprises across various industries.

Feel free to reach out for collaboration opportunities.


Reply