Integrate Stripe Connect in Ruby
- Include the Stripe gem in your Ruby application by adding it to your Gemfile:
gem 'stripe'
- Install the gem using bundler:
bundle install
- Require the Stripe library in your application code:
require 'stripe'
Configure Stripe
Create Connected Accounts
- To create a connected account for a user on your platform, use the following code example. This process involves redirecting the user to Stripe's onboarding form:
account = Stripe::Account.create({
type: 'express'
business_type: 'individual',
country: 'US',
})
- Generate an account link to redirect the user for onboarding:
account_link = Stripe::AccountLink.create({
account: account.id,
refresh_url: 'https://example.com/reauth',
return_url: 'https://example.com/return',
type: 'account_onboarding',
})
- Redirect the user to `account_link.url` for completing their Stripe account setup.
Handle Marketplace Charges
- Use Stripe's built-in features to charge a customer and transfer funds to the connected account:
charge = Stripe::Charge.create({
amount: 1000,
currency: 'usd',
customer: 'cus_xxx',
transfer_data: {
destination: 'acct_xxx',
},
})
- To handle marketplace fees, use the `application_fee_amount` attribute:
charge = Stripe::Charge.create({
amount: 1000,
currency: 'usd',
customer: 'cus_xxx',
transfer_data: {
destination: 'acct_xxx',
},
application_fee_amount: 123,
})
Use Webhooks for Payment Events
- Implement webhooks to listen for events related to your Stripe account and connected accounts.
- Set up a webhook endpoint in your Stripe dashboard and handle the events in your application code. This helps in processing successful transfers, payments, and more:
webhook_secret = 'whsec_xxx'
payload = request.body.read
sig_header = request.env['HTTP_STRIPE_SIGNATURE']
event = nil
begin
event = Stripe::Webhook.construct_event(
payload, sig_header, webhook_secret
)
rescue JSON::ParserError => e
status 400
return
rescue Stripe::SignatureVerificationError => e
status 400
return
end
case event.type
when 'charge.succeeded'
charge = event.data.object
# Handle successful charge
when 'account.updated'
account = event.data.object
# Handle account updates
end
Testing Your Stripe Integration
- Use Stripe's test mode to experiment with API endpoints, webhooks, and transactions without affecting real funds.
- Utilize Stripe's test card numbers and accounts for simulating various scenarios, such as successful payments or declined card transactions.
Additional Resources
- Refer to the [Stripe Connect documentation](https://stripe.com/docs/connect) for comprehensive details on implementing different features.
- Utilize the Ruby SDK's documentation for further customization and advanced use-cases.