Docusign integration with rails 4 - ruby-on-rails

I am using the docusign_rest gem for DocuSign REST API, and following are my DocuSign configuration.
# config/initializers/docusign_rest.rb
require 'docusign_rest'
DocusignRest.configure do |config|
config.username = 'myemail#email.com'
config.password = 'MyPassword'
config.integrator_key = 'My-key'
config.account_id = 'account_id'
config.endpoint = 'https://www.docusign.net/restapi'
config.api_version = 'v1'
end
When I try to connect and get account_id, I get nil as a response.
client = DocusignRest::Client.new
puts client.get_account_id # Returns nil.
I am using rails-4.1.4 and ruby-2.2.2
What did I miss? Please suggest.

Not sure if you figured this out or not quite yet. Here is another solution that wasn't too difficult using httparty. If you're trying to create a document for a template for example, your request might look like so:
baseUrl = "https://demo.docusign.net/restapi/v2/accounts/acct_number/envelopes"
#lease = Lease.find(lease.id)
#unit = #lease.unit
#application = #lease.application
#manager = #lease.property_manager
#application.applicants.each do |renter|
req = HTTParty.post(baseUrl,
body: {
"emailSubject": "DocuSign API call - Request Signature - Boom",
"templateId": "id of your template",
"templateRoles": [{
"name": "#{renter.background.legal_name}",
"email": "#{renter.email}",
"recipientId": "1",
"roleName": "Lessee",
"tabs": {
"texttabs": [{
"tablabel": "Rent",
"value": "#{#lease.rent}"
},{
"tablabel": "Address",
"value": "987 apple lane"
}]
}
},{
"email": "#{#manager.email}",
"name": "#{#manager.name}",
"roleName": "Lessor",
"tabs": {
"texttabs": [{
"tablabel": "Any",
"value": "#{#lease.labels}"
},{
"tablabel": "Address",
"value": "987 hoser lane"
}]
}
}],
"status": "sent"
}.to_json,
headers: {
"Content-Type" => "application/json",
'Accept' => 'application/json',
'X-DocuSign-Authentication' => '{
"Username" : "place your",
"Password" : "credentials",
"IntegratorKey" : "here"
}'
}, :debug_output => $stdout )
debug output on the final line is to allow you to debug the api request, it can be removed at any time.

This was a bug in docusign_rest 0.1.1; that method always returned nil. That bug has been fixed and the latest gem version includes that fix.

Related

Selecting distinct values from a JSON -- in ruby

I have a json data like below :
data :[
{
"application_number": 1274930,
"status": "Removed",
},
{
"application_number": 1550670,
"status": "Registered",
},
{
"application_number": 1562368,
"status": "Registered",
},
{
"application_number": 1625492,
"status": "Objected",
},
{
"application_number": 1644092,
"status": "Registered",
},
{
"application_number": 1691808,
"status": "Removed",
},
{
"application_number": 1726161,
"status": "Registered",
}
]
I want to get the unique values of status only. Something like this:
["Removed", "Objected", "Registered"]
I found a similar question and solution there was in javascript :- _.keys(_.countBy(data, function(data) { return data.name; }));
Is there a similar way in ruby to find this ?
you achieve this by following ways:
uniq_status = []
data.each do |tupple|
uniq_status << tupple['status'] if status.include?(tupple['status'])
end
uniq_tupple
#$> ["Removed", "Objected", "Registered"
data.collect{|tupple|tupple["status"]}.uniq
#$> ["Removed", "Objected", "Registered"
data.group_by {|tupple| tupple["status"]}.keys
#$> ["Removed", "Objected", "Registered"
data.uniq {|tupple| tupple["status"]}.collect{|tupple|tupple['status']}
#$> ["Removed", "Objected", "Registered"
I hope this will help you.

Create calendar event using ruby outlook

I am trying create a event in calendar,
Iam able get all the data like calendar,contacts and emails by following below documentaion,
https://learn.microsoft.com/en-us/outlook/rest/ruby-tutorial,
But when try to create a event using ruby_outlook getting below error
{"ruby_outlook_error"=>401,
"ruby_outlook_response"=>{"error"=>{"code"=>"InvalidAudience", "message"=>"The audience claim value is invalid 'aud'.",
"innerError"=>{"requestId"=>"75984820-5241-11ea-b6fc-fc4dd44c1550", "date"=>"2020-02-18T11:26:08"}}}}
Below code is for creating event
def def index
token = get_access_token //getting access token
if token
outlook_client = RubyOutlook::Client.new
event_payload =
{
"Subject": "Discuss the Calendar REST API",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": {
"DateTime": "2020-03-03T18:00:00",
"TimeZone": "Pacific Standard Time"
},
"End": {
"DateTime": "2020-03-03T19:00:00",
"TimeZone": "Pacific Standard Time"
},
"Attendees": [
{
"EmailAddress": {
"Address": "john#example.com",
"Name": "John Doe"
},
"Type": "Required"
}
]
}
outlook_client.create_event(token, event_payload, nil, 'user#domain.com')
end
end
Your issue is that the token that you fetched was using the Microsoft graph API but now you are trying to create an even through the Outlook API. You cannot use a token issued for Graph ("aud": "graph.microsoft.com") against the Outlook endpoint. You need a token with "aud": "outlook.office.com".Better is use the graph API itself using the graph gem to create an event since you already have the token fetched from it.
To do that first create the MicrosoftGraph object
def create_service_auth
access_token = get_access_token
callback = Proc.new do |r|
r.headers['Authorization'] = "Bearer #{access_token}"
r.headers['Content-Type'] = 'application/json'
r.headers['X-AnchorMailbox'] = "#{ email_of_calendar_for_which_to_create_the_event }"
end
#graph = ::MicrosoftGraph.new(base_url: 'https://graph.microsoft.com/v1.0',
cached_metadata_file: File.join(MicrosoftGraph::CACHED_METADATA_DIRECTORY, 'metadata_v1.0.xml'),
&callback)
end
Then create the event -
def create_event
event = {
subject: summary,
body: {
content_type: "HTML",
content: description
},
start: {
date_time: start_time,
time_zone: timezone
},
end: {
date_time: end_time,
time_zone: timezone
},
response_requested: true,
organizer: {emailAddress: { name: "#{organizer.full_name}", address: email_of_calendar_for_which_to_create_the_event }},
attendees: [
{
email_address: {
address: attendee_email,
name: "#{attendee.full_name}"
},
type: "required"
}
]
}
result = #graph.me.events.create(event)
end

proper syntax for generating JSON body in API call

With the following long controller action code
#available = Available.find(694)
#tareservation_id = 8943
#request_date_time = Time.now.utc.iso8601
#request_id = Time.now.to_i
#in_date = (Date.today + 24.days).strftime("%Y-%m-%d").to_s
#book = %Q|{
"booking": {
"currencyCode": "USD",
"languageCode": "es",
"paxNationality": "ES",
"clientRef": {
"value": \"#{#tareservation_id}\",
"mustBeUnique": true
},
"items": [
{
"itemNumber": 1,
"immediateConfirmationRequired": true,
"productCode": \"#{#available.product_code}\",
"leadPaxName":
{ "firstName": "Guy",
"lastName": "Test"
},
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
} ]
},
"requestAuditInfo":
{ "agentCode": "001",
"requestPassword": "pass",
"requestDateTime": \"#{#requestDateTime}\",
"requestID": #{#request_id} },
"versionNumber": "2.0"
}|
This then must be shipped off to the API as JSON in the body call
#result = HTTParty.post(
'https://test.com/search',
:body => JSON.parse(#book).to_json,
headers: {
'Content-Type' => 'application/json',
'Accept' => 'application/json',
'Connection' => 'Keep-Alive'
}
)
If the following block is removed:
,
"product":
{
"period":
{
"start": "2018-08-27",
"quantity": 2
}
}
in console JSON.parse(#start), parses properly. With the block JSON::ParserError: 784: unexpected token. Yet I fail to see what is incorrect here?
Is Rails handling of string for future JSON conversion really strict on syntax, particularly since there is interpretation of instance variables - both as strings and integers - and har returns involved? What would it be then? Or is there a safer solution to get out of what quickly becomes quicksand?
It turns out that pasting too many lines into the console (iTerm2, in this case) does something to the memory. 25 lines of code pasted in a single time is the maximum observered where behaviour is as expected.

QuickBooks API Create Customer POST request FAIL

I would like to create a customer by quickbooks API.
First thing everything is working well with a GET request.
But when I try a POST request I get
Error code="100">General Authentication Error
Here's the Oauth2 token =>
at = OAuth2::AccessToken.new(::QB_OAUTH2_CONSUMER, acces_token)
Here's the new_customer =>
new_customer =
{
"BillAddr": {
"Line1": "10 rue Des Champs",
"City": "Paris",
"Country": "FRANCE",
"CountrySubDivisionCode": "FR",
"PostalCode": "75020"
},
"Notes": "Just a test",
"Title": "Mr",
"GivenName": "John",
"MiddleName": "",
"FamilyName": "Doe",
"Suffix": "",
"FullyQualifiedName": "John Doe",
"CompanyName": "DonwtownLA",
"DisplayName": "DonwtownLA",
"PrimaryPhone": {
"FreeFormNumber": "0123456789"
},
"PrimaryEmailAddr": {
"Address": "johndoe#gmail.com"
}
}
Here's the URL =>
at.post("https://quickbooks.api.intuit.com/v3/company/#{realm_id}/customer")
Anyone can help me for this I cant see what I'm doing wrong.
Thanks in advance.
Ok I got It !
Here's the code for creating user from Quickbooks Controller
def create_qb_customer
data =
{
"Notes": "This is from Darta",
"GivenName": "#{params[:first_name]}",
"FamilyName": "#{params[:last_name]}",
"CompanyName": "#{params[:company]}",
"PrimaryEmailAddr": {
"Address": "#{params[:email]}"
}
}
realm_id = QbToken.last.realm_id
url = URI("https://sandbox-quickbooks.api.intuit.com/v3/company/#{realm_id}/customer/")
http = Net::HTTP.new(url.host, url.port)
http.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Content-Type"] = 'application/json'
request["Authorization"] = "Bearer #{QbToken.last.serial}"
request["Cache-Control"] = 'no-cache'
request["Postman-Token"] = 'XXXXXX-cf4c-XXXXX-8d7c-XXXXXXXXX'
request.body = data.to_json
response = http.request(request)
p response.read_body
flash.notice = "Your QuickBooks customer is successfully created !"
redirect_to list_all_project_path
end
Please try the call using Postman. The following blog post should be helpful.
https://developer.intuit.com/hub/blog/2017/08/03/quick-start-quickbooks-online-rest-api-oauth-2-0
Please check if you are passing the content-type as 'application/json'.

Successful consumption of a Azure Machine Learning API?

Does anyone have good documentation of a successful implementation of the Azure ML studio API in a web app that's not ASP.net? I'd like to run on it with ruby on rails, but I guess I have to figure it out on my own.
It is simply a rest API call. Look at this...
data = {
"Inputs": {
"input1":
{
"ColumnNames": ["YearBuild", "City", "State", "HomeType", "TaxAssesmentYear", "LotSize", "HomeSize", "NumBedrooms"],
"Values": [ [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], [ "0", "Anchorage", "AK ", "Apartment", "0", "0", "0", "0" ], ]
}, },
"GlobalParameters": {
}
}
body = str.encode(json.dumps(data))
url = 'https://ussouthcentral.services.azureml.net/workspaces/45aeb4d8283d4be6ae211592f5366af5/services/07ffeeb6fcb84f16bc62cdcf67fd95b3/execute?api-version=2.0&details=true'
api_key = 'abc123' # Replace this with the API key for the web service
headers = {'Content-Type':'application/json', 'Authorization':('Bearer '+ api_key)}
req = urllib2.Request(url, body, headers)
Give a shot at trying with the postman app in chrome first. Setting your headers, just as above, your data goes in the post payload in the json format.
Here you'll find Ruby code (not python)
data = {
'Inputs' => {
'input1' => [
{
'weekday' => 1,
'hour' => 2,
'events' => 0
}
]
},
'GlobalParameters' => {}
}
body = data.to_json
url = 'https://asiasoutheast.services.azureml.net/subscriptions/[tour stuff...]execute?api-version=2.0&format=swagger'
api_key = '[your api key]'
headers = {'Content-Type': 'application/json', 'Authorization': ('Bearer '+ api_key)}
RestClient::Request.execute(method: :post, url: url, payload: body, headers: headers)

Resources