-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsigndoc_trigger.py
More file actions
189 lines (178 loc) · 6.69 KB
/
signdoc_trigger.py
File metadata and controls
189 lines (178 loc) · 6.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import requests
import json
import base64
import sys
import os
from datetime import datetime
import xml.etree.ElementTree as ET
# --- Hardcoded Values, Change as per your enviornment ---
TEMPLATE_FILE_PATH = r"C:\_Kofax\SignDOCS\SFDCDemo\Quote_Q-721814.pdf"
OUTPUT_DIR = r"C:\_Kofax\SignDOCS\SFDCDemo\Outputs"
OUTPUT_FILE = os.path.join(OUTPUT_DIR, "signdoc_response.xml")
BASE_URL = "https://<<Your_SignDOC_Server>>/cirrus/rest/v8"
API_KEY = "<<your API Key>>"
def encode_pdf_to_base64(pdf_path):
try:
with open(pdf_path, "rb") as pdf_file:
encoded_pdf = base64.b64encode(pdf_file.read()).decode('utf-8')
return encoded_pdf
except FileNotFoundError:
raise FileNotFoundError(f"PDF file not found: {pdf_path}")
except Exception as e:
raise Exception(f"Error encoding PDF file: {str(e)}")
def validate_email(email):
import re
pattern = r'^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$'
return re.match(pattern, email) is not None
def call_signdoc_api(name, email, pdf_content):
today_str = datetime.today().strftime('%d-%m-%Y')
url = f"{BASE_URL}/package?autoprepare=false&schedule=true&delete_existing=true"
payload = json.dumps({
"name": "SignDOC Demo - Quote ID O-1018824",
"type": "PACKAGE",
"signers": [
{
"id": "signer-1",
"name": name,
"email": email
}
],
"documents": [
{
"content": pdf_content,
"id": "document-1",
"name": "Loan Application",
"signatureFields": [
{
"id": "signature_field_1",
"name": "signature_field_1",
"signerId": "signer-1",
"alternateName": f"{name} signature",
"required": True,
"widgets": [
{
"index": 0,
"pageNumber": 2,
"top": 150,
"left": 450,
"right": 580,
"bottom": 110,
"tabIndex": 2
}
]
}
],
"textFields": [
{
"id": "txt_name",
"name": "Applicant_name",
"description": "Name",
"signerId": "signer-1",
"value": name,
"readOnly": True,
"multiLine": False,
"maxLength": 1024,
"widgets": [
{
"index": 0,
"pageNumber": 2,
"top": 185,
"left": 170,
"right": 330,
"bottom": 165,
"tabIndex": 0
}
]
},
{
"id": "txt_DocDate",
"name": "txt_DocDate",
"description": "Document Date",
"signerId": "signer-1",
"value": today_str,
"readOnly": True,
"multiLine": False,
"maxLength": 1024,
"widgets": [
{
"index": 0,
"pageNumber": 2,
"top": 185,
"left": 450,
"right": 580,
"bottom": 165,
"tabIndex": 1
}
]
}
]
}
]
})
headers = {
'Content-Type': 'application/json',
'Accept': 'application/xml',
'api-key': API_KEY
}
try:
response = requests.post(url, headers=headers, data=payload)
os.makedirs(OUTPUT_DIR, exist_ok=True)
with open(OUTPUT_FILE, 'w', encoding='utf-8') as f:
f.write(response.text)
package_id = None
if response.status_code == 201:
try:
root = ET.fromstring(response.text)
ns = {"ns2": "http://www.kofax.com/ksd/cirrus/rest/v8"}
package_id = root.findtext("ns2:ID", namespaces=ns)
if not package_id:
url_text = root.findtext("ns2:url", namespaces=ns)
if url_text and "/" in url_text:
package_id = url_text.split("/")[-1]
except Exception as e:
print(f"Warning: Could not parse package ID: {e}")
return {
'status_code': response.status_code,
'response_text': response.text,
'output_file': OUTPUT_FILE,
'success': response.status_code == 201,
'package_id': package_id
}
except requests.exceptions.RequestException as e:
raise Exception(f"API request failed: {str(e)}")
def main():
if len(sys.argv) != 3:
print("Usage: python signdoc_trigger.py <name> <email>")
sys.exit(1)
name = sys.argv[1]
email = sys.argv[2]
if not validate_email(email):
print(f"Error: Invalid email format: {email}", file=sys.stderr)
sys.exit(1)
if not os.path.isfile(TEMPLATE_FILE_PATH):
print(f"Error: PDF file not found: {TEMPLATE_FILE_PATH}", file=sys.stderr)
sys.exit(1)
if not TEMPLATE_FILE_PATH.lower().endswith('.pdf'):
print(f"Error: File must be a PDF: {TEMPLATE_FILE_PATH}", file=sys.stderr)
sys.exit(1)
print("Encoding PDF to Base64...")
pdf_content = encode_pdf_to_base64(TEMPLATE_FILE_PATH)
print("Calling SignDOC API...")
result = call_signdoc_api(
name=name,
email=email,
pdf_content=pdf_content
)
print(f"API Response Status: {result['status_code']}")
print(f"Response saved to: {result['output_file']}")
if result['success']:
print("SignDOC package created successfully!")
if result['package_id']:
print(f"Package ID: {result['package_id']}")
else:
print(f"API call failed with status {result['status_code']}")
print("Response content:")
print(result['response_text'])
sys.exit(1)
if __name__ == "__main__":
main()