Send Salesforce Attachment with Docusign - salesforce

I'm trying to use DocuSign API in Salesforce (apex code) to send an envelope with the document.
It is working when using templateid that was setup in my DocuSign sandbox, but I want to use Salesforce attachment that related to the record, and I'm getting an exception
dfsle.DocuSignException: Unable to read content for documents: Disti1234B.pdf (001f400000za2c9AAA).
Any idea why I'm getting it?
Note that I tried using in SF both Attachment and File, but got the same error in both.
Trace:
FATAL_ERROR Class.dfsle.EnvelopeAPI: line 1027, column 1
Class.dfsle.EnvelopeAPI.APIEnvelope.<init>: line 1065, column 1
Class.dfsle.EnvelopeAPI.createEnvelope: line 1155, column 1
Class.dfsle.EnvelopeAPI.createEnvelope: line 1144, column 1
Class.dfsle.EnvelopeService.sendEnvelope: line 641, column 1
Class.dfsle.EnvelopeService.sendEnvelope: line 607, column 1
Code script:
Id accountId = '001f400000za2c9'; // The ID of the initiating Salesforce object.
// Create an empty envelope.
dfsle.Envelope myEnvelope = dfsle.EnvelopeService.getEmptyEnvelope(new dfsle.Entity(accountId));
//we will use a Salesforce contact record as a Recipient here
Contact myContact = [SELECT Id, Name, Email FROM Contact where Id = '003f400001Gk49f'];
//use the Recipient.fromSource method to create the Recipient
dfsle.Recipient myRecipient = dfsle.Recipient.fromSource(
myContact.Name, // Recipient name
myContact.Email, // Recipient email
null, //Optional phone number
'Signer 1', //Role Name. Specify the exact role name from template
new dfsle.Entity(myContact.Id)); //source object for the Recipient
//add Recipient to the Envelope
myEnvelope = myEnvelope.withRecipients(new List<dfsle.Recipient> { myRecipient });
/*WITH TEMPLATE ID IT IS WORKING FINE
//myTemplateId contains the DocuSign Id of the DocuSign Template
dfsle.UUID myTemplateId = dfsle.UUID.parse('f4252788-0799-4786-bac4-7c6a3f1d37a8');
//create a new document for the Envelope
dfsle.Document myDocument = dfsle.Document.fromTemplate(
myTemplateId, // templateId in dfsle.UUID format
'myTemplate'); // name of the template
*/
Attachment att = [SELECT Id, Name, Body, ContentType,LastModifiedDate,BodyLength FROM Attachment WHERE Id = '00Pf400000KPKBh'];
dfsle.Document myDocument = new dfsle.Document(att.Id, 'File', 1, att.Name, 'pdf', att.BodyLength, att.LastModifiedDate, accountId);
//add document to the Envelope
myEnvelope = myEnvelope.withDocuments(new List<dfsle.Document> { myDocument });
myEnvelope = dfsle.EnvelopeService.sendEnvelope(myEnvelope, true);

Still not sure why it is happened, but I was able to get it work by using the following method:
list<dfsle.Document> l_doc = dfsle.DocumentService.getDocuments(ContentVersion.getSObjectType(), new set<Id>{'068f400000EFNuaAAH'});
Note that according to docusign documentation it is working only with documents (File in salesforce), it is not working with Salesforce Attachment

Related

How to generate DocuSign embedded signing url from apex?

I want to generate the DocuSign embedded URL to get the documents signed by the community user.
I am able to achieve the requirement. Here is the solution
Initial things
DocuSign setup from both sides (Salesforce and DocuSign itself).
Signing user must be assigned “DocuSign Sender” permission set to sign the
document(s).
Create and send an envelope – First method
public static String sendEnvelope(String recordId) {
Id mySourceId = recordId; // The ID of the initiating Salesforce object
// Create an empty envelope and add a Salesforce Document and embedded signer
recipient
// The embedded signer will be the current user with sequence and routing
order 1 and role "Signer 1" by default
List<dfsle.Document> myDocuments = new List<dfsle.Document>();
// Content Version need to be param or queried
myDocuments =
dfsle.DocumentService.getDocuments(ContentVersion.getSObjectType(),
new Set<Id> { ContentVersionId(s) });
dfsle.Envelope dsEnvelope = dfsle.EnvelopeService.getEmptyEnvelope(
new dfsle.Entity(mySourceId))//The initiating Salesforce entity current SF user
.withDocuments(myDocuments)
.withRecipients(new List<dfsle.Recipient> {
dfsle.Recipient.newEmbeddedSigner() // An embedded signer
}
);
// Send the envelope.
dsEnvelope = dfsle.EnvelopeService.sendEnvelope(
dsEnvelope, // The envelope to send
true // Send now?
);
// Return string value of DocuSign envelope ID
return String.valueOf(dsEnvelope.docuSignId);
}
Host an embedded signing session – second method
// passing envId as parameter that we will receive from above method
public static String getEmbeddedSigningUrl(String envId) {
// url will be redirect URL
Url mySigningUrl = dfsle.SigningService.getEmbeddedSigningUrl(
dfsle.UUID.parse(envId), // envId value as a UUID
new URL(url) // url value as a URL
);
// Return string value of url to controller
return mySigningUrl.toExternalForm();
}
Variable Source id – It is the parent object record id where we want to store the signed documents back into salesforce.
Set of content version ids which are stored as files with s1,d1 tags etc.
myDocuments =
dfsle.DocumentService.getDocuments(ContentVersion.getSObjectType(),
new Set<Id> { ContentVersionId(s) });
Redirect URL - After signing the document(s) where we want to redirect the user.
In the case of using DocuSign in the context of Community user
Note: In the DocuSign Setup tab choose Configuration in the left menu, then go to the Settings tab and choose a user next to Enable System sender. This allows Community users to send envelopes even if they are not a member of the DocuSign account. In that case, envelopes will be sent from the admin user that you selected.
Important Points to remember
Embedded URL is valid only for 5 mins by default, if we want to increase the time
we will have to talk to the DocuSign support team and it can be increased max up
to 15 mins depending on the service plan.
References
https://developers.docusign.com/docs/salesforce/how-to/embedded-sending-signing/

Salesforce DocuSign Integration

Use Case - Salesforce Docusign implementation:
We have Parent and child object in salesforce where Parent have authorize signer and Relationship Manger email information and their each child object have document which we need to sign by authorize signer and relationship manger.
We need to send all the child object documents in single envelope. And when the signing ceremony completed we need to attach respective signed documents to their respective child records.
Currently, we can planning to do through Apex Toolkit or DocuSign rest API.
Example: Authorized signer and RM present on account record. And each contact associated with account having document which are attached by Contact person. Account owner should have button where it should fetch all the document from related contact, create envelope, should tagging the signature on each document and able to send to authorized Signer and RM.
Authorized Signer should received all the document with in single envelope. They signed all the document. Once Signed by them all the signed document should go back to respective contact.
Note: Business wants to see all the Recipients status and document sent to end user in salesforce as well.
Can you please provide input on this and share some sample as per our use case?
The flow here would be to pull the documents with DocumentService.getLinkedDocuments and then set up anchor tabs. If you want to send multiple documents, you'll need to set the Anchor Population Scope to Document. If docs are numbered in the order of the list 1, 2, 3. You will use .withOptions for the writeBack. Example can be found here:
https://www.docusign.com/blog/developers/whats-new-summer-21-apex-toolkit
And a sample code (except for the writeback part):
//Find your contact to add
Contact myContact = [SELECT Id, Name, Email FROM Contact WHERE Name = 'Snow Beard' LIMIT 1];
//This sets tab as an anchor tab. If using this with multiple documents,
// Ask customer support to set Account Setting Anchor Population Scope to Document.
dfsle.Tab hereTab = new dfsle.SignHereTab()
.withScale(1) // 1/2 scale
.withRequired(true) // Signing mandatory
.withDataLabel('SignHereMeHardy')
.withAnchor(
new dfsle.Tab.Anchor(
'Anchor1', // Anchor string
true, // allow white space in anchor string
true, // Anchor string is not case sensitive
'right', // Horizontal alignment in relation to the anchor text
true, // Ignore if the anchor text is not present in the document
true, // Must match the value of the anchor string in its entirety
'pixels', // Unit of the x and y offset properties
10, // X offset
10 // Y offset
)
)
//This places the tab on the first docunent in the list on page one. Requires DocuSign Support to set Anchor Population Scope to Document.
.withPosition(
new dfsle.Tab.Position(
1, //Document id matches order of documents
1, //Page id
null,
null,
20,
20
)
);
//use the Recipient.fromSource method to create the Recipient
dfsle.Recipient myRecipient = dfsle.Recipient.fromSource
(
myContact.Name, // Recipient name
myContact.Email, // Recipient email
null, //Optional phone number
'Signer 1', //Role Name. Specify the exact role name from template if using a template or use Default 'Signer 1'
new dfsle.Entity(myContact.Id) //source object for the Recipient
)
.withTabs(new List<dfsle.Tab> { // Associate the tabs with this recipient
hereTab
});
Opportunity myOpportunity = [SELECT Id FROM Opportunity WHERE Name = 'Sailcloth' LIMIT 1];
//This pulls all the documents from the Opportunity Object and adds them to documents list
List<dfsle.Document> documents = dfsle.DocumentService.getLinkedDocuments
(
ContentVersion.getSObjectType(),
new Set<Id>{myOpportunity.Id},
false
);
// Create an empty envelope.
// This shows how to pull documents from an object in Salesforce. In this case an Opportunity
dfsle.Envelope myEnvelope = dfsle.EnvelopeService.getEmptyEnvelope(new dfsle.Entity(myOpportunity.Id))
.withRecipients(new List<dfsle.Recipient> { myRecipient })
.withDocuments(documents);
// Send the envelope
try {
dfsle.EnvelopeService.sendEnvelope(myEnvelope, true);
} catch (dfsle.APIException ex) {
system.debug(ex);
if (ex.error.code == dfsle.APIErrorCode.CONSENT_REQUIRED) {
// user is a valid member of the DocuSign account, but has not granted consent to this application
} else {
// handle other errors
}
}

Integration Salesforce with Docusign Invalid type: dfsle.Envelope

I'm trying to integrate the Salesforce with DocuSign with Docusign Apex Toolkit, but dfsle class is not available in my org. I installed the Apex Tool Kit (https://developers.docusign.com/docs/salesforce/how-to/apex-toolkit-install/)
Id MySourceId = '00Q0m00000884XXXXX';
dfsle.Envelope myEnvelope = dfsle.EnvelopeService.getEmptyEnvelope(new dfsle.Entity(mySourceId));
Lead myContact = [SELECT Id, Name, Email FROM lead where id = '00Q0m00000884XXXX'];
//use the Recipient.fromSource method to create the Recipient
dfsle.Recipient myRecipient = dfsle.Recipient.fromSource(
myContact.Name, // Recipient name
myContact.Email, // Recipient email
null, //Optional phone number
'Signer 1', //Role Name. Specify the exact role name from template
new dfsle.Entity(myContact.Id)); //source object for the Recipient
dfsle.UUID myTemplateId = dfsle.UUID.parse('28386dbc-2576-4637-bb77-c86938fe080f');
//create a new document for the Envelope
dfsle.Document myDocument = dfsle.Document.fromTemplate(
myTemplateId, // templateId in dfsle.UUID format
'Self Sales Teste'); // name of the template
// Send the envelope.
myEnvelope = dfsle.EnvelopeService.sendEnvelope(
myEnvelope, // The envelope to send
true); // Send now?
try {
dfsle.EnvelopeService.sendEnvelope(envelope, true);
} catch (dfsle.APIException ex) {
if (ex.error.code == dfsle.APIErrorCode.CONSENT_REQUIRED) {
// user is a valid member of the DocuSign account, but has not granted consent to this application
} else {
// handle other errors
}
}
Error: Line: 3, Column: 1
Error: Invalid type: dfsle.Envelope
Have same issue few weeks ago :) Go to your Salesforce Setup. Type Installed Packages in quick find box. Make sure the DocuSign App Launcher is installed. Check package prefix.

Gmail (for business) API doesn't allow to send email from Alias?

I want to email my customers using different "roles" (e.g. info# , customer-support#, tech-support#, no-reply#).
I've tried 2 approaches:
Multiple "users"/accounts in my Gmail for business application.
Single gmail
account with multiple aliases.
I started by setting up a Service Account with global delegation for my Gmail for Business application.
To test that it works, I've set up 2 users: lev#mydomain.com and root#mydomain.com. Indeed, I can successfully send email both from lev# and root#.
However, when I tried adding 5 distinct user accounts for my application, Gmail got paranoid of bots/abuse and asked me to prove that all the accounts are "human" including setting up passwords, signing in and SMS-text validation via phone. Moreover, they require different phones for different accounts to prove it's a different person. So the setup of the accounts becomes a major issue.
I also want to avoid creating multiple accounts since I'm paying for each one, and since semantically, all the roles are just a single account. So aliases seem like a better idea.
The problem is that when I'm trying to send email and set the "from" field to the alias (e.g. from:no-reply#mydomain.com), I'm getting the following exception:
Exception in thread "main" com.google.api.client.googleapis.json.GoogleJsonResponseException: 403 Forbidden
{
"code" : 403,
"errors" : [ {
"domain" : "global",
"message" : "Delegation denied for root#mydomain.com",
"reason" : "forbidden"
} ],
"message" : "Delegation denied for root#mydomain.com"
}
Anyone faced and solved this issue?
The authentication/credential code is as follows:
/*
* Set up a hashmap HashMap<String, Gmail> gmailServiceByAccount where
* gmailServiceByAccount.get(emailAccount) contains an authorized Gmail service
*/
private void prepareService(String emailAccount) throws Exception {
if (gmailServiceByAccount.containsKey(emailAccount)) {
return;
}
HttpTransport httpTransport = GoogleNetHttpTransport.newTrustedTransport();
JsonFactory jsonFactory = JacksonFactory.getDefaultInstance();
GoogleCredential credential = new GoogleCredential.Builder()
.setTransport(httpTransport)
.setJsonFactory(jsonFactory)
.setServiceAccountId(Config.getInstance().getProperty(Config.gmail_service_account))
.setServiceAccountPrivateKeyFromP12File(new File(Config.getInstance().getPathToGmailCredential()))
.setServiceAccountScopes(Arrays.asList(GmailScopes.GMAIL_COMPOSE))
.setServiceAccountUser(emailAccount)
.build();
gmailServiceByAccount.put(
emailAccount,
new Gmail.Builder(httpTransport, jsonFactory, credential)
.setApplicationName(Config.getInstance().getProperty(Config.google_client_api_application_name))
.build());
}
And the code which sends the email is as follows:
/**
* Send an email using the parameters provided.
*
* #param fromPersonalName : the free text description of the "from" address (e.g. "Customer Suppport" or "No Reply").
* #param fromAddress : the email address of the sender, the mailbox account (e.g. customer-support#mydomain.com).
* #param to : the email address of the recepient.
* #param subject : Subject of the email.
* #param htmlContent : (may be null) The HTML-styled body text of the email.
* #param plainTextContent : (may be null) The plain text body of the email (e.g if the customer email client does not support or disables html email).
*/
public void sendMail(String fromPersonalName, String fromAddress, String to, String subject, String htmlContent, String plainTextContent)
throws Exception {
prepareService(fromAddress);
Properties props = new Properties();
Session session = Session.getDefaultInstance(props, null);
MimeMessage email = new MimeMessage(session);
InternetAddress tAddress = new InternetAddress(to);
InternetAddress fAddress = new InternetAddress(fromAddress);
fAddress.setPersonal(fromPersonalName);
email.setFrom(fAddress);
email.addRecipient(javax.mail.Message.RecipientType.TO, tAddress);
email.setSubject(subject);
Multipart multiPart = new MimeMultipart("alternative");
if (!StringValidation.isEmpty(plainTextContent)) {
MimeBodyPart textPart = new MimeBodyPart();
textPart.setContent(plainTextContent, "text/plain");
textPart.setHeader("Content-Type", "text/plain; charset=\"UTF-8\"");
multiPart.addBodyPart(textPart);
}
if (!StringValidation.isEmpty(htmlContent)) {
MimeBodyPart htmlPart = new MimeBodyPart();
htmlPart.setContent(htmlContent, "text/html; charset=\"UTF-8\"");
multiPart.addBodyPart(htmlPart);
}
email.setContent(multiPart);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
email.writeTo(bytes);
String encodedEmail = Base64.encodeBase64URLSafeString(bytes.toByteArray());
Message message = new Message();
message.setRaw(encodedEmail);
gmailServiceByAccount.get(fromAddress).users().messages().send(fromAddress, message).execute();
}
After additional research, it looks like the only option is to have multiple users.
The code I've posted indeed works for multiple users, but not for anything else.
I've tried multiple options including aliases and group email accounts. I'd either get "delegation denied" or "invalid grant" errors.
I've tried contacting Google For Business customer and tech support, but they don't support the API.
There's a great workaround to creating several users without having to go through phone validation. Just specify these users as "existing users" when you're signing into Google For Business initially, and activate them before you even transfer the domain.
For the account I've created without pre-existing users, I had to ask my friend's phones for phone validation.
You can now send emails using aliases as long as those aliases are defined for the user whose login credentials you're using.
This works for the Gmail for business only.
Setting up aliases to non-existent address can be tricky, so have a look at this how to set up a catch-all routing:
catchall-for-domain-aliases-in-gsuite-gmail
Just additionally to Ladi's post, it seem to be easier to setup now. Make an alias account and configure it so you can send emails (https://support.google.com/domains/answer/9437157?hl=en&ref_topic=6293345) and set the 'from' field on the message to the alias (but still use 'me' on the API call)

How to get downloadable link for attachment?

I uploaded jpeg image for an account. The jpeg image file id is 069i0000001dkl8 and it can't access via,
https://c.na15.content.force.com/servlet/servlet.FileDownload?file=069i0000001dkl8
But it can acces via,
https://c.na15.content.force.com/sfc/servlet.shepherd/version/download/068i0000001hwPn?asPdf=false&operationContext=CHATTER
Is there a way that I can get downloadable URL for attachment in salesforce (using api calls)?
Or Is there a way that I can build downloadable URL by processing some fields in API object (SObject)?
Thanks.
In winter 15 Salesforce made this possible. You can create a class that converts an attachment to ContentVersion and ContentDistribution. Then pass the user the DistributionPublicUrl field of ContentDistribution.
Code will be something like this
list<Attachment> invoices = [select id, name, body from attachment limit 10];
list<ContentVersion> contents = new list<ContentVersion>();
list<ContentDistribution> dists = new list<ContentDistribution>();
for(Attachment inv: invoices){
ContentVersion cont = new ContentVersion();
cont.Title = inv.Name;
cont.PathOnClient = inv.Name;
cont.VersionData = inv.Body;
contents.add(cont);
}
insert contents;
for(ContentVersion cont : contents){
ContentDistribution cd = new ContentDistribution();
cd.name = cont.Title;
cd.ContentVersionId = cont.id;
cd.PreferencesAllowOriginalDownload = true;
cd.PreferencesAllowPDFDownload = true;
cd.PreferencesAllowViewInBrowser = true;
dists.add(cd);
}
insert dists ;
Technically speaking, you are dealing with ContentDocument (069 key prefix) and ContentVersion (068 key prefix) records rather than an Attachment (00P key prefix).
Have a look at the Data Model for Content Objects:
You can use SOQL to create a query that will get you the correct ContentVersion for a ContentDocument. The resulting ID can then be used to create the download URL.
Alternatively, you could get the binary contents of the attachment from the ContentVersion directly via the API.
Incidentally, the Salesforce Stackexchange site is a great place to ask Salesforce specific questions.

Resources