Can't create class object in quickbooks using quickbooks ruby gem - ruby

I would like to create Account object for Quickbooks. However, when I try:
service.create(account_object)
It returns the error:
Quickbooks::InvalidModelException: Classification is not included in the list
I tried putting in one of the default values(https://developer.intuit.com/docs/0025_quickbooksapi/0050_data_services/030_entity_services_reference/account), but it returns the same error..

Classification in account will be something like Liability, Revenue, Expense or Asset etc.
Go to this URL https://developer.intuit.com/docs/api/accounting/Account
look at AccountType section => Child attributes
It have all list of classification and account type that we can use while creating accounts
You can use below sample code to create account
begin
oauth_client = OAuth::AccessToken.new($qb_oauth_consumer, token, secret)
service = Quickbooks::Service::Account.new(:access_token => oauth_client, :company_id => realm_id)
new_account = Quickbooks::Model::Account.new(:name => 'Undeposited money', :account_type => 'Other Current Asset', :classification => 'Asset' )
create_acccount = service.create(new_account)
rescue Exception => e
# e.message will show response of quickbooks for you request
puts e.message
# e.message.inspect will show logs
puts e.backtrace.inspect
end

Related

How can I retrieve a full list of companies (advertisers) from the Google Ad Manager API?

I'm building a rails 5 API that interacts with Google Ad Manager API and I need a way to retrieve the list of companies (also called advertisers) so I can use them in order to create new orders and eventually, line items.
I haven't been able to find this in the Ad Manager documentation, not for ruby and not for other languages either.
I don't have any code yet since I don't know what service to use.
I'd expect an array of advertisers: [{:name => 'Company 1', :id => '1234'}, {:name => 'Company 2', :id => '4321'}]
Any help would be really appreciated. I haven't been able to find this in the Ad Manager documentation, not for ruby and not for other languages either.
Thanks in advance!
I have found the answer. I was wrong, it is part of the Ruby examples:
def get_advertisers(ad_manager)
company_service = ad_manager.service(:CompanyService, API_VERSION)
# Create a statement to select companies.
statement = ad_manager.new_statement_builder do |sb|
sb.where = 'type = :type'
sb.with_bind_variable('type', 'ADVERTISER')
end
# Retrieve a small amount of companies at a time, paging
# through until all companies have been retrieved.
page = {:total_result_set_size => 0}
begin
# Get the companies by statement.
page = company_service.get_companies_by_statement(
statement.to_statement()
)
# Print out some information for each company.
unless page[:results].nil?
page[:results].each_with_index do |company, index|
puts '%d) Company with ID %d, name "%s", and type "%s" was found.' %
[index + statement.offset, company[:id], company[:name],
company[:type]]
end
end
# Increase the statement offset by the page size to get the next page.
statement.offset += statement.limit
end while statement.offset < page[:total_result_set_size]
puts 'Total number of companies: %d' % page[:total_result_set_size]
end

Google Adwords API error: invalid grant

I'm receiving this error trying to authenticate with the Adwords API using a service account and JWT with the Ruby API library.
I am copying the example provided, but it just doesn't seem to work.
/home/michael/.rvm/gems/ruby-2.1.2/gems/signet-0.5.1/lib/signet/oauth_2/client.rb:941:in `fetch_access_token': Authorization failed. Server message: (Signet::AuthorizationError)
{
"error" : "invalid_grant"
}
adwords_api.yml
---
# This is an example configuration file for the AdWords API client library.
# Please fill in the required fields, and copy it over to your home directory.
:authentication:
# Authentication method, methods currently supported: OAUTH2, OAUTH2_JWT.
:method: OAUTH2_JWT
# Auth parameters for OAUTH2_JWT method. See:
# https://developers.google.com/accounts/docs/OAuth2ServiceAccount
:oauth2_issuer: 43242...apps.googleusercontent.com
:oauth2_secret: 'notasecret'
# You can provide path to a file with 'oauth2_keyfile' or the key itself with
# 'oauth2_key' option.
:oauth2_keyfile: /home/.../google-api-key.p12
# To impersonate a user set prn to an email address.
:oauth2_prn: my#email.com
# Other parameters.
:developer_token: ua...w
:client_customer_id: 123-123-1234
:user_agent: test-agent
:service:
# Only production environment is available now, see: http://goo.gl/Plu3o
:environment: PRODUCTION
:connection:
# Enable to request all responses to be compressed.
:enable_gzip: false
# If your proxy connection requires authentication, make sure to include it in
# the URL, e.g.: http://user:password#proxy_hostname:8080
# :proxy: INSERT_PROXY_HERE
:library:
:log_level: INFO
test.rb
#!/usr/bin/env ruby
require 'adwords_api'
def use_oauth2_jwt()
adwords = AdwordsApi::Api.new
adwords.authorize()
campaign_srv = adwords.service(:CampaignService, API_VERSION)
selector = {
:fields => ['Id', 'Name', 'Status'],
:ordering => [
{:field => 'Name', :sort_order => 'ASCENDING'}
]
}
response = campaign_srv.get(selector)
if response and response[:entries]
campaigns = response[:entries]
campaigns.each do |campaign|
puts "Campaign ID %d, name '%s' and status '%s'" %
[campaign[:id], campaign[:name], campaign[:status]]
end
else
puts 'No campaigns were found.'
end
end
if __FILE__ == $0
API_VERSION = :v201409
begin
use_oauth2_jwt()
# HTTP errors.
rescue AdsCommon::Errors::HttpError => e
puts "HTTP Error: %s" % e
# API errors.
rescue AdwordsApi::Errors::ApiException => e
puts "Message: %s" % e.message
puts 'Errors:'
e.errors.each_with_index do |error, index|
puts "\tError [%d]:" % (index + 1)
error.each do |field, value|
puts "\t\t%s: %s" % [field, value]
end
end
end
end
This is going to be difficult to answer definitively as it's authorisation based so the error message is a glorified "not authorised" message.
All I can really do is suggest a few things to check (acknowledging you've probably went through these already):
Your developer token is definately showing as 'Approved'? (you can check this in the client centre - through the setting cog then account then adwords api centre)
You have registered an application through Google Developer Console
You (or the owner of the account you are trying to access) have authorised your application - probably by following this guide and definately seeing one of these things at somepoint:
If you have checked all of these then the only other thing I can suggest is a post to the official forum where they tend to be helpful and often take authorisation issues 'offline' to have a look at the actual soap requests etc. (I have found this much quicker and easier than trying to wade through the levels of AdWords 'support')
Good luck!
After several more hours of fiddling, I finally got it working by setting the oauth2_prn to the primary email on the MCC and Google Apps for Business account.

Mandrill - No message exists with id

I'm having an issue using the mandrill API for ruby and i'm not sure if it's a lack of ruby/api understanding on my part of if there's an issue with the mandrill api.
I have this method which sends an email with mandrill, and then I make another api call using the id returned from mandrill.messages.send to make another call to mandrill to get the email header message-id so i can store that in a db table.
Why am I getting the error Mandrill::UnknownMessageError (No message exists with the id '64fba1cce24942dea1ada4f905fd7871'): when the id clearly exists as seen in the comments for the logging events?
# Sends an email to all users for the account_id on the issue
def send_email
require 'mandrill'
...
mandrill = Mandrill::API.new Mandrill::API_KEY
# Email contents
message = {
:subject => self.name,
:from_name => self.account.subdomain,
:text => self.description,
:to => [{
:email => user.email,
:name => user.name
}],
:text => self.description,
:from_email => "noreply#myapp.com",
:headers => {
'reply-to' => 'update#myapp.com'
}
}
results = mandrill.messages.send message # Send email through mandrill
# Loop through results of sent email
results.each do |result|
logger.debug "result id = #{result['_id']}" # LOGS result id = 64fba1cce24942dea1ada4f905fd7871
logger.debug "result = #{result}" # LOGS result = {"email"=>"tomcaflisch#gmail.com", "status"=>"sent", "_id"=>"64fba1cce24942dea1ada4f905fd7871", "reject_reason"=>nil}
id = result['_id'] # Mandrill's internal id from api call results that sent the email
# CAUSES Mandrill::UnknownMessageError (No message exists with the id '64fba1cce24942dea1ada4f905fd7871'):
info = mandrill.messages.content id # Get info for sent email with a specific mandrill id
end
end
I think you just have to give it a little bit of time.
I am facing the same error on messages.info(id).
However, search('*') is finding all messages sent but not providing correct status information.
I think the following snippet of gem code is getting 500 status (instead of 200) when messages.info(id) is called:
def call(url, params={})
params[:key] = #apikey
params = JSON.generate(params)
r = #session.post(:path => "#{#path}#{url}.json", :headers => {'Content-Type' => 'application/json'}, :body => params)
cast_error(r.body) if r.status != 200
return JSON.parse(r.body)
end
Also, gem code is hosted on bitbucket instead of more common github. Not sure how to raise an issue there for support.
Sorry can't be of much help but thought I should share my experience also to get more visibility for the problem.

Rho Mobile: Parse and create a model using JSON

I am able to parse a JSON using the following code
$httpresult = #params['body']
$jsonresult = Rho::JSON.parse($httpresult)
But I don't know how to create a model from $jsonresult.
First, using app_info you can print the result coming from the server to check if the response is valid JSON string.
Second, i think you must decode the url in order to parse it by using:
Rho::JSON.parse(Rho::RhoSupport.url_decode(#params['body']))
Once you've the data in json_result, you can put them in a pre-existing Model.
Supposing that you've already created a model with the name "Product", you can use transactions to speed up the process.
At the beginning of your module you've to require the model name:
require_source 'Product'
Then you can do this callback:
def get_callback
if #params['status'] == "ok"
json_result = Rho::JSON.parse(#params['body'])
db = ::Rho::RHO.get_src_db('Product')
db.start_transaction
Product.delete_all
begin
json_result.each do |item|
Product.create({:Brand => item["B rand"], :Name => item["Name"], :SKU => d["SKU"]})
end
db.commit
rescue Exception => e
trace_msg = e.backtrace.join("\n")
puts 'Application initialize failed: ' + e.inspect + ";Trace: #{trace_msg}"
db.rollback
end
WebView.navigate Rho::RhoConfig.start_path
else
WebView.navigate url_for :action => :show_error
end
end

undefined method error on local server where method works on live server-Why is the new code breaking it?

I'm trying to integrate our app with MailChimp, so that new users get added to our mailing list and new paid subscribers get updated on the mailing list as paid subscribers (we have a MERGE VARS for that). In order to test that the list is updating properly when the customer pays for a subscription, I'm trying to run the code with the test server for Stripe. (I inherited the code after we had tested it, so I haven't done this before.)
I'm running into an undefined method error, and I can't figure out where it's coming from, since it is working just fine on the live site, and I haven't changed that part of the code.
in the initializer file stripe.rb, I changed Stripe.api_key
="the live secret key" to the test secret key, just subbing in the other key.
I did the same in our layout/application.html.erb file (where we put the initial call to Stripe per Stripe's instructions), swapping out the public live key for the public test key.
In the account_controller processing method (which is called for payment processing on the Stripe token and updating our server with the type of subscription.):
def processing
begin
if params[:coupon][0] != "_"
#coupon = params[:coupon]
else
#coupon = nil
end
customer = Stripe::Customer.create(
:email => current_user.email,
:card => params[:stripeToken],
:plan => params[:plan],
:coupon => #coupon
)
current_user.subscription = params[:plan]
current_user.stripe_id = customer.id
current_user.canceled = false
current_user.save!
rescue Stripe::CardError => e
flash[:error] = e.message
end
#only this code is new, from here:
#for gibbon updating subscription status
gb=Gibbon::API.new
email=current_user.email
subscription=user.subscription
updated_date=user.updated_at.strftime('%B %d, %Y')
gb.lists.subscribe({:id => "our list id", :email => {:email => "#{email}"}, :merge_vars => {:SUB => "test", :UPDATE => "#{updated_date}"}, :update_existing=>true , :double_optin => false, :send_welcome=> false})
#to here is new code
current_user
respond_to do |format|
format.html { redirect_to account_confirmation_path }
end
end
I'm getting a "NoMethodError in AccountController#processing
undefined method 'canceled=' for #User:an-id-here" (note the #User: an id here is in pointy brackets, but those aren't showing up here.)
error. This code works on the live site, so that makes me think it must be something I've done here. Canceled is a column on our User model, which is a boolean indicating whether they've canceled. It is not set as attr_accesible or attr_accessor, but as I said, that code hasn't changed and works on the live site.
I'm not sure what the problem is and I feel like I don't have enough information to start figuring it out. The server is only recording the same error message as shows up in the browser. (Oh, and I'm running the test code only on my local server, not the live server).
What might be causing the undefined method error? I'm not seeing anything in the code I changed that should do it.

Resources