From 87a8b0b38607298b1f9ae1772f82173a1e0bd0e5 Mon Sep 17 00:00:00 2001 From: Yuki Date: Mon, 15 Mar 2021 16:55:56 -0700 Subject: [PATCH] Add decline code to userInfo of STPError (#112) --- Stripe/STPError.swift | 8 ++++++++ Tests/Tests/StripeErrorTest.swift | 20 ++++++++++++++++++++ 2 files changed, 28 insertions(+) diff --git a/Stripe/STPError.swift b/Stripe/STPError.swift index 4948e0c085..bd6cc005cb 100644 --- a/Stripe/STPError.swift +++ b/Stripe/STPError.swift @@ -48,6 +48,10 @@ public class STPError: NSObject { /// The error type returned by the Stripe API. /// - seealso: https://stripe.com/docs/api#errors-type @objc public static let stripeErrorTypeKey = "com.stripe.lib:StripeErrorTypeKey" + /// If the value of `userInfo[stripeErrorCodeKey]` is `STPError.cardDeclined`, + /// the value for this key contains the decline code. + /// - seealso: https://stripe.com/docs/declines/codes + @objc public static let stripeDeclineCodeKey = "com.stripe.lib:DeclineCodeKey" /// The card number is not a valid credit card number. @objc public static let invalidNumber = STPCardErrorCode.invalidNumber.rawValue @@ -186,6 +190,10 @@ public enum STPCardErrorCode: String { let cardErrorCode = codeMapEntry?["code"] let localizedMessage = codeMapEntry?["message"] if let cardErrorCode = cardErrorCode { + if cardErrorCode == STPCardErrorCode.cardDeclined.rawValue, + let decline_code = errorDictionary["decline_code"] { + userInfo[STPError.stripeDeclineCodeKey] = decline_code + } userInfo[STPError.cardErrorCodeKey] = cardErrorCode } if localizedMessage != nil { diff --git a/Tests/Tests/StripeErrorTest.swift b/Tests/Tests/StripeErrorTest.swift index 1b07861a9b..35c0988110 100644 --- a/Tests/Tests/StripeErrorTest.swift +++ b/Tests/Tests/StripeErrorTest.swift @@ -123,4 +123,24 @@ class StripeErrorTest: XCTestCase { XCTAssertEqual( error.userInfo[STPError.errorMessageKey] as? String, response["error"]!["message"]) } + + func testCardDeclinedError() { + let response = [ + "error": [ + "type": "card_error", + "message": "Your card has insufficient funds.", + "code": "card_declined", + "decline_code": "insufficient_funds", + ] + ] + guard let error = NSError.stp_error(fromStripeResponse: response) else { + XCTFail() + return + } + XCTAssertEqual(error.domain, STPError.stripeDomain) + XCTAssertEqual(error.code, STPErrorCode.cardError.rawValue) + XCTAssertEqual(error.userInfo[STPError.cardErrorCodeKey] as? String, STPCardErrorCode.cardDeclined.rawValue) + XCTAssertEqual(error.userInfo[NSLocalizedDescriptionKey] as? String, NSError.stp_cardErrorDeclinedUserMessage()) + XCTAssertEqual(error.userInfo[STPError.stripeDeclineCodeKey] as? String, "insufficient_funds") + } }