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'.
Related
I am struggling creating an order with Orders v2 PayPal API.
I have the token, and I do a request with these headers to create the order:
{
"intent": "CAPTURE",
"purchase_units": [{
"description": "Payment",
"amount": {
"value": 'X',
"currency_code": "EUR",
"breakdown": {
"item_total": {
"currency_code": "EUR",
"value": 'X'
},
}
},
"items": [{
"unit_amount": {
"currency_code": "EUR",
"value": 'X'
},
"quantity": "1",
"name": 'item name',
}]
}],
"application_context": {
"brand_name": "My brand name",
"locale": "it-IT",
"return_url": 'my-return-url',
}
}
The order is created and I get the approveurl to let the user to pay.
With the approveurl I do this call:
try {
var response = await http.post(approveurl, body: jsonEncode({"payer_id": payerId}), headers: {
"content-type": "application/json",
'Authorization': 'Bearer ' + accessToken
});
final body = jsonDecode(response.body);
if (response.statusCode == 200) {
return body;
}
return null;
} catch (e) {
rethrow;
}
But I get this reponse:
url = "https://www.sandbox.paypal.com/checkoutnow?token=..."
payerId = "..."
accessToken = "..."
response = {Response}
request = {Request} POST https://www.sandbox.paypal.com/checkoutnow?token=...
statusCode = 302
reasonPhrase = "Found"
contentLength = 61
headers = {_InternalLinkedHashMap} size = 9
0 = {map entry} "paypal-debug-id" -> "95934918777a1"
1 = {map entry} "cache-control" -> "max-age=0, no-cache, no-store, must-revalidate"
2 = {map entry} "location" -> "/webapps/hermes?token=..."
3 = {map entry} "set-cookie" -> "X-PP-SILOVER=name%3DSANDBOX3.WEB.1%26silo_version%3D880%26app%3Dhermesnodeweb%26TIME%3D1595167415%26..."
4 = {map entry} "date" -> "Sun, 19 Jul 2020 14:03:35 GMT"
5 = {map entry} "vary" -> "Accept"
6 = {map entry} "strict-transport-security" -> "max-age=63072000"
7 = {map entry} "content-length" -> "61"
8 = {map entry} "content-type" -> "text/plain; charset=utf-8"
isRedirect = false
persistentConnection = true
And the response.body is:
Found. Redirecting to /webapps/hermes?token=...
With the approvalurl I do this call:
The approval URL is not for you to call. It's a web URL, not an API URL. It's for the paying customer to log in and give their approval of the payment.
However, redirecting them to it would be a bad web experience. For modern web design, you should instead offer an "in context" approval, where your site remains loaded in the background. Here's how to do that: https://developer.paypal.com/demo/checkout/#/pattern/server
With this integration you don't read the approval_url yourself, simply return the Order id when fetched from createOrder.
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
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.
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.
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)