Integrating Google Plus with Rails - ruby-on-rails-3.1

I already have the login (OAuth) piece working with my app, what I am trying to do now is pull down the authenticated users' activity list (status feed, for example).
The user has the option to pull this list down after the fact of them being authenticated and here is my code, thus far:
# User Model
def gplus
auth = authorizations.find_by_provider("gplus")
client = Google::APIClient.new(application_name: "AppName", application_version: '1.0', authorization: nil)
plus = client.discovered_api('plus', 'v1')
result = client.execute(
key: API["gplus"][Rails.env]["secret"],
api_method: plus.people.get,
parameters: { 'collection' => 'public', 'userId' => 'me' }
)
return result.data
end
Here is the problem I keep running into (from rails console)
#<Google::APIClient::Schema::Plus::V1::Person:0x3fe649ed04bc
DATA:{"error"=>{"errors"=>[{"domain"=>"usageLimits", "reason"=>"keyInvalid", "message"=>"Bad Request"}], "code"=>400, "message"=>"Bad Request"}}>
I am using the https://github.com/google/google-api-ruby-client... any reason why this won't work?

Code is close, but not quite there!
You're getting the auth object, but not actually passing it to your client there (you're setting it to nil).
You seem to be passing your client secret as the API key, which will cause problems. They API key is for a "simple API access" key from the API console - you don't need to pass anything if you're using an oAuth 2.0 token. If you'd like, you can pass a Server simple API key. This actually catches incorrectly using access tokens for a different project, so can be handy, but isn't required.
You don't need to specify a collection argument for plus.people.get
Additionally, make sure that the Google+ API is enabled under Services in the API console: http://developers.google.com/+

Related

GET /admin/webhooks.json returns an empty array

When doing GET /admin/webhooks.json it simply returns:
{"webhooks"=>[]}
I've created 8 webhooks using the admin panel but I can't seem to access them using the API. If I enter https://SHOP_NAME.myshopify.com/admin/webhooks.json directly into the browser it does return all the webhooks.
Here's the call I'm making using the credentials from a private app:
require 'httparty'
data = HTTParty.get("https://<API_KEY>:<PASSWORD>#<SHOP_NAME>.myshopify.com/admin/webhooks.json", :headers => {'Content-Type' => 'application/json'})
Any idea what I'm doing wrong?
Scanning through the Shopify API authentication docs doesn't give any indication that HTTP basic authentication of the form https://<API_KEY>:<PASSWORD>#... is supported.
This may be the reason why you can't query the hooks. In you browser you may use a web session. You can verify by removing the basic auth from the url and open again in you browser
https://<SHOP_NAME>.myshopify.com/admin/webhooks.json
The /admin/webhooks.json endpoint only returns the webhooks that you have registered with that API key. That's why I'm seeing an empty array.

Issue with Headers when using oAuth token to connect to Xero API via HTTParty

I'm trying to connect to the Xero API via a Public application, and I've got a separate process that does the oAuth flow which stores off the token and token secret which I then turn around to use in this script.
My issue is when I go to use that token in a HTTParty call, I keep getting a Consumer_key_unknown error and I'm not sure why.
Script;
require 'httparty'
def nonce_generator()
random = Random.new
random.rand(100000000000)
end
//statics for testing
XERO_API_URL = 'https://api.xero.com/api.xro/2.0/'
TOKEN = "token received back from initial oauth process"
TOKEN_SECRET = "token secret received back from initial oauth process"
XERO_CONS_KEY = "my cons key per Xero Developer/Applications page"
XERO_CONS_SECRET = "my cons secret per Xero Developer/Applications page"
AUTH = "oauth_consumer_key=#{XERO_CONS_KEY}&
oauth_token=#{TOKEN}&
oauth_token_secret=#{TOKEN_SECRET}&
oauth_signature_method=RSA-SHA1&
oauth_timestamp=#{Time.now.to_i}&
oauth_nonce=#{nonce_generator()}"
//test it works
xero_accounts = HTTParty.get("#{XERO_API_URL}/accounts", :headers => { "Authorization" => AUTH }, "Accept" => "application/json")
NB: I've split AUTH across multiple lines here for ease of viewing they're all on one line in my script.
I've tried swapping AUTH out for either;
AUTH = "Token #{TOKEN}"
AUTH = "Bearer #{TOKEN}"
to no effect. I've used a similar script with the Kounta API which works via the Bearer token.
I've thought about using the Xeroizer/Xero Gateway gems but both are built with the aim of doing the oAuth for you and carrying that forward, whereas I've already done that as a separate process.
Any comments welcomed!
Gave up trying to sort it out that way and sifted through the gem until I found an authorise from access token method which works fine;
require 'xeroizer'
client = Xeroizer::PublicApplication.new(XERO_CONS_KEY, XERO_CONS_SECRET)
client.authorize_from_access(TOKEN, TOKEN_SECRET)
puts client.Organisation.all

How to get a refresh token when using the Google Calendar API Ruby Library?

I'm a newbie trying to implement the Google Calendar API into a web-based app and after following the instructions that they provide to the t, fetching information only works for about 20 minutes (while the access token is still valid). I understand that you need a refresh token in order to generate a new access token, but running this script from the terminal (which google provided in their documentation) doesn't provide a refresh token.
The code I executed in terminal:
google-api oauth-2-login --scope=https://www.googleapis.com/auth/calendar --client- id=CLIENT_ID --client-secret=CLIENT_SECRET
This generated a .yaml file with all of my keys which looks like this:
---
mechanism: oauth_2
scope: SCOPE_HERE
client_id: CLIENT_ID_HERE
client_secret: CLIENT_SECRET_HERE
access_token: ACCESS_TOKEN_HERE
refresh_token:
And the code that they provided if the access token expires:
oauth_yaml = YAML.load_file('.google-api.yaml')
client = Google::APIClient.new
client.authorization.client_id = oauth_yaml["client_id"]
client.authorization.client_secret = oauth_yaml["client_secret"]
client.authorization.scope = oauth_yaml["scope"]
client.authorization.refresh_token = oauth_yaml["refresh_token"]
client.authorization.access_token = oauth_yaml["access_token"]
if client.authorization.refresh_token && client.authorization.expired?
client.authorization.fetch_access_token!
end
service = client.discovered_api('calendar', 'v3')
So, according the yaml file, client.authorization.refresh_token is always 'nil', and it never gets a new access token. Also, client.authorization.expired? always returns false, even after the app has stopped working.
I've seen some other questions on here pertaining to the same issue, but since I'm generating my tokens via a terminal command, I'm not really sure how to go about getting that refresh token.
You need to specify that you want offline access to get a refresh token: access_type=offline
See https://developers.google.com/accounts/docs/OAuth2WebServer#offline

What is the difference between a Stripe Access Token and API SK key?

The Stripe API reference says this about authentication:
The example they give is this:
require "stripe"
Stripe.api_key = "sk_test_BQokikJOvBiI2HlWgH4olfQ2"
The sk_test_BQokikJOvBiI2HlWgH4olfQ2 secret key is found in the account settings on Stripe's webpage. I understand this is the secret api key for my application to talk with Stripe.
But then I read this documentation on getting started with Stripe Connect:
When using our official API libraries, we recommend that you pass in the
access_token with every request, instead of setting the API key globally.
This is because the access_token used in any API request depends on the user
you're charging on behalf of.
The example they give is:
# Not recommended: setting global API key state
Stripe.api_key = ACCESS_TOKEN
Stripe::Customer.create(
:description => "example#stripe.com"
)
# Recommended: sending API key with every request
Stripe::Customer.create(
{:description => "example#stripe.com"},
ACCESS_TOKEN # user's access token from the Stripe Connect flow
)
Here, the access token is returned to the application after a user has connected to the application through Stripe Connect. The access token can be used to perform actions on behalf of that user, like charging their card.
So, they pass the API key with every request, but why would the user's access token be an api key? I thought from the first documentation that the api key is supposed to be my application's secret api key? Instead, they are setting the user's access token. How will Stripe identify my application then if I'm setting the user's access token and not my own secret key?
Then, I read their example on integrating Stripe Checkout with Sinatra. The code sample they give is:
require 'sinatra'
require 'stripe'
set :publishable_key, ENV['PUBLISHABLE_KEY']
set :secret_key, ENV['SECRET_KEY']
Stripe.api_key = settings.secret_key
....
get '/' do
erb :index
end
post '/charge' do
# Amount in cents
#amount = 500
customer = Stripe::Customer.create(
:email => 'customer#example.com',
:card => params[:stripeToken]
)
charge = Stripe::Charge.create(
:amount => #amount,
:description => 'Sinatra Charge',
:currency => 'usd',
:customer => customer.id
)
erb :charge
end
So in this instance, they set the API Key to be the application's secret key. They don't pass any Access Token in the request either. So I'm a bit confused why an Access Token would be set as a secret API Key in the previous doc or why I should pass it with each request, when all their example docs don't even do that.
To understand this, you should know first that the Stripe API can be used to build applications that serve two kinds of audiences:
to accept payments from end-users as a merchant (normal use-case) and
to provide add-on services to merchants having their own Stripe
accounts (eg. one service helps me configure the emails to be sent out on different Stripe events)
Hence, all the API endpoints can be authorized in two ways:
the API key way which you can directly get from your Account Settings. This identifies your Stripe account
the access token way through Stripe Connect. This identifies the Stripe account of the connected merchant.
What the Stripe Connect docs is telling you is that suppose you are building an application that serves use-case #2 above, then you must remember to authorize each of your API calls with the right access token and not have a global API key (which, by the way, is fully acceptable for use case #1) as you might be making changes incorrectly to the wrong account(s).
So, if use case #1 is what you want to do, you don't have to worry about Stripe Connect at all.

Google Developer API keys & YouTube API

I started a web based dev project using YouTube and when I signed up for the API all I received was a client ID and email ID. However in the Ruby example text for calling the data API it states:
def initialize(scope)
credentials = Google::APIClient::ClientSecrets.load
#authorization = Signet::OAuth2::Client.new(
:authorization_uri => credentials.authorization_uri,
:token_credential_uri => credentials.token_credential_uri,
:client_id => credentials.client_id,
:client_secret => credentials.client_secret,
:redirect_uri => credentials.redirect_uris.first,
:scope => scope
I don't know where to go to grab these credentials. Ideas?
Since YouTube is now Google-account-based, these credentials need to be acquired on the Google Developers Console (pick the YouTube Data API), and you'll have to initiate the normal Google sign-in process. Your client_id and client_secret are generated when you create a new application on the console, your redirect_uri is set based on your application structure.
While Signet has a nice OAuth2 module associated with it, I've found Omniauth to be very easy to work with (and you can still use it in conjunction with Signet). If you don't need to customize the sign in process, Omniauth puts most of this in a black box (it's very high-touch), and handles token refreshes, etc. for you. I might use the Omniauth Google strategy to get your tokens, then the Google Ruby client to make requests.

Resources