Skip to content
This repository has been archived by the owner on Jan 22, 2021. It is now read-only.

Commit

Permalink
Added better success page
Browse files Browse the repository at this point in the history
  • Loading branch information
adreyfus-stripe committed Nov 19, 2019
1 parent d888c16 commit 50ca174
Show file tree
Hide file tree
Showing 9 changed files with 99 additions and 22 deletions.
19 changes: 16 additions & 3 deletions client/success.html
Expand Up @@ -7,7 +7,6 @@

<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/global.css" />
<script src="/session_ended.js" defer></script>

This comment has been minimized.

Copy link
@Davidmid

Davidmid Nov 21, 2019

client / success . html

</head>

<body>
Expand All @@ -19,10 +18,10 @@
<div class="sr-payment-summary completed-view">
<h1>Your test payment succeeded!</h1>
<h4>
View PaymentIntent response:</a>

This comment has been minimized.

Copy link
@Davidmid

Davidmid Nov 21, 2019

< id - good
< password- good

View CheckoutSession response:</a>
</h4>
</div>
<div class="sr-section hidden completed-view">
<div class="sr-section completed-view">
<div class="sr-callout">
<pre>

Expand Down Expand Up @@ -56,5 +55,19 @@ <h4>
</div>
</div>
</div>
<script>
var urlParams = new URLSearchParams(window.location.search);
var sessionId = urlParams.get("session_id")
if (sessionId) {
fetch("/checkout-session?sessionId=" + sessionId).then(function(result){
return result.json()
}).then(function(session){
var sessionJSON = JSON.stringify(session, null, 2);
document.querySelector("pre").textContent = sessionJSON;
}).catch(function(err){
console.log('Error when fetching Checkout session', err);
});
}
</script>
</body>
</html>
14 changes: 12 additions & 2 deletions server/java/src/main/java/com/stripe/sample/Server.java
Expand Up @@ -42,7 +42,7 @@ public Boolean getIsBuyingSticker() {

public static void main(String[] args) {
port(4242);

Dotenv dotenv = Dotenv.load();

Stripe.apiKey = dotenv.get("STRIPE_SECRET_KEY");
Expand All @@ -58,6 +58,16 @@ public static void main(String[] args) {
return gson.toJson(responseData);
});

// Fetch the Checkout Session to display the JSON result on the success page
get("/checkout-session", (request, response) -> {
response.type("application/json");

String sessionId = request.queryParams("sessionId");
Session session = Session.retrieve(sessionId);

return gson.toJson(session);
});

post("/create-checkout-session", (request, response) -> {
response.type("application/json");
PostBody postBody = gson.fromJson(request.body(), PostBody.class);
Expand All @@ -70,7 +80,7 @@ public static void main(String[] args) {
SubscriptionData.Item plan = new SubscriptionData.Item.Builder().setPlan(planId).build();
SubscriptionData subscriptionData = new SubscriptionData.Builder().addItem(plan).build();

builder.setSuccessUrl(domainUrl + "/success.html").setCancelUrl(domainUrl + "/cancel.html")
builder.setSuccessUrl(domainUrl + "/success.html?session_id={CHECKOUT_SESSION_ID}").setCancelUrl(domainUrl + "/cancel.html")
.setSubscriptionData(subscriptionData).addPaymentMethodType(PaymentMethodType.CARD);

if (postBody.getIsBuyingSticker()) {
Expand Down
15 changes: 10 additions & 5 deletions server/node/server.js
Expand Up @@ -23,6 +23,13 @@ app.get("/", (req, res) => {
res.sendFile(path);
});

// Fetch the Checkout Session to display the JSON result on the success page
app.get("/checkout-session", async (req, res) => {
const { sessionId } = req.query;
const session = await stripe.checkout.sessions.retrieve(sessionId);
res.send(session);
});

app.post("/create-checkout-session", async (req, res) => {
const planId = process.env.SUBSCRIPTION_PLAN_ID;
const domainURL = process.env.DOMAIN;
Expand All @@ -48,7 +55,7 @@ app.post("/create-checkout-session", async (req, res) => {
}
]
},
success_url: `${domainURL}/success.html`,
success_url: `${domainURL}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/cancel.html`
});
} else {
Expand All @@ -62,7 +69,7 @@ app.post("/create-checkout-session", async (req, res) => {
}
]
},
success_url: `${domainURL}/success.html`,
success_url: `${domainURL}/success.html?session_id={CHECKOUT_SESSION_ID}`,
cancel_url: `${domainURL}/cancel.html`
});
}
Expand Down Expand Up @@ -118,9 +125,7 @@ app.post("/webhook", async (req, res) => {
items[0].custom.name === "Pasha e-book"
) {
console.log(
`🔔 Customer is subscribed and bought an e-book! Send the e-book to ${
customer.email
}.`
`🔔 Customer is subscribed and bought an e-book! Send the e-book to ${customer.email}.`
);
} else {
console.log(`🔔 Customer is subscribed but did not buy an e-book.`);
Expand Down
12 changes: 9 additions & 3 deletions server/php-slim/index.php
Expand Up @@ -26,7 +26,6 @@
Stripe::setApiKey(getenv('STRIPE_SECRET_KEY'));
return $next($request, $response);
});


$app->get('/', function (Request $request, Response $response, array $args) {
// Display checkout page
Expand All @@ -38,6 +37,13 @@
return $response->withJson([ 'publicKey' => $pub_key ]);
});

$app->get('/checkout-session', function (Request $request, Response $response, array $args) {
$id = $request->getQueryParams()['sessionId'];
$checkout_session = \Stripe\Checkout\Session::retrieve($id);

return $response->withJson($checkout_session);
});

$app->post('/create-checkout-session', function(Request $request, Response $response, array $args) {
$domain_url = getenv('DOMAIN');
$plan_id = getenv('SUBSCRIPTION_PLAN_ID');
Expand All @@ -46,7 +52,7 @@
if($body->isBuyingSticker) {
// Customer is signing up for a subscription and purchasing the extra e-book
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . '/success.html',
'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . '/cancel.html',
'payment_method_types' => ['card'],
'subscription_data' => [
Expand All @@ -64,7 +70,7 @@
} else {
// Customer is only signing up for a subscription
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . '/success.html',
'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . '/cancel.html',
'payment_method_types' => ['card'],
'subscription_data' => [
Expand Down
9 changes: 9 additions & 0 deletions server/php/public/checkout-session.php
@@ -0,0 +1,9 @@
<?php

require_once 'shared.php';

$id = $_GET["sessionId"];

$checkout_session = \Stripe\Checkout\Session::retrieve($id);

echo json_encode($checkout_session);
4 changes: 2 additions & 2 deletions server/php/public/create-checkout-session.php
Expand Up @@ -8,7 +8,7 @@
if($body->isBuyingSticker) {
// Customer is signing up for a subscription and purchasing the extra e-book
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . '/success.html',
'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . '/cancel.html',
'payment_method_types' => ['card'],
'subscription_data' => [
Expand All @@ -26,7 +26,7 @@
} else {
// Customer is only signing up for a subscription
$checkout_session = \Stripe\Checkout\Session::create([
'success_url' => $domain_url . '/success.html',
'success_url' => $domain_url . '/success.html?session_id={CHECKOUT_SESSION_ID}',
'cancel_url' => $domain_url . '/cancel.html',
'payment_method_types' => ['card'],
'subscription_data' => [
Expand Down
17 changes: 15 additions & 2 deletions server/php/public/success.html
Expand Up @@ -7,7 +7,6 @@

<link rel="stylesheet" href="css/normalize.css" />
<link rel="stylesheet" href="css/global.css" />
<script src="/session_ended.js" defer></script>
</head>

<body>
Expand All @@ -22,7 +21,7 @@ <h4>
View PaymentIntent response:</a>
</h4>
</div>
<div class="sr-section hidden completed-view">
<div class="sr-section completed-view">
<div class="sr-callout">
<pre>

Expand Down Expand Up @@ -56,5 +55,19 @@ <h4>
</div>
</div>
</div>
<script>
var urlParams = new URLSearchParams(window.location.search);
var sessionId = urlParams.get("session_id")
if (sessionId) {
fetch("/checkout-session.php?sessionId=" + sessionId).then(function(result){
return result.json()
}).then(function(session){
var sessionJSON = JSON.stringify(session, null, 2);
document.querySelector("pre").textContent = sessionJSON;
}).catch(function(err){
console.log('Error when fetching Checkout session', err);
});
}
</script>
</body>
</html>
16 changes: 13 additions & 3 deletions server/python/server.py
Expand Up @@ -18,7 +18,8 @@
stripe.api_key = os.getenv('STRIPE_SECRET_KEY')
stripe.api_version = os.getenv('STRIPE_API_VERSION')

static_dir = str(os.path.abspath(os.path.join(__file__ , "..", os.getenv("STATIC_DIR"))))
static_dir = str(os.path.abspath(os.path.join(
__file__, "..", os.getenv("STATIC_DIR"))))
app = Flask(__name__, static_folder=static_dir,
static_url_path="", template_folder=static_dir)

Expand All @@ -32,6 +33,13 @@ def get_example():
def get_publishable_key():
return jsonify({'publicKey': os.getenv('STRIPE_PUBLISHABLE_KEY')})

# Fetch the Checkout Session to display the JSON result on the success page
@app.route('/checkout-session', methods=['GET'])
def get_checkout_session():
id = request.args.get('sessionId')
checkout_session = stripe.checkout.Session.retrieve(id)
return jsonify(checkout_session)


@app.route('/create-checkout-session', methods=['POST'])
def create_checkout_session():
Expand All @@ -43,7 +51,8 @@ def create_checkout_session():
if data['isBuyingSticker']:
# Customer is signing up for a subscription and purchasing the extra e-book
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + "/success.html",
success_url=domain_url +
"/success.html?session_id={CHECKOUT_SESSION_ID}",
cancel_url=domain_url + "/cancel.html",
payment_method_types=["card"],
subscription_data={"items": [{"plan": plan_id}]},
Expand All @@ -59,7 +68,8 @@ def create_checkout_session():
else:
# Customer is only signing up for a subscription
checkout_session = stripe.checkout.Session.create(
success_url=domain_url + "/success.html",
success_url=domain_url +
"/success.html?session_id={CHECKOUT_SESSION_ID}",
cancel_url=domain_url + "/cancel.html",
payment_method_types=["card"],
subscription_data={"items": [{"plan": plan_id}]},
Expand Down
15 changes: 13 additions & 2 deletions server/ruby/server.rb
@@ -1,3 +1,5 @@
# frozen_string_literal: true

require 'stripe'
require 'sinatra'
require 'dotenv'
Expand Down Expand Up @@ -26,7 +28,7 @@ def create_checkout_session(is_buying_sticker, plan_id, domain_url)
checkout_session = if is_buying_sticker
# Customer is signing up for a subscription and purchasing the extra e-book
Stripe::Checkout::Session.create(
success_url: domain_url + '/success.html',
success_url: ENV['DOMAIN'] + '/success.html?session_id={CHECKOUT_SESSION_ID}',
cancel_url: domain_url + '/cancel.html',
payment_method_types: ['card'],
subscription_data: {
Expand All @@ -42,7 +44,7 @@ def create_checkout_session(is_buying_sticker, plan_id, domain_url)
else
# Customer is only signing up for a subscription
Stripe::Checkout::Session.create(
success_url: domain_url + '/success.html',
success_url: ENV['DOMAIN'] + '/success.html?session_id={CHECKOUT_SESSION_ID}',
cancel_url: domain_url + '/cancel.html',
payment_method_types: ['card'],
subscription_data: {
Expand All @@ -63,6 +65,15 @@ def create_checkout_session(is_buying_sticker, plan_id, domain_url)
}.to_json
end

# Fetch the Checkout Session to display the JSON result on the success page
get '/checkout-session' do
content_type 'application/json'
session_id = params[:sessionId]

session = Stripe::Checkout::Session.retrieve(session_id)
session.to_json
end

post '/webhook' do
# You can use webhooks to receive information about asynchronous payment events.
# For more about our webhook events check out https://stripe.com/docs/webhooks.
Expand Down

0 comments on commit 50ca174

Please sign in to comment.