简体   繁体   中英

How to get card brand using Stripe and Swift

    STPAPIClient.shared().createToken(withCard: cardParams) { (token, error) in
        if error != nil {
            //fail
        } else if let token = token {
            print(token.card?.brand) //Optional(__C.STPCardBrand)
            print(token.card?.brand.hashValue) //Optional(0)
            print(token.card?.brand.rawValue) //Optional(0)
        }
    }

Does anyone know why Stripe isn't returning the card brand? I'm using a Stripe test card and the rest of the info is getting returned.

So checking the API documentation I found that brand is en enum:

var brand: STPCardBrand { get }

having these values:

typedef NS_ENUM(NSInteger, STPCardBrand) {
    STPCardBrandVisa,
    STPCardBrandAmex,
    STPCardBrandMasterCard,
    STPCardBrandDiscover,
    STPCardBrandJCB,
    STPCardBrandDinersClub,
    STPCardBrandUnknown,
};

You could also consider using the static stringFromBrand function:

Returns a string representation for the provided card brand; ie [NSString stringFromBrand:STPCardBrandVisa] == @"Visa". Declaration

  • (nonnull NSString *)stringFromBrand:(STPCardBrand)brand;

class func string(from brand: STPCardBrand) -> String

Example:

print(STPCard.stringFromBrand(from: token.card?.brand))

Swift 4:

print(STPCard.string(from: token.card!.brand))

@OlegDanu's answer with unwrapping

As he said use STPCard.stringFromBrand(from: token.card?.brand) but card? is an Optional of type STPCard and I didn't realize that and spent some time trying to unwrap it. Anyway it's best to unwrap it first

if let card = token.card { }

Here's the code below

STPAPIClient.shared().createToken(withCard: card, completion: { 
    [weak self] (token, error) in

    if let error = error {
        print(error.localizedDescription)
        return
    }

    guard let token = token else { return }

    // card is an Optional of type STPCard
    if let card = token.card {

       let brand = STPCard.string(from: card.brand)

       print(brand)
    }
})

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