Skip to content

Authorize Many Users Dynamically

DragonStarWebDesign edited this page May 26, 2012 · 5 revisions

Authorize Users dynamically and enable multiple users to connect their WePay account with your app. Assuming you've set up wepay.yml to your needs, set up a controller action to redirect the user to WePay with your custom redirect_uri. For example:

# app/controllers/users_controller.rb
...

def wepay_connect
  @user = User.find(params[:id])
  wepay_gateway = WepayRails::Payments::Gateway.new
  redirect_to wepay_gateway.auth_code_url(user_wepay_auth_url @user, only_path: false)
end

This will redirect the user to WePay for authentication. Once they log in or create an account, they will be redirected to user_wepay_auth_url(@user, only_path: false). Call get_access_token on a WepayRails::Payments::Gateway object to authorize a user and return the access token. Following the above example, the action could look like this:

# app/controllers/users_controller.rb
...

def wepay_auth
  if params[:code].present?
    wepay_gateway = WepayRails::Payments::Gateway.new
    access_token = wepay_gateway.get_access_token(params[:code], user_wepay_auth_url(@user, only_path:     false) )
    if @user.update_attributes(wepay_token: access_token, wepay_id: wepay_gateway.account_id)
      flash[:success] = "Your WePay account is now connected!  You're ready to start receiving payments!"
    end
  else
    flash[:notice] = "Your WePay account was not connected."
    redirect_to root_path

In the above example, wepay_gateway is an instance of WepayRails::Payments::Gateway which has two attr_accessor methods: :access_token and :account_id. Calling get_access_token with a valid access key in the params hash will return the :access_toekn attribute, and also set the :account_id attribute to the user's WePay user id.

With a valid access_token and account_id, you are now able to dynamically create accounts for users of your application and accept payments. A User model might have the following code:

# app/models/user.rb
...

before_create :create-wepay_account

private

  def create_wepay_account
    wepay_gateway = WepayRails::Payments::Gateway.new(self.user.wepay_token)
    response = wepay_gateway.create_account({
      name: "New User Acocunt",
      description: "This account will collect payments on behalf of my app.,
      reference_id: self.id, # optional, leave blank for WePay to generate a reference_id for you
      image_uri: "http://www.example.com/assets/account-graphic.png"
    })
    if response["error"].present?
      self.errors.add(:base, "#{response['error'].titleize}: #{response['error_description']}")
      return false 
    else
      self.wepay_account_id = response["account_id"]
      self.save
    end
  end

In the above code, response is a hash of the JSON response returned by WePay. You can see possible options and responses on WePay's website: https://www.wepay.com/developer/reference

Clone this wiki locally