ruby on rails braintree fail on duplicate payment method - ruby-on-rails

i am trying to implement braintree payments into a ruby app, and everything seems to be working fine, but when i pass fail_on_duplicate_payment_method_card as an option i am getting invalid keys: options[fail_on_duplicate_payment_method_card]
result = Braintree::PaymentMethod.create(
:customer_id => current_user.customer_cim_id,
:payment_method_nonce => 'fake-valid-amex-nonce',
:cardholder_name => "#{current_user.first_name} #{current_user.last_name}",
:options => {
:make_default => true,
:fail_on_duplicate_payment_method_card => true
}
)
if result.success?
customer = Braintree::Customer.find(current_user.customer_cim_id)
puts customer.id
puts customer.payment_methods[0].token
else
p result.errors
end

Full disclosure: I work at Braintree. If you have any further questions, feel free to contact our support team.
fail_on_duplicate_payment_method_card should be fail_on_duplicate_payment_method.
result = Braintree::PaymentMethod.create(
:customer_id => current_user.customer_cim_id,
:payment_method_nonce => 'fake-valid-amex-nonce',
:cardholder_name => "#{current_user.first_name} #{current_user.last_name}",
:options => {
:make_default => true,
:fail_on_duplicate_payment_method => true
}
)

Related

Time frame for displaying user count is not working in Rails 4.2

I am having a dashboard which shows the user created / deleted count of today, yesterday, this week, this month etc;
For this they wrote a condition in controller to get these counts and also scopes in model.
The above scenario is working fine in Rails 3.2 but not working in Rails 4.2.
This is my code:
controller:
protected
def get_user_counts(conditions = {})
includes = []
if conditions.empty?
# nothing
elsif conditions.keys.first.include?("accounts.")
includes = [:account]
end
result = []
[
{:label => 'today', :start => Time.zone.now.beginning_of_day, :end => Time.zone.now.end_of_day},
{:label => 'yesterday', :start => 1.days.ago.beginning_of_day, :end => 1.days.ago.end_of_day},
{:label => 'this week', :start => Time.zone.now.beginning_of_week, :end => Time.zone.now.end_of_week},
{:label => 'last week', :start => 7.days.ago(Time.zone.now.beginning_of_week), :end => 7.days.ago(Time.zone.now.end_of_week)},
{:label => 'this month', :start => Time.zone.now.beginning_of_month, :end => Time.zone.now.end_of_month},
{:label => 'last month', :start => Time.zone.now.prev_month.beginning_of_month, :end => Time.zone.now.prev_month.end_of_month},
].each do |time_frame|
result << [time_frame[:label], User.includes(includes).where(conditions).only_deleted.deleted_between(time_frame[:start], time_frame[:end]).count, User.includes(includes).where(conditions).with_deleted.created_between(time_frame[:start], time_frame[:end]).count]
end
return result
end
model:
scope :created_between, lambda { |start_at, end_at|
{ :conditions => {'users.created_at' => (start_at..end_at)} }
}
scope :deleted_between, lambda { |start_at, end_at|
# Don't forget to use 'count_only_deleted' or 'find_only_deleted' in combination
# with this, or you'll always return zero users. :with_deleted and :only_deleted
# keys do not work in named_scope.
{ :conditions => {'users.deleted_at' => (start_at..end_at)} }
}
Is there any wrong in my code or need any modifications, especially in model scope? Please help.
Problem is with scopes.Eager loading of scopes in Rails 4 has been restricted.
You can change your scope like this :
scope :created_between, -> (start_at, end_at) { where(created_at: (start_at..end_at)) }

Rails What is the best way to generate a json form a large amout of data

I am working on a project that is a backend for a mobile app.
Una of the API calls returns a large amount of data as a json and it takes a lot to genrate the json.
Right now, I am pre processing the data to generate a hash with all the information and the
Places.each do |item|
place = item.place
place.discounts.each do |discount|
response_item = {
:id => place.id,
:latitude => item.latitude,
:longitude => item.longitude,
:name => place.name,
:url_image => place.img,
:stars => 0,
:is_habitue => false,#is_habitue,
:discount => {
:id => discount.id,
:title => discount.title,
:description => discount.description,
:raw_title => discount.raw_title,
:expiration => discount.expiration
}
}
categories = []
place.categories.each do |category|
categories.append ({
:name => category.name,
:label => category.label
})
end
response_item[:categories] = categories
benefits = []
discount.benefits.each do |benefit|
benefits.append ({
:benefit_type => benefit.benefit_type,
:label => benefit.label
})
end
response_item[:benefits] = benefits
processed_places.append response_item
end
end
render :json => {:places=>processed_places}, :status=>200
I takes about 1.4 seconds to process 2700 results but more than 6 seconds to generate the json.
thanks
Maybe you could try RABL. It's got great features :)

Rails splited code not working

I am using rails 2.3. In my application it uses
val = Party.find(:all, :conditions => [" type in ('Physician') || id in (?)",PartyLabel.find(:all,:conditions=>"label_id=#{Label.find_by_label("Can Schedule").id}").collect{|p| p.party_id if Party.find(p.party_id).respond_to?("provider_organizations")}], :with_disabled => true).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
code to achieve some requirements. Now i wants to split the code in to 2 parts.
1. phys = Physician.find(:all, :include => :provider_organizations, :with_disabled => true).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
it's working fine.. and the second part will be
2. sch = Party.find(:all, :include => [:as_labels], :conditions => {:label => {:label => "Can Schedule"}}.respond_to?("provider_organizations")).select{|physician| not physician.provider_organizations.blank? }.collect{|enum| [enum.display_name_schedule, enum.id]}
it shows NoMethodError (undefined method 'provider_organizations' for #<ProviderOrganization:0x1ab81c20>): error message... Any comments could be appreciated..
It looks like respond_to?("provider_organizations") is called for a wrong object. Here is your code #2:
sch = Party.find(
:all,
:include => [:as_labels],
:conditions => {
:label => {
:label => "Can Schedule"
}
}.respond_to?("provider_organizations") # What's this ???
).select{ |physician|
not physician.provider_organizations.blank?
}.collect{ |enum|
[enum.display_name_schedule, enum.id]
}
If I understand it correctly, the respond_to? should be inside the select:
...
).select{ |physician|
physician.respond_to?("provider_organizations") && not physician.provider_organizations.blank?
}.collect{ ...

The amount is invalid paypal_adaptive gem rails

I am receiving this error in my log console:
The amount is invalid
I am working in development env, with http://localhost:3000/
I have in my controller:
def pay
pay_request = PaypalAdaptive::Request.new
data = {
"returnUrl" => user_orders_url(current_user),
"requestEnvelope" => {"errorLanguage" => "en_US"},
"currencyCode" => "USD",
"receiverList" =>
{ "receiver" => [
{"receiver"=> [{"email"=>"email1", "amount"=>"10.00", "primary" => true}, {"email"=>"email2", "amount"=>"9.00", "primary" => false}]}
]},
"cancelUrl" => user_orders_url(current_user),
"actionType" => "PAY",
"ipnNotificationUrl" => ipn_notification_user_orders_url(current_user)
}
pay_response = pay_request.pay(data)
if pay_response.success?
# Send user to paypal
redirect_to pay_response.preapproval_paypal_payment_url
else
puts pay_response.errors.first['message']
redirect_to root_url, alert: "Something went wrong. Please contact support."
end
end
What am I doing bad?
Can you test with
"amount"=>10
Or
"amount"=>"10"
The error was fixed:
The error is in "primary" => true and "primary" => false.
I have removed this code and now the controller does works fine.
Thank you very much!

This transaction is invalid. Please return to the recipient's website and try again

This is my controller:
setup_purchase method does works fine for me with my data api, but preapprove_payment method does not works.
def pay
gateway = ActiveMerchant::Billing::PaypalAdaptivePayment.new(
:login => "email",
:password => "pass",
:signature => "signature",
:appid => "APP-80W284485P519543T" )
response = gateway.preapprove_payment(
:return_url => user_orders_url(current_user),
:cancel_url => user_orders_url(current_user),
:sender_email =>"email",
:start_date => Time.now,
:end_date => Time.now,
:currency_code =>"USD",
:max_amount => "20",
:maxNumberOfPayments => "2")
puts response.preapproval_key
puts gateway.debug
# for redirecting the customer to the actual paypal site to finish the payment.
redirect_to (gateway.redirect_url_for(response["preapproval_key"]))
end
I get in log:
PA-8K9332086D720151L
{:url=>#<URI::HTTPS:0xdf9bd18 URL:https://svcs.sandbox.paypal.com/AdaptivePayments/Preapproval>, :request=>"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<PreapprovalRequest>\n <requestEnvelope>\n <detailLevel>ReturnAll</detailLevel>\n <errorLanguage>en_US</errorLanguage>\n <senderEmail>email</senderEmail>\n </requestEnvelope>\n <endingDate>2012-07-20T19:09:20</endingDate>\n <startingDate>2012-07-20T19:09:20</startingDate>\n <maxTotalAmountOfAllPayments>20</maxTotalAmountOfAllPayments>\n <maxNumberOfPayments>2</maxNumberOfPayments>\n <currencyCode>USD</currencyCode>\n <cancelUrl>http://localhost:3000/en/u/maserranocaceres/orders</cancelUrl>\n <returnUrl>http://localhost:3000/en/u/maserranocaceres/orders</returnUrl>\n</PreapprovalRequest>\n", :response=>"{\"responseEnvelope\":{\"timestamp\":\"2012-07-20T10:09:22.459-07:00\",\"ack\":\"Success\",\"correlationId\":\"ada6a3e7da93d\",\"build\":\"DEV\"},\"preapprovalKey\":\"PA-8K9332086D720151L\"}"}
Full response:
#<ActiveMerchant::Billing::AdaptivePaymentResponse:0xc817278 #json="{\"responseEnvelope\":{\"timestamp\":\"2012-07-23T07:43:56.603-07:00\",\"ack\":\"Success\",\"correlationId\":\"7f759c5da73ad\",\"build\":\"DEV\"},\"preapprovalKey\":\"PA-1M101813XU7801314\"}", #response=#<Hashie::Rash preapproval_key="PA-1M101813XU7801314" response_envelope=#<Hashie::Rash ack="Success" build="DEV" correlation_id="7f759c5da73ad" timestamp="2012-07-23T07:43:56.603-07:00">>, #xml_request="<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<PreapprovalRequest>\n <requestEnvelope>\n <detailLevel>ReturnAll</detailLevel>\n <errorLanguage>en_US</errorLanguage>\n <senderEmail>microf_1342709161_per#gmail.com</senderEmail>\n </requestEnvelope>\n <endingDate>2012-08-22T16:43:54</endingDate>\n <startingDate>2012-07-23T16:43:54</startingDate>\n <maxTotalAmountOfAllPayments>20</maxTotalAmountOfAllPayments>\n <maxNumberOfPayments>1</maxNumberOfPayments>\n <currencyCode>USD</currencyCode>\n <cancelUrl>http://localhost:3000/en/u/maserranocaceres/orders</cancelUrl>\n <returnUrl>http://localhost:3000/en/u/maserranocaceres/orders</returnUrl>\n</PreapprovalRequest>\n", #request={"PreapprovalRequest"=>{"requestEnvelope"=>{"detailLevel"=>"ReturnAll", "errorLanguage"=>"en_US", "senderEmail"=>"email"}, "endingDate"=>"2012-08-22T16:43:54", "startingDate"=>"2012-07-23T16:43:54", "maxTotalAmountOfAllPayments"=>"20", "maxNumberOfPayments"=>"1", "currencyCode"=>"USD", "cancelUrl"=>"http://localhost:3000/en/u/maserranocaceres/orders", "returnUrl"=>"http://localhost:3000/en/u/maserranocaceres/orders"}}, #action="Preapproval">
What am I doing wrong?
The problem was fixed.
Change
gateway.redirect_url_for(response["preapprovalKey"])
to
gateway.redirect_pre_approval_url_for(response["preapprovalKey"])
The correct method is redirect_pre_approval_url_for
You can see the fix in this post:
preapproved payments with paypal in rails 3.2
Thank you very much!

Resources