Last active
August 29, 2015 14:21
-
-
Save pedromg/629d8309f4c8c4a39bc9 to your computer and use it in GitHub Desktop.
Stripe Charge for Google AppEngine
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package payment | |
import ( | |
"fmt" | |
"appengine" | |
"appengine/urlfetch" | |
"github.com/stripe/stripe-go" | |
"github.com/stripe/stripe-go/currency" | |
"github.com/stripe/stripe-go/charge" | |
"github.com/stripe/stripe-go/customer" | |
) | |
func chargeViaStripe(context appengine.Context, providerKey, customerId, | |
idempotencyKey string, booking *Booking) (string, bool, string, error) { | |
// set provider key | |
stripe.Key = providerKey | |
// Stripe call via Appengine | |
s := setStripeChargeClient(context, providerKey) | |
// set currency | |
curr, err := getBookingCurrency(booking.Currency) | |
if err != nil { | |
return "", false, "", ErrInvalidCurrency | |
} | |
description := fmt.Sprintf("Charge for Booking %v", booking.Id) | |
args := &stripe.ChargeParams{ | |
Customer: customerId, | |
Amount: uint64(booking.Total * 100), | |
Currency: curr, | |
Desc: description, | |
Email: booking.BookedBy.Email, | |
} | |
args.Params.IdempotencyKey = idempotencyKey | |
// Do not use charge.New(args) since it will use the default http.Client on | |
// the Backend. Use you baked Backend new appengine-context-request-activated | |
// client: s.New(args) | |
ch, err := s.New(args) | |
if err != nil { | |
context.Debugf("# Stripe Charge error for booking: %v: %v", | |
booking.Id, err) | |
return "", false, "", err | |
} | |
// return | |
return ch.ID, ch.Paid, ch.Status, nil | |
} | |
// Set the Stripe Backend http.Client to this specific appengine client context. | |
// On Appengine an http call is tied to the context (urlfetch.Client(context)), | |
// so we need to do this initialization for each call since stripe-go lib was | |
// primarly build to use always the same http.Client settings. The API URL and | |
// version is not exposed outside of the stripe-go package, so we need to add it manually. | |
func setStripeChargeClient(context appengine.Context, key string) *charge.Client { | |
c := &charge.Client{} | |
var b stripe.Backend | |
b = stripe.BackendConfiguration{stripe.APIBackend, "https://api.stripe.com/v1", | |
urlfetch.Client(context)} | |
c.Key = key | |
c.B = b | |
return c | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment