Skip to content

Instantly share code, notes, and snippets.

@thorwebdev
Last active May 15, 2016 17:38
Show Gist options
  • Save thorwebdev/02ee764d8bdee93d1f69b723dc1a8112 to your computer and use it in GitHub Desktop.
Save thorwebdev/02ee764d8bdee93d1f69b723dc1a8112 to your computer and use it in GitHub Desktop.
Advanced Stripe Integration Training: Customers + Subscriptions
require 'sinatra'
require 'sinatra/reloader' if development?
require "stripe"
Stripe.api_key = "sk_test_***"
get '/' do
# Output index.erb template to user
erb :index
end
get '/customers' do
# Get a list of ten customers
customers = Stripe::Customer.all(:limit => 10)
# Store customer list in an instance variable
@c = customers.data
#Output customers.erb template to user
erb :customers
end
get '/customer/:cid' do
# Output params hash in bash
puts params.inspect
# Retrieve customer ID from params hash
cid = params[:cid]
# Retrieve customer object from Stripe API
# Store customer object in an instance variable
@customer = Stripe::Customer.retrieve(cid)
# Show customer.erb template to user
erb :customer
end
post '/charge' do
# Output the params hash with the values from Checkout in the bash
puts params.inspect
# Store Stripe Token and Customer Email Address in local variables
token = params[:stripeToken]
email = params[:stripeEmail]
# Create a new Customer
# Store the Response in a local variable
customer = Stripe::Customer.create(
:source => token,
:email => email,
:description => "Ruby customer"
)
# Charge the Customer instead of the card
Stripe::Charge.create(
:amount => 2000, # in cents
:currency => "eur",
:customer => customer.id
)
# Output the Customer ID to the user
"Successfully created customer with ID: #{customer.id}"
end
<h1><%= @customer.email %> // <%= @customer.id %></h1>
<h2># Subscriptions: <%= @customer.subscriptions.total_count %></h2>
<ol>
<% @customer.subscriptions.each do |sub| %>
<li><%= sub.plan.name %></li>
<%end%>
</ol>
<table>
<% @c.each do |customer| %>
<tr>
<td><%= customer.id %><td>
<td><%= customer.email %></td>
<td><a href="../customer/<%= customer.id %>">Subscriptions [<%= customer.subscriptions.total_count %>] </a></td>
</tr>
<% end %>
</table>
<form action="/charge" method="POST">
<script
src="https://checkout.stripe.com/checkout.js" class="stripe-button"
data-key="pk_test_****"
data-amount="2000"
data-name="schaeffonline.de"
data-description="2 widgets"
data-image="https://cdn.shopify.com/s/files/1/0302/2969/products/great-cookie-m_and_m-cookie-03_1024x1024.jpg"
data-locale="auto"
data-zip-code="true"
data-currency="eur">
</script>
</form>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment