def post_to_twitter
message = from some where
url = URI.parse('http://twitter.com/statuses/update.xml')
req = Net::HTTP::Post.new(url.path)
req.basic_auth 'account', 'password'
req.set_form_data({'status' => message})
res = Net::HTTP.new(url.host, url.port).start {|http| http.request(req) }
case res
when Net::HTTPSuccess, Net::HTTPRedirection
# ok
else
# false
end
end
this is the code for the twitter update, It is always be false when I post some updates to twitter through this action.
Can I know where is wrong?
I advise you to use Twitter gem
Using the API you you just have to do:
httpauth = Twitter::HTTPAuth.new('username', 'password')
client = Twitter::Base.new(httpauth)
client.update('Heeeeyyyyooo from the Twitter Gem')
And using OAuth(which I highly recommend):
oauth = Twitter::OAuth.new('consumer token', 'consumer secret')
oauth.authorize_from_access('access token', 'access secret')
client = Twitter::Base.new(oauth)
client.update('Heeeyyyyoooo from Twitter Gem!')
Related
How can I make a get request to a repository if my user hasn't generated a personal token and I have just the access token from authentication with oauth2?
I have tried some options with postman but I can't fix it.
I want to access a private repository
What I'm trying to do:
require "uri"
require "net/http"
url = URI("https://api.github.com/repos/username/repository_name")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "Bearer ACCESS_TOKEN"
request["Cookie"] = "_octo=GH1.1.1832634711.1663350372; logged_in=no"
response = https.request(request)
puts response.read_body
One of my collaborators resolve in this way, I hope to be helpful to someone else
def get_github_link
#group=Group.find(params[:id])
if current_user.gh_access_token.nil?
flash[:notice] = "You havn't your GithHub account linked, this is a private repository!"
redirect_to #group and return
end
if #group.status=="private"
url = URI.parse("https://api.github.com/repos/#{current_user.gh_username}/#{#group.git_repository}")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Post.new(url)
request["Authorization"] = "token #{current_user.gh_access_token}"
request["Content-Type"] = 'application/json'
request["Accept"] = 'application/vnd.github+json'
request["Coockies"] = 'login-yes'
request.body = {owner: #group.user.gh_username}.to_json
response = https.request(request)
else
url = URI.parse("https://api.github.com/repos/#{#group.user.gh_username}/#{#group.git_repository}")
https = Net::HTTP.new(url.host, url.port)
https.use_ssl = true
request = Net::HTTP::Get.new(url)
request["Authorization"] = "token #{current_user.gh_access_token}"
request["Accept"] = 'application/vnd.github+json'
request.body = {owner: #group.user.gh_username}.to_json
response = https.request(request)
end
#url = URI.parse("https://api.github.com/repos/"+#group.git_url.remove("https://github.com/"))
json = JSON.parse(response.body, symbolize_names: true)
if eval(response.code.to_s) === 200
redirect_to #group.git_url, allow_other_host: true and return
else
flash[:notice] = "You have not the access to this repository, please conctact the admin"
redirect_to #group and return
end
end
I am upgrading PayPal Invoicing feature from v1 to v2 (Because v1 is deprecated) in my Ruby on Rails application.
Since there's no official library/gem supporting v2 invoicing, so I decided to build everything as per this official documentation here: https://developer.paypal.com/docs/api/invoicing/v2.
The flow is like this:
System will get an access-token based on ClientID and ClientSecret
From this access-token, I will be generating a new invoice_number by sending curl request to: https://api.sandbox.paypal.com/v2/invoicing/generate-next-invoice-number
Upon receiving the invoice_number, I am sending curl request to create draft invoice endpoint with all the required data
curl -v -X POST https://api.sandbox.paypal.com/v2/invoicing/invoice
The issue I am facing is with the last point. I am getting 201 created response from create draft invoice endpoint but the endpoint is not returning me the complete invoice object along with Invoice ID.
Here's what I am getting:
"201"
{"rel"=>"self", "href"=>"https://api.sandbox.paypal.com/v2/invoicing/invoices/INV2-Z3K7-Y79X-36EM-ZQX8", "method"=>"GET"}
If you try opening this link, you'll see this:
{
"name":"AUTHENTICATION_FAILURE",
"message":"Authentication failed due to invalid authentication credentials or a missing Authorization header.",
"links": [
{
"href":"https://developer.paypal.com/docs/api/overview/#error",
"rel":"information_link"
}
]
}
Not sure what I am missing here!
Below is the code for reference:
require 'net/http'
require 'uri'
require 'json'
class PaypalInvoice
def initialize order
#order = order
#client_id = ENV['PAYPAL_CLIENT_ID']
#client_secret = ENV['PAYPAL_CLIENT_SECRET']
#base_url = ENV['AD_PP_ENV'] == 'sandbox' ? 'https://api.sandbox.paypal.com' : 'https://api.paypal.com'
#paypal_access_token_identifier = 'paypal_access_token'
#request_id ||= SecureRandom.uuid
end
def create_draft_invoice
raise "Paypal token not found" unless Rails.cache.exist?(#paypal_access_token_identifier)
invoice_number = "#141"
sleep 5
try = 0
uri = URI.parse(#base_url + "/v2/invoicing/invoices")
request = Net::HTTP::Post.new(uri)
request['X-PAYPAL-SANDBOX-EMAIL-ADDRESS'] = ENV['PAYPAL_CLIENT_EMAIL']
request['Authorization'] = "Bearer #{Rails.cache.fetch(#paypal_access_token_identifier)['access_token']}"
request['Content-Type'] = 'application/json'
request['PayPal-Request-Id'] = #request_id.to_s
request.body = JSON.dump({
"detail" => get_detail(invoice_number),
"invoicer" => get_invoicer,
"primary_recipients" => get_primary_recipients,
"items" => items_info,
"configuration" => {
"partial_payment" => {
"allow_partial_payment" => false,
},
"allow_tip" => false,
"tax_calculated_after_discount" => true,
"tax_inclusive" => true
}
})
req_options = {
use_ssl: uri.scheme == "https",
}
response = Net::HTTP.start(uri.host, uri.port, req_options) do |http|
http.request(request)
end
p 'method: create_draft_invoice. response: '
p response.code
p JSON.parse(response.body)
raise "Paypal token expired" if response.code.to_s == '401'
rescue RuntimeError => error
p "#{error.to_s}"
try += 1
access_token_response_status = get_new_access_token
retry if access_token_response_status.to_s == '200' and try <= 1
end
end
This:
{"rel"=>"self", "href"=>"https://api.sandbox.paypal.com/v2/invoicing/invoices/INV2-Z3K7-Y79X-36EM-ZQX8", "method"=>"GET"}
Is the endpoint for an API call, specifically 'Show invoice details': https://developer.paypal.com/docs/api/invoicing/v2/#invoices_get
Loading it in a browser w/o an Authorization: Bearer <Access-Token> header will give an AUTHENTICATION_FAILURE.
There's currently a bug in Sandbox with unconfirmed emails, so make sure your Sandbox emails are confirmed
Problem
When i try to validate the code returned from the Apple SSO client flow, I keep getting a unsupported_grant_type 400 error.
The docs say that an unsupported_grant_type will be returned when The authenticated client is not authorized to use the grant type. I've enabled Apple SSO on the App Id, the Service Id, and have even verified my support email domains. What am I missing? Is there some other approval step I need to complete to get authorized?
I've tried removing params from my verification request, but still get the same error code.
Details
The SSO redirect gives me a form-encoded POST body that looks something like this: {"state"=>"x", "code"=>"y", "id_token"=>"z"}.
I then attempt to validate the token by calling validate_auth_token.
def validate_auth_token(token, is_refresh = false)
uri = URI.parse('https://appleid.apple.com/auth/token')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
headers = { 'Content-Type': 'text/json' }
request = Net::HTTP::Post.new(uri.path, headers)
request_body = {
client_id: #client_id,
client_secret: retreive_client_secret
}
if is_refresh
request_body[:grant_type] = 'refresh_token'
request_body[:refresh_token] = token
else
request_body[:grant_type] = 'authorization_code'
request_body[:code] = token
request_body[:redirect_uri] = "https://#{Rails.application.secrets.backend_host_port}/apple"
end
request.body = request_body.to_json
response = https.request(request)
p JSON.parse response.body
end
def retreive_client_secret
cert = retreive_secret_cert
ecdsa_key = OpenSSL::PKey::EC.new cert
algorithm = 'ES256'
headers = {
'alg': algorithm,
'kid': #key_id
}
claims = {
'iss': #team_id,
'iat': Time.now.to_i,
'exp': Time.now.to_i + 5.months.to_i,
'aud': 'https://appleid.apple.com',
'sub': #client_id
}
token = JWT.encode claims, ecdsa_key, algorithm, headers
token
end
Where #client_id is the "Service ID" I submitted in the initial SSO request, #key_id is the id of the private key downloaded from the apple key dashboard, and #team_id is our apple team id. retrieve_secret_cert simply gets the cert file body used to generate the client secret.
Given all this, I would expect a TokenResponse, but keep getting the same error {"error"=>"unsupported_grant_type"} with no additional explanation.
The token validation request needs to be form encoded, not json encoded. Also, the request wasn't validating correctly when I included an alg header in the JWT, but worked after I removed it.
Here's the updated code:
def validate_auth_token(token, is_refresh = false)
uri = URI.parse('https://appleid.apple.com/auth/token')
https = Net::HTTP.new(uri.host, uri.port)
https.use_ssl = true
request_body = {
client_id: #client_id,
client_secret: retreive_client_secret
}
if is_refresh
request_body[:grant_type] = 'refresh_token'
request_body[:refresh_token] = token
else
request_body[:grant_type] = 'authorization_code'
request_body[:code] = token
request_body[:redirect_uri] = "https://#{Rails.application.secrets.backend_host_port}/auth"
end
request = Net::HTTP::Post.new(uri.path)
request.set_form_data(request_body)
response = https.request(request)
JSON.parse response.body
end
def retreive_client_secret
cert = retreive_secret_cert
ecdsa_key = OpenSSL::PKey::EC.new cert
algorithm = 'ES256'
headers = {
'kid': #key_id
}
claims = {
'iss': #team_id,
'iat': Time.now.to_i,
'exp': Time.now.to_i + 5.minutes.to_i,
'aud': 'https://appleid.apple.com',
'sub': #client_id
}
token = JWT.encode claims, ecdsa_key, algorithm, headers
token
end
Thank you sudhakar19 for pointing out the encoding error.
I am using Satelizer for social logins in a rails app.
There's no ruby implementation, so I made one adapted from the node version.
So, after pressing the login with twitter button, I get to my controller, and the following code produces the message: "Bad Authentication data", code: 215
What am I doing wrong?
requestTokenUrl = 'https://api.twitter.com/oauth/request_token'
accessTokenUrl = 'https://api.twitter.com/oauth/access_token'
profileUrl = 'https://api.twitter.com/1.1/users/show.json?screen_name='
requestTokenOauth = {
consumer_key: ENV['TWITTER_KEY'],
consumer_secret: ENV['TWITTER_SECRET'],
callback: ENV['TWITTER_CALLBACK']
};
params = {'oauth' => requestTokenOauth }
require "net/https"
require "uri"
uri = URI.parse requestTokenUrl
http = Net::HTTP.new(uri.host, uri.port)
# https stuff
http.use_ssl = true
http.verify_mode = OpenSSL::SSL::VERIFY_NONE
request = Net::HTTP::Post.new(uri.request_uri)
request.set_form_data(params)
response = http.request(request)
binding.pry
I am trying to make an http request to send and sms through kannel using ruby but its not working,what could be the problem with the code in this method. Thanx
require 'net/http'
def self.send_sms( to, from, message)
id = rand(36**8).to_s(36)
uri= URI('http://localhost:13013/cgi-bin/sendsms?')
params = {username: 'skylinesms', password: 'password', from: '#{from}',
text: '#{message}',
'dlr-url': '#{Rails.application.routes.url_helpers.deliver_url(:id => id)}',
'dlr-mask': 3
}
uri.query = URI.encode_www_form(params)
req = Net::HTTP::Get.new(uri.to_s)
res = Net::HTTP.get_response(uri)
res
end