Stripe Integration - Dynamically adding attr value in to the hidden_field

元气小坏坏 提交于 2020-01-05 10:26:10

问题


I'm working on integrating Stripe with my Rails project, and have it working to the point where when a new user signs up they are added as a customer in Stripe. I'm having some problems sending the plan_id to them, however.

The URL of the sign up form includes the plan_id as a parameter depending on which plan is selected from the pricing table, for example:

http://localhost:3000/users/sign_up?plan_id=1

The sign up form includes the following hidden field, which should pass the plan_id to Stripe:

<%= f.hidden_field :plan_id, value:  params[:plan_id] %>

The following code is in the user.rb model, to create the new Stripe customer:

after_create :save_with_payment

def save_with_payment
    if valid?
      customer = Stripe::Customer.create(description: email, plan: plan_id, card:    stripe_card_token)
      self.stripe_customer_token = customer.id
      save!
    end
end

The following code is in the User controller:

def create
  @user = User.new(params[:user])
  if @user.save_with_payment
    redirect_to @user, :notice => "Thank you for subscribing!"
  else
    render :new
  end
end

When I submit the sign up form, the new user is created and seen in Stripe. The issue is that the plan_id value is not being passed to Stripe, so the customer is not being associated with a plan. In addition, the value of plan_id is not being saved under that user in the database.

When asking this question earlier, I was told the solution would be to dynamically add an attr value into the hidden_field. I'm not certain how I could go about doing that, but I'd expect to need to modify the coffeescript that validates the form's cc info:

$(document).on 'ready page:load',  ->
  user.setupForm()
  Stripe.setPublishableKey($('meta[name="stripe-key"]').attr('content'))
  return

user =
  setupForm: ->

    $('form#new_user').on "submit", (event) ->
      $('input[type=submit]').attr('disabled', true)
      user.processCard()
      event.preventDefault()

  processCard: ->
    card =
      number: $('#card_number').val()
      cvc: $('#card_code').val()
      expMonth: $('#date_month').val()
      expYear: $('#date_year').val()

    Stripe.createToken(card, user.handleStripeResponse)

  handleStripeResponse: (status, response) ->
    if status == 200
      $('#user_stripe_card_token').val(response.id)
      $('#new_user')[0].submit()
    else
      $('#stripe_error').text(response.error.message)
      $('input[type=submit]').attr('disabled', false)

来源:https://stackoverflow.com/questions/27449180/stripe-integration-dynamically-adding-attr-value-in-to-the-hidden-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!