Рекуррентные платежи Paypal Active Merchant

Я использую гем Active Merchant для обработки платежей через сайт. Но теперь я хочу, чтобы эти платежи повторялись ежемесячно. Есть ли способ использовать активного мерчанта или?

подписка_controller.rb

    class SubscriptionsController < ApplicationController
  def new
    @home_page = true
    @white = true
    @subscription = Subscription.new(token: params[:token])
    if !logged_in?
      redirect_to signup_url
    end
  end

  def create
    @subscription = Subscription.new(subscription_params)
    @subscription.remote_ip = request.remote_ip
    @subscription.user_id = current_user.id
    if @subscription.save
      if @subscription.purchase
        @subscription.send_thank_you_email
        redirect_to thankyou_path
      else
        raise ActiveRecord::Rollback
        flash[:notice] = "It seems something went wrong with the paypal transaction. Please check that your credit card is valid and has credit in it and try again."
        redirect_to :back
      end
    else
      flash[:notice] = "Something went wrong with marking your purchase as complete. Please contact support to check it out."
      redirect_to :back
    end
  end

  def purchase
    response = GATEWAY.setup_purchase(999,
      ip: request.remote_ip,
      return_url: new_subscription_url,
      cancel_return_url: root_url,
      currency: "USD",
      items: [{name: "Order", description: "Recurring payment for ******", quantity: "1", amount: 999}]
    )
    redirect_to GATEWAY.redirect_url_for(response.token)
  end

  def thank_you
    @home_page = true
    @white = true
  end

  private

    def subscription_params
      params.require(:subscription).permit(:token)
    end


end

модель подписки.rb

def purchase
    response = GATEWAY.purchase(999, express_purchase_options)
    response.success?
  end

  def token=(token)
    self[:token] = token
    if new_record? && !token.blank?
      # you can dump details var if you need more info from buyer
      details = GATEWAY.details_for(token)
      puts details.params["PayerInfo"]["PayerName"].inspect
      self.payer_id = details.payer_id
      self.first_name = details.params["PayerInfo"]["PayerName"]["FirstName"]
      self.last_name = details.params["PayerInfo"]["PayerName"]["LastName"]
    end
  end

  # send thank you email
  def send_thank_you_email
    UserMailer.thank_you(self).deliver_now
  end

  private

  def express_purchase_options
    {
      :ip => remote_ip,
      :token => token,
      :payer_id => payer_id
    }
  end

среда production.rb

config.after_initialize do
    ActiveMerchant::Billing::Base.mode = :production
    ::GATEWAY = ActiveMerchant::Billing::PaypalExpressGateway.new(
      :login => ENV['PAYPAL_LOGIN'],
      :password => ENV['PAYPAL_PASSWORD'],
      :signature => ENV['PAYPAL_SIGNATURE']
    )
  end

person Petros Kyriakou    schedule 10.04.2016    source источник


Ответы (1)


Я думаю, что у ActiveMerchant было что-то вроде этого:

    subscription = PAYPAL_EXPRESS_GATEWAY.recurring(@subscription.price_in_cents, nil, 
        :description => 'blah',
        :start_date => Date.tomorrow, 
        :period => 'Year',
        :frequency => 1,
        :amount => price,
        :currency => 'USD'
    )

См. этот ответ Поддерживает ли ActiveMerchant транзакцию на основе подписки

Также см. это: https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal_express.rb

https://github.com/activemerchant/active_merchant/blob/master/lib/active_merchant/billing/gateways/paypal/paypal_recurring_api.rb

person Nick M    schedule 10.04.2016
comment
но как мне его использовать? где мне это реализовать в моем случае? - person Petros Kyriakou; 10.04.2016
comment
Кажется, вы можете создать действие в одном из ваших контроллеров, потребовать ActiveMerchant, а затем создать запрос с информацией о вашем продукте. - person Nick M; 10.04.2016
comment
после исследования я думаю, что повторение PayPal устарело. Таким образом, теперь я реализовал гем paypal_recurring, который отлично справляется со своей задачей. - person Petros Kyriakou; 10.04.2016
comment
Подробнее об отказе от регулярного выставления счетов в ActiveMerchant: github.com/activemerchant/active_merchant/pull/1178 - person Eliot Sykes; 05.05.2017