Commit d69e365c authored by Volkov Gherman's avatar Volkov Gherman

Create default logic docusign app

parent a0d62440
...@@ -151,4 +151,5 @@ cython_debug/ ...@@ -151,4 +151,5 @@ cython_debug/
# option (not recommended) you can uncomment the following to ignore the entire idea folder. # option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/ .idea/
.DS_Store .DS_Store
docusign_test_app-python/ private.key
from os import path
import re
demo_docs_path = path.abspath(path.join(path.dirname(path.realpath(__file__)), "static/demo_documents"))
# Pattern for validating signer name and email
pattern = re.compile("([^\w \-\@\.\,])+")
signer_client_id = 1000 # Used to indicate that the signer will use embedded
# signing. Represents the signer"s userId within
# your application.
authentication_method = "None" # How is this application authenticating
minimum_buffer_min = 3
# Template name for create template example
template_name = "Example Signer and CC template v2"
# Name of static doc file
doc_file = "World_Wide_Corp_fields.pdf"
# Name of static pdf file
pdf_file = "World_Wide_Corp_lorem.pdf"
# Base uri for callback function
base_uri_suffix = "/restapi"
# Default languages for brand
languages = {
"Arabic": "ar",
"Armenian": "hy",
"Bahasa Indonesia": "id",
"Bahasa Malay": "ms",
"Bulgarian": "bg",
"Chinese Simplified": "zh_CN",
"Chinese Traditional": "zh_TW",
"Croatian": "hr",
"Czech": "cs",
"Danish": "da",
"Dutch": "nl",
"English UK": "en_GB",
"English US": "en",
"Estonian": "et",
"Farsi": "fa",
"Finnish": "fi",
"French": "fr",
"French Canada": "fr_CA",
"German": "de",
"Greek": "el",
"Hebrew": "he",
"Hindi": "hi",
"Hungarian": "hu",
"Italian": "it",
"Japanese": "ja",
"Korean": "ko",
"Latvian": "lv",
"Lithuanian": "lt",
"Norwegian": "no",
"Polish": "pl",
"Portuguese": "pt",
"Portuguese Brasil": "pt_BR",
"Romanian": "ro",
"Russian": "ru",
"Serbian": "sr",
"Slovak": "sk",
"Slovenian": "sl",
"Spanish": "es",
"Spanish Latin America": "es_MX",
"Swedish": "sv",
"Thai": "th",
"Turkish": "tr",
"Ukrainian": "uk",
"Vietnamese": "vi"
}
# Default settings for updating and creating permissions
settings = {
"useNewDocuSignExperienceInterface": "optional",
"allowBulkSending": "true",
"allowEnvelopeSending": "true",
"allowSignerAttachments": "true",
"allowTaggingInSendAndCorrect": "true",
"allowWetSigningOverride": "true",
"allowedAddressBookAccess": "personalAndShared",
"allowedTemplateAccess": "share",
"enableRecipientViewingNotifications": "true",
"enableSequentialSigningInterface": "true",
"receiveCompletedSelfSignedDocumentsAsEmailLinks": "false",
"signingUiVersion": "v2",
"useNewSendingInterface": "true",
"allowApiAccess": "true",
"allowApiAccessToAccount": "true",
"allowApiSendingOnBehalfOfOthers": "true",
"allowApiSequentialSigning": "true",
"enableApiRequestLogging": "true",
"allowDocuSignDesktopClient": "false",
"allowSendersToSetRecipientEmailLanguage": "true",
"allowVaulting": "false",
"allowedToBeEnvelopeTransferRecipient": "true",
"enableTransactionPointIntegration": "false",
"powerFormRole": "admin",
"vaultingMode": "none"
}
API_TYPE = {
"ESIGNATURE": "eSignature",
"MONITOR": "Monitor",
"CLICK": "Click",
"ROOMS": "Rooms",
"ADMIN": "Admin"
}
import base64
from os import path
from docusign_esign import EnvelopesApi, EnvelopeDefinition, Document, Signer, CarbonCopy, SignHere, Tabs, Recipients
from ...consts import demo_docs_path, pattern
from ...jwt_helpers import create_api_client
class Eg002SigningViaEmailController:
@classmethod
def worker(cls, args, doc_docx_path, doc_pdf_path):
"""
1. Create the envelope request object
2. Send the envelope
"""
envelope_args = args["envelope_args"]
# 1. Create the envelope request object
envelope_definition = cls.make_envelope(envelope_args, doc_docx_path, doc_pdf_path)
api_client = create_api_client(base_path=args["base_path"], access_token=args["access_token"])
# 2. call Envelopes::create API method
# Exceptions will be caught by the calling function
envelopes_api = EnvelopesApi(api_client)
results = envelopes_api.create_envelope(account_id=args["account_id"], envelope_definition=envelope_definition)
envelope_id = results.envelope_id
return {"envelope_id": envelope_id}
@classmethod
def make_envelope(cls, args, doc_docx_path, doc_pdf_path):
"""
Creates envelope
Document 1: An HTML document.
Document 2: A Word .docx document.
Document 3: A PDF document.
DocuSign will convert all of the documents to the PDF format.
The recipients" field tags are placed using <b>anchor</b> strings.
"""
# document 1 (html) has sign here anchor tag **signature_1**
# document 2 (docx) has sign here anchor tag /sn1/
# document 3 (pdf) has sign here anchor tag /sn1/
#
# The envelope has two recipients.
# recipient 1 - signer
# recipient 2 - cc
# The envelope will be sent first to the signer.
# After it is signed, a copy is sent to the cc person.
# create the envelope definition
env = EnvelopeDefinition(
email_subject="Please sign this document set"
)
doc1_b64 = base64.b64encode(bytes(cls.create_document1(args), "utf-8")).decode("ascii")
# read files 2 and 3 from a local directory
# The reads could raise an exception if the file is not available!
with open(path.join(demo_docs_path, doc_docx_path), "rb") as file:
doc2_docx_bytes = file.read()
doc2_b64 = base64.b64encode(doc2_docx_bytes).decode("ascii")
with open(path.join(demo_docs_path, doc_pdf_path), "rb") as file:
doc3_pdf_bytes = file.read()
doc3_b64 = base64.b64encode(doc3_pdf_bytes).decode("ascii")
# Create the document models
document1 = Document( # create the DocuSign document object
document_base64=doc1_b64,
name="Order acknowledgement", # can be different from actual file name
file_extension="html", # many different document types are accepted
document_id="1" # a label used to reference the doc
)
document2 = Document( # create the DocuSign document object
document_base64=doc2_b64,
name="Battle Plan", # can be different from actual file name
file_extension="docx", # many different document types are accepted
document_id="2" # a label used to reference the doc
)
document3 = Document( # create the DocuSign document object
document_base64=doc3_b64,
name="Lorem Ipsum", # can be different from actual file name
file_extension="pdf", # many different document types are accepted
document_id="3" # a label used to reference the doc
)
# The order in the docs array determines the order in the envelope
env.documents = [document1, document2, document3]
# Create the signer recipient model
signer1 = Signer(
email=args["signer_email"],
name=args["signer_name"],
recipient_id="1",
routing_order="1"
)
# routingOrder (lower means earlier) determines the order of deliveries
# to the recipients. Parallel routing order is supported by using the
# same integer as the order for two or more recipients.
# create a cc recipient to receive a copy of the documents
cc1 = CarbonCopy(
email=args["cc_email"],
name=args["cc_name"],
recipient_id="2",
routing_order="2"
)
# Create signHere fields (also known as tabs) on the documents,
# We"re using anchor (autoPlace) positioning
#
# The DocuSign platform searches throughout your envelope"s
# documents for matching anchor strings. So the
# signHere2 tab will be used in both document 2 and 3 since they
# use the same anchor string for their "signer 1" tabs.
sign_here1 = SignHere(
anchor_string="**signature_1**",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
sign_here2 = SignHere(
anchor_string="/sn1/",
anchor_units="pixels",
anchor_y_offset="10",
anchor_x_offset="20"
)
# Add the tabs model (including the sign_here tabs) to the signer
# The Tabs object wants arrays of the different field/tab types
signer1.tabs = Tabs(sign_here_tabs=[sign_here1, sign_here2])
# Add the recipients to the envelope object
recipients = Recipients(signers=[signer1], carbon_copies=[cc1])
env.recipients = recipients
# Request that the envelope be sent by setting |status| to "sent".
# To request that the envelope be created as a draft, set to "created"
env.status = args["status"]
return env
@classmethod
def create_document1(cls, args):
""" Creates document 1 -- an html document"""
return f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
</head>
<body style="font-family:sans-serif;margin-left:2em;">
<h1 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
color: darkblue;margin-bottom: 0;">World Wide Corp</h1>
<h2 style="font-family: "Trebuchet MS", Helvetica, sans-serif;
margin-top: 0px;margin-bottom: 3.5em;font-size: 1em;
color: darkblue;">Order Processing Division</h2>
<h4>Ordered by {args["signer_name"]}</h4>
<p style="margin-top:0em; margin-bottom:0em;">Email: {args["signer_email"]}</p>
<p style="margin-top:0em; margin-bottom:0em;">Copy to: {args["cc_name"]}, {args["cc_email"]}</p>
<p style="margin-top:3em;">
Candy bonbon pastry jujubes lollipop wafer biscuit biscuit. Topping brownie sesame snaps sweet roll pie.
Croissant danish biscuit soufflé caramels jujubes jelly. Dragée danish caramels lemon drops dragée.
Gummi bears cupcake biscuit tiramisu sugar plum pastry. Dragée gummies applicake pudding liquorice.
Donut jujubes oat cake jelly-o.
Dessert bear claw chocolate cake gummies lollipop sugar plum ice cream gummies cheesecake.
</p>
<!-- Note the anchor tag for the signature field is in white. -->
<h3 style="margin-top:3em;">Agreed: <span style="color:white;">**signature_1**/</span></h3>
</body>
</html>
"""
DS_JWT = {
"ds_client_id": "a2ecda0a-ebda-48f6-b784-a75a51608e07",
"ds_impersonated_user_id": "6c83e6cd-4cac-4aeb-a20e-22ab78b1f020", # The id of the user.
"private_key_file": "./app/private.key", # Create a new file in your repo source folder named private.key then copy and paste your RSA private key there and save it.
"authorization_server": "account-d.docusign.com",
"doc_docx": "World_Wide_Corp_Battle_Plan_Trafalgar.docx",
"doc_pdf": "World_Wide_Corp_lorem.pdf"
}
\ No newline at end of file
from .jwt_helper import create_api_client, get_jwt_token, get_private_key
\ No newline at end of file
from docusign_esign import ApiClient
from os import path
def get_jwt_token(private_key, scopes, auth_server, client_id, impersonated_user_id):
"""Get the jwt token"""
api_client = ApiClient()
api_client.set_base_path(auth_server)
response = api_client.request_jwt_user_token(
client_id=client_id,
user_id=impersonated_user_id,
oauth_host_name=auth_server,
private_key_bytes=private_key,
expires_in=4000,
scopes=scopes
)
return response
def get_private_key(private_key_path):
"""
Check that the private key present in the file and if it is, get it from the file.
In the opposite way get it from config variable.
"""
private_key_file = path.abspath(private_key_path)
if path.isfile(private_key_file):
with open(private_key_file) as private_key_file:
private_key = private_key_file.read()
else:
private_key = private_key_path
return private_key
def create_api_client(base_path, access_token):
"""Create api client and construct API headers"""
api_client = ApiClient()
api_client.host = base_path
api_client.set_default_header(header_name="Authorization", header_value=f"Bearer {access_token}")
return api_client
\ No newline at end of file
from os import path
import sys
import subprocess
from docusign_esign import ApiClient
from docusign_esign.client.api_exception import ApiException
from app.jwt_helpers import get_jwt_token, get_private_key
from app.eSignature.examples.eg002_signing_via_email import Eg002SigningViaEmailController
from app.jwt_config import DS_JWT
# pip install DocuSign SDK
subprocess.check_call([sys.executable, '-m', 'pip', 'install', 'docusign_esign'])
SCOPES = [
"signature", "impersonation"
]
def get_consent_url():
url_scopes = "+".join(SCOPES)
# Construct consent URL
redirect_uri = "https://developers.docusign.com/platform/auth/consent"
consent_url = f"https://{DS_JWT['authorization_server']}/oauth/auth?response_type=code&" \
f"scope={url_scopes}&client_id={DS_JWT['ds_client_id']}&redirect_uri={redirect_uri}"
return consent_url
def get_token(private_key, api_client):
# Call request_jwt_user_token method
token_response = get_jwt_token(private_key, SCOPES, DS_JWT["authorization_server"], DS_JWT["ds_client_id"],
DS_JWT["ds_impersonated_user_id"])
access_token = token_response.access_token
# Save API account ID
user_info = api_client.get_user_info(access_token)
accounts = user_info.get_accounts()
api_account_id = accounts[0].account_id
base_path = accounts[0].base_uri + "/restapi"
return {"access_token": access_token, "api_account_id": api_account_id, "base_path": base_path}
def get_args(api_account_id, access_token, base_path):
signer_email = input("Please enter the signer's email address: ")
signer_name = input("Please enter the signer's name: ")
cc_email = input("Please enter the cc email address: ")
cc_name = input("Please enter the cc name: ")
envelope_args = {
"signer_email": signer_email,
"signer_name": signer_name,
"cc_email": cc_email,
"cc_name": cc_name,
"status": "sent",
}
args = {
"account_id": api_account_id,
"base_path": base_path,
"access_token": access_token,
"envelope_args": envelope_args
}
return args
def run_example(private_key, api_client):
jwt_values = get_token(private_key, api_client)
args = get_args(jwt_values["api_account_id"], jwt_values["access_token"], jwt_values["base_path"])
envelope_id = Eg002SigningViaEmailController.worker(args, DS_JWT["doc_docx"], DS_JWT["doc_pdf"])
print("Your envelope has been sent.")
print(envelope_id)
def main():
api_client = ApiClient()
api_client.set_base_path(DS_JWT["authorization_server"])
api_client.set_oauth_host_name(DS_JWT["authorization_server"])
private_key = get_private_key(DS_JWT["private_key_file"]).encode("ascii").decode("utf-8")
try:
run_example(private_key, api_client)
except ApiException as err:
body = err.body.decode('utf8')
if "consent_required" in body:
consent_url = get_consent_url()
print("Open the following URL in your browser to grant consent to the application:")
print(consent_url)
consent_granted = input("Consent granted? Select one of the following: \n 1)Yes \n 2)No \n")
if consent_granted == "1":
run_example(private_key, api_client)
else:
sys.exit("Please grant consent")
main()
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment