Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for creating a Checkout Session via the CLI #203

Merged
merged 2 commits into from
Sep 27, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions pkg/cmd/trigger.go
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ func newTriggerCmd() *triggerCmd {
"charge.failed",
"charge.refunded",
"charge.succeeded",
"checkout.session.completed",
"customer.created",
"customer.deleted",
"customer.updated",
Expand Down Expand Up @@ -61,6 +62,7 @@ needed to create the triggered event.
charge.failed
charge.refunded
charge.succeeded
checkout.session.completed
customer.created
customer.deleted
customer.updated
Expand Down Expand Up @@ -124,6 +126,7 @@ func (tc *triggerCmd) runTriggerCmd(cmd *cobra.Command, args []string) error {
"charge.failed": examples.ChargeFailed,
"charge.refunded": examples.ChargeRefunded,
"charge.succeeded": examples.ChargeSucceeded,
"checkout.session.completed": examples.CheckoutSessionCompleted,
"customer.created": examples.CustomerCreated,
"customer.deleted": examples.CustomerDeleted,
"customer.updated": examples.CustomerUpdated,
Expand Down
68 changes: 68 additions & 0 deletions pkg/requests/examples.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package requests

import (
"encoding/json"
"errors"
"fmt"
"net/http"
"regexp"
Expand Down Expand Up @@ -66,6 +67,7 @@ func (ex *Examples) performStripeRequest(req *Base, endpoint string, params *Req
if err != nil {
return nil, err
}

return parseResponse(resp)
}

Expand Down Expand Up @@ -140,6 +142,63 @@ func (ex *Examples) ChargeSucceeded() error {
return err
}

// CheckoutSessionCompleted creates a checkout session
// https://stripe.com/docs/api/checkout/sessions/create?lang=curl
func (ex *Examples) CheckoutSessionCompleted() error {
req, params := ex.buildRequest(http.MethodPost, []string{
"success_url=https://httpbin.org/post",
"cancel_url=https://httpbin.org/post",
"payment_method_types[]=card",
"line_items[][name]=T-shirt",
"line_items[][description]=Comfortable cotton t-shirt",
"line_items[][amount]=1500",
"line_items[][currency]=usd",
"line_items[][quantity]=2",
})

paymentSession, err := ex.performStripeRequest(req, "/v1/checkout/sessions", params)
if err != nil {
return err
}

sessID, ok := paymentSession["id"]
if !ok {
return errors.New("Unable to retrieve PaymentSession ID")
}

// Undocumented API GET /v1/payment_pages
req, params = ex.buildRequest(http.MethodGet, []string{
fmt.Sprintf("session_id=%s", sessID),
})

paymentPage, err := ex.performStripeRequest(req, "/v1/payment_pages", params)
if err != nil {
return err
}

paymentPageID, ok := paymentPage["id"]
if !ok {
return errors.New("Unable to retrieve PaymentPage ID")
}

paymentMethod, err := ex.paymentMethodCreatedWithToken(validToken)
if err != nil {
return err
}

pmID, ok := paymentMethod["id"]
if !ok {
return errors.New("Unable to retrieve PaymentMethod ID")
}

// Undocumented API POST /v1/payment_pages/<ID>/confirm
req, params = ex.buildRequest(http.MethodPost, []string{
fmt.Sprintf("payment_method=%s", pmID),
})
_, err = ex.performStripeRequest(req, fmt.Sprintf("/v1/payment_pages/%s/confirm", paymentPageID), params)
return err
}

func (ex *Examples) customerCreated(data []string) (map[string]interface{}, error) {
req, params := ex.buildRequest(http.MethodPost, data)
return ex.performStripeRequest(req, "/v1/customers", params)
Expand Down Expand Up @@ -524,6 +583,15 @@ func (ex *Examples) paymentMethodCreated(card string) (map[string]interface{}, e
return ex.performStripeRequest(req, "/v1/payment_methods", params)
}

func (ex *Examples) paymentMethodCreatedWithToken(token string) (map[string]interface{}, error) {
req, params := ex.buildRequest(http.MethodPost, []string{
"type=card",
fmt.Sprintf("card[token]=%s", token),
"billing_details[email]=stripe@example.com",
})
return ex.performStripeRequest(req, "/v1/payment_methods", params)
}

// PaymentMethodAttached creates a customer and payment method,
// then attaches the customer to the payment method
func (ex *Examples) PaymentMethodAttached() error {
Expand Down
61 changes: 61 additions & 0 deletions pkg/requests/examples_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -382,3 +383,63 @@ func TestResendEventDoesNotErrorWithValidEventID(t *testing.T) {
t.Log(err)
require.Nil(t, err)
}

func TestSessionCompleted(t *testing.T) {
i := 0
ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
switch i {
case 0: // /v1/checkout/sessions
i++
w.WriteHeader(http.StatusOK)
data := jsonBytes()
w.Write(data)
case 1: // /v1/payment_pages
i++
q := r.URL.Query()
require.EqualValues(t, "test-id", q.Get("session_id"))

w.WriteHeader(http.StatusOK)
data := jsonBytes()
w.Write(data)
case 2: // /v1/payment_methods
i++
body, err := ioutil.ReadAll(r.Body)
require.Nil(t, err)

require.NotEmpty(t, body)
require.EqualValues(t, "type=card&card[token]=tok_visa&billing_details[email]=stripe%40example.com", string(body))

w.WriteHeader(http.StatusOK)
data := jsonBytes()
w.Write(data)
case 3: // /v1/payment_pages/<ID>/confirm
i++
path := r.URL.EscapedPath()
t.Log(path)
require.True(t, strings.Contains(path, "test-id"))

body, err := ioutil.ReadAll(r.Body)
require.Nil(t, err)

require.NotEmpty(t, body)
require.EqualValues(t, "payment_method=test-id", string(body))

w.WriteHeader(http.StatusOK)
data := jsonBytes()
w.Write(data)
default:
w.WriteHeader(http.StatusOK)
}
}))
defer ts.Close()

ex := Examples{
APIBaseURL: ts.URL,
APIVersion: "v1",
APIKey: "secret-key",
}

err := ex.CheckoutSessionCompleted()
t.Log(err)
require.Nil(t, err)
}