简体   繁体   中英

Charging through Stripe for iOS

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.

At the point where STPPaymentContext calls didCreatePaymentResult on its delegate, the token has already been created, so there's no need to try to create a second token. I'd have a look at the example iOS backend, which works with the "standard" example application in the Stripe SDK:

https://github.com/stripe/example-ios-backend

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM