how to request for refunds in paypal using paypal-recurring gem in (ruby on rails) application - ruby-on-rails-3

Using paypal-recurring gem, how can we ask for full refunds for a recurring profile? I'm using Ruby on Rails for developing my application. I tried searching for it, but didn't found appropriate answer to my problem.
I've found this link:
https://www.x.com/developers/paypal/documentation-tools/api/refundtransaction-api-operation-soap
But I don't understand how to integrate it with my app.
I'm using this gem,
https://github.com/fnando/paypal-recurring
And my code is as follows:
def refund_full_paypal_transaction
PayPal::Recurring.new({
:profile_id => "customers profile id",
:transaction_id => "to_be_refunded transaction_id",
:reference => "12345",
:refund_type => :full,
:amount => "whatever amount",
:currency => "USD"
})
end

It looks like the gem already provides RefundTransaction for you. I'm not a Ruby developer, but if you look at /lib/paypal/recurring/request.rb you'll see it's a simple class that builds your API requests for you.
The METHODS array at the top specifies the different requests that it seems to support, and RefundTransaction is one of them.
So again, I can't give too detailed an answer without knowing Ruby better, but from what I see you can simply pass in the refund attribute there along with the original transaction ID to be refunded and it'll handle the rest for you.
Hope that helps.

# Request a refund.
ppr = PayPal::Recurring.new({
:profile_id => "I-VCEL6TRG35CU",
:transaction_id => "ABCEDFGH",
:reference => "1234",
:refund_type => :partial,
:amount => "9.00",
:currency => "USD"
})
response = ppr.refund
worked !!! found in https://github.com/fnando/paypal-recurring/blob/master/lib/paypal/recurring/base.rb
Thanks !!!

Related

Oauth Client Creation Rails

I'm working with rails to create a client for the Fitbit API (very similar to twitter api) on Rails.
In my device.rb file
def fitbit_data
#client = Fitgem::Client.new (
:consumer_key => 'bb1', #I understand the security issues here and will change it for production
:consumer_secret => '81f',
:token => oauth_token,
:secret => oauth_token_secret,
:user_id => uid
)
end
It says that my syntax is wrong and asks for a ')' after :consumer_key. How do I get the syntax correct?
Note: this answer is applicable for Rails 4.1.4 and Fitgem 0.10.0.
I think the issue here is that to initialize a client, you have to pass in a hash. Additionally, I do not believe it's necessary to specify a user_id key. See my code below:
$client = Fitgem::Client.new ({ :consumer_key => ENV["FITBIT_CONSUMER_KEY"],
:consumer_secret => ENV["FITBIT_CONSUMER_SECRET"],
:token => ENV["OAUTH_TOKEN"],
:secret => ENV["OAUTH_SECRET"] })
Let me know if this helps.

RavenDB Query: Have to use Customize() instead of Include()

I'm getting an error that I'm exceeding the number of requests allowed per session (30) when using this query (using Include instead of Customize):
ApplicationServer appServer = QuerySingleResultAndSetEtag(session => session
.Include<ApplicationServer>(x => x.CustomVariableGroupIds)
.Include<ApplicationServer>(x => x.ApplicationIdsForAllAppWithGroups)
.Include<ApplicationServer>(x => x.CustomVariableGroupIdsForAllAppWithGroups)
.Include<ApplicationServer>(x => x.CustomVariableGroupIdsForGroupsWithinApps)
.Include<ApplicationServer>(x => x.InstallationEnvironmentId)
.Load <ApplicationServer>(id))
as ApplicationServer;
Note, the error occurs on this line, which is called for each AppWithGroup within an application:
appGroup.Application = QuerySingleResultAndSetEtag(session =>
session.Load<Application>(appGroup.ApplicationId)) as Application;
However, this query (using Customize) doesn't create extra requests:
ApplicationServer appServer = QuerySingleResultAndSetEtag(session =>
session.Query<ApplicationServer>()
.Customize(x => x.Include<ApplicationServer>(y => y.CustomVariableGroupIds))
.Customize(x => x.Include<ApplicationServer>(y => y.ApplicationIdsForAllAppWithGroups))
.Customize(x => x.Include<ApplicationServer>(y => y.CustomVariableGroupIdsForAllAppWithGroups))
.Customize(x => x.Include<ApplicationServer>(y => y.CustomVariableGroupIdsForGroupsWithinApps))
.Customize(x => x.Include<ApplicationServer>(y => y.InstallationEnvironmentId))
.Where(server => server.Id == id).FirstOrDefault())
as ApplicationServer;
However, the above query causes an error:
Attempt to query by id only is blocked, you should use call
session.Load("applications/2017"); instead of
session.Query().Where(x=>x.Id == "applications/2017");
You can turn this error off by specifying
documentStore.Conventions.AllowQueriesOnId = true;, but that is not
recommend and provided for backward compatibility reasons only.
I had to set AllowQueriesOnId = true because it was the only way I could get this to work.
What am I doing wrong in the first query to cause the includes not to work?
By the way, another post had the same issue where he had to use Customize. I'd like to do this correctly though.
I'm not sure why the load isn't doing this for you, What version of raven are you on? I just tested this in Raven 2.5 build 2700 and the include is bringing back the information for me in a single request.
Anyway, with the load not working quite like i would expect, i would switch to a set of lazy queries to get what you want in 2 server round trips. http://ravendb.net/docs/2.5/client-api/querying/lazy-operations.
Another option that might work out better for you, (depending on what you are really doing with all of that data) is a transformer. http://ravendb.net/docs/2.5/client-api/querying/results-transformation/result-transformers?version=2.5
Hope that helps.

How do I test my JSON API with Sinatra + rspec

I have a post method that accepts JSON:
post '/channel/create' do
content_type :json
#data = JSON.parse(env['rack.input'].gets)
if #data.nil? or !#data.has_key?('api_key')
status 400
body({ :error => "JSON corrupt" }.to_json)
else
status 200
body({ :error => "Channel created" }.to_json)
end
As a newbie to rspec I am bewildered trying to figure out how to write a test against that POST with an acceptable JSON payload. The closest I got to is this which is woefully inaccurate but I don't seem to be asking the Google god the right questions to help me out here.
it "accepts create channel" do
h = {'Content-Type' => 'application/json'}
body = { :key => "abcdef" }.to_json
post '/channel/create', body, h
last_response.should be_ok
end
Any best practice guidance for testing APIs in Sinatra will be most appreciated also.
The code you've used is fine, although I would structure it slightly differently as I don't like to use it blocks the way you normally see them, I think it encourages testing of more than one aspect of a system at a time:
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
subject { last_response }
it { should be_ok }
I've used let because it's better than an instance variable in a before block (kudos to you for not doing that). The post is in a before block because it's not really part of the spec, but a side effect that occurs prior to what you're speccing. The subject is the response and that makes the it a simple call.
Because checking the response is ok is needed so often I put it in a shared example:
shared_examples_for "Any route" do
subject { last_response }
it { should be_ok }
end
and then call it as such:
describe "Creating a new channel" do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, {'CONTENT_TYPE' => 'application/json'}
end
it_should_behave_like "Any route"
# now spec some other, more complicated stuff…
subject { JSON.parse(last_response.body) }
it { should == "" }
and because the content type changes so often, I put that in a helper:
module Helpers
def env( *methods )
methods.each_with_object({}) do |meth, obj|
obj.merge! __send__(meth)
end
end
def accepts_html
{"HTTP_ACCEPT" => "text/html" }
end
def accepts_json
{"HTTP_ACCEPT" => "application/json" }
end
def via_xhr
{"HTTP_X_REQUESTED_WITH" => "XMLHttpRequest"}
end
It's easy to add this in where it's needed by including it via the RSpec config:
RSpec.configure do |config|
config.include Helpers, :type => :request
then:
describe "Creating a new channel", :type => :request do
let(:body) { { :key => "abcdef" }.to_json }
before do
post '/channel/create', body, env(:accepts_json)
end
Having said all that, personally, I wouldn't post using JSON. HTTP POST is simple to handle, and every form and javascript library does it easily and well. Respond with JSON by all means, but don't post JSON, HTTP is a lot easier.
Edit: after writing out the Helpers bit above I realised it would be more helpful as a gem.
Looks like the ability to do post :update, '{"some": "json"}' was added to the internal ActionPack test_case.rb used by rspec in this commit:
https://github.com/rails/rails/commit/5b9708840f4cc1d5414c64be43c5fc6b51d4ecbf
Since you're using Sinatra I'm not sure the best way to get those changes—you might be able to upgrade ActionPack directly, or patch from the above commit.
If you want to look at last_response as JSON, you could try rack-test-json which makes this trivial:
expect(last_response).to be_json
expect(last_response.as_json['key']).to be == 'value'

How to get contact list from yahoo in rails using OAuth

I can successfully get the contacts from google using OAuth gem in rails. my gmail configuration is :
:google=>{
:key=>"***",
:secret=>"***",
:expose => true,
:scope=>"https://www.google.com/m8/feeds/"
}
now i want to get contact from yahoo and hot mail. How to get that contact I have given following configuration in my oauth_consumer.rb file
:yahoo=>{
:client=>:oauth_gem,
:expose => true,
:allow_login => true,
:key=>"**",
:secret=>"**",
:scope=>"https://me.yahoo.com"
}
:hotmail=>{
:client=>:oauth_gem,
:expose => true,
:allow_login => true,
:key=>"**",
:secret=>"**"
}
when i am trying to do same like what is done in google it gives error like undefined methoddowncase' for nil:NilClass`
I have also tried contacts gem but fail to load contacts.
Please try to use OmniContacts https://github.com/Diego81/omnicontacts this will help you alot.
In your gemfile
gem "omnicontacts"
Create config/initializers/omnicontacts.rb
require "omnicontacts"
Rails.application.middleware.use OmniContacts::Builder do
importer :gmail, "client_id", "client_secret", {:redirect_path => "/oauth2callback", :ssl_ca_file => "/etc/ssl/certs/curl-ca-bundle.crt"}
importer :yahoo, "consumer_id", "consumer_secret", {:callback_path => '/callback'}
importer :hotmail, "client_id", "client_secret"
importer :facebook, "client_id", "client_secret"
end
Create an app to yahoo https://developer.apps.yahoo.com/projects
This will ask to verify your domain. So, just change your domain of localhost:3000 to local.appname.com:3000 or prefer your live server... (change host in local --- sudo gedit /etc/hosts)
in your controller
#contacts = request.env['omnicontacts.contacts']
#user = request.env['omnicontacts.user']
puts "List of contacts of #{user[:name]} obtained from #{params[:importer]}:"
#contacts.each do |contact|
puts "Contact found: name => #{contact[:name]}, email => #{contact[:email]}"
end

Error with facebook access token

My problem is on facebook callback url. I am using fbgraph gem on Rails 3.0.
I ask for extended permissions on my tab application. So in the callback I wait code parameter and access_token.
I extract this code from fbgraph official GIT repository.
def authorize
begin
#auth.client.authorization_code = params[:code]
#In access_token line should return me access__token but throw a error message (see below)
access_token = #auth.client.access_token! # => Rack::OAuth2::AccessToken
#facebook_user = FbGraph::User.me(access_token).fetch # => FbGraph::User
#MORE CODE WITHOUT IMPORTANCE
redirect_to :controller => "dashboard", :action => "index"
rescue Exception => e
logger.info(e.message)
end
end
Throw this error message:
Rack::OAuth::Client::Error # => #status = 400, Message => Missing redirect uri
Please I need help quickly. Excuse me and thanks in advance
I'm using the fb_graph gem which is similar. In order to get the access_token you also need to supply the callback URI - this is the fb_graph version:
client.redirect_uri = "http://your.callback.uri"
client.authorization_code = params[:code]
access_token = client.access_token!
Update:
Looking at the fbgraph gem documentation I think you need to replace these two lines:
#auth.client.authorization_code = params[:code]
access_token = #auth.client.access_token!
With this:
access_token = #auth.client.authorization.process_callback(params[:code], :redirect_uri => callback_url)
To be honest I looked at using the fbgraph gem but the documentation was so bad that I switched to fb_graph instead which is similar and actually has some useful examples in the documentation.