def create_student_form(sender, instance=None, created=False, **kwargs): if created: client = HSClient(api_key=os.environ['HELLO_SIGN_API_KEY']) hsign = client.send_signature_request( test_mode=True,title=instance.title, subject='subject',message=instance.description, signers=[{'email_address': instance.project.client.email, 'name': instance.project.client.first_name}],files=[instance.file.path], signing_redirect_url = "https://safe-mesa-32305.herokuapp.com/contracts/", ) # instance.sign_url = hsign.json_data.get('signing_url') # instance.save(update_fields=["sign_url"]) # obj = client.get_embedded_object('SIGNATURE_ID') # print(obj) print(hsign.json_data) instance.sign_url = hsign.json_data.get('signing_url') instance.save(update_fields=["sign_url"]) # sign_url = obj.sign_url # instance.sign_url = sign_url # instance.save() subject = "new form" message = "{}, has a new form that requires a signature. \n{}. Please check your email for a hello sign " \ "email and sign the form online".format(instance.project.client.first_name,instance.description,), # send_mail(subject, message, "Cesar Marroquin <*****@*****.**>",["{}".format(instance.project.client.email)]) #### send text to parent when child is absent client = TwilioRestClient(os.environ['TWILIO_ACCOUNT_ID'], os.environ['TWILIO_TOKEN']) text = client.messages.create(to="+1{}".format(instance.project.client.phone_number.national_number),from_="+17023235267",body=message)
def get_signature_request_file(self): client = HSClient(api_key=HELLOSIGN_API_KEY) filename = '%s/%s.pdf' % (HELLOSIGN_SIGNED_DIR, self.uuid) if os.path.exists(filename): return filename if self.signature_request_id: created = client.get_signature_request_file( self.signature_request_id, filename) if created: return filename return False
def test_get_account_info(self): ''' Test retrieving account information ''' # Valid account result = self.client.get_account_info() self.assertEqual(isinstance(result, Account), True) # Account does not exist try: new_client = HSClient(api_key='non valid api key') new_client.get_account_info() self.fail() except Unauthorized: pass
def embedded_requesting(request): if request.method == 'POST': try: user_email = request.POST['user_email'] signer_name = request.POST['signer_name'] signer_email = request.POST['signer_email'] hsclient = HSClient(api_key=API_KEY) files = [] form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): files.append(handle_uploaded_file( request.FILES['upload_file'])) signers = [{"name": signer_name, "email_address": signer_email}] cc_email_addresses = [] sr = hsclient.create_embedded_unclaimed_draft( test_mode=True, client_id=CLIENT_ID, is_for_embedded_signing=True, requester_email_address=user_email, files=files, draft_type="request_signature", subject="The NDA we talked about", message= "Please sign this NDA and then we can discuss more. Let me know if you have any questions.", signers=signers, cc_email_addresses=cc_email_addresses) sign_url = sr.claim_url except NoAuthMethod: return render( request, 'hellosign/embedded_requesting.html', { 'error_message': "Please update your settings to include a " + "value for API_KEY.", }) else: return render(request, 'hellosign/embedded_requesting.html', { 'client_id': CLIENT_ID, 'sign_url': str(sign_url) }) else: return render_to_response('hellosign/embedded_requesting.html', context_instance=RequestContext(request))
def sendsigrequest(request): apikey = creds['alexmcferronAPIKEY'] clientID = creds['alexmcferronClientID'] client = HSClient(api_key=apikey) #account = client.get_account_info() #emailaddress = client.account.email_address response = client.send_signature_request_embedded( test_mode=True, client_id=clientID, files=["slowpdf2.pdf"], title="embedded", subject="Ticket 277902", message="Ticket 277902", signers=[{ 'email_address': '*****@*****.**', 'name': 'andrew' } #{'email_address': '*****@*****.**', 'name': 'freedom'} ], use_text_tags=False, ) exploreSignatureRequestResponseObject(response) print(response) message = utilTimeStampAndMessage( "TIME SIGNATURE REQUEST CREATED - call is finished") print(message) sigRequestURL = 'notSet' if len(listOfSignRequests) > 0: mySignatureID = listOfSignRequests.pop(0) sigRequestURL = client.get_embedded_object(mySignatureID) print(mySignatureID + " =signatureID") print(_myDictSignatureRequestID_ToEmail[mySignatureID]) urlOnly = sigRequestURL.sign_url results = {} results.update({'TempUrl': urlOnly}) results.update({'clientID': clientID}) message = utilTimeStampAndMessage("CALLING THE IFRAME NOW ALEX M") print(message) return render(request, "sign.html", results)
def index(): client = HSClient(api_key=HS_APP_KEY) embedded_sign = client.send_signature_request_embedded_with_template( test_mode=True, client_id=HS_CLIENT_ID, template_id=TEMPLATE_ID, subject='<subject>', message='<message>', signers=[{ 'role_name': '<role>', 'email_address': '<email>', 'name': '<name>' }]) embed_id = client.get_embedded_object(embedded_sign.signatures[0].signature_id) sign_url = str(embed_id.sign_url) return render_template('index.html', client_id=HS_CLIENT_ID, sign_url=sign_url)
def sendembeddedtemplate(request): apikey = creds['alexmcferronAPIKEY'] clientID = creds['alexmcferronClientID'] client = HSClient(api_key=apikey) files = ["slowpdf2.pdf"] signer_roles = [ { 'name': 'Baltar', 'order': 1 }, { 'name': 'Madame President', 'order': 2 }, { 'name': 'Lee Adama', 'order': 3 }, ] cc_roles = ['Deck Chief', 'Admiral', 'Starbuck'] merge_fields = [{'name': 'mymerge', 'type': 'text'}] template_draft = client.create_embedded_template_draft( client_id=clientID, signer_roles=signer_roles, test_mode=True, files=files, title='Battlestar Test Draft', subject='There are cylons onboard', message='Halp', cc_roles=cc_roles, merge_fields=merge_fields) template_id = template_draft.template_id url = template_draft.edit_url print(url) results = {} results.update({'TempUrl': url}) results.update({'clientID': clientID}) message = utilTimeStampAndMessage("CALLING THE IFRAME NOW ALEX M") print(message) return render(request, "sign.html", results)
def get_signer_signing_url(self, signer): signature_id = None signatures = self.signatures signer_email = signer.email.lower() try: ## convert to lower jsut incase hellosign one day fixes their error signature_id = [s for s in signatures if s.get('signer_email_address').lower() == signer_email][0].get('signature_id', None) except IndexError: logger.error('Could not find signer: %s in %s' % (signer_email, signatures)) if signature_id is not None: HS_CLIENT = HSClient(api_key=settings.HELLOSIGN_API_KEY) embedded_signing_object = HS_CLIENT.get_embedded_object(signature_id) return embedded_signing_object.sign_url return None
def embedded_signing(request): ''' Embedded signing demo ''' if request.method == 'POST': try: user_email = request.POST['email'] user_name = request.POST['name'] hsclient = HSClient(api_key=API_KEY) files = [ os.path.dirname(os.path.realpath(__file__)) + "/docs/nda.pdf" ] signers = [{"name": user_name, "email_address": user_email}] cc_email_addresses = [] sr = hsclient.send_signature_request_embedded( test_mode=True, client_id=CLIENT_ID, files=files, title="NDA with Acme Co.", subject="The NDA we talked about", message= "Please sign this NDA and then we can discuss more. Let me know if you have any questions.", signers=signers, cc_email_addresses=cc_email_addresses) embedded = hsclient.get_embedded_object( sr.signatures[0].signature_id) except KeyError: return render( request, 'hellosign/embedded_signing.html', {'error_message': "Please enter both your name and email."}) except NoAuthMethod: return render( request, 'hellosign/embedded_signing.html', { 'error_message': "Please update your settings to include a value for API_KEY." }) else: return render(request, 'hellosign/embedded_signing.html', { 'client_id': CLIENT_ID, 'sign_url': str(embedded.sign_url) }) else: return render_to_response('hellosign/embedded_signing.html', context_instance=RequestContext(request))
def oauth_callback(request): ''' Handles an OAuth callback. Retrieves the code and exchanges it for a valid access token. ''' try: code = request.GET['code'] state = request.GET['state'] hsclient = HSClient(api_key=API_KEY) oauth = hsclient.get_oauth_data(code, CLIENT_ID, SECRET, state) request.session['access_token'] = oauth.access_token request.session['token_type'] = oauth.access_token_type print "Got OAuth Token: %s" % oauth.access_token except KeyError: return render(request, 'hellosign/oauth_callback.html', {'error_message': "No code or state found"}) except BadRequest, e: return render(request, 'hellosign/oauth_callback.html', {'error_message': str(e)})
def create_student_form(sender, instance=None, created=False, **kwargs): if created: for student in Student.objects.filter(school_class__name=instance.school_class.name): form = StudentForm.objects.create(class_form=instance,student=student,file=instance.file,title=instance.title, subject=instance.subject,message=instance.message, signer=Parent.objects.filter(student=student)[0],due_date=instance.due_date, ) client = HSClient(api_key=os.environ['HELLO_SIGN_API_KEY']) hsign = client.send_signature_request( test_mode=True,title=form.title, subject=form.subject,message=form.message, signers=[{'email_address': form.signer.email, 'name': form.signer.first_name}],files=[form.file.path] ) form.sign_url = hsign.json_data.get('signing_url') form.save(update_fields=["sign_url"]) for parent in student.parent.filter(student=student): subject = "new form" message = "{}, has a new form that requires a signature. \n{}. Please check your email for a hello sign " \ "email and sign the form online".format(student.first_name,instance.message,), send_text_email(subject,message,parent)
def sendembeddedrequest(request): apikey = creds['alexmcferronAPIKEY'] clientID = creds['alexmcferronClientID'] client = HSClient(api_key=apikey) response = client.create_embedded_unclaimed_draft( test_mode=True, client_id=clientID, draft_type='request_signature', requester_email_address='*****@*****.**', is_for_embedded_signing=True, files=['slowpdf2.pdf']) print(response) url = response.claim_url results = {} results.update({'TempUrl': url}) results.update({'clientID': clientID}) message = utilTimeStampAndMessage("CALLING THE IFRAME NOW ALEX M") print(message) return render(request, "sign.html", results)
def invoice_sign(request, uuid): invoice = get_object_or_404(Invoice, uuid=uuid) client = HSClient(api_key=HELLOSIGN_API_KEY) try: response = client.get_signature_request('%s' % invoice.signature_request_id) client.cancel_signature_request(invoice.signature_request_id) except (NotFound, Gone): pass filename = request.POST.get('filename', invoice.uuid) filename = '%s/%s' % (HELLOSIGN_PRESIGN_DIR, filename) fields = [ [ { "api_id": "uniqueIdHere_2", "name": "", "type": "signature", "x": 450, "y": 310, "width": 240, "height": 60, "required": True, "signer": 0 } ] ] if os.path.exists(filename): response = client.send_signature_request_embedded( test_mode=HELLOSIGN_TEST_MODE, client_id=HELLOSIGN_CLIENT_ID, title=invoice.uuid, signers=[ { 'email_address': invoice.email, 'name': invoice.company_name, } ], form_fields_per_document=json.dumps(fields), files=[filename] ) invoice.signature_request_id = response.signature_request_id else: return http.HttpResponse(json.dumps({'sign_url': False}), content_type="application/json") signature = response.signatures[0] invoice.signature_id = signature.signature_id invoice.save() data = client.get_embedded_object(signature.signature_id) return http.HttpResponse(json.dumps(data.json_data), content_type="application/json")
def setUp(self): params = {'api_key': test_helper.api_key} try: params['env'] = test_helper.env except AttributeError: params['env'] = 'production' self.client = HSClient(**params) self.client_id = test_helper.client_id self.client_secret = test_helper.client_secret if params['env'] == 'production' and not BaseTestCase.warned: BaseTestCase.warned = True print("\n\n") print( " ==================================================================" ) print( " = WARNING: We advise against running the tests against your =" ) print( " = personal account as they perform destructive actions. =" ) print( " ==================================================================" ) while True: resp = input(' > Continue (type yes or hit Ctrl+C to exit)?') if resp == 'yes': # Continue to tests break elif resp == 'no': # Stop here import sys sys.exit() else: # Ask question again pass print() print()
from oauth2client.service_account import ServiceAccountCredentials ### Imports hellosign SDK and Initializes Client from HelloSign API from hellosign_sdk import HSClient ### Other libraries from gdrive_functions import download_file, upload_file from hellosign_functions import send_sign_req, download_completed_offer, send_reminder from main_function import main import datetime print("Imported libraries") # Initializes a client using my corporate email API Key # Obtain API Key from your Hello Sign account sign_client = HSClient( api_key='****************************************************') print("Defined Hello Sign Client") # Initializes Google Sheets API Service from client scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] # Path to your JSON file that includes all the API credentials once enabled on GCP creds = ServiceAccountCredentials.from_json_keyfile_name( '********************************.json', scope) client = gspread.authorize(creds) # Obtains a Google Sheets service sheet = client.open_by_key(sheet_file_id)
import os import csv from hellosign_sdk import HSClient # Initialize HSClient using api key client = HSClient(api_key=os.environ['HELLOSIGN_API_KEY']) account = client.get_account_info() print(account) page = 1 with open('documents.csv', 'r') as csvfile: reader = csv.reader(csvfile) header = next(reader) for row in reader: # row variable is a list that represents a row in csv print(row) print(client.get_signature_request_file(row[0], filename=row[0]))
def setUp(self): self.client = HSClient(api_key=api_key)
import os import csv from hellosign_sdk import HSClient # Initialize HSClient using api key client = HSClient(api_key=os.environ['HELLOSIGN_API_KEY']) account = client.get_account_info() print(account) with open('documents.csv', 'w') as csvfile: reader = csv.writer(csvfile, newline='\n') reader.writerow([ 'signature_request_id', 'test_mode', 'is_complete', 'title', 'signed_at', 'signer_email_address', 'signer_name', 'signature_id', ]) page = 1 signature_request_list = client.get_signature_request_list(page_size=20, page=page) while len(signature_request_list): print(len(signature_request_list))
def main(): client = HSClient(api_key='cd024ab0dbbd0f138420f793da365b0e879180a083924c8b2ac7b9dbee48e35c')
def get_hellosign_client(): return HSClient(api_key=get_config('hellosign key'))
def embedded_signing_with_template(request): try: hsclient = HSClient(api_key=API_KEY) except NoAuthMethod: return render( request, 'hellosign/embedded_signing_with_template.html', { 'error_message': "Please update your settings to include a value for API_KEY." }) if request.method == 'POST': try: signers = [] post_dict = parser.parse(request.POST.urlencode()) template_id = post_dict["template"] for (key, value) in post_dict["signerRole"].iteritems(): if value: value['role_name'] = key signers.append(value) ccs = [] if 'ccRole' in post_dict and len(post_dict['ccRole']) > 0: for (key, value) in post_dict["ccRole"].iteritems(): # if value: ccs.append({'role_name': key, 'email_address': value}) custom_fields = [] if 'cf' in post_dict and len(post_dict['cf']) > 0: for (key, value) in post_dict["cf"].iteritems(): if value: custom_fields.append({key: value}) sr = hsclient.send_signature_request_embedded_with_template( test_mode=True, client_id=CLIENT_ID, template_id=template_id, title="NDA with Acme Co.", subject="The NDA we talked about", message= "Please sign this NDA and then we can discuss more. Let me know if you have any questions.", signing_redirect_url=None, signers=signers, ccs=ccs, custom_fields=custom_fields) embedded = hsclient.get_embedded_object( sr.signatures[0].signature_id) # TODO: need some more validations here # except KeyError: # return render(request, 'hellosign/embedded_signing_with_template.html', { # 'error_message': "Please enter both your name and email.", # }) except NoAuthMethod: pass else: return render(request, 'hellosign/embedded_signing_with_template.html', { 'client_id': CLIENT_ID, 'sign_url': str(embedded.sign_url) }) else: template_list = hsclient.get_template_list() templates = [] for template in template_list: template_data = dict(template.json_data) del template_data['accounts'] templates.append(template_data) templates = json.dumps(templates) return render(request, 'hellosign/embedded_signing_with_template.html', {'templates': templates})
def setUp(self): try: self.env = test_helper.env except AttributeError: self.env = 'production' self.client = HSClient(api_key=test_helper.api_key, env=self.env)
def oauth(request): ''' OAuth demo page ''' try: access_token = request.session['access_token'] token_type = request.session['token_type'] except KeyError: access_token = None token_type = None if request.method == 'POST': try: user_email = request.POST['email'] user_name = request.POST['name'] user_hsclient = HSClient(access_token=access_token, access_token_type=token_type) files = [ os.path.dirname(os.path.realpath(__file__)) + "/docs/nda.pdf" ] signers = [{"name": user_name, "email_address": user_email}] cc_email_addresses = [] sr = user_hsclient.send_signature_request( True, files, None, "OAuth Demo - NDA", "The NDA we talked about", "Please sign this NDA and then we can discuss more. Let me know if you have any questions.", None, signers, cc_email_addresses) except KeyError: return render( request, 'hellosign/oauth.html', { 'error_message': "Please enter both your name and email.", 'client_id': CLIENT_ID }) except NoAuthMethod: return render( request, 'hellosign/oauth.html', { 'error_message': "Please update your settings to include a " + "value for API_KEY.", 'client_id': CLIENT_ID }) else: if isinstance(sr, SignatureRequest): return render( request, 'hellosign/oauth.html', { 'message': 'Request sent successfully.', 'access_token': access_token, 'token_type': token_type, 'client_id': CLIENT_ID }) else: return render(request, 'hellosign/oauth.html', { 'error_message': 'Unknow error', 'client_id': CLIENT_ID }) else: return render( request, 'hellosign/oauth.html', { 'access_token': access_token, 'token_type': token_type, 'client_id': CLIENT_ID })
from pprint import pprint from hellosign_sdk import HSClient import os import requests import json API_KEY = os.environ['API_KEY'] CLIENT_ID = os.environ['CLIENT_ID'] client = HSClient(api_key=API_KEY) MENU_CHOICES = { 1 : "send non-embedded signature request", 2 : "get signature request", 3 : "send non-embedded signature request with template", 4 : "send non-embedded signature request with template & custom fields", 5 : "cancel signature request", 6 : "send a reminder for signature request", 7 : "get account info", 8 : "get template", 9 : "send non-embedded signature request with template NOT USING SDK", 10: "send non-embedded sig request with file_url NOT USING SDK", 11: "list signature requests", 12: "send embedded signature request", 13: "send embedded signature request with template", 14: "get files of signature request", 0 : "exit app", } def run_app(): '''Runs the console app.'''
def services_init(hello_sign_api_key, sheet_name, bucket_name): """ Initializes all the services from the used APIs Input: hello_sign_api_key (String): API Key for the Hello Sign Client. Obtained from the websiste sheet_name (String): The name of the Google Sheet requesting access to bucket_name (String): The name of the Cloud Storage bucket where the APIs credentials files are stored. Output: sheet (Obj). Google Sheets Client File Object. Supposed to open the offers Tracker Sheet drive_service (Obj). Google Drive Client. Bridges the Script with an authorized Project with Google Drive API enabled sign_client (Obj). Hello Sign Client to make the documents completion verification and send signature requests """ # Initializes a client using my corporate email API Key sign_client = HSClient(api_key=hello_sign_api_key) #ENV VAR print("Defined Hello Sign Client") # Initializes Cloud Storage client to access the Google Sheets API and Google Drive API clients credentials files # In the same GCP project, a storage bucket was created and these credentials files uploaded # The following lines of code access these files and downloads them to the temporary Cloud Function directory storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) blobs = bucket.list_blobs(delimiter='/') for blob in blobs: destination_uri = '/tmp/{}'.format(blob.name) blob.download_to_filename(destination_uri) print( "Downloaded Google Drive API and Google Sheets API .json and .pickle clients files" ) # Initializes Google Sheets API Service from client scope = [ 'https://spreadsheets.google.com/feeds', 'https://www.googleapis.com/auth/drive' ] creds = ServiceAccountCredentials.from_json_keyfile_name(opla_path, scope) #ENV VAR client = gspread.authorize(creds) # Obtains a Google Sheets service sheet = client.open(sheet_name).sheet1 #ENV VAR print("Defined Google Sheets Service") # Initializes Google Drive API Service from client SCOPES = ['https://www.googleapis.com/auth/drive'] creds = None # The file token.pickle stores the user's access and refresh tokens, and is # created automatically when the authorization flow completes for the first time. #if os.path.exists('/tmp/tokendownload2.pickle'): with open(token_path, 'rb') as token: creds = pickle.load(token) print("Obtained token pickle file") # # Generates token file for the first time if not found in bucket blob # # If there are no (valid) credentials available, let the user log in. # if not creds or not creds.valid: # if creds and creds.expired and creds.refresh_token: # creds.refresh(Request()) # else: # flow = InstalledAppFlow.from_client_secrets_file( # '/tmp/client_id.json', SCOPES) # creds = flow.run_local_server(port=0) # # Save the credentials for the next run # with open('/tmp/tokendownload2.pickle', 'wb') as token: # pickle.dump(creds, token) # Obtains a Google Drive service drive_service = build('drive', 'v3', credentials=creds, cache_discovery=False) print("Defined Google Drive Service") return sheet, drive_service, sign_client
email = str(sys.argv[4]) name = str(sys.argv[5]) filename = str(sys.argv[6]) sourcepath = str(sys.argv[7]) targetpath = str(sys.argv[8]) """ file = open("C://xampp//htdocs//CMS//ajax//samplefile.txt", "a") file.write(str(sys.argv)) file.write(title) file.write(subject) file.write(message) file.write(email) file.write(name) file.write(filename) file.write(sourcepath) file.write(targetpath) """ client = HSClient(api_key='6c8ae769dc48d8feb6f78d369cb52815ab576c6b6c655385e2442e14a13f3bef') client.send_signature_request( test_mode=True, title=title, subject=subject, message=message, signers=[{ 'email_address': email, 'name': name}] , files=[filename] ) os.remove(filename)
from django.conf import settings from hellosign_sdk import HSClient client = HSClient(api_key=settings.HELLO_SIGN_API_KEY) template_id = "0558d2f6c9f02acf7f16422f69582ff72cb810f7"