use trial with gem paypal-sdk-rest - ruby-on-rails

I have my site in ruby on rails and for subscription payments I am using the paypal paypal-sdk-rest gem. But I need the first payment to have a lower value and then the next payment to have the normal value so that users can subscribe and test the subscription. I have been reading in the paypal api and a trial with a lower value can be applied. Is it possible to apply trial to the paypal gem paypal-sdk-rest? this is my code of how I create the plans:
def creacion_planes
plan = Plan.new({
:name => 'Monthly $20',
:description => '$20 plan (monthly charge)',
:type => 'infinite',
:payment_definitions => [{
:name => 'Plan monthly $20',
:type => 'REGULAR',
:frequency_interval => '1',
:frequency => 'MONTH', #WEEK, DAY, YEAR, MONTH.
:cycles => '0',
:amount => {
:currency => 'USD',
:value => '20.00'
}
}],
:merchant_preferences => {
:return_url => complete_paypal_checkouts_planes_url,
:cancel_url => update_plan_url,
:max_fail_attempts => '0',
:auto_bill_amount => 'YES',
:initial_fail_amount_action => 'CONTINUE'
}
})
# Create plan
if plan.create
# Plan update activation object
plan_update = {
:op => 'replace',
:path => '/',
:value => {
:state => 'ACTIVE'
}
}
# Activate plan
if plan.update(plan_update)
puts("Billing plan activated with ID [#{plan.id}]")
redirect_to success_payment_path(:plan_id => plan.id, :plan => "plan_mensual20")
else
logger.error payment.error.inspect
end
else
logger.error payment.error.inspect
end
end
And this is my code of how I create the agreement:
def create
agreement = Agreement.new({
:name => params[:name],
:description => params[:description],
:start_date => (Time.now + 20*60).utc.iso8601, #'2020-04-26T23:00:04Z' (Time.now + 1.days).utc.iso8601
:plan => {
:id => params[:plan_id]
},
:payer => {
:payment_method => 'paypal'
}
})
if agreement.create
redirect = agreement.links.find{|v| v.rel == "approval_url" }.href
redirect_to redirect
else
logger.error agreement.error.inspect
end
end

Do not use that old paypal-ruby-sdk. It is obsolete and uses an old version of billing plans, which is not compatible with the current subscriptions API.
Instead, integrate the subscriptions API via direct HTTPS calls. Here is the guide: https://developer.paypal.com/docs/subscriptions/
An example with a trial period is provided.

Related

HTTParty Post Some parts JSON encoded, some not

I am trying to send a post request to a separate app where I need to send a matching signature that is not json encoded and the data, which is json encoded. I keep getting errors when I try to do this, so I'm just not understanding how to format it, and I can't find any examples on SO or their documentation (or anywhere else on the web).
signature = create_signature
result = HTTParty.post("weburl.com/file/to/post_to.php",
:body => {[ signature,
:data => { :timestamp => #message.created_at,
:url => company.request_host,
:name => #message.name,
:email => #message.email,
:phone => #message.phone,
:product => #message.service,
:comments => #message.message
}.to_json
]},
:headers => { 'Content-Type' => 'application/x-www-form-urlencoded' },
:verify => false )
The error I'm getting currently is syntax error, unexpected '}', expecting => ]}, ^
I've also tried without the arrays, without the data array, etc.
How do I format this to properly submit this info?
I think you need to move your .to_json to the end of the object.
:body => {[ signature,
:data => { :timestamp => #message.created_at,
:url => company.request_host,
:name => #message.name,
:email => #message.email,
:phone => #message.phone,
:product => #message.service,
:comments => #message.message
}
].to_json},

Strange expectation errors with RSpec

I've tested my controller and have got strange errors like this:
expected: ("376")
got: (376)
Please stub a default value first if message might be received with other args as well.
This is my spec:
it 'should send confirm-email if information is good' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {true}
expect(OrderMailer).to receive_message_chain(:send_finish_notification, :deliver)
patch :save_order, {:id => order.id , :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
And I've got this error in some logically close specs. But some tests passes, like this one:
it 'should not update user data if order errors is not empty' do
sign_in user
allow(Order).to receive(:find).with(order.id.to_s).and_return(order)
allow(order).to receive(:finalize) {order}
allow(order.errors).to receive(:empty?) {false}
expect(User).to_not receive(:update_user_data)
patch :save_order, {:id => order.id, :order => {:street_address => 'Baker street', :apt => '123#', :zip_id => zip.id, :frequency_id => frequency.id, :amount_per_hour => '5',
:extras_ids => '', :phone_number => '3213', :credit_card_number => '4242424242424242', :credit_card_cvv => '777',
:credit_card_expiration => '12/20', :source_information => ''}}
end
to_s or to_i doesn't help. The error line in controller -
#order = Order.find(params[:id]
So what could be in that case ? 'Cause it looks like some specs passes, but similar to them don't. Any suggestions ?

Active Merchant and Authorize.net returning failure in production

I have an app that has some basic ecommerce activity. I tried it with a test authorize.net account, and it works fine. I entered in the APIs for production mode though, and I keep getting redirected to the failure screen when I try to purchase anything. I'm not getting any errors, nothing in the logs on heroku, and I don't even know where to start debugging. I am connecting to Authorize.net successfully, transactions are successful in development mode - I based it heavily off of Ryan Bate's RailsCast episode 145 (http://railscasts.com/episodes/145-integrating-active-merchant), but here are some highlights of my code (since I'm testing ti, I'm forcing it to do 1 cent transactions despite what I order)
in enviroments/production.rb
config.after_initialize do
ActiveMerchant::Billing::Base.mode = :production
::GATEWAY = ActiveMerchant::Billing::AuthorizeNetGateway.new(
:login => "scrubbed",
:password => "scrubbed",
:test => false
)
end
orders_controller.rb
def create
#order = Order.new(params[:order])
#order.cart = current_cart
if #order.save
if #order.purchase
#order.state = 'paid'
#order.save
render :action => "success"
end
else
render :action => "failure"
end
else
redirect_to home_page_path, notice: "The order failed to save"
end
end
def purchase
response = GATEWAY.purchase(1, credit_card, purchase_options)
transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response)
#cart.update_attribute(:purchased_at, Time.now) if response.success?
response.success?
end
order.rb
def purchase
response = GATEWAY.purchase(1, credit_card, purchase_options)
transactions.create!(:action => "purchase", :amount => price_in_cents, :response => response)
#cart.update_attribute(:purchased_at, Time.now) if response.success?
response.success?
end
private
def purchase_options
{
:ip => ip_address,
:billing_address => {
:first_name => first_name,
:last_name => last_name,
:address1 => address_line_1,
:address2 => address_line_2,
:city => city,
:state => billing_state,
:country => "US",
:zip => zip_code,
:phone => phone_number,
:company => company
},
:shipping_address => {
:first_name => sfirst_name,
:last_name => slast_name,
:address1 => saddress_line_1,
:address2 => saddress_line_2,
:city => scity,
:state => sbilling_state,
:country => "US",
:zip => szip_code,
:phone => sphone_number,
:company => scompany
}
}
end
def validate_card
unless credit_card.valid?
credit_card.errors.full_messages.each do |message|
errors.add :base, message
end
end
end
def credit_card
#credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:brand => card_type,
:number => card_number,
:verification_value => card_verification,
:month => card_expires_on.month,
:year => card_expires_on.year,
:first_name => first_name,
:last_name => last_name
)
end
I haven't personally dealt with authorize.net but I have used a similar web service which also required PCI compliance. In my case this meant that I needed a valid SSL certificate for transactions to work in production. In fact, if I remember correctly the transaction was failing in a very similar way and it wasn't obvious that was the cause.
It looks like authorize.net requires some type of security depending on which API you are making use of.
http://developer.authorize.net/integration/
I need to ask just to be sure - Have you done everything to get your merchant account setup with Authorize.net and your Bank for production usage already, and you've coordinated with them to start posting funds to your bank account when the money starts coming in?
If so, check out their developer documentation page here for the difference between test and production transactions
http://developer.authorize.net/guides/AIM/5_TestTrans.html
Transactions that work in test mode should work in production mode when everything is properly configured on the Gateway side. I would contact authorize.net there may be technical or administrative details which need to be finalized for your account to process live transactions.

ActiveMerchant: Buyer Account Balance Doesn't Decrease

I'm using ActiveMerchant gem with Ruby 1.9.3 and Rails 3.1
I already set up a buyer dummy account and a seller dummy account on PayPal using WebPayments Pro. When I run this script and look in my paypal sandbox, my seller account is deposited $10 in funds correctly.
The problem is that when I look at the sandbox for my buyer account, the balance does not decrease. Where is my seller getting the money from?
My code is here:
require "rubygems"
require "active_merchant"
ActiveMerchant::Billing::Base.mode = :test
gateway = ActiveMerchant::Billing::PaypalGateway.new(
:login => "seller_1328509472_biz_api1.gmail.com",
:password => "*******",
:signature => "******"
)
credit_card ||= ActiveMerchant::Billing::CreditCard.new(
:type => "visa",
:number => "4193536536887351",
:verification_value => "123",
:month => 2,
:year => 2017,
:first_name => "TESTING",
:last_name => "BUYER"
)
if credit_card.valid?
response = gateway.authorize(1000, credit_card, :ip => "98.248.144.120", :billing_address => { :name => 'Test User', :company => '', :address1 => '1 Main St', :address2 => '', :city => 'San Jose', :state => 'CA', :zip => '95131'})
if response.success?
gateway.capture(1000, response.authorization)
else
puts "Response Unsuccessful Error: #{response.message}"
end
else
puts "Error: credit card is not valid. #{credit_card.errors.full_messages.join('. ')}"
end
Please help me! I have been stuck on this for ages, and I am very confused.
Because you're specifying a credit card directly, there is no 'account' as such that it takes the funds from.
The API method you're using, DoDirectPayment, charges a credit card directly. It is not connected to a PayPal account, nor does it use the balance of a PayPal account.
If you want to charge a PayPal account rather than a credit card, use PayPal Express Checkout: http://railscasts.com/episodes/146-paypal-express-checkout

RSPEC how to post to a controller? What's wrong with this?

I'm trying to post to my controller in RSPEC, see anything wrong with this? It's failing w/o error:
it "should store create an IncomingMail record" do
lambda {
post 'create', {
"from" => 'XXX',
"to" => 'XXX',
"cc" => 'XXX',
"subject" => 'XXX',
"message_text" => 'XXX',
"message_html" => 'XXX' }
}.should change { IncomingMail.count }.by(1)
end
Updated:
it "should store create an IncomingMail record" do
post :create,
:from => 'xx',
:to => 'xx',
:cc => 'xx',
:subject => 'xx',
:message_text => 'xx',
:message_html => 'xx'
mail = IncomingMail.last(:order => 'created_at desc')
mail.from.should == 'xx'
end
Controller
class IncomingMailsController < ApplicationController
require 'iconv'
#make sure that rails doesn't raise an exception because we have no way of knowing the token
skip_before_filter :verify_authenticity_token
def create
begin
#incoming_mail = IncomingMail.create(
:from => params[:from],
:to => params[:to],
:cc => params[:cc],
:subject => params[:subject],
:message_text => message_text_utf8,
:message_html => message_html_utf8
)
.....
This is how i do it :
Route Example :
post 'train_ability/:ability' => :train_ability, :as => 'train_ability'
Spec :
it "should increase the strength ability by one point and also update the strength_points by one if strength is the trained ability" do
#user.str = 10
#user.str_points = 0
#user.save!
post :train_ability, :ability => 'str'
#user.reload
flash[:error].should be_nil
#user.str_points.should == 1
#user.str.should == 11
end

Resources