Testing Adwords Api with Service Account - ruby-on-rails

I am using https://github.com/googleads/google-api-ads-ruby/ gem for using adwords api for OfflineConversionFeedService.
Code looks alright:
module AdwordsHelper
def mark_conversion_in_ads(customer)
begin
config_filename = File.join(Rails.root, 'config', 'adwords_api.yml')
adwords = AdwordsApi::Api.new(config_filename)
conversion_feed_srv =
adwords.service(:OfflineConversionFeedService, :v201702)
conversion_time = Time.new.strftime("%Y%m%d %H%M%S")
conversion_value = '100'.to_f
feed = {
:google_click_id => customer.gclid,
:conversion_name => 'LeadCreatedAll',
:conversion_time => conversion_time,
:conversion_value => conversion_value,
:conversion_currency_code => 'GBP'
}
return_feeds = conversion_feed_srv.mutate([
{:operator => 'ADD', :operand => feed}])
return_feeds[:value].each do |return_feed|
puts ("Uploaded offline conversion value %.2f for Google Click ID '%s', " +
'to %s') % [return_feed[:conversion_value],
return_feed[:google_click_id],
return_feed[:conversion_name]]
end
rescue AdwordsApi::Errors::ApiException => e
puts e.backtrace
Logger.log_message("Exception occurred: %s\n%s" % [e.to_s, e.message])
rescue AdsCommon::Errors::OAuth2VerificationRequired => e
puts "Authorization credentials are not valid. Edit adwords_api.yml for " +
"OAuth2 client ID and secret and run misc/setup_oauth2.rb example " +
"to retrieve and store OAuth2 tokens."
puts "See this wiki page for more details:\n\n " +
'https://github.com/googleads/google-api-ads-ruby/wiki/OAuth2'
# 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
end
My adwords_api.yml file is:
---
:authentication:
:method: OAUTH2_SERVICE_ACCOUNT
:oauth2_keyfile: "/path/to_prod_manager_server_account_file/jsonkey.json"
:developer_token: test_level_developer_token_of_production_manager_account
:client_customer_id: client_customer_id_of_test_manager_account
:oauth2_token:
:access_token: access_token_generated_setup_oauth.rb
:issued_at: 2017-03-16 13:12:25.005441000 +05:30
:expires_in: 3600
:id_token:
:service:
:environment: PRODUCTION
:connection:
:enable_gzip: false
:library:
:log_level: INFO
I have been trying to test this setup for a long time and am getting this error:
Exception occurred: [AuthenticationError.NOT_ADS_USER # ; trigger:'']
[AuthenticationError.NOT_ADS_USER # ; trigger:'']
I have tried a lot of links:
managing test accounts
Can someone please provide exact steps on how to test it out.
For some more clarification, I have Test Account developer key in adwords.
Using adwords api v201702
The api I am trying to use is
OfflineConversion

Related

[RUBY]Server/Client | Command Client to start Using function

So I am working on some stupid simulation of mining cryptocoins - just for fun.
But I have run into an issue I want to command the client to start using a function but I am not sure how to do it, my code is bellow for Server.rb and Client.rb
Client
require 'socket'
s = TCPSocket.new 'localhost', 2626
while line = s.gets
puts line
end
s.close
Server.rb
#!/bin/ruby
require "socket"
require 'securerandom'
PORT = 2626
server_pool = TCPServer.open(PORT)
sndc_block_time = 200 # Size of block
sndc_block_time = 10 # Time to brake block 1,1 out of 200, 200
sndc_coin_blocks= 126^2 # Ammount of available blocks
sndc_coin_balance = 0
sub_blocks = 0 # Sub blocks user wants to mine
addr = SecureRandom.hex # generate a random hexadecimal address
# Notify message shown when user registers a new address
disclaimer = "Welcome to the SendCoin Network!
A new address has been registered and saved
to your computer desktop!"
def handle_connection(client)
puts "New client! #{client} \n\n"
end
puts "Listening on #{PORT}. Press CTRL+C to cancel."
while client = server_pool.accept
if Thread.new { handle_connection(client) }
if sndc_coin_blocks < 126^2 / 4
sndc_coin_blocks + 126^2 / 4 # Add a quarter of the original size
end
if Dir['../MyAddress/*.addr'].any? == true
# Statrs Mining
client.puts "Starting to mine.."
sleep(5)
client.puts "Current blocks: " + sndc_coin_blocks.to_s
client.puts "Block Size: " + sndc_coin_balance.to_s
client.puts "Approximate time to mine 1 sub-block: " + sndc_block_time.to_s
client.puts "Searching for block.."
sleep(3)
if sndc_block_time != 10
sndc_block_time = 10
end
client.puts "Started mining..."
elsif Dir['../addresses/*.addr'].any? == false
File.open("../addresses/"+addr+".addr", "w") do |f| # Create file
f.write(sndc_coin_balance.to_s)
end
client.puts "New address generated: " + addr.to_s + " , you may realunch the app now and enter your address!"
# Start Mining
puts "> File 'address.addr' has been generated for#{client}"
end
end
end
So essentially I want after this line of code:
client.puts "Started mining..."
.. to command the client to (client.rb) to start using a function.

Rake task not saving or creating new record in database

I've created a ruby script that executes fine if I run it from Console.
The script fetches some information from various websites and saves it to my database table.
However, when I want to turn the code into a rake task, the code still runs, but it does not save any new records. I don't get any errors from the rake either.
# Add your own tasks in files placed in lib/tasks ending in .rake,
# for example lib/tasks/capistrano.rake, and they will automatically be available to Rake.
require File.expand_path('../config/application', __FILE__)
Rails.application.load_tasks
require './crawler2.rb'
task :default => [:crawler]
task :crawler do
### ###
require 'rubygems'
require 'nokogiri'
require 'open-uri'
start = Time.now
$a = 0
sites = ["http://www.nytimes.com","http://www.news.com"]
for $a in 0..sites.size-1
url = sites[$a]
$i = 75
$error = 0
avoid_these_links = ["/tv", "//www.facebook.com/"]
doc = Nokogiri::HTML(open(url))
links = doc.css("a")
hrefs = links.map {|link| link.attribute('href').to_s}.uniq.sort.delete_if {|href| href.empty?}.delete_if {|href| avoid_these_links.any? { |w| href =~ /#{w}/ }}.delete_if {|href| href.size < 10 }
#puts hrefs.length
#puts hrefs
for $i in 0..hrefs.length
begin
#puts hrefs[60] #for debugging)
#file = open(url)
#doc = Nokogiri::HTML(file) do
if hrefs[$i].downcase().include? "http://"
doc = Nokogiri::HTML(open(hrefs[$i]))
else
doc = Nokogiri::HTML(open(url+hrefs[$i]))
end
image = doc.at('meta[property="og:image"]')['content']
title = doc.at('meta[property="og:title"]')['content']
article_url = doc.at('meta[property="og:url"]')['content']
description = doc.at('meta[property="og:description"]')['content']
category = doc.at('meta[name="keywords"]')['content']
newspaper_id = 1
puts "\n"
puts $i
#puts "Image: " + image
#puts "Title: " + title
#puts "Url: " + article_url
#puts "Description: " + description
puts "Catory: " + category
Article.create({
:headline => title,
:caption => description,
:thumbnail_url => image,
:category_id => 3,
:status => true,
:journalist_id => 2,
:newspaper_id => newspaper_id,
:from_crawler => true,
:description => description,
:original_url => article_url}) unless Article.exists?(original_url: article_url)
$i +=1
#puts $i #for debugging
rescue
#puts "Error here: " + url+hrefs[$i] if $i < hrefs.length
$i +=1 # do_something_* again, with the next i
$error +=1
end
end
puts "Page: " + url
puts "Articles: " + hrefs.length.to_s
puts "Errors: " + $error.to_s
$a +=1
end
finish = Time.now
diff = ((finish - start)/60).to_s
puts diff + " Minutes"
### ###
end
The code executes fine, if I save the file as crawler.rb and open it in Console by doing --> " load './crawler2.rb' ". When I use the exact same code in a rake task, I get no new records.
I figured out what was wrong.
I need to remove:
require './crawler2.rb'
task :default => [:crawler]
and instead edit the following:
task :crawler => :environment do
Now the crawler runs every ten minutes with a bit of help from Heroku scheduler :-)
Thanks for the help guys - and sorry for the bad formatting. Hope this answer may help others.

Error Number in LDAP binding using ruby

I m using following code to check whether the provided parameters are correct or not for binding..
require 'rubygems'
require 'net/ldap'
ldap = Net::LDAP.new
ldap.host = your_server_ip_address
ldap.port = 389
ldap.auth "joe_user", "opensesame"
if ldap.bind
# authentication succeeded
else
# authentication failed
end
If user and password is incorrect it returns false but if host or port number is incorrect it displays error (exception)
no connection to server (Net::LDAP::LdapError)
I want to capture this error also and want to show error msg separately for incoreect user/pass and for incorrect port/host name. How can i do this
You can check all possible exceptions here: https://www.rubydoc.info/gems/net-ldap/Net/LDAP/Error
But some errors are not considered exceptions, so you have to get them with get_operation_result
ldap = Net::LDAP.new
begin
ldap.host = '1.2.3.4'
ldap.auth 'cn=config', 'myPassword'
ldap.bind
rescue Net::LDAP::AuthMethodUnsupportedError => e
puts "Net::LDAP::AuthMethodUnsupportedError: #{e}"
rescue Net::LDAP::BindingInformationInvalidError => e
puts "Net::LDAP::BindingInformationInvalidError: #{e}"
rescue Net::LDAP::ConnectionError => e
puts "Net::LDAP::ConnectionError: #{e}"
rescue Net::LDAP::ConnectionRefusedError => e
puts "Net::LDAP::ConnectionRefusedError: #{e}"
rescue Net::LDAP::SocketError => e
puts "Net::LDAP::SocketError: #{e}"
rescue StandardError => e
# Timeout errors are rescued here
puts "StandardError: #{e}"
end
# Wrong user/pass is not an exception and must be checked here
p ldap.get_operation_result

Is it possible to access the AdSense API using ruby?

I am trying to access the AdSense Management API using ruby. They recommend using their generic Google-API client library:
http://code.google.com/p/google-api-ruby-client/#Google_AdSense_Management_API
This hasn't been very helpful and I have run into errors:
Faraday conflicts in google_drive and google-api-client
Where should I start in order to get access to my AdSense data?
Thanks in advance.
Unfortunately, we haven't prepared any sample code for the AdSense Management API... yet! As you point out, though, the client library is generic, and should work with any of the newer Google APIs, so some of the other samples may help.
If you're running into any specific issues, please create a question focused on those and point me to it, and I'll do my best to help.
If you want a quick sample to get started, I can cook that up for you, but we should make sure the issues you're running into have to do with the AdSense Management API itself, and not just the client library, as the one you were linking to.
[Edit]
Here's a quick sample, based on Sinatra:
#!/usr/bin/ruby
require 'rubygems'
require 'sinatra'
require 'google/api_client'
FILENAME = 'auth.obj'
OAUTH_CLIENT_ID = 'INSERT_OAUTH2_CLIENT_ID_HERE'
OAUTH_CLIENT_SECRET = 'INSERT_OAUTH2_CLIENT_SECRET_HERE'
before do
#client = Google::APIClient.new
#client.authorization.client_id = OAUTH_CLIENT_ID
#client.authorization.client_secret = OAUTH_CLIENT_SECRET
#client.authorization.scope = 'https://www.googleapis.com/auth/adsense'
#client.authorization.redirect_uri = to('/oauth2callback')
#client.authorization.code = params[:code] if params[:code]
# Load the access token here if it's available
if File.exist?(FILENAME)
serialized_auth = IO.read(FILENAME)
#client.authorization = Marshal::load(serialized_auth)
end
if #client.authorization.refresh_token && #client.authorization.expired?
#client.authorization.fetch_access_token!
end
#adsense = #client.discovered_api('adsense', 'v1.1')
unless #client.authorization.access_token || request.path_info =~ /^\/oauth2/
redirect to('/oauth2authorize')
end
end
get '/oauth2authorize' do
redirect #client.authorization.authorization_uri.to_s, 303
end
get '/oauth2callback' do
#client.authorization.fetch_access_token!
# Persist the token here
serialized_auth = Marshal::dump(#client.authorization)
File.open(FILENAME, 'w') do |f|
f.write(serialized_auth)
end
redirect to('/')
end
get '/' do
call = {
:api_method => #adsense.reports.generate,
:parameters => {
'startDate' => '2011-01-01',
'endDate' => '2011-08-31',
'dimension' => ['MONTH', 'CUSTOM_CHANNEL_NAME'],
'metric' => ['EARNINGS', 'TOTAL_EARNINGS']
}
}
response = #client.execute(call)
output = ''
if response && response.data && response.data['rows'] &&
!response.data['rows'].empty?
result = response.data
output << '<table><tr>'
result['headers'].each do |header|
output << '<td>%s</td>' % header['name']
end
output << '</tr>'
result['rows'].each do |row|
output << '<tr>'
row.each do |column|
output << '<td>%s</td>' % column
end
output << '</tr>'
end
output << '</table>'
else
output << 'No rows returned'
end
output
end

Are there any open-source examples of using LocationLabs or Loc-Aid through Ruby?

LocationLabs and Loc-Aid are location aggregation services that expose REST APIs. They currently offer Java, .NET and PHP SDKs. The API is not complex but, still, as a learning tool, it would be nice to have a Ruby tutorial or example to play with, extent, etc.
After further analysis, I built my application on Loc-Aid's infrastructure. Since there weren't many Ruby examples I could find, I'm sharing a snippet from my app.
# Get SAVON soap client locaid location services
# Parameters:
# - none
# Returns: SOAP client for locaid location services
def get_location_client
Savon::Client.new do
wsdl.document = LOCAID_CONFIG['use_local_wsdl'] ?
File.expand_path(LOCAID_CONFIG['get_location_wsdl'].to_s, ::Rails.root.to_s) :
LOCAID_CONFIG['get_location_wsdl'].to_s
wsdl.endpoint = LOCAID_CONFIG['get_location_endpoint'].to_s
end
end
# Strip the return result from locaid response as a hash
# Parameters:
# - raw_response: Raw response XMLfrom locaid services
# - response_name: Response name which wrap the response return result in locaid response XML
# Returns: Hash corresponding to the key "return" in locaid soap response hash.
# Sample Raw Response:
# {:subscribe_phone_response=>{:return=>{:error=>{:error_code=>"00001", :error_message=>"Invalid or inactive user"}, :transaction_id=>"14028251"},
# :"#xmlns:ns2"=>"http://webservice.portico.locaid.net/"}}
def strip_locaid_return(raw_response, response_name)
unless raw_response.to_hash.has_key?(response_name)
raise TropoExceptions::ExternalError
end
raw_response[response_name][:return]
end
# Get location from locaid by the caller id
# Parameters:
# - #caller_id: Caller id get from scope value
# Returns: none
def location_from_locaid
client = get_location_client
client.http.read_timeout = LOCAID_CONFIG['get_location_timeout'].to_i
# Call locaider service to get location
response = client.request :wsdl, :get_locations_x do |soap|
soap.body = {
:login => LOCAID_CONFIG['login'],
:password => LOCAID_CONFIG['password'],
:class_id => LOCAID_CONFIG['class_id'],
:msisdn_list => ["1#{#caller_id}"],
:coor_type => "DECIMAL",
:location_method => LOCAID_CONFIG['location_method'],
:sync_type => "SYN",
:overage => "1"
}
end
result_hash = strip_locaid_return(response, :get_locations_x_response)
if result_hash.has_key?(:error)
raise TropoExceptions::ExternalError
end
yield result_hash[:location_response].is_a?(Array) ?
result_hash[:location_response][0] :
result_hash[:location_response]
rescue Savon::Error, Timeout::Error => e
logger.error e
yield nil
end
end

Resources