Charging through Stripe for iOS

Viewed 606

I'm having trouble charging a user through Stripe. The paymentResult object I receive in the following delegate method

func paymentContext(_ paymentContext: STPPaymentContext, didCreatePaymentResult paymentResult: STPPaymentResult, completion: @escaping STPErrorBlock) {

}

is a STPCard object, but according the documentation to complete a charge with my backend I need an STPToken. I've tried using

STPAPIClient.shared().createToken(withCard: card) {}

to create a STPToken with the STPCard object I received, but I get an error saying the card parameter doesn't have the required variable 'number'. Does anyone know what may be going on or if there is a way to complete a charge with just the STPCard object? Thank you.

2 Answers

If you use stripe id from card instead of token, you need to include customer object, see How to use Stripe and Apple Pay in iOS

Here's how to handle that in Go

package main

import (
    "net"
    "encoding/json"
    "fmt"
    "net/http"
    "log"
    "os"
    "github.com/stripe/stripe-go/charge"
)

func main() {
    stripe.Key = "sk_test_mM2MkqO61n7vvbVRfeYmBgWm00Si2PtWab"

    http.HandleFunc("/request_charge", handleCharge)
    if err := http.ListenAndServe(":8080", nil); err != nil {
        panic(err)
    }
}

var customerId = "cus_Eys6aeP5xR89ab"

type PaymentResult struct {
    StripeId string `json:"stripe_id"`
}

func handleCharge(w http.ResponseWriter, r *http.Request) {
    decoder := json.NewDecoder(r.Body)
    var t PaymentResult
    err := decoder.Decode(&t)
    if err != nil {
        panic(err)
    }

    params := &stripe.ChargeParams{
        Amount:      stripe.Int64(150),
        Currency:    stripe.String(string(stripe.CurrencyUSD)),
        Description: stripe.String("Charge from my Go backend"),
        Customer: stripe.String(customerId),
    }

    params.SetSource(t.StripeId)
    ch, err := charge.New(params)
    if err != nil {
        fmt.Fprintf(w, "Could not process payment: %v", err)
        fmt.Println(ch)
        w.WriteHeader(400)
    }

    w.WriteHeader(200)
}
Related