From 116982a2e913a9f1f21c6aa39c1277dd003e5671 Mon Sep 17 00:00:00 2001 From: Jenkins 2 Date: Mon, 14 Sep 2020 18:09:32 +1000 Subject: [PATCH] Removed Visacheckout --- .../Core/Models/VisaCheckoutLaunchParams.h | 20 - .../Core/Models/VisaCheckoutLaunchParams.m | 29 - BNPayment/Core/Models/VisaCheckoutResponse.h | 19 - BNPayment/Core/Models/VisaCheckoutResponse.m | 24 - .../Models/VisaCheckoutTransactionParams.h | 10 - .../Models/VisaCheckoutTransactionParams.m | 14 - .../Network/Endpoints/VisaCheckoutEndpoint.h | 19 - .../Network/Endpoints/VisaCheckoutEndpoint.m | 44 -- .../BNPayment-Example/APPaymentRequest.swift | 42 -- .../BNPayment-Example/APPaymentResponse.swift | 51 -- Example/BNPayment-Example/APProcessor.swift | 240 ------- .../APRESTPaymentResponse.swift | 70 -- .../APRecurringPayment.swift | 31 - Example/BNPayment-Example/APmodels.swift | 36 - Example/BNPayment-Example/AppDelegate.h | 16 - Example/BNPayment-Example/AppDelegate.m | 85 --- Example/BNPayment-Example/AppSettings.h | 92 --- Example/BNPayment-Example/AppSettings.m | 521 -------------- Example/BNPayment-Example/ApplePaySDK.h | 19 - Example/BNPayment-Example/BNColor.swift | 27 - .../BNPayment-Example-Bridging-Header.h | 8 - .../CardsTableViewCell.swift | 96 --- .../CardsViewController.swift | 437 ------------ Example/BNPayment-Example/Compatibility.h | 47 -- .../CustomDataViewController.swift | 116 ---- .../DeveloperViewController.swift | 348 ---------- .../OHHTTPStubsResponse+HTTPMessage.h | 78 --- .../OHHTTPStubsResponse+HTTPMessage.m | 76 --- .../JSON/OHHTTPStubsResponse+JSON.h | 57 -- .../JSON/OHHTTPStubsResponse+JSON.m | 48 -- .../Mocktail/OHHTTPStubs+Mocktail.h | 100 --- .../Mocktail/OHHTTPStubs+Mocktail.m | 260 ------- .../MyDetailsViewController.swift | 35 - .../NSURLRequest+HTTPBodyTesting.h | 48 -- .../NSURLRequest+HTTPBodyTesting.m | 86 --- .../OHHTTPStubs+NSURLSessionConfiguration.m | 78 --- .../NSURLSession/OHHTTPStubsMethodSwizzling.h | 51 -- .../NSURLSession/OHHTTPStubsMethodSwizzling.m | 47 -- Example/BNPayment-Example/OHHTTPStubs.h | 219 ------ Example/BNPayment-Example/OHHTTPStubs.m | 637 ------------------ .../BNPayment-Example/OHHTTPStubsResponse.h | 301 --------- .../BNPayment-Example/OHHTTPStubsResponse.m | 220 ------ .../OHPathHelpers/OHPathHelpers.h | 87 --- .../OHPathHelpers/OHPathHelpers.m | 52 -- .../ProductsViewController.swift | 66 -- Example/BNPayment-Example/TODO | 2 - .../TestData/VisaCheckoutParams.json | 14 - .../TestData/VisaCheckoutTransaction.json | 19 - Example/BNPayment-Example/ViewController.h | 14 - Example/BNPayment-Example/ViewController.m | 244 ------- Example/BNPayment-Example/main.m | 16 - 51 files changed, 5316 deletions(-) delete mode 100644 BNPayment/Core/Models/VisaCheckoutLaunchParams.h delete mode 100644 BNPayment/Core/Models/VisaCheckoutLaunchParams.m delete mode 100644 BNPayment/Core/Models/VisaCheckoutResponse.h delete mode 100644 BNPayment/Core/Models/VisaCheckoutResponse.m delete mode 100644 BNPayment/Core/Models/VisaCheckoutTransactionParams.h delete mode 100644 BNPayment/Core/Models/VisaCheckoutTransactionParams.m delete mode 100644 BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.h delete mode 100644 BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.m delete mode 100644 Example/BNPayment-Example/APPaymentRequest.swift delete mode 100644 Example/BNPayment-Example/APPaymentResponse.swift delete mode 100644 Example/BNPayment-Example/APProcessor.swift delete mode 100644 Example/BNPayment-Example/APRESTPaymentResponse.swift delete mode 100644 Example/BNPayment-Example/APRecurringPayment.swift delete mode 100644 Example/BNPayment-Example/APmodels.swift delete mode 100644 Example/BNPayment-Example/AppDelegate.h delete mode 100644 Example/BNPayment-Example/AppDelegate.m delete mode 100755 Example/BNPayment-Example/AppSettings.h delete mode 100755 Example/BNPayment-Example/AppSettings.m delete mode 100644 Example/BNPayment-Example/ApplePaySDK.h delete mode 100644 Example/BNPayment-Example/BNColor.swift delete mode 100644 Example/BNPayment-Example/BNPayment-Example-Bridging-Header.h delete mode 100644 Example/BNPayment-Example/CardsTableViewCell.swift delete mode 100644 Example/BNPayment-Example/CardsViewController.swift delete mode 100755 Example/BNPayment-Example/Compatibility.h delete mode 100644 Example/BNPayment-Example/CustomDataViewController.swift delete mode 100644 Example/BNPayment-Example/DeveloperViewController.swift delete mode 100755 Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.h delete mode 100755 Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.m delete mode 100755 Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.h delete mode 100755 Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.m delete mode 100755 Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.h delete mode 100755 Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.m delete mode 100644 Example/BNPayment-Example/MyDetailsViewController.swift delete mode 100755 Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.h delete mode 100755 Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.m delete mode 100755 Example/BNPayment-Example/NSURLSession/OHHTTPStubs+NSURLSessionConfiguration.m delete mode 100755 Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.h delete mode 100755 Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.m delete mode 100755 Example/BNPayment-Example/OHHTTPStubs.h delete mode 100755 Example/BNPayment-Example/OHHTTPStubs.m delete mode 100755 Example/BNPayment-Example/OHHTTPStubsResponse.h delete mode 100755 Example/BNPayment-Example/OHHTTPStubsResponse.m delete mode 100755 Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.h delete mode 100755 Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.m delete mode 100644 Example/BNPayment-Example/ProductsViewController.swift delete mode 100644 Example/BNPayment-Example/TODO delete mode 100644 Example/BNPayment-Example/TestData/VisaCheckoutParams.json delete mode 100644 Example/BNPayment-Example/TestData/VisaCheckoutTransaction.json delete mode 100644 Example/BNPayment-Example/ViewController.h delete mode 100644 Example/BNPayment-Example/ViewController.m delete mode 100644 Example/BNPayment-Example/main.m diff --git a/BNPayment/Core/Models/VisaCheckoutLaunchParams.h b/BNPayment/Core/Models/VisaCheckoutLaunchParams.h deleted file mode 100644 index 810529b..0000000 --- a/BNPayment/Core/Models/VisaCheckoutLaunchParams.h +++ /dev/null @@ -1,20 +0,0 @@ -#import "BNBaseModel.h" - -@interface VisaCheckoutLaunchParams : BNBaseModel - -@property (nonatomic, strong) NSString *apikey; -@property (nonatomic, strong) NSString *currencyCode; -@property (nonatomic, strong) NSString *subtotal; -@property (nonatomic, strong) NSString *externalClientId; -@property (nonatomic, strong) NSString *externalProfileId; -@property (nonatomic, strong) NSString *total; -@property (nonatomic, strong) NSString *locale; -@property (nonatomic, strong) NSString *collectShipping; -@property (nonatomic, strong) NSString *message; -@property (nonatomic, strong) NSString *buttonAction; -@property (nonatomic, strong) NSString *buttonImageUrl; -@property (nonatomic, strong) NSString *jsLibraryUrl; - --(void)setAmount:(NSNumber *)amount; - -@end diff --git a/BNPayment/Core/Models/VisaCheckoutLaunchParams.m b/BNPayment/Core/Models/VisaCheckoutLaunchParams.m deleted file mode 100644 index 0d2772f..0000000 --- a/BNPayment/Core/Models/VisaCheckoutLaunchParams.m +++ /dev/null @@ -1,29 +0,0 @@ -#import "VisaCheckoutLaunchParams.h" - -@implementation VisaCheckoutLaunchParams - -+ (NSDictionary *)JSONMappingDictionary { - return @{ - @"apikey" : @"apikey", - @"currencyCode" : @"currencyCode", - @"subtotal" : @"subtotal", - @"externalClientId" : @"externalClientId", - @"externalProfileId" : @"externalProfileId", - @"total" : @"total", - @"locale" : @"locale", - @"collectShipping" : @"collectShipping", - @"message" : @"message", - @"buttonAction" : @"buttonAction", - @"buttonImageUrl" : @"buttonImageUrl", - @"jsLibraryUrl" : @"jsLibraryUrl", - }; -} - --(void)setAmount:(NSNumber *)amount{ - - self.total = [NSString stringWithFormat: @"%f",[amount floatValue]/100.00]; - self.subtotal = self.total; - -} - -@end diff --git a/BNPayment/Core/Models/VisaCheckoutResponse.h b/BNPayment/Core/Models/VisaCheckoutResponse.h deleted file mode 100644 index 4186760..0000000 --- a/BNPayment/Core/Models/VisaCheckoutResponse.h +++ /dev/null @@ -1,19 +0,0 @@ -#import "BNBaseModel.h" - -@interface VisaCheckoutResponse : BNBaseModel - -@property (nonatomic, strong) NSString *region; -@property (nonatomic, strong) NSString *merchant; -@property (nonatomic, strong) NSString *payment; -@property (nonatomic, strong) NSString *state; -@property (nonatomic, strong) NSString *currency; -@property (nonatomic, strong) NSNumber *amount; -@property (nonatomic, strong) NSString *comment; -@property (nonatomic, strong) NSArray *captures; -@property (nonatomic, strong) NSString *receipt; -@property (nonatomic, strong) NSString *cardType; -@property (nonatomic, strong) NSString *cardHolderName; -@property (nonatomic, strong) NSString *creditCardToken; -@property (nonatomic, strong) NSString *truncatedCard; - -@end diff --git a/BNPayment/Core/Models/VisaCheckoutResponse.m b/BNPayment/Core/Models/VisaCheckoutResponse.m deleted file mode 100644 index ff2ea1a..0000000 --- a/BNPayment/Core/Models/VisaCheckoutResponse.m +++ /dev/null @@ -1,24 +0,0 @@ -#import "VisaCheckoutResponse.h" - -@implementation VisaCheckoutResponse - -+ (NSDictionary *)JSONMappingDictionary { - return @{ - @"region" : @"region", - @"merchant" : @"merchant", - @"payment" : @"payment", - @"state" : @"state", - @"currency" : @"currency", - @"amount" : @"amount", - @"comment" : @"comment", - @"captures" : @"captures", - @"receipt" : @"receipt", - @"creditCardToken" : @"creditCardToken", - @"cardHolderName" : @"cardHolderName", - @"truncatedCard" : @"truncatedCard", - @"cardType" : @"cardType", - - }; -} - -@end diff --git a/BNPayment/Core/Models/VisaCheckoutTransactionParams.h b/BNPayment/Core/Models/VisaCheckoutTransactionParams.h deleted file mode 100644 index cf5cbcd..0000000 --- a/BNPayment/Core/Models/VisaCheckoutTransactionParams.h +++ /dev/null @@ -1,10 +0,0 @@ -#import "BNBaseModel.h" - -@interface VisaCheckoutTransactionParams : BNBaseModel - -@property (nonatomic, strong) NSString *encPaymentData; -@property (nonatomic, strong) NSString *callid; -@property (nonatomic, strong) NSString *encKey; -@property (nonatomic, strong) NSDictionary *paymentJsonData; - -@end diff --git a/BNPayment/Core/Models/VisaCheckoutTransactionParams.m b/BNPayment/Core/Models/VisaCheckoutTransactionParams.m deleted file mode 100644 index c8373fc..0000000 --- a/BNPayment/Core/Models/VisaCheckoutTransactionParams.m +++ /dev/null @@ -1,14 +0,0 @@ -#import "VisaCheckoutTransactionParams.h" - -@implementation VisaCheckoutTransactionParams - -+ (NSDictionary *)JSONMappingDictionary { - return @{ - @"encPaymentData" : @"encPaymentData", - @"callid" : @"callid", - @"encKey" : @"encKey", - @"paymentJsonData" : @"paymentJsonData" - }; -} - -@end diff --git a/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.h b/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.h deleted file mode 100644 index 0f332ce..0000000 --- a/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.h +++ /dev/null @@ -1,19 +0,0 @@ -#import -#import "BNPaymentHandler.h" -#import "VisaCheckoutTransactionParams.h" -#import "VisaCheckoutResponse.h" -#import "VisaCheckoutLaunchParams.h" -#import "BNHTTPClient.h" -@import Foundation; - -@class VisaCheckoutLaunchParams; -@class VisaCheckoutResponse; -@class VisaCheckoutTransactionParams; - -@interface VisaCheckoutEndpoint : NSObject - -+(NSURLSessionDataTask *)getVisaCheckoutWithCompletionHandler:(void(^)(VisaCheckoutLaunchParams* visaCheckoutLaunchParams,NSError* error))completionHandler; - -+(NSURLSessionDataTask *)processTransactionFromVisaCheckout:(VisaCheckoutTransactionParams*)visaCheckoutTransactionParams WithCompletionHandler:(void(^)(VisaCheckoutResponse* visaCheckoutResponse,NSError* error))completionHandler; - -@end diff --git a/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.m b/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.m deleted file mode 100644 index 3b9eaf3..0000000 --- a/BNPayment/Core/Network/Endpoints/VisaCheckoutEndpoint.m +++ /dev/null @@ -1,44 +0,0 @@ -#import "VisaCheckoutEndpoint.h" - -@implementation VisaCheckoutEndpoint - -+(NSURLSessionDataTask *)getVisaCheckoutWithCompletionHandler:(void(^)(VisaCheckoutLaunchParams* visaCheckoutLaunchParams,NSError* error))completionHandler{ - - BNHTTPClient *httpClient = [[BNPaymentHandler sharedInstance] getHttpClient]; - - NSString *endpointURL = @"visacheckout_params"; - - NSURLSessionDataTask *dataTask = [httpClient GET:endpointURL parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) { - - NSError *error; - - VisaCheckoutLaunchParams* visaCheckoutLaunchParams= [[VisaCheckoutLaunchParams alloc]initWithJSONDictionary:responseObject error:&error]; - - completionHandler(visaCheckoutLaunchParams, error); - - } failure:^(NSURLSessionDataTask *task, NSError *error) { - completionHandler(nil, error); - }]; - - return dataTask; -} - - -+(NSURLSessionDataTask *)processTransactionFromVisaCheckout:(VisaCheckoutTransactionParams*)visaCheckoutTransactionParams WithCompletionHandler:(void(^)(VisaCheckoutResponse* visaCheckoutResponse,NSError* error))completionHandler{ - - BNHTTPClient *httpClient = [[BNPaymentHandler sharedInstance] getHttpClient]; - - NSString *endpointURL = @"visacheckout_transaction"; - - NSURLSessionDataTask *dataTask = [httpClient POST:endpointURL parameters:[visaCheckoutTransactionParams JSONDictionary] success:^(NSURLSessionDataTask *task, id responseObject) { - NSError *error; - - VisaCheckoutResponse* visaCheckoutResponse= [[VisaCheckoutResponse alloc]initWithJSONDictionary:responseObject error:&error]; - - completionHandler(visaCheckoutResponse, error); - } failure:^(NSURLSessionDataTask *task, NSError *error) { - completionHandler(nil, error); - }]; - return dataTask; -} -@end diff --git a/Example/BNPayment-Example/APPaymentRequest.swift b/Example/BNPayment-Example/APPaymentRequest.swift deleted file mode 100644 index 0a2cd58..0000000 --- a/Example/BNPayment-Example/APPaymentRequest.swift +++ /dev/null @@ -1,42 +0,0 @@ -// -// APPaymentRequest.swift -// ApplePaySDK -// -// Created by Max Mattini on 16/03/2017. -// Copyright © 2017 Max Mattini. All rights reserved. -// - -import Foundation -import PassKit - -open class APPaymentRequest:NSObject -{ - public var payment:PKPayment? - public var appKey:String - public var appSecret:String - public var custNumber:String - public var custReference:String - public var receiptNumber:String? - public var recurringPayment:APRecurringPayment? - public var paymentType:APTrnTypes - - public init(payment: PKPayment?, appKey:String, appSecret:String, custNumber:String, custReference: String, receiptNumber:String, result: String, recurringPayment:APRecurringPayment?, paymentType: APTrnTypes) { - self.payment = payment - self.appKey = appKey - self.appSecret = appSecret - self.custNumber = custNumber - self.custReference = custReference - self.receiptNumber = receiptNumber - self.recurringPayment = recurringPayment - self.paymentType = paymentType - } - - public convenience init(payment: PKPayment?, appKey:String, appSecret:String, custNumber:String, custReference: String, paymentType: APTrnTypes) { - self.init(payment: payment, appKey:appKey, appSecret:appSecret, custNumber:custNumber, custReference: custReference, receiptNumber:"", result: "", recurringPayment:nil, paymentType: paymentType) } - - public override convenience init() - { - self.init(payment: nil, appKey:"", appSecret:"", custNumber:"", custReference: "", receiptNumber:"", result: "", recurringPayment:nil, paymentType: APTrnTypes.PURCHASE) - } - -} diff --git a/Example/BNPayment-Example/APPaymentResponse.swift b/Example/BNPayment-Example/APPaymentResponse.swift deleted file mode 100644 index 69cafaf..0000000 --- a/Example/BNPayment-Example/APPaymentResponse.swift +++ /dev/null @@ -1,51 +0,0 @@ -// -// APPaymentResponse.swift -// PayDemo -// -// Created by Max Mattini on 16/03/2017. -// Copyright © 2017 IPPayments. All rights reserved. -// - -import Foundation - -open class APPaymentResponse:NSObject -{ - public var errorCode:String - public var declineCode:String - public var errorDescription:String - public var settlementDate:String - public var timestamp:String - public var receiptNumber:String - public var result:String - - public func hasError() -> Bool - { - return "Error" == self.result - } - - public func setError(errorDescription:String) -> Void - { - self.result = "Error" - self.errorDescription = errorDescription - } - - public init(errorCode: String, declineCode:String, errorDescription:String, settlementDate:String, timestamp: String, receiptNumber:String, result: String) { - self.errorCode = errorCode - self.declineCode = declineCode - self.errorDescription = errorDescription - self.settlementDate = settlementDate - self.timestamp = timestamp - self.receiptNumber = receiptNumber - self.result = result - } - - public override convenience init() - { - self.init(errorCode: "", declineCode:"", errorDescription:"", settlementDate:"", timestamp: "", receiptNumber:"", result: "") - } - - public convenience init(errorCode: String, declineCode:String) - { - self.init(errorCode: errorCode, declineCode: declineCode, errorDescription:"", settlementDate:"", timestamp: "", receiptNumber:"", result: "") - } -} diff --git a/Example/BNPayment-Example/APProcessor.swift b/Example/BNPayment-Example/APProcessor.swift deleted file mode 100644 index d257e84..0000000 --- a/Example/BNPayment-Example/APProcessor.swift +++ /dev/null @@ -1,240 +0,0 @@ -// -// APProcessor.swift -// IPApplePaySDK -// -// Created by Max Mattini on 15/03/2017. -// Copyright © 2017 Max Mattini. All rights reserved. -// - -import Foundation -import PassKit - -open class APProcessor : NSObject{ - let kTestUrl:String = "https://devsandbox.ippayments.com.au/rapi/applepaypayments/AppleTest/applepaypayments" - - public func submitPayment(paymentRequest:APPaymentRequest) -> APRESTPaymentResponse? - { - return processPayment(paymentRequest: paymentRequest) - } - - public func submitRecurringPayment(paymentRequest:APPaymentRequest) -> APRESTPaymentResponse? - { - paymentRequest.paymentType = .RECURRING - return processPayment(paymentRequest: paymentRequest) - } - - private func errorResponse(response: APRESTPaymentResponse, msg:String) -> APRESTPaymentResponse - { - print(msg) - response.setError(errorDescription: msg) - return response - } - - private func error(response: APRESTPaymentResponse, msg:String) -> (APRESTPaymentResponse, PKPaymentToken?) - { - print(msg) - response.setError(errorDescription: msg) - return (response, nil) - } - - private func createAndCheckRequest(paymentRequest:APPaymentRequest) -> (APRESTPaymentResponse, PKPaymentToken?) - { - let response = APRESTPaymentResponse(errorCode: "200", declineCode: "200") - - let _tokenData: PKPaymentToken = paymentRequest.payment!.token - guard !_tokenData.paymentData.isEmpty else { - return error(response: response, msg:"Payment data should not be empty.") - } - - guard !paymentRequest.appKey.isEmpty, !paymentRequest.appSecret.isEmpty else { - return error(response: response, msg: "ApiKey or AppSecret should not be empty.") - } - - guard !paymentRequest.custNumber.isEmpty else { - return error(response: response, msg: "Customer number should not be empty.") - } - - guard !paymentRequest.custReference.isEmpty else { - return error(response: response, msg:"Customer reference should not be empty.") - } - - return (response, _tokenData) - - } - - private func processPayment(paymentRequest:APPaymentRequest) -> APRESTPaymentResponse? - { - let (response, _tokenData) = createAndCheckRequest(paymentRequest:paymentRequest) - - guard let tokenData = _tokenData else { - - return response - } - - //create a query string to send apiKey and apiSecret to ipp webservice - let queryString = kTestUrl - - // TODO [[]]z do not trace this payment data for production - print("tokenData: \(tokenData)") - - // create a request with url - guard let theUrl = URL(string:queryString) else { - return errorResponse(response: response, msg:"Cannot create URL.") - } - var theRequest = URLRequest(url: theUrl) - theRequest.timeoutInterval = 60.0 - theRequest.cachePolicy = .useProtocolCachePolicy - - var trnTypeId = "" - switch (paymentRequest.paymentType) { - case .PURCHASE: - trnTypeId = "1" - case .AUTHORIZATION: - trnTypeId = "2" - case .RECURRING: - trnTypeId = "7" - default: - //by default treat this as purchase ?? - trnTypeId = "1" - } - - var jsonDictionary:[String:Any] = [ - "custRef" : paymentRequest.custReference, - "custNumber" : paymentRequest.custNumber, - "trnTypeId" : trnTypeId, - "transactionIdentifier" : tokenData.transactionIdentifier, - "paymentInstrumentName" : tokenData.paymentInstrumentName, - "paymentNetwork" : tokenData.paymentNetwork - ] - - do { - if let paymentDataDict = try JSONSerialization.jsonObject(with: tokenData.paymentData, options: []) as? [String: AnyObject] { - jsonDictionary["paymentData"] = paymentDataDict - } - } catch { - return errorResponse(response: response, msg:"Interface error.") - } - - if let _receiptNumber = paymentRequest.receiptNumber { - jsonDictionary["receiptNumber"] = _receiptNumber; - } - - if(paymentRequest.paymentType == .RECURRING){ - //for recurring payments only - if let _recurringPayment = paymentRequest.recurringPayment { - var recurringDictionary:[String:String] = [:] - - let _frequency = _recurringPayment.frequency - let _startDate = _recurringPayment.startDate - let _endDate = _recurringPayment.endDate - guard !_frequency.isEmpty, !_startDate.isEmpty, !_endDate.isEmpty else { - return errorResponse(response: response, msg:"Payment frequency/startDate/endDate should not be empty.") - } - recurringDictionary["frequency"] = _frequency - recurringDictionary["startDate"] = _startDate - recurringDictionary["endDate"] = _endDate - - let _numOfPayments = _recurringPayment.numOfPayments - if !_numOfPayments.isEmpty{ - recurringDictionary["numOfPayments"] = _numOfPayments - } - jsonDictionary["recurring"] = recurringDictionary; - } - } - - do { - let jsonData = try JSONSerialization.data(withJSONObject:jsonDictionary, options:[.prettyPrinted]) - let dataString = String(data: jsonData, encoding: String.Encoding.utf8)! - - theRequest.httpMethod = "POST" - theRequest.addValue("application/json", forHTTPHeaderField:"Content-Type") - theRequest.httpBody = jsonData - - let authDictionary:[String:String] = ["appKey" : paymentRequest.appKey, "appSecret" : paymentRequest.appSecret] - - theRequest.allHTTPHeaderFields = authDictionary - - print(" request : \(theRequest)") - print(" json : \(jsonDictionary)") - print("request body : \(dataString)") - print("request headers : \(theRequest.allHTTPHeaderFields)") - - let session = URLSession.shared - let (retData, _, err) = session.synchronousDataTaskWithRequest(request: theRequest) - - guard err == nil, retData != nil else { - return errorResponse(response: response, msg:"Interface error.") - } - - let dataString1 = String(data: retData!, encoding: String.Encoding.utf8)! - // BE Results : {"Result":"APPROVED","ErrorCode":0,"DecCode":0,"DecDescription":null} - print("BE Results : \(dataString1)") - - do { - if let jsonResponseDict = try JSONSerialization.jsonObject(with: retData!, options: []) as? [String: AnyObject] { - - let jsonResponseData = jsonResponseDict["d"] - if jsonResponseData == nil { - - // Server may have returned a response containing an error - // The "ExceptionType" value is returned from my .NET server used in sample - if let jsonExceptioTypeData = jsonResponseDict["ExceptionType"] { - let f = #function - print("\(f) ERROR : Server returned an exception") - print("\(f) ERROR : Server error details = \(jsonExceptioTypeData)") - return errorResponse(response: response, msg:"Interface error.") - - } else { - - //handle response and returning data - - if let _state = jsonResponseDict["state"] as? String { - response.state = _state - } - - if let _comment = jsonResponseDict["comment"] as? String { - response.comment = _comment - } - -// if let number = jsonResponseDict["ErrorCode"] as? NSNumber { -// response.state = number.stringValue -// } -// -// if let result = jsonResponseDict["Result"] as? String { -// response.state = result -// } - -// if let _receipt = jsonResponseDict["Reciept"] { -// response.receiptNumber = _receipt as! String -// } - } - } - } - } catch { - return errorResponse(response: response, msg:"Cannot get JSON from response") - } - } catch { - return errorResponse(response: response, msg:"Cannot create data from JSON") - } - return response - } -} - -public extension URLSession { - - /// Return data from synchronous request - func synchronousDataTaskWithRequest(request: URLRequest) -> (Data?, URLResponse?, Error?) { - var data: Data?, response: URLResponse?, error: Error? - - let semaphore = DispatchSemaphore(value: 0) - - dataTask(with: request) { - data = $0; response = $1; error = $2 - semaphore.signal() - }.resume() - - semaphore.wait() - - return (data, response, error) - } -} diff --git a/Example/BNPayment-Example/APRESTPaymentResponse.swift b/Example/BNPayment-Example/APRESTPaymentResponse.swift deleted file mode 100644 index 6d0b28e..0000000 --- a/Example/BNPayment-Example/APRESTPaymentResponse.swift +++ /dev/null @@ -1,70 +0,0 @@ -// -// APPaymentResponse.swift -// PayDemo -// -// Created by Max Mattini on 16/03/2017. -// Copyright © 2017 IPPayments. All rights reserved. -// - -import Foundation - -open class APRESTPaymentResponse:NSObject -{ - /* - "currency": null, - "operations": null, - "payment": null, - "captures": null, - "state": null, - "region": null, - "operationInProgress": false, - "amount": 0, - "refunds": null, - "comment": null, - "merchant": null - - */ - - - - public var currency:String - public var payment:String - public var state:String - public var region:String - public var amount:Double - public var comment:String - public var merchant:String - - - public func hasError() -> Bool - { - return "1" == self.state - } - - public func setError(errorDescription:String) -> Void - { - self.state = "1" - self.comment = errorDescription - } - - public init(currency:String, payment:String, state:String, region:String, amount:Double, comment:String, merchant:String) { - self.currency = currency - self.payment = payment - self.state = state - self.region = region - self.amount = amount - self.comment = comment - self.merchant = merchant - } - - public override convenience init() - { - self.init(currency: "", payment:"", state:"", region:"", amount: 0.0, comment:"", merchant: "") - } - - public convenience init(errorCode: String, declineCode:String) - { - self.init(currency: "", payment:"", state:errorCode, region:"", amount: 0.0, comment:declineCode, merchant: "") - } - -} diff --git a/Example/BNPayment-Example/APRecurringPayment.swift b/Example/BNPayment-Example/APRecurringPayment.swift deleted file mode 100644 index e55b12b..0000000 --- a/Example/BNPayment-Example/APRecurringPayment.swift +++ /dev/null @@ -1,31 +0,0 @@ -// -// APRecurringPayment.swift -// ApplePaySDK -// -// Created by Max Mattini on 16/03/2017. -// Copyright © 2017 Max Mattini. All rights reserved. -// -// ApplePaySDK-Swift -import Foundation - -open class APRecurringPayment:NSObject -{ - public var frequency:String - public var startDate:String - public var endDate:String - public var numOfPayments:String - public var noEnd:Bool - - public init(frequency: String, startDate:String, endDate:String, numOfPayments:String, noEnd: Bool) { - self.frequency = frequency - self.startDate = startDate - self.endDate = endDate - self.numOfPayments = numOfPayments - self.noEnd = noEnd - } - - public override convenience init() - { - self.init(frequency: "", startDate:"", endDate:"", numOfPayments:"", noEnd: false) - } -} diff --git a/Example/BNPayment-Example/APmodels.swift b/Example/BNPayment-Example/APmodels.swift deleted file mode 100644 index 7bf0775..0000000 --- a/Example/BNPayment-Example/APmodels.swift +++ /dev/null @@ -1,36 +0,0 @@ -// -// IPAPmodels.swift -// IPApplePaySDK -// -// Created by Max Mattini on 15/03/2017. -// Copyright © 2017 Max Mattini. All rights reserved. -// - -import Foundation -import PassKit - -open class APPaymentDetail:NSObject -{ - public var trnTypeId:String - public var receiptNumber:String - - public init(trnTypeId: String, receiptNumber:String) { - self.trnTypeId = trnTypeId - self.receiptNumber = receiptNumber - } - - public override convenience init() - { - self.init(trnTypeId: "", receiptNumber:"") - } -} - - -public enum APTrnTypes:Int { - case PURCHASE = 1 - case AUTHORIZATION = 2 - case RECURRING = 7 -} - - - diff --git a/Example/BNPayment-Example/AppDelegate.h b/Example/BNPayment-Example/AppDelegate.h deleted file mode 100644 index 8768931..0000000 --- a/Example/BNPayment-Example/AppDelegate.h +++ /dev/null @@ -1,16 +0,0 @@ -// -// AppDelegate.h -// BNPayment-Example -// -// Created by Bambora On Mobile AB on 11/12/2015. -// Copyright (c) 2015 Bambora On Mobile AB. All rights reserved. -// - -#import - -@interface AppDelegate : UIResponder - -@property (strong, nonatomic) UIWindow *window; - -@end - diff --git a/Example/BNPayment-Example/AppDelegate.m b/Example/BNPayment-Example/AppDelegate.m deleted file mode 100644 index 4d7c73b..0000000 --- a/Example/BNPayment-Example/AppDelegate.m +++ /dev/null @@ -1,85 +0,0 @@ -// -// AppDelegate.m -// BNPayment-Example -// -// Created by Bambora On Mobile AB on 11/12/2015. -// Copyright (c) 2015 Bambora On Mobile AB. All rights reserved. -// - -#import "AppDelegate.h" -#import "BNPayment/BNPayment.h" - -#import "BNPayment_Example-Swift.h" -#import "AppSettings.h" -#import "OHHTTPStubs.h" -#import "OHHTTPStubsResponse.h" -#import "OHPathHelpers.h" - -@interface AppDelegate () - -@end - -@implementation AppDelegate - -- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { - // Override point for customization after application launch. - NSError *error; - - [BNPaymentHandler setupWithMerchantAccount:[[AppSettings sharedInstance] getCurrentRunModeMerchantGuid] - baseUrl:[[AppSettings sharedInstance] getRunModeUrl] - debug:YES - error:&error]; - - - [BNTouchIDValidation enable]; - - NSDictionary* data = [[AppSettings sharedInstance] retrieveJsonDataforKey:kRegistrationData]; - [BNRegisterCCParams setRegistrationJsonData: data]; - - UITabBarController* Tcontroller =(UITabBarController*)self.window.rootViewController; - - Tcontroller.tabBar.barTintColor = UIColor.purpleColor; - - [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor grayColor] } - forState:UIControlStateNormal]; - [[UITabBarItem appearance] setTitleTextAttributes:@{ NSForegroundColorAttributeName : [UIColor whiteColor] } - forState:UIControlStateSelected]; - - [[UITabBar appearance] setTintColor:[UIColor whiteColor]]; - - [[UISegmentedControl appearance] setTintColor:UIColor.purpleColor]; - - [self mockVisaCheckParams]; - [self mockVisaCheckoutTransaction]; - - return YES; -} - - --(void)mockVisaCheckParams{ - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return [request.URL.path isEqualToString:@"/rapi/visacheckout_params"]; - } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { - NSString *filePath = OHPathForFile(@"VisaCheckoutParams.json", self.class); - OHHTTPStubsResponse *response = [[OHHTTPStubsResponse responseWithFileAtPath:filePath statusCode:200 headers:@{@"Content-Type":@"application/json"}] responseTime:1]; - return response; - }]; - -} - - - --(void)mockVisaCheckoutTransaction{ - - [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - return [request.URL.path isEqualToString:@"/rapi/visacheckout_transaction"]; - } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { - NSString *filePath = OHPathForFile(@"VisaCheckoutTransaction.json", self.class); - OHHTTPStubsResponse *response = [[OHHTTPStubsResponse responseWithFileAtPath:filePath statusCode:200 headers:@{@"Content-Type":@"application/json"}] responseTime:3]; - return response; - }]; - -} - -@end diff --git a/Example/BNPayment-Example/AppSettings.h b/Example/BNPayment-Example/AppSettings.h deleted file mode 100755 index e0747ed..0000000 --- a/Example/BNPayment-Example/AppSettings.h +++ /dev/null @@ -1,92 +0,0 @@ -// -// Settings.h -// DoNow -// -// Created by Oskar Henriksson on 11/05/2016. -// Copyright © 2016 Bambora. All rights reserved. -// - -#import - -#import -#import -#import - -@class BNAuthorizedCreditCard; -@class BNPaymentParams; -@interface AppSettings : NSObject - -+ (AppSettings *)sharedInstance; - -@property (nonatomic, strong) NSString *username; -@property (nonatomic) BOOL offlineMode; -@property (nonatomic) BOOL touchIDMode; - -@property (nonatomic) BOOL HPPMode; -@property (nonatomic) BOOL velocityMode; -@property (nonatomic) BOOL payOnceMode; - -@property (nonatomic) BOOL scanVisualCues; -@property (nonatomic) BOOL scanCardHolderName; - -@property (nonatomic, strong) NSString *sban; -@property (nonatomic, strong) NSString *pban; - - - -- (void)updateDonatedAmount:(NSInteger)amount; -- (NSInteger)donatedAmount; -- (NSInteger)selectedCardIndex; - -- (void) setTouchIDMode:(BOOL) newTouchIDMode newRunMode:(NSInteger) newRunMode; -- (void) setVelocityMode:(BOOL) newVelocityMode newRunMode:(NSInteger) newRunMode; -- (void) setRunMode:(NSInteger) runMode; -- (void) setRunModeMerchantGuid:(NSInteger) newRunMode newMerchantGuid:(NSString*) newMerchantGuid; -- (void) setVisaCheckoutMode:(BOOL) newVisaCheckoutMode; -- (BOOL) getVisaCheckoutMode; - -- (void) setCardRegistrationGuiSetting:(BNCardRegistrationGuiSetting*) guiSetting; -- (void) setSubmitSinglePaymentCardGuiSetting:(BNSubmitSinglePaymentCardGuiSetting*) guiSetting; - - -- (BNCardRegistrationGuiSetting* )getCardRegistrationGuiSetting; -- (BNSubmitSinglePaymentCardGuiSetting* )getSubmitSinglePaymentGuiSetting; - -- (NSInteger) getRunMode; -- (NSString *)getRunModeUrl; -- (NSString *)getCurrentRunModeMerchantGuid; -- (NSString *)getMerchantGuid: (NSInteger) runModeParam; - - -- (NSString*) getRunModeNameByLevel:(NSNumber*) level; -- (NSInteger) getRunModeByName:(NSString*) name; -- (NSString*) getRunModeMerchantGuidKey:(NSInteger) newRunMode; -- (NSString*) getTestUrl; -- (NSString*) getTestToken; - -- (NSString*) getProdUrl; -- (NSString*) getProdToken; - -- (NSString*) getCompileDate; -- (NSString*) getCompileTime; - -- (BNAuthorizedCreditCard *)selectedCard; - - --(BOOL) maxSavedCardReached; --(void) incrementNumberOfSavedCard; --(void) decrementNumberOfSavedCard; - - -- (BNPaymentParams *) createMockPaymentParameters:(NSNumber*) amount comment:(NSString*) comment token:(NSString*) token; - -#define kRegistrationData @"registrationData" -#define kPaymentData @"paymentData" - - --(NSDictionary*) retrieveJsonDataforKey:(NSString*)key; - --(void) persistJsonDataRegistration:(NSString*) s forKey:(NSString*)key; - -@end - diff --git a/Example/BNPayment-Example/AppSettings.m b/Example/BNPayment-Example/AppSettings.m deleted file mode 100755 index dd1e54a..0000000 --- a/Example/BNPayment-Example/AppSettings.m +++ /dev/null @@ -1,521 +0,0 @@ -// -// Settings.m -// DoNow -// -// Created by Oskar Henriksson on 11/05/2016. -// Copyright © 2016 Bambora. All rights reserved. -// - -#import "AppSettings.h" -#import -#import -#import - - -@interface AppSettings () -@property (nonatomic) NSInteger runMode; -@property (nonatomic) NSInteger numberOfCardsSaved; -@property (nonatomic, strong) NSString *merchantGuid; -@property (nonatomic, strong) BNSubmitSinglePaymentCardGuiSetting *submitSinglePaymentCardGuiSetting; -@property (nonatomic, strong) BNCardRegistrationGuiSetting *cardRegistrationGuiSetting; - - -@end - -#define kRunModeUndefined 0 -#define kRunModeDev 1 -#define kRunModeUAT 2 -#define kRunModeProd 3 -#define kRunModeDefault kRunModeUAT - - -#define kMaxCard (20) - -static NSString *const DonationAmountKey = @"donationAmount"; -static NSString *const ProfileNameKey = @"profileName"; -static NSString *const FavoriteCardKey = @"FavoriteCard"; -static NSString *const OfflineModeKey = @"OfflineMode"; -static NSString *const TouchIDModeKey = @"TouchIDMode"; -static NSString *const HPPModeKey = @"HPPMode"; -static NSString *const velocityModeKey = @"velocityMode"; -static NSString *const numberOfCardsSavedKey = @"numberOfCardsSaved"; -static NSString *const payOnceModeKey = @"payOnceMode"; -static NSString *const ScanVisualCuesHiddenKey = @"ScanVisualCuesHidden"; -static NSString *const ScanCardHolderNameKey = @"ScanCardHolderName"; -static NSString *const VisaCheckoutModeKey = @"VisaCheckoutMode"; - -@implementation AppSettings { - -} - -+ (AppSettings *)sharedInstance { - static AppSettings *_sharedInstance = nil; - - static dispatch_once_t onceToken; - dispatch_once(&onceToken, ^{ - _sharedInstance = [[AppSettings alloc] init]; - _sharedInstance.runMode = kRunModeUndefined; - _sharedInstance.numberOfCardsSaved = [_sharedInstance restoreNumberOfCardSaved]; - }); - - return _sharedInstance; -} - -- (instancetype)init { - self = [super init]; - - if (self != nil){ - // - } - - return self; -} - -- (NSString *)username { - NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; - NSString *userName = [userDefaults objectForKey:ProfileNameKey]; - return userName ? userName : @"Mattias Johansson"; -} - -- (void)setUsername:(NSString *)string { - NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; - [userDefaults setObject:string forKey:ProfileNameKey]; -} - -- (void)updateDonatedAmount:(NSInteger)amount { - NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; - NSInteger donationAmount = [userDefaults integerForKey:DonationAmountKey]; - [userDefaults setInteger:donationAmount+amount forKey:DonationAmountKey]; -} - -- (NSInteger)donatedAmount { - NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults]; - return [userDefaults integerForKey:DonationAmountKey]; -} - -- (NSInteger)selectedCardIndex { - return 0; -} - - - // - - - (void)setOfflineMode:(BOOL)offlineMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:offlineMode forKey:OfflineModeKey]; - } - -- (BOOL)offlineMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:OfflineModeKey]; -} - - -- (void)setTouchIDMode:(BOOL)newTouchIDMode newRunMode:(NSInteger) newRunMode{ - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:newTouchIDMode forKey:TouchIDModeKey]; -} - -- (BOOL)getVisaCheckoutMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:VisaCheckoutModeKey]; -} - -- (void)setVisaCheckoutMode:(BOOL)newVisaCheckoutMode{ - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:newVisaCheckoutMode forKey:VisaCheckoutModeKey]; -} - -- (BOOL)touchIDMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:TouchIDModeKey]; -} - - - -- (void)setHPPMode:(BOOL)hppMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:hppMode forKey:HPPModeKey]; - [userDefault synchronize]; -} - -- (BOOL)HPPMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:HPPModeKey]; -} - -- (void)setVelocityMode:(BOOL)newVelocityMode newRunMode:(NSInteger) newRunMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:newVelocityMode forKey:velocityModeKey]; - [userDefault synchronize]; -} - -- (BOOL)velocityMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:velocityModeKey]; -} - -- (void)persistNumberOfCardSaved:(NSInteger) cardNumber { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setInteger:cardNumber forKey:numberOfCardsSavedKey]; - [userDefault synchronize]; -} - -- (NSInteger) restoreNumberOfCardSaved { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - NSInteger n = [userDefault integerForKey:numberOfCardsSavedKey]; - return n; -} - --(BOOL) maxSavedCardReached -{ - BOOL b1 = (self.numberOfCardsSaved >= ((NSInteger) kMaxCard)); - return b1; -} - --(void) incrementNumberOfSavedCard; -{ - self.numberOfCardsSaved = self.numberOfCardsSaved + 1; - [self persistNumberOfCardSaved:self.numberOfCardsSaved]; -} - --(void) decrementNumberOfSavedCard; -{ - self.numberOfCardsSaved = self.numberOfCardsSaved - 1; - [self persistNumberOfCardSaved:self.numberOfCardsSaved]; -} - -- (void)setPayOnceMode:(BOOL)velocityMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:velocityMode forKey:payOnceModeKey]; - [userDefault synchronize]; -} - -- (BOOL)payOnceMode { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:payOnceModeKey]; -} - -- (BOOL)scanVisualCues { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return ![userDefault boolForKey:ScanVisualCuesHiddenKey]; -} - -- (void)setScanVisualCues:(BOOL)scanVisualCues { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:!scanVisualCues forKey:ScanVisualCuesHiddenKey]; - [userDefault synchronize]; -} - -- (BOOL)scanCardHolderName { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - return [userDefault boolForKey:ScanCardHolderNameKey]; -} - -- (void)setScanCardHolderName:(BOOL)scanCardHolderName { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setBool:scanCardHolderName forKey:ScanCardHolderNameKey]; - [userDefault synchronize]; -} - -- (NSInteger) getRunMode { - if (_runMode == kRunModeUndefined){ - _runMode = [[NSUserDefaults standardUserDefaults] integerForKey:@"runMode"]; - } - if (_runMode == kRunModeUndefined){ - _runMode = kRunModeDefault; - } - return _runMode; -} - -- (NSInteger) getRunModeByName:(NSString*) name { - NSDictionary *map = @{ - @"Dev":@(kRunModeDev), - @"UAT":@(kRunModeUAT), - @"Prod":@(kRunModeProd)}; - if ([[map allKeys] containsObject:name]){ - return [[map objectForKey:name] integerValue]; - } - return kRunModeUndefined; -} - -- (NSString*) getRunModeNameByLevel:(NSNumber*) level { - NSDictionary< NSNumber*, NSString*> *map = @{ - @(kRunModeDev): @"Dev", - @(kRunModeUAT): @"UAT", - @(kRunModeProd): @"Prod"}; - if ([[map allKeys] containsObject:level]){ - return [map objectForKey:level]; - } - return @"?"; -} - - - -- (void) setRunMode:(NSInteger) newRunMode { - if (newRunMode <= kRunModeProd && newRunMode >= kRunModeDev){ - [[NSUserDefaults standardUserDefaults] setInteger:newRunMode forKey:@"runMode"]; - [[NSUserDefaults standardUserDefaults] synchronize]; - _runMode = newRunMode; - } -} - - -- (NSString *)getRunModeUrl { - NSInteger i = [self getRunMode]; - NSNumber* runMode= [NSNumber numberWithInteger:i]; - NSDictionary *runModeUrls = @{ - @(1):@"https://devsandbox.ippayments.com.au/rapi/", - @(2):@"https://uat.ippayments.com.au/rapi/", - @(3):@"https://www.ippayments.com.au/rapi/"}; - NSString* url = runModeUrls[runMode]; - return url; -} - - -- (NSString *)getCurrentRunModeMerchantGuid { - if (_merchantGuid == nil){ - NSInteger runMode = [self getRunMode]; - _merchantGuid = [self getMerchantGuid: runMode]; - } - if (_merchantGuid == nil){ - _merchantGuid = @""; - } - return _merchantGuid; -} - -- (NSString *)getMerchantGuid: (NSInteger) runModeParam { - NSString* currentRunningModeMerchantGuidKey = [self getRunModeMerchantGuidKey: runModeParam]; - if (runModeParam==kRunModeDefault && [[NSUserDefaults standardUserDefaults] valueForKey: currentRunningModeMerchantGuidKey]==nil) - { - NSString* path = [[NSBundle mainBundle] pathForResource:@"MerchantID" ofType:@"txt"]; - NSString* defaultMerchantGuid = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:NULL]; - return defaultMerchantGuid; - } - else - { - return [[NSUserDefaults standardUserDefaults] valueForKey: currentRunningModeMerchantGuidKey]; - } -} - - - - - -- (NSString *)getRunModeMerchantGuidKey : (NSInteger) runModeParam{ - - NSNumber* runMode= [NSNumber numberWithInteger:runModeParam]; - NSDictionary *runModeMerchantGuidKey = @{ - @(1):@"MerchantGuid-Dev", - @(2):@"MerchantGuid-Uat", - @(3):@"MerchantGuid-Prod"}; - NSString* merchantGuidKey = runModeMerchantGuidKey[runMode]; - return merchantGuidKey; -} - -- (void) setRunModeMerchantGuid:(NSInteger) newRunMode newMerchantGuid:(NSString*) newMerchantGuid { - if (newRunMode <= kRunModeProd && newRunMode >= kRunModeDev){ - NSString* merchantGuidKey = [self getRunModeMerchantGuidKey: newRunMode] ; - [[NSUserDefaults standardUserDefaults] setValue: newMerchantGuid forKey: merchantGuidKey]; - [[NSUserDefaults standardUserDefaults] synchronize]; - _merchantGuid = newMerchantGuid; - } -} - - -- (BNCardRegistrationGuiSetting* )getCardRegistrationGuiSetting{ - if(_cardRegistrationGuiSetting==nil) - { - _cardRegistrationGuiSetting = [[BNCardRegistrationGuiSetting alloc] init]; - _cardRegistrationGuiSetting.titleText =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationTitleText]]; - _cardRegistrationGuiSetting.cardHolderWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationCardHolderWatermark]]; - _cardRegistrationGuiSetting.cardNumberWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationCardNumberWatermark]]; - _cardRegistrationGuiSetting.expiryDateWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationExpiryDateWatermark]]; - _cardRegistrationGuiSetting.securityCodeWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationSecurityCodeWatermark]]; - _cardRegistrationGuiSetting.registrationButtonColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationButtonColor]]; - _cardRegistrationGuiSetting.registerButtonText =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationButtonText]]; - if([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]allKeys] containsObject:[BNCardRegistrationGuiSetting GetGuiKey:registrationCardIODisable]]) - { - _cardRegistrationGuiSetting.registrationCardIODisable =[[NSUserDefaults standardUserDefaults] boolForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationCardIODisable]]; - } - else - { - _cardRegistrationGuiSetting.registrationCardIODisable=NO; - } - _cardRegistrationGuiSetting.registrationCardIOColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNCardRegistrationGuiSetting GetGuiKey:registrationCardIOColor]]; - - } - return _cardRegistrationGuiSetting; -} - -- (BNSubmitSinglePaymentCardGuiSetting* )getSubmitSinglePaymentGuiSetting{ - if(_submitSinglePaymentCardGuiSetting==nil) - { - _submitSinglePaymentCardGuiSetting = [[BNSubmitSinglePaymentCardGuiSetting alloc] init]; - _submitSinglePaymentCardGuiSetting.titleText =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payTitleText]]; - _submitSinglePaymentCardGuiSetting.cardHolderWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payCardHolderWatermark]]; - _submitSinglePaymentCardGuiSetting.cardNumberWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payCardNumberWatermark]]; - _submitSinglePaymentCardGuiSetting.expiryDateWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payExpiryDateWatermark]]; - _submitSinglePaymentCardGuiSetting.securityCodeWatermark =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:paySecurityCodeWatermark]]; - _submitSinglePaymentCardGuiSetting.switchButtonColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:switchButtonColor]]; - _submitSinglePaymentCardGuiSetting.payButtonColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payButtonColor]]; - _submitSinglePaymentCardGuiSetting.payButtonText =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payButtonText]]; - _submitSinglePaymentCardGuiSetting.loadingBarColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:loadingBarColor]]; - if([[[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]allKeys] containsObject:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:cardIODisable]]) - { - _submitSinglePaymentCardGuiSetting.cardIODisable =[[NSUserDefaults standardUserDefaults] boolForKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:cardIODisable]]; - } - else - { - _submitSinglePaymentCardGuiSetting.cardIODisable=NO; - } - _submitSinglePaymentCardGuiSetting.cardIOColor =[[NSUserDefaults standardUserDefaults] valueForKey: [BNSubmitSinglePaymentCardGuiSetting GetGuiKey:cardIOColor]]; - } - return _submitSinglePaymentCardGuiSetting; -} - - - - - -//Set CardRegistrationGuiSetting to the NSUserDefaults, and catch as class property. -- (void) setCardRegistrationGuiSetting:(BNCardRegistrationGuiSetting*) guiSetting{ - if(guiSetting==nil) - return; - - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.titleText forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationTitleText]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.cardHolderWatermark forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationCardHolderWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.cardNumberWatermark forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationCardNumberWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.expiryDateWatermark forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationExpiryDateWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.securityCodeWatermark forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationSecurityCodeWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.registerButtonText forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationButtonText]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.registrationButtonColor forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationButtonColor]]; - [[NSUserDefaults standardUserDefaults] setBool:guiSetting.registrationCardIODisable forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationCardIODisable]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.registrationCardIOColor forKey:[BNCardRegistrationGuiSetting GetGuiKey:registrationCardIOColor]]; - [[NSUserDefaults standardUserDefaults] synchronize]; - _cardRegistrationGuiSetting = guiSetting; -} - -//Set setSubmitSinglePaymentCardGuiSetting to the NSUserDefaults, and catch as class property. -- (void) setSubmitSinglePaymentCardGuiSetting:(BNSubmitSinglePaymentCardGuiSetting*) guiSetting{ - if(guiSetting==nil) - return; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.titleText forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payTitleText]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.cardHolderWatermark forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payCardHolderWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.cardNumberWatermark forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payCardNumberWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.expiryDateWatermark forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payExpiryDateWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.securityCodeWatermark forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:paySecurityCodeWatermark]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.payButtonText forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payButtonText]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.payButtonColor forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:payButtonColor]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.switchButtonColor forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:switchButtonColor]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.loadingBarColor forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:loadingBarColor]]; - [[NSUserDefaults standardUserDefaults] setBool:guiSetting.cardIODisable forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:cardIODisable]]; - [[NSUserDefaults standardUserDefaults] setValue: guiSetting.cardIOColor forKey:[BNSubmitSinglePaymentCardGuiSetting GetGuiKey:cardIOColor]]; - [[NSUserDefaults standardUserDefaults] synchronize]; - _submitSinglePaymentCardGuiSetting = guiSetting; -} - - - - -- (NSString *)getTestUrl { - return @""; -} - -- (NSString *)getTestToken { - return @""; -} - -- (NSString *)getProdUrl { - return @""; -} - -- (NSString *)getProdToken { - return @""; -} - -- (NSString *)getCompileDate { - return [NSString stringWithUTF8String:__DATE__]; -} - -- (NSString *)getCompileTime { - return [NSString stringWithUTF8String:__TIME__]; -} - - - -- (BNAuthorizedCreditCard *)selectedCard { - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - NSInteger selectedIndex = [userDefault integerForKey:FavoriteCardKey]; - NSArray *cards = [[BNPaymentHandler sharedInstance] authorizedCards]; - - if(selectedIndex < cards.count) { - return cards[selectedIndex]; - } - - return nil; -} - - --(NSDictionary*) readJsonFromResource:(NSString*) resourceName -{ - NSString *filePath = [[NSBundle mainBundle] pathForResource:resourceName ofType:@"json"]; - NSError *deserializingError; - NSURL *localFileURL = [NSURL fileURLWithPath:filePath]; - NSData *contentOfLocalFile = [NSData dataWithContentsOfURL:localFileURL]; - id object = [NSJSONSerialization JSONObjectWithData:contentOfLocalFile - options:kNilOptions - error:&deserializingError]; - - return object; -} - - --(NSDictionary*) retrieveJsonDataforKey:(NSString*)key -{ - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - NSString* jsonText = [userDefault stringForKey:key]; - if (jsonText != nil || [jsonText length]>0 ){ - - NSData *data = [jsonText dataUsingEncoding:NSUTF8StringEncoding]; - id json = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil]; - - return json; - } else { - - NSDictionary* data = [self readJsonFromResource:key]; - return data; - } - return nil; -} - --(void) persistJsonDataRegistration:(NSString*) s forKey:(NSString*)key -{ - NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults]; - [userDefault setObject:s forKey:key]; - [userDefault synchronize]; -} - - -- (BNPaymentParams *) createMockPaymentParameters:(NSNumber*) amount comment:(NSString*) comment token:(NSString*) token{ - NSString* paymentIdentifier = [NSString stringWithFormat:@"%u", arc4random_uniform(INT_MAX)]; - BNPaymentParams *mockObject = [BNPaymentParams paymentParamsWithId:paymentIdentifier currency:@"AUD" amount:amount token:token comment:comment]; - - NSDictionary* data = [self retrieveJsonDataforKey:kPaymentData]; - [mockObject setPaymentJsonData: data]; - - - return mockObject; -} - -- (BNPaymentParams *) createMockSinglePaymentParameters:(NSNumber*) amount comment:(NSString*) comment{ - NSString* paymentIdentifier = [NSString stringWithFormat:@"%u", arc4random_uniform(INT_MAX)]; - BNPaymentParams *mockObject = [BNPaymentParams paymentParamsWithId:paymentIdentifier currency:@"AUD" amount:amount token:@"" comment:comment]; - - NSDictionary* data = [self retrieveJsonDataforKey:kPaymentData]; - [mockObject setPaymentJsonData: data]; - - - return mockObject; -} -@end diff --git a/Example/BNPayment-Example/ApplePaySDK.h b/Example/BNPayment-Example/ApplePaySDK.h deleted file mode 100644 index bfe6110..0000000 --- a/Example/BNPayment-Example/ApplePaySDK.h +++ /dev/null @@ -1,19 +0,0 @@ -// -// ApplePaySDK.h -// ApplePaySDK -// -// Created by Max Mattini on 16/03/2017. -// Copyright © 2017 Max Mattini. All rights reserved. -// - -#import - -//! Project version number for ApplePaySDK. -FOUNDATION_EXPORT double ApplePaySDKVersionNumber; - -//! Project version string for ApplePaySDK. -FOUNDATION_EXPORT const unsigned char ApplePaySDKVersionString[]; - -// In this header, you should import all the public headers of your framework using statements like #import - - diff --git a/Example/BNPayment-Example/BNColor.swift b/Example/BNPayment-Example/BNColor.swift deleted file mode 100644 index 0b85366..0000000 --- a/Example/BNPayment-Example/BNColor.swift +++ /dev/null @@ -1,27 +0,0 @@ -// -// Created by Max Mattini on 2/08/2016. -// - -import Foundation - -open class BNColor:NSObject -{ - - func UIColorFromRGB(rgbValue: UInt) -> UIColor { - return UIColor( - red: CGFloat((rgbValue & 0xFF0000) >> 16) / 255.0, - green: CGFloat((rgbValue & 0x00FF00) >> 8) / 255.0, - blue: CGFloat(rgbValue & 0x0000FF) / 255.0, - alpha: CGFloat(1.0) - ) - } - - static public let purple = UIColor.purple - static public let primary = UIColor(red: 130, green: 71, blue: 181, alpha: 1) - static public let amethyst = UIColor(red: 69 , green: 39, blue: 89, alpha: 1) - static public let fadetViolet = UIColor(red: 202, green: 172, blue: 223, alpha: 1) - static public let mutedLight = UIColor(red: 246, green: 246, blue: 246, alpha: 1) - static public let muted = UIColor(red: 240, green: 240, blue: 240, alpha: 1) - static public let mutedDark = UIColor(red: 200, green: 200, blue: 200, alpha: 1) - -} diff --git a/Example/BNPayment-Example/BNPayment-Example-Bridging-Header.h b/Example/BNPayment-Example/BNPayment-Example-Bridging-Header.h deleted file mode 100644 index 7a7724f..0000000 --- a/Example/BNPayment-Example/BNPayment-Example-Bridging-Header.h +++ /dev/null @@ -1,8 +0,0 @@ -// -// Use this file to import your target's public headers that you would like to expose to Swift. -// -#import -#import - -#import "AppSettings.h" - diff --git a/Example/BNPayment-Example/CardsTableViewCell.swift b/Example/BNPayment-Example/CardsTableViewCell.swift deleted file mode 100644 index 60a5106..0000000 --- a/Example/BNPayment-Example/CardsTableViewCell.swift +++ /dev/null @@ -1,96 +0,0 @@ -// -// CardsTableViewCell.swift -// BNPayment-Example -// -// Created by Max Mattini on 28/03/2017. -// Copyright © 2017 Bambora. All rights reserved. -// - -import UIKit - -class CardsTableViewCell: UITableViewCell { - - @IBOutlet weak var lblType: UILabel! - @IBOutlet weak var btnDelete: UIButton! - @IBOutlet weak var lblExpiry: UILabel! - @IBOutlet weak var lblCardNumber: UILabel! - @IBOutlet weak var btnPreAuth: UIButton! - - @IBOutlet weak var lblCardHolder: UILabel! - @IBAction func btnDeleteAction(_ sender: Any) { - BNPaymentHandler.sharedInstance().remove(card) - NotificationCenter.default.post(name: .refreshCards, object: nil) - } - - @IBAction func btnAliasAction(_ sender: Any) { - } - - @IBOutlet weak var btnAlias: UIButton! - - var card:BNAuthorizedCreditCard? = nil - var paymentParams: BNPaymentParams? = nil - var cardViewContoller: CardsViewController? = nil - override func awakeFromNib() { - super.awakeFromNib() - // Initialization code - } - - //Define parent view controller. - var parentViewController: UIViewController? { - var parentResponder: UIResponder? = self - while parentResponder != nil { - parentResponder = parentResponder!.next - if let viewController = parentResponder as? UIViewController { - return viewController - } - } - return nil - } - - public func configure(card: BNAuthorizedCreditCard, paymentParam: BNPaymentParams) - { - self.card = card - self.paymentParams = paymentParam - lblCardNumber.text = card.creditCardNumber - - - if let mm = card.creditCardExpiryMonth, let yy = card.creditCardExpiryYear { - lblExpiry.text = "\(mm)/\(yy)" - } - lblType.text = card.creditCardType - lblType.isHidden = false - - if let cardHolder = card.creditCardHolder { - lblCardHolder.text = cardHolder - - } - } - - //PreAuth button click handler. - @IBAction func btnPreAuthAction(_ sender: Any) { - //submit PreAuth token. - BNPaymentHandler.sharedInstance().submitPreAuthToken(paymentParams, requirePaymentValidation:AppSettings.sharedInstance().touchIDMode){ - (response: [String:String]?, result:BNPaymentResult , error:Error?) -> Void in - //display message. - if let cardsViewController = self.parentViewController as? CardsViewController { - cardsViewController.displayStatus(response: response, result:result , - paymentType:PreAuthToken, error:error) - } - } - } - - override func setSelected(_ selected: Bool, animated: Bool) { - super.setSelected(selected, animated: animated) - - // Configure the view for the selected state - } - - - - -} - -extension Notification.Name { - static let refreshCards = Notification.Name("refreshCards") -} - diff --git a/Example/BNPayment-Example/CardsViewController.swift b/Example/BNPayment-Example/CardsViewController.swift deleted file mode 100644 index ee1e215..0000000 --- a/Example/BNPayment-Example/CardsViewController.swift +++ /dev/null @@ -1,437 +0,0 @@ -// -// CardsViewController.swift -// BNPayment-Example -// -// Created by Max Mattini on 27/03/2017. -// Copyright © 2017 Bambora. All rights reserved. -// - -import UIKit -import LocalAuthentication - -class CardsViewController: UIViewController { - - - @IBOutlet weak var lblSavedCreditCards: UILabel! - @IBOutlet weak var activityIndicator: UIActivityIndicatorView! - @IBOutlet weak var btnNonRecurringPayment: UIButton! - @IBOutlet weak var tableView: UITableView! - - public var amount:NSNumber = 100 - public var comment:String = "" - - // Used in one-time payment - private var tmpCard:BNAuthorizedCreditCard? - let notificationName = Notification.Name("refreshCards") - - - // MARK: - Life cycle - - - @IBOutlet weak var addCardButton: UIBarButtonItem! - - - - - override func viewDidLoad() { - super.viewDidLoad() - - self.title=self.comment - - let btndAddCard = UIButton(type: .custom) - btndAddCard.setImage(UIImage(named: "addcard"), for: .normal) - btndAddCard.frame = CGRect(x: 0, y: 0, width: 35, height: 35) - btndAddCard.addTarget(self, action: #selector(CardsViewController.addCard), for: .touchUpInside) - let containVew = UIView(frame:CGRect(x: 0, y: 0, width: 40, height: 40)) - containVew.addSubview(btndAddCard) - addCardButton.customView=containVew - - let contentInsets = UIEdgeInsets(top: 0, left: 0.0, bottom: 0, right: 0.0) - tableView.contentInset = contentInsets - tableView.estimatedRowHeight = 200.0 - tableView.delegate = self - tableView.dataSource = self - tableView.allowsSelection = true - tableView.separatorStyle = .none - tableView.reloadData() - - activityIndicator.isHidden = true - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - private func updateMessage() { - if let authorizedCards = BNPaymentHandler.sharedInstance().authorizedCards() { - if authorizedCards.count > 0 { - lblSavedCreditCards.text = "Click any of the saved cards below to pay." - } - else { - lblSavedCreditCards.text = "No saved cards. Press + to register a card" - } - } - } - - override func viewWillAppear(_ animated: Bool) - { - NotificationCenter.default.addObserver(self, selector: #selector(CardsViewController.refreshCards), name: notificationName, object: nil) - updateMessage() - } - - override func viewWillDisappear(_ animated: Bool){ - NotificationCenter.default.removeObserver(self, name: notificationName, object: nil) - } - - // MARK: - Start/top UI - func stopUI() - { - activityIndicator.isHidden = false - activityIndicator.hidesWhenStopped = true - activityIndicator.startAnimating() - } - - func startUI() - { - activityIndicator.isHidden = true - activityIndicator.stopAnimating() - } - - private func inProgress() -> Bool - { - return activityIndicator.isAnimating - } - - // MARK: - selectors - - @objc public func refreshCards(notification:Notification) { - tableView.reloadData() - updateMessage() - } - - - - @objc public func addCard() { - - let vc = BNCreditCardRegistrationVC() - let guiSetting = AppSettings.sharedInstance().getCardRegistrationGuiSetting(); - vc.guiSetting = guiSetting; - vc.completionBlock = self.completeCardRegistrationBlock; - - if let nav = self.navigationController { - nav.pushViewController(vc, animated: true) - } - - } - - - - - private func completeCardRegistrationBlock(p1:BNCCRegCompletion, card:BNAuthorizedCreditCard?) ->Void - { - if let nav = self.navigationController { - nav.popViewController(animated: true) - } - tableView.reloadData() - guard let _ = card else { - let title = "No card" - let message = "No credit card was registered!" - - let alertController = UIAlertController( - title: title, - message:message, - preferredStyle: UIAlertController.Style.alert - ) - - let cancelAction = UIAlertAction( - title: "OK", style: UIAlertAction.Style.default) { (action) in - // ... - } - - alertController.addAction(cancelAction) - self.present(alertController, animated: true, completion: nil) - return - } - - } - - - @IBAction func btnAddCardPreAuth(_ sender: Any) { - - let vc = BNSubmitSinglePaymentCardVC() - let guiSetting = AppSettings.sharedInstance().getSubmitSinglePaymentGuiSetting(); - vc.guiSetting = guiSetting; - vc.paymentType = PreAuthCard; - vc.isRequirePaymentAuthorization = AppSettings.sharedInstance().touchIDMode - let paymentParams:BNPaymentParams = AppSettings.sharedInstance().createMockPaymentParameters(amount, comment:"This is a test preAuth!", token:""); - - vc.paymentParams = paymentParams; - vc.completionBlock = self.completeNonRecurringPaymentBlock; - - if let nav = self.navigationController { - nav.pushViewController(vc, animated: true) - } - } - - - // MARK: - actions - @IBAction func btnNonRecurringPaymentAction(_ sender: Any) { - - // stopUI() - - let vc = BNSubmitSinglePaymentCardVC() - let guiSetting = AppSettings.sharedInstance().getSubmitSinglePaymentGuiSetting(); - vc.guiSetting = guiSetting; - vc.paymentType = SubmitPaymentCard; - vc.isRequirePaymentAuthorization = AppSettings.sharedInstance().touchIDMode - let paymentParams:BNPaymentParams = AppSettings.sharedInstance().createMockPaymentParameters(amount, comment:comment, token:""); - - vc.paymentParams = paymentParams; - vc.completionBlock = self.completeNonRecurringPaymentBlock; - vc.enableVisaCheckout = AppSettings.sharedInstance().getVisaCheckoutMode() - if let nav = self.navigationController { - nav.pushViewController(vc, animated: true) - } - } - - - - private func completeNonRecurringPaymentBlock(response:[String:String]?, authorizedCreditCard:BNAuthorizedCreditCard?, result:BNPaymentResult, error :Error?) ->Void - { - if let nav = self.navigationController { - nav.popViewController(animated: true) - } - - tableView.reloadData() - - self.displayStatus(response: response, result:result , - paymentType:SubmitPaymentCard, error:error); - return - - - } - - - - private func buildAuthorisationErrorMessage(error:Error?) -> String - { - var message = "" - if let error = error { - switch error._code { - case LAError.Code.systemCancel.rawValue: - message += " Session cancelled. " + error.localizedDescription - case LAError.Code.userCancel.rawValue: - message += " Please try again. " + error.localizedDescription - case LAError.Code.userFallback.rawValue: - message += " Authentication" + " Password option selected" - - case LAError.Code.touchIDNotEnrolled.rawValue: - message += "TouchID is not enrolled. " + error.localizedDescription - case LAError.Code.passcodeNotSet.rawValue: - message += "A passcode has not been set. " + error.localizedDescription - default: - message += "Authentication failed. " + error.localizedDescription - } - } - return message - } - - - private func buildErrorMessage( paymentIsNotAuthorised: Bool ,paymentType: PaymentType, error:Error?) -> String - { - let paymentTypeText = BNPaymentType.getDisplayText(by: paymentType); - - var message = paymentIsNotAuthorised ? "" : "The "+paymentTypeText!+" did not succeed: " - if let error = error { - if !paymentIsNotAuthorised { - message = message + error.localizedDescription - } else { - - switch error._code { - case LAError.Code.systemCancel.rawValue: - message += " Session cancelled. " + error.localizedDescription - case LAError.Code.userCancel.rawValue: - message += " Please try again. " + error.localizedDescription - case LAError.Code.userFallback.rawValue: - message += " Authentication" + " Password option selected" - - case LAError.Code.touchIDNotEnrolled.rawValue: - message += "TouchID is not enrolled. " + error.localizedDescription - case LAError.Code.passcodeNotSet.rawValue: - message += "A passcode has not been set. " + error.localizedDescription - default: - message += "Authentication failed. " + error.localizedDescription - } - } - } - return message - } - - - public func displayStatus(response: [String:String]?, result:BNPaymentResult , - paymentType:PaymentType, error:Error?) - { - - let success = (result == BNPaymentSuccess) - let paymentNotAuthorised = (result == BNPaymentNotAuthorized) - let paymentTypeText = BNPaymentType.getDisplayText(by: paymentType); - let title = success ? "Success" : (paymentNotAuthorised ? (paymentTypeText!+" Not Authorised") : "Failure") - var receipt = "?" - if let response = response, let r = response["receipt"] { - receipt = r - } - let message = success ? "The "+paymentTypeText!+" succeeded. Receipt:\(receipt)" : (paymentNotAuthorised ? buildAuthorisationErrorMessage(error: error) : BNHTTPResponseSerializer.buildBackendErrorMessage(error:error) - ) - notifyUser(title, message: message) - } - - private func notifyUser(_ title: String, message: String?) { - let alert = UIAlertController(title: title, - message: message, - preferredStyle: .alert) - let cancelAction = UIAlertAction(title: "OK", style: .cancel, handler: nil) - - alert.addAction(cancelAction) - - self.present(alert, animated: true, completion: nil) - } - -} - - -extension CardsViewController: UITableViewDelegate -{ - // MARK: - UITableViewDelegate - func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) - { - let _cell = cell as! CardsTableViewCell - _cell.contentView.backgroundColor = indexPath.row % 2 == 0 ? UIColor.lightGray : UIColor.gray - } - - func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) - { - tableView.deselectRow(at: indexPath, animated: true) - if let authorizedCards = BNPaymentHandler.sharedInstance().authorizedCards() { - - let card = authorizedCards[ indexPath.row] - submitPaymentToken(card: card) - } - } - - private func submitPaymentToken(card: BNAuthorizedCreditCard) - { - - let params:BNPaymentParams = AppSettings.sharedInstance().createMockPaymentParameters(amount, comment:comment, token:card.creditCardToken) - - stopUI() - BNPaymentHandler.sharedInstance().makePaymentExt(with: params, requirePaymentValidation:AppSettings.sharedInstance().touchIDMode){ - (response: [String:String]?, result:BNPaymentResult , error:Error?) -> Void in - - self.startUI() - self.displayStatus(response: response, result:result , - paymentType:SubmitPaymentToken, error:error) - } - } -} - -extension CardsViewController: UITableViewDataSource -{ - // MARK: - UITableViewDataSource - func numberOfSectionsInTableView(tableView: UITableView) -> Int { - return 1 - } - - func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { - if let authorizedCards = BNPaymentHandler.sharedInstance().authorizedCards() { - return authorizedCards.count - } - return 0 - } - - func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { - let cellIdentifier = "CardsTableViewCell" - let cell = self.tableView.dequeueReusableCell(withIdentifier: cellIdentifier, for: indexPath as IndexPath) - as! CardsTableViewCell - - if let authorizedCards = BNPaymentHandler.sharedInstance().authorizedCards() { - - let card = authorizedCards[ indexPath.row] - let params:BNPaymentParams = AppSettings.sharedInstance().createMockPaymentParameters(amount, comment:comment, token:card.creditCardToken) - - cell.configure(card: card, paymentParam: params) - - } - - return cell - } -} - - -public extension BNHTTPResponseSerializer -{ - class func extractBackendErrorMessage(error:Error?) -> (NSNumber, String, String, String) - { - if let nserror = error as NSError? { - - let userInfo = nserror.userInfo - - if let jsonText = userInfo[BNResponseSerializationErrorDataString] as? String { - - if let data = jsonText.data(using: String.Encoding.utf8) { - - do { - let dict:[String:AnyObject]? = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] - - let status = dict?["status"] as? NSNumber ?? NSNumber(value: 0) - let title = dict?["title"] as? String ?? "" - let type = dict?["type"] as? String ?? "" - let detail = dict?["detail"] as? String ?? "" - - return (status, title, type, detail) - } catch { - return (0, "", "", "") - } - } - } - } - return (0, "", "", "") - } - - class func buildBackendErrorMessage(error:Error?) -> String - { - let (status, title, type, detail) = self.extractBackendErrorMessage(error:error) - if (status != 0) - { - return "status:\(status) title:\(title) type:\(type)\ndetail:\(detail)" - } - return "?" - } - - class func extractBackendErrorDetails(error:Error?) -> String - { - if let nserror = error as NSError? { - - let userInfo = nserror.userInfo - - if let jsonText = userInfo[BNResponseSerializationErrorDataString] as? String { - - if let data = jsonText.data(using: String.Encoding.utf8) { - - do { - let dict:[String:AnyObject]? = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] - let detail = dict?["Detail"] as? String ?? "" - - return (detail) - } catch { - return ("") - } - } - } - } - return ("") - } - -} - - diff --git a/Example/BNPayment-Example/Compatibility.h b/Example/BNPayment-Example/Compatibility.h deleted file mode 100755 index b41ddda..0000000 --- a/Example/BNPayment-Example/Compatibility.h +++ /dev/null @@ -1,47 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -/* - * This file allows to keep compatibility with older SDKs which didn't have - * the latest features and associated macros yet. - */ - - -#ifndef NS_DESIGNATED_INITIALIZER - #if __has_attribute(objc_designated_initializer) - #define NS_DESIGNATED_INITIALIZER __attribute__((objc_designated_initializer)) - #else - #define NS_DESIGNATED_INITIALIZER - #endif -#endif - -// Allow to use nullability macros and keywords even if not supported yet -#if ! __has_feature(nullability) - #define NS_ASSUME_NONNULL_BEGIN - #define NS_ASSUME_NONNULL_END - #define nullable - #define __nullable - #define __nonnull -#endif diff --git a/Example/BNPayment-Example/CustomDataViewController.swift b/Example/BNPayment-Example/CustomDataViewController.swift deleted file mode 100644 index f462588..0000000 --- a/Example/BNPayment-Example/CustomDataViewController.swift +++ /dev/null @@ -1,116 +0,0 @@ -// -// DeveloperViewController.swift -// BNPayment-Example -// -// Created by Chen LIN on 1/6/17. -// Copyright © 2017 Bambora. All rights reserved. -// - -import UIKit - -class CustomDataViewController: UIViewController { - - - @IBOutlet weak var btnSaveData: UIButton! - @IBOutlet weak var tvEditor: UITextView! - - - @IBOutlet weak var scType: UISegmentedControl! - - override func viewDidLoad() { - super.viewDidLoad() - - - if let json = AppSettings.sharedInstance().retrieveJsonDataforKey(kRegistrationData), JSONSerialization.isValidJSONObject(json) { - - tvEditor.text = stringify(json: json) - } - } - - @IBAction func scTypeChanged(_ sender: Any) { - let sc = sender as! UISegmentedControl - - tvEditor.resignFirstResponder() - - if let json = AppSettings.sharedInstance().retrieveJsonDataforKey( sc.selectedSegmentIndex == 0 ? kRegistrationData : kPaymentData), JSONSerialization.isValidJSONObject(json) { - - tvEditor.text = stringify(json: json) - } - } - - - @IBAction func saveData(_ sender: Any) { - if scType.selectedSegmentIndex == 0 { - validateThenSave(tf:tvEditor, key:kRegistrationData); - - if let json = AppSettings.sharedInstance().retrieveJsonDataforKey( kRegistrationData), JSONSerialization.isValidJSONObject(json) { - - BNRegisterCCParams.setRegistrationJsonData(json) - } - - } else { - validateThenSave(tf:tvEditor, key:kPaymentData); - } - } - - func stringify(json: Any) -> String - { - if JSONSerialization.isValidJSONObject(json) { - - do { - let prettyJsonData = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted) - - let prettyPrintedJson = NSString(data: prettyJsonData, encoding: String.Encoding.utf8.rawValue)! - - return prettyPrintedJson as String - } catch { - print("json error: \(error)") - } - } - return "" - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - - fileprivate func validateThenSave(tf:UITextView, key:String) { - let jsonText = tf.text - - print("\(key) data:\n \(jsonText ?? "")") - - tf.resignFirstResponder() - - if let data = jsonText?.data(using: String.Encoding.utf8) { - - do { - let _:[String:AnyObject]? = try JSONSerialization.jsonObject(with: data, options: []) as? [String:AnyObject] - - AppSettings.sharedInstance().persistJsonDataRegistration(jsonText, forKey: key) - - } catch let error as NSError { - print(error) - let title = "JSON Error" - let message = error.localizedDescription - - let alertController = UIAlertController( - title: title, - message:message, - preferredStyle: UIAlertController.Style.alert - ) - - let cancelAction = UIAlertAction( - title: "OK", style: UIAlertAction.Style.default) { (action) in - if let json = AppSettings.sharedInstance().retrieveJsonDataforKey(key), JSONSerialization.isValidJSONObject(json) { - - tf.text = self.stringify(json: json) - } } - - alertController.addAction(cancelAction) - self.present(alertController, animated: true, completion: nil) - } - } - } -} diff --git a/Example/BNPayment-Example/DeveloperViewController.swift b/Example/BNPayment-Example/DeveloperViewController.swift deleted file mode 100644 index 2dcbfed..0000000 --- a/Example/BNPayment-Example/DeveloperViewController.swift +++ /dev/null @@ -1,348 +0,0 @@ -// -// File.swift -// BNPayment-Example -// -// This developer view is no longer the previous developer view. -// The previous developer view now called CustomDataView. -// -// Copyright © 2017 Bambora. All rights reserved. -// - - -import UIKit - -class DeveloperViewController: UIViewController { - - @IBOutlet weak var settingView: UIScrollView! - - @IBOutlet weak var segRunMode: UISegmentedControl! - @IBOutlet weak var txtMerchantGuid: UITextField! - - @IBOutlet weak var rdTouchId: UISwitch! - @IBOutlet weak var rdVelocity: UISwitch! - @IBOutlet weak var lbVersion: UILabel! - @IBOutlet weak var rdVisaCheckout: UISwitch! - - - //registration form customisation. - @IBOutlet weak var txtRegistrationFormTitle: UITextField! - @IBOutlet weak var txtRegistrationCardHolderName: UITextField! - @IBOutlet weak var txtRegistrationCardNumber: UITextField! - @IBOutlet weak var txtRegistrationExpiryDate: UITextField! - @IBOutlet weak var txtRegistrationSecurityCode: UITextField! - @IBOutlet weak var txtRegistrationButtonColor: UITextField! - @IBOutlet weak var txtRegistrationButtonText: UITextField! - @IBOutlet weak var registrationCardIOSwitch: UISwitch! - @IBOutlet weak var txtRegistrationCardIOColor: UITextField! - - - //submit single card payment form customisation. - @IBOutlet weak var txtPaymentFormTitle: UITextField! - @IBOutlet weak var txtPaymentCardHolderName: UITextField! - @IBOutlet weak var txtPaymentCardNumber: UITextField! - @IBOutlet weak var txtPaymentExpiryDate: UITextField! - @IBOutlet weak var txtPaymentSecurityCode: UITextField! - @IBOutlet weak var txtPaymentButtonColor: UITextField! - @IBOutlet weak var txtPaymentButtonText: UITextField! - @IBOutlet weak var txtPaymentSwitchButtonColor: UITextField! - @IBOutlet weak var txtPaymentLoadingColor: UITextField! - @IBOutlet weak var paymentCardIOSwitch: UISwitch! - @IBOutlet weak var txtPaymentCardIOColor: UITextField! - - var clickedTextField: UITextField! - - - - override func viewDidLoad() { - super.viewDidLoad() - //load current mode. - let currentRunMode: Int = AppSettings.sharedInstance().getRunMode(); - //init the segRunMode control. - let segRunModeIndex: Int = currentRunMode - 1 - segRunMode.selectedSegmentIndex = segRunModeIndex - //init the merchant guid text field. - txtMerchantGuid.text = AppSettings.sharedInstance().getCurrentRunModeMerchantGuid(); - - rdVelocity.isOn = AppSettings.sharedInstance().velocityMode; - rdTouchId.isOn = AppSettings.sharedInstance().touchIDMode; - rdVisaCheckout.isOn = AppSettings.sharedInstance().getVisaCheckoutMode(); - - let dictionary = Bundle.main.infoDictionary!; - let version = dictionary["CFBundleShortVersionString"] as! String; - let build = dictionary["CFBundleVersion"] as! String; - - lbVersion.text = "Version \(version)(\(build)) \(AppSettings.sharedInstance().getCompileDate() ?? "")"; - - //init customisation settings. - initCardRegistrationGuiSetting() - initSubmitSinglePaymentSetting() - - setInputDelegate() - } - - - func setInputDelegate(){ - - txtMerchantGuid.delegate=self - - txtRegistrationFormTitle.delegate=self - txtRegistrationCardHolderName.delegate=self - txtRegistrationCardNumber.delegate=self - txtRegistrationExpiryDate.delegate=self - txtRegistrationSecurityCode.delegate=self - txtRegistrationButtonColor.delegate=self - txtRegistrationButtonText.delegate=self - - txtPaymentFormTitle.delegate=self - txtPaymentCardHolderName.delegate=self - txtPaymentCardNumber.delegate=self - txtPaymentExpiryDate.delegate=self - txtPaymentSecurityCode.delegate=self - txtPaymentButtonColor.delegate=self - txtPaymentButtonText.delegate=self - txtPaymentSwitchButtonColor.delegate=self - txtPaymentLoadingColor.delegate=self - - NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWasShown), name: UIResponder.keyboardDidShowNotification, object: nil) - NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillBeHidden), name: UIResponder.keyboardWillHideNotification, object: nil) - } - - - - @objc func keyboardWasShown(_ aNotification: Notification) { - let info = aNotification.userInfo - let keyboardFrame: NSValue = (info?[UIResponder.keyboardFrameEndUserInfoKey] as? NSValue)! - let kbSize = keyboardFrame.cgRectValue - let contentInsets: UIEdgeInsets = UIEdgeInsets.init(top: 0.0, left: 0.0, bottom: (kbSize.height), right: 0.0) - settingView.contentInset = contentInsets - settingView.scrollIndicatorInsets = contentInsets - var aRect: CGRect = view.frame - aRect.size.height -= (kbSize.height) - if (clickedTextField != nil) && !aRect.contains(clickedTextField.frame.origin) { - let scrollPoint = CGPoint(x: 0.0, y: clickedTextField.frame.origin.y - (kbSize.height)) - settingView.setContentOffset(scrollPoint, animated: true) - } - } - - @objc func keyboardWillBeHidden(_ aNotification: Notification) { - let contentInsets = UIEdgeInsets.zero - settingView.contentInset = contentInsets - settingView.scrollIndicatorInsets = contentInsets - } - - func resetAccountAndMode(){ - try? BNPaymentHandler.setup(withMerchantAccount: AppSettings.sharedInstance().getCurrentRunModeMerchantGuid(), baseUrl: AppSettings.sharedInstance().getRunModeUrl(), debug: true) - } - - - override func viewDidAppear(_ animated: Bool) - { - settingView.contentSize = CGSize(width:self.view.frame.width,height:lbVersion.frame.maxY+30) - } - - @IBAction func btnSaveClick(_ sender: UIButton) { - - let isValidMerchantGuid = isValidGuid(guid: txtMerchantGuid.text!) - if(isValidMerchantGuid) - { - txtMerchantGuid.resignFirstResponder() - //The segment button is the most accure source. - let currentRunningMode: Int = segRunMode.selectedSegmentIndex + 1 - AppSettings.sharedInstance().setRunModeMerchantGuid(currentRunningMode, newMerchantGuid: txtMerchantGuid.text) - //Alert pop up. - let alertTitle: String = "Merchant Guid Updated." - let alertMessage: String = "Merchant guid updated." - let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) - //Okay action. - let okAction = UIAlertAction(title: "Ok", style: .default, handler: {(_ action: UIAlertAction) in - - }) - alertController.addAction(okAction) - present(alertController, animated: true, completion: {}) - resetAccountAndMode() - } - else{ - //Alert pop up. - let alertTitle: String = "Invalid Format." - let alertMessage: String = "Please enter valid guid format." - let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) - //Okay action. - let okAction = UIAlertAction(title: "Ok", style: .default, handler: {(_ action: UIAlertAction) in - - }) - alertController.addAction(okAction) - present(alertController, animated: true, completion: {}) - } - - - } - - - - @IBAction func btnSaveGuiCustomisation(_ sender: UIButton) { - //Card registration customisation. - saveCardRegistrationGuiCustomisation() - //Submit single card payment customisation. - saveSubmitSinglePaymentCustomisation() - let alertTitle: String = "Gui Customisation Updated." - let alertMessage: String = "Gui customisation updated.\nPlease go to the form to check the change" - let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) - //Okay action. - let okAction = UIAlertAction(title: "Ok", style: .default, handler: {(_ action: UIAlertAction) in - - }) - alertController.addAction(okAction) - present(alertController, animated: true, completion: { }) - - } - - func saveCardRegistrationGuiCustomisation() - { - let cardRegistrationGuiSetting: BNCardRegistrationGuiSetting = BNCardRegistrationGuiSetting() - cardRegistrationGuiSetting.titleText = txtRegistrationFormTitle.text - cardRegistrationGuiSetting.cardHolderWatermark = txtRegistrationCardHolderName.text - cardRegistrationGuiSetting.cardNumberWatermark = txtRegistrationCardNumber.text - cardRegistrationGuiSetting.expiryDateWatermark = txtRegistrationExpiryDate.text - cardRegistrationGuiSetting.securityCodeWatermark = txtRegistrationSecurityCode.text - cardRegistrationGuiSetting.registrationButtonColor = txtRegistrationButtonColor.text - cardRegistrationGuiSetting.registerButtonText = txtRegistrationButtonText.text - cardRegistrationGuiSetting.registrationCardIODisable = !(registrationCardIOSwitch.isOn) - cardRegistrationGuiSetting.registrationCardIOColor=txtRegistrationCardIOColor.text - AppSettings.sharedInstance().setCardRegistrationGuiSetting(cardRegistrationGuiSetting) - } - - func saveSubmitSinglePaymentCustomisation() - { - let submitSinglePaymentCardGuiSetting: BNSubmitSinglePaymentCardGuiSetting = BNSubmitSinglePaymentCardGuiSetting() - submitSinglePaymentCardGuiSetting.titleText = txtPaymentFormTitle.text - submitSinglePaymentCardGuiSetting.cardHolderWatermark = txtPaymentCardHolderName.text - submitSinglePaymentCardGuiSetting.cardNumberWatermark = txtPaymentCardNumber.text - submitSinglePaymentCardGuiSetting.expiryDateWatermark = txtPaymentExpiryDate.text - submitSinglePaymentCardGuiSetting.payButtonColor = txtPaymentButtonColor.text - submitSinglePaymentCardGuiSetting.payButtonText = txtPaymentButtonText.text - submitSinglePaymentCardGuiSetting.securityCodeWatermark = txtPaymentSecurityCode.text - submitSinglePaymentCardGuiSetting.switchButtonColor = txtPaymentSwitchButtonColor.text - submitSinglePaymentCardGuiSetting.switchButtonColor = txtPaymentSwitchButtonColor.text - submitSinglePaymentCardGuiSetting.loadingBarColor = txtPaymentLoadingColor.text - submitSinglePaymentCardGuiSetting.cardIODisable = !(paymentCardIOSwitch.isOn) - submitSinglePaymentCardGuiSetting.cardIOColor=txtPaymentCardIOColor.text - AppSettings.sharedInstance().setSubmitSinglePaymentCardGuiSetting(submitSinglePaymentCardGuiSetting) - } - - - func initCardRegistrationGuiSetting() - { - let cardRegistrationGuiSetting = AppSettings.sharedInstance().getCardRegistrationGuiSetting() - txtRegistrationFormTitle.text = cardRegistrationGuiSetting?.titleText; - txtRegistrationCardHolderName.text = cardRegistrationGuiSetting?.cardHolderWatermark - txtRegistrationCardNumber.text = cardRegistrationGuiSetting?.cardNumberWatermark - txtRegistrationExpiryDate.text = cardRegistrationGuiSetting?.expiryDateWatermark - txtRegistrationSecurityCode.text = cardRegistrationGuiSetting?.securityCodeWatermark - txtRegistrationButtonColor.text = cardRegistrationGuiSetting?.registrationButtonColor - txtRegistrationButtonText.text = cardRegistrationGuiSetting?.registerButtonText - registrationCardIOSwitch.setOn(!(cardRegistrationGuiSetting?.registrationCardIODisable)!, animated: true) - txtRegistrationCardIOColor.text = cardRegistrationGuiSetting?.registrationCardIOColor - } - - func initSubmitSinglePaymentSetting() - { - let submitSinglePaymentCardGuiSetting = AppSettings.sharedInstance().getSubmitSinglePaymentGuiSetting() - txtPaymentFormTitle.text = submitSinglePaymentCardGuiSetting?.titleText - txtPaymentCardHolderName.text = submitSinglePaymentCardGuiSetting?.cardHolderWatermark - txtPaymentCardNumber.text = submitSinglePaymentCardGuiSetting?.cardNumberWatermark - txtPaymentExpiryDate.text = submitSinglePaymentCardGuiSetting?.expiryDateWatermark - txtPaymentButtonColor.text = submitSinglePaymentCardGuiSetting?.payButtonColor - txtPaymentButtonText.text = submitSinglePaymentCardGuiSetting?.payButtonText - txtPaymentSecurityCode.text = submitSinglePaymentCardGuiSetting?.securityCodeWatermark - txtPaymentSwitchButtonColor.text = submitSinglePaymentCardGuiSetting?.switchButtonColor - txtPaymentLoadingColor.text = submitSinglePaymentCardGuiSetting?.loadingBarColor - paymentCardIOSwitch.setOn(!(submitSinglePaymentCardGuiSetting?.cardIODisable)!, animated: true) - txtPaymentCardIOColor.text = submitSinglePaymentCardGuiSetting?.cardIOColor - } - - - - @IBAction func sgRunModeChange(_ sender: UISegmentedControl) { - if sender == segRunMode { - let changedRunMode: Int = segRunMode.selectedSegmentIndex + 1 - let currentMode: Int = AppSettings.sharedInstance().getRunMode() - if changedRunMode != currentMode { - - - //Alert pop up. - let alertTitle: String = "Change Environment." - let alertMessage: String = "All your saved cards will be deleted." - let alertController = UIAlertController(title: alertTitle, message: alertMessage, preferredStyle: .alert) - //Okay action. - let okAction = UIAlertAction(title: "Ok", style: .default, handler: {(_ action: UIAlertAction) in - self.txtMerchantGuid.resignFirstResponder() - - let url1: String = AppSettings.sharedInstance().getRunModeUrl() - AppSettings.sharedInstance().setRunMode(changedRunMode) - self.txtMerchantGuid.text = AppSettings.sharedInstance().getMerchantGuid(changedRunMode) - let cards = BNPaymentHandler.sharedInstance().authorizedCards() - for card: BNAuthorizedCreditCard in cards! { - BNPaymentHandler.sharedInstance().remove(card) - AppSettings.sharedInstance().decrementNumberOfSavedCard() - } - let url2: String = AppSettings.sharedInstance().getRunModeUrl() - print("New url '\(url2)' <- Old url '\(url1)'") - self.resetAccountAndMode() - }) - //Cancel action. - let cancelAction = UIAlertAction(title: "Cancel", style: .default, handler: {(_ action: UIAlertAction) in - self.segRunMode.selectedSegmentIndex = currentMode - 1 - - }) - alertController.addAction(cancelAction) - alertController.addAction(okAction) - present(alertController, animated: true, completion: { }) - } - } - } - - - - @IBAction func rdVisaCheckoutChange(_ sender: UISwitch) { - AppSettings.sharedInstance().setVisaCheckoutMode(rdVisaCheckout.isOn) - } - - - @IBAction func rdTouchIdChange(_ sender: Any) { - AppSettings.sharedInstance().setTouchIDMode(rdTouchId.isOn, newRunMode: AppSettings.sharedInstance().getRunMode()); - } - - - @IBAction func rdVelocityChange(_ sender: Any) { - AppSettings.sharedInstance().setVelocityMode(rdVelocity.isOn, newRunMode: AppSettings.sharedInstance().getRunMode()); - } - - - @discardableResult func isValidGuid(guid: String) -> Bool { - let guidPred = NSPredicate(format: "SELF MATCHES %@", "((\\{|\\()?[0-9a-fA-F]{8}-?([0-9a-fA-F]{4}-?){3}[0-9a-fA-F]{12}(\\}|\\))?)|(\\{(0x[0-9a-fA-F]+,){3}\\{(0x[0-9a-fA-F]+,){7}0x[0-9a-fA-F]+\\}\\})") - if(guidPred.evaluate(with: guid)){ - return true; - } - return false - } - -}; - - -extension DeveloperViewController: UITextFieldDelegate{ - - func textFieldShouldReturn(_ textField: UITextField) -> Bool { - return textField.resignFirstResponder() - } - - func textFieldShouldBeginEditing(_ textField: UITextField) -> Bool{ - clickedTextField = textField - return true - } - - -} - - - - diff --git a/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.h b/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.h deleted file mode 100755 index 6cb7fcd..0000000 --- a/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.h +++ /dev/null @@ -1,78 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -/* This category is not available on watchOS because CFNetwork is needed for its implementation but isn't available on Nano */ -#if __has_include() - -#import "OHHTTPStubsResponse.h" -#import "Compatibility.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - * Adds support for building stubs from "HTTP Messages" conforming to - * the format output by `curl -is` - * - * @note This category is not available on watchOS - */ -@interface OHHTTPStubsResponse (HTTPMessage) - -/*! @name Building a response from HTTP Message data */ - - -/** - * Builds a response given a message data as returned by `curl -is [url]`, that is containing both the headers and the body. - * - * This method will split the headers and the body and build a OHHTTPStubsResponse accordingly - * - * @param responseData The NSData containing the whole HTTP response, including the headers and the body - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - */ -+(instancetype)responseWithHTTPMessageData:(NSData*)responseData; - -/** - * Builds a response given the name of a `"*.response"` file containing both the headers and the body. - * - * The response file is expected to be in the specified bundle (or the application bundle if nil). - * This method will split the headers and the body and build a OHHTTPStubsResponse accordingly - * - * @param responseName The name of the `"*.response"` file (without extension) containing the whole - * HTTP response (including the headers and the body) - * @param bundleOrNil The bundle in which the `"*.response"` file is located. If `nil`, the - * `[NSBundle bundleForClass:self.class]` will be used. - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - */ - -+(instancetype)responseNamed:(NSString*)responseName - inBundle:(nullable NSBundle*)bundleOrNil; - - -@end - -NS_ASSUME_NONNULL_END - -#endif diff --git a/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.m b/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.m deleted file mode 100755 index 9f3e027..0000000 --- a/Example/BNPayment-Example/HTTPMessage/OHHTTPStubsResponse+HTTPMessage.m +++ /dev/null @@ -1,76 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -#if __has_include() -#import - -#import "OHHTTPStubsResponse+HTTPMessage.h" - -@implementation OHHTTPStubsResponse (HTTPMessage) - -#pragma mark Building response from HTTP Message Data (dump from "curl -is") - -+(instancetype)responseWithHTTPMessageData:(NSData*)responseData; -{ - NSData *data = [NSData data]; - NSInteger statusCode = 200; - NSDictionary *headers = @{}; - - CFHTTPMessageRef httpMessage = CFHTTPMessageCreateEmpty(kCFAllocatorDefault, FALSE); - if (httpMessage) - { - CFHTTPMessageAppendBytes(httpMessage, responseData.bytes, responseData.length); - - data = responseData; // By default - - if (CFHTTPMessageIsHeaderComplete(httpMessage)) - { - statusCode = (NSInteger)CFHTTPMessageGetResponseStatusCode(httpMessage); - headers = (__bridge_transfer NSDictionary *)CFHTTPMessageCopyAllHeaderFields(httpMessage); - data = (__bridge_transfer NSData *)CFHTTPMessageCopyBody(httpMessage); - } - CFRelease(httpMessage); - } - - return [self responseWithData:data - statusCode:(int)statusCode - headers:headers]; -} - -+(instancetype)responseNamed:(NSString*)responseName - inBundle:(nullable NSBundle*)responsesBundle -{ - NSURL *responseURL = [responsesBundle?:[NSBundle bundleForClass:self.class] URLForResource:responseName - withExtension:@"response"]; - - NSData *responseData = [NSData dataWithContentsOfURL:responseURL]; - NSAssert(responseData, @"Could not find HTTP response named '%@' in bundle '%@'", responseName, responsesBundle); - - return [self responseWithHTTPMessageData:responseData]; -} - -@end - -#endif diff --git a/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.h b/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.h deleted file mode 100755 index cdcacb5..0000000 --- a/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.h +++ /dev/null @@ -1,57 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -#import "OHHTTPStubsResponse.h" -#import "Compatibility.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - * Adds convenience methods to manipulate JSON objects directly. - * Pass in an `NSDictionary` or `NSArray` to generate a corresponding JSON output. - */ -@interface OHHTTPStubsResponse (JSON) - -/** - * Builds a response given a JSON object for the response body, status code, and headers. - * - * @param jsonObject Object representing the response body. - * Typically a `NSDictionary`; may be any object accepted by `+[NSJSONSerialization dataWithJSONObject:options:error:]` - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * If a "Content-Type" header is not included, "Content-Type: application/json" will be added. - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note This method typically calls `responseWithData:statusCode:headers:`, passing the serialized JSON - * object as the data parameter and adding the Content-Type header if necessary. - */ -+ (instancetype)responseWithJSONObject:(id)jsonObject - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.m b/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.m deleted file mode 100755 index 75405df..0000000 --- a/Example/BNPayment-Example/JSON/OHHTTPStubsResponse+JSON.m +++ /dev/null @@ -1,48 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -#import "OHHTTPStubsResponse+JSON.h" - -@implementation OHHTTPStubsResponse (JSON) - -/*! @name Building a response from JSON objects */ - -+ (instancetype)responseWithJSONObject:(id)jsonObject - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders -{ - if (!httpHeaders[@"Content-Type"]) - { - NSMutableDictionary* mutableHeaders = [NSMutableDictionary dictionaryWithDictionary:httpHeaders]; - mutableHeaders[@"Content-Type"] = @"application/json"; - httpHeaders = [NSDictionary dictionaryWithDictionary:mutableHeaders]; // make immutable again - } - - return [self responseWithData:[NSJSONSerialization dataWithJSONObject:jsonObject options:0 error:nil] - statusCode:statusCode - headers:httpHeaders]; -} - -@end diff --git a/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.h b/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.h deleted file mode 100755 index c7ef6af..0000000 --- a/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.h +++ /dev/null @@ -1,100 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2015 Jinlian (Sunny) Wang - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -//////////////////////////////////////////////////////////////////////////////// - -#import "OHHTTPStubs.h" -#import "Compatibility.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - * Error codes for the OHHTTPStubs Mocktail category - */ -typedef NS_ENUM(NSInteger, OHHTTPStubsMocktailError) { - /** The specified path does not exist */ - OHHTTPStubsMocktailErrorPathDoesNotExist = 1, - /** The specified path was not readable */ - OHHTTPStubsMocktailErrorPathFailedToRead, - /** The specified path is not a directory */ - OHHTTPStubsMocktailErrorPathIsNotFolder, - /** The specified file is not a valid Mocktail file */ - OHHTTPStubsMocktailErrorInvalidFileFormat, - /** The specified Mocktail file has invalid headers */ - OHHTTPStubsMocktailErrorInvalidFileHeader, - /** An unexpected internal error occured */ - OHHTTPStubsMocktailErrorInternalError -}; - -extern NSString* const MocktailErrorDomain; - -@interface OHHTTPStubs (Mocktail) - -/** - * Add a stub given a file in the format of Mocktail as defined at https://github.com/square/objc-mocktail. - * - * This method will split the HTTP method Regex, the absolute URL Regex, the headers, the HTTP status code and - * response body, and use them to add a stub. - * - * @param fileName The name of the mocktail file (without extension of '.tail') in the Mocktail format. - * @param bundleOrNil The bundle in which the mocktail file is located. If `nil`, the `[NSBundle bundleForClass:self.class]` will be used. - * @param error An out value that returns any error encountered during stubbing. Returns an NSError object if any error; otherwise returns nil. - * - * @return a stub descriptor that uniquely identifies the stub and can be later used to remove it with - * `removeStub:`. - */ -+(id)stubRequestsUsingMocktailNamed:(NSString *)fileName inBundle:(nullable NSBundle*)bundleOrNil error:(NSError **)error; - -/** - * Add a stub given a file URL in the format of Mocktail as defined at https://github.com/square/objc-mocktail. - * - * This method will split the HTTP method Regex, the absolute URL Regex, the headers, the HTTP status code and - * response body, and use them to add a stub. - * - * @param fileURL The URL pointing to the file in the Mocktail format. - * @param error An out value that returns any error encountered during stubbing. Returns an NSError object if any error; otherwise returns nil. - * - * @return a stub descriptor that uniquely identifies the stub and can be later used to remove it with - * `removeStub:`. - */ -+(id)stubRequestsUsingMocktail:(NSURL *)fileURL error:(NSError **)error; - -/** - * Add stubs using files under a folder in the format of Mocktail as defined at https://github.com/square/objc-mocktail. - * - * This method will retrieve all the files under the folder; for each file with surfix of ".tail", it will split the HTTP method Regex, the absolute URL Regex, the headers, the HTTP status code and response body, and use them to add a stub. - * - * @param path The name of the folder containing files in the Mocktail format. - * @param bundleOrNil The bundle in which the path is located. If `nil`, the `[NSBundle bundleForClass:self.class]` will be used. - * @param error An out value that returns any error encountered during stubbing. Returns an NSError object if any error; otherwise returns nil. - * - * @return an array of stub descriptor that uniquely identifies the stub and can be later used to remove it with - * `removeStub:`. - */ -+(NSArray *)stubRequestsUsingMocktailsAtPath:(NSString *)path inBundle:(nullable NSBundle*)bundleOrNil error:(NSError **)error; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.m b/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.m deleted file mode 100755 index 9575947..0000000 --- a/Example/BNPayment-Example/Mocktail/OHHTTPStubs+Mocktail.m +++ /dev/null @@ -1,260 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2015 Jinlian (Sunny) Wang - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -//////////////////////////////////////////////////////////////////////////////// - -#import "OHHTTPStubs+Mocktail.h" - -NSString* const MocktailErrorDomain = @"Mocktail"; - -@implementation OHHTTPStubs (Mocktail) - - -+(NSArray *)stubRequestsUsingMocktailsAtPath:(NSString *)path inBundle:(nullable NSBundle*)bundleOrNil error:(NSError **)error -{ - NSURL *dirURL = [bundleOrNil?:[NSBundle bundleForClass:self.class] URLForResource:path withExtension:nil]; - if (!dirURL) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorPathDoesNotExist userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path '%@' does not exist.", path]}]; - } - return nil; - } - - // Make sure path points to a directory - NSNumber *isDirectory; - BOOL success = [dirURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil]; - BOOL isDir = (success && [isDirectory boolValue]); - - if (!isDir) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorPathIsNotFolder userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Path '%@' is not a folder.", path]}]; - } - return nil; - } - - // Read the content of the directory - NSError *bError = nil; - NSFileManager *fileManager = [NSFileManager defaultManager]; - NSArray *fileURLs = [fileManager contentsOfDirectoryAtURL:dirURL includingPropertiesForKeys:nil options:0 error:&bError]; - - if (bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorPathFailedToRead userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Error reading path '%@'.", dirURL.absoluteString]}]; - } - return nil; - } - - //stub the Mocktail-formatted requests - NSMutableArray *descriptorArray = [[NSMutableArray alloc] initWithCapacity:fileURLs.count]; - for (NSURL *fileURL in fileURLs) - { - if (![fileURL.absoluteString hasSuffix:@".tail"]) - { - continue; - } - id descriptor = [[self class] stubRequestsUsingMocktail:fileURL error: &bError]; - if (descriptor && !bError) - { - [descriptorArray addObject:descriptor]; - } - } - - return descriptorArray; -} - -+(id)stubRequestsUsingMocktailNamed:(NSString *)fileName inBundle:(nullable NSBundle*)bundleOrNil error:(NSError **)error -{ - NSURL *responseURL = [bundleOrNil?:[NSBundle bundleForClass:self.class] URLForResource:fileName withExtension:@"tail"]; - - if (!responseURL) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorPathDoesNotExist userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' does not exist.", fileName]}]; - } - return nil; - } - else - { - return [[self class] stubRequestsUsingMocktail:responseURL error:error]; - } -} - -+(id)stubRequestsUsingMocktail:(NSURL *)fileURL error:(NSError **)error -{ - NSError *bError = nil; - NSStringEncoding originalEncoding; - NSString *contentsOfFile = [NSString stringWithContentsOfURL:fileURL usedEncoding:&originalEncoding error:&bError]; - - if (!contentsOfFile || bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorPathFailedToRead userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' does not read.", fileURL.absoluteString]}]; - } - return nil; - } - - NSScanner *scanner = [NSScanner scannerWithString:contentsOfFile]; - NSString *headerMatter = nil; - [scanner scanUpToString:@"\n\n" intoString:&headerMatter]; - NSArray *lines = [headerMatter componentsSeparatedByString:@"\n"]; - if (lines.count < 4) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInvalidFileFormat userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' has invalid amount of lines:%u.", fileURL.absoluteString, (unsigned)lines.count]}]; - } - return nil; - } - - /* Handle Mocktail format, adapted from Mocktail implementation - For more details on the file format, check out: https://github.com/square/objc-Mocktail */ - NSRegularExpression *methodRegex = [NSRegularExpression regularExpressionWithPattern:lines[0] options:NSRegularExpressionCaseInsensitive error:&bError]; - - if (bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInvalidFileFormat userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' has invalid method regular expression pattern: %@.", fileURL.absoluteString, lines[0]]}]; - } - return nil; - } - - NSRegularExpression *absoluteURLRegex = [NSRegularExpression regularExpressionWithPattern:lines[1] options:NSRegularExpressionCaseInsensitive error:&bError]; - - if (bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInvalidFileFormat userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' has invalid URL regular expression pattern: %@.", fileURL.absoluteString, lines[1]]}]; - } - return nil; - } - - NSInteger statusCode = [lines[2] integerValue]; - - NSMutableDictionary *headers = @{@"Content-Type":lines[3]}.mutableCopy; - - // From line 4 to '\n\n', expect HTTP response headers. - NSRegularExpression *headerPattern = [NSRegularExpression regularExpressionWithPattern:@"^([^:]+):\\s+(.*)" options:0 error:&bError]; - if (bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInternalError userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Internal error while stubbing file '%@'.", fileURL.absoluteString]}]; - } - return nil; - } - - - // Allow bare Content-Type header on line 4 before named HTTP response headers - NSRegularExpression *bareContentTypePattern = [NSRegularExpression regularExpressionWithPattern:@"^([^:]+)+$" options:0 error:&bError]; - if (bError) - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInternalError userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"Internal error while stubbing file '%@'.", fileURL.absoluteString]}]; - } - return nil; - } - - for (NSUInteger line = 3; line < lines.count; line ++) { - NSString *headerLine = lines[line]; - NSTextCheckingResult *match = [headerPattern firstMatchInString:headerLine options:0 range:NSMakeRange(0, headerLine.length)]; - - if (line == 3 && !match) { - match = [bareContentTypePattern firstMatchInString:headerLine options:0 range:NSMakeRange(0, headerLine.length)]; - if (match) { - NSString *key = @"Content-Type"; - NSString *value = [headerLine substringWithRange:[match rangeAtIndex:1]]; - headers[key] = value; - continue; - } - } - - if (match) - { - NSString *key = [headerLine substringWithRange:[match rangeAtIndex:1]]; - NSString *value = [headerLine substringWithRange:[match rangeAtIndex:2]]; - headers[key] = value; - } - else - { - if (error) - { - *error = [NSError errorWithDomain:MocktailErrorDomain code:OHHTTPStubsMocktailErrorInvalidFileHeader userInfo:@{NSLocalizedDescriptionKey: [NSString stringWithFormat:@"File '%@' has invalid header: %@.", fileURL.absoluteString, headerLine]}]; - } - return nil; - } - } - - // Handle binary which is base64 encoded - NSUInteger bodyOffset = [headerMatter dataUsingEncoding:NSUTF8StringEncoding].length + 2; - - return [OHHTTPStubs stubRequestsPassingTest:^BOOL(NSURLRequest *request) { - NSString *absoluteURL = (request.URL).absoluteString; - NSString *method = request.HTTPMethod; - - if ([absoluteURLRegex numberOfMatchesInString:absoluteURL options:0 range:NSMakeRange(0, absoluteURL.length)] > 0) - { - if ([methodRegex numberOfMatchesInString:method options:0 range:NSMakeRange(0, method.length)] > 0) - { - return YES; - } - } - - return NO; - } withStubResponse:^OHHTTPStubsResponse*(NSURLRequest *request) { - if([headers[@"Content-Type"] hasSuffix:@";base64"]) - { - NSString *type = headers[@"Content-Type"]; - NSString *newType = [type substringWithRange:NSMakeRange(0, type.length - 7)]; - headers[@"Content-Type"] = newType; - - NSData *body = [NSData dataWithContentsOfURL:fileURL]; - body = [body subdataWithRange:NSMakeRange(bodyOffset, body.length - bodyOffset)]; - body = [[NSData alloc] initWithBase64EncodedData:body options:NSDataBase64DecodingIgnoreUnknownCharacters]; - - OHHTTPStubsResponse *response = [OHHTTPStubsResponse responseWithData:body statusCode:(int)statusCode headers:headers]; - return response; - } - else - { - OHHTTPStubsResponse *response = [OHHTTPStubsResponse responseWithFileAtPath:fileURL.path - statusCode:(int)statusCode headers:headers]; - [response.inputStream setProperty:@(bodyOffset) forKey:NSStreamFileCurrentOffsetKey]; - return response; - } - }]; -} - -@end diff --git a/Example/BNPayment-Example/MyDetailsViewController.swift b/Example/BNPayment-Example/MyDetailsViewController.swift deleted file mode 100644 index a7a57e3..0000000 --- a/Example/BNPayment-Example/MyDetailsViewController.swift +++ /dev/null @@ -1,35 +0,0 @@ -// -// MyDetailsViewController.swift -// BNPayment-Example -// -// Created by Max Mattini on 30/03/2017. -// Copyright © 2017 Bambora. All rights reserved. -// - -import UIKit - -class MyDetailsViewController: UIViewController { - - override func viewDidLoad() { - super.viewDidLoad() - - // Do any additional setup after loading the view. - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - - - /* - // MARK: - Navigation - - // In a storyboard-based application, you will often want to do a little preparation before navigation - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - // Get the new view controller using segue.destinationViewController. - // Pass the selected object to the new view controller. - } - */ - -} diff --git a/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.h b/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.h deleted file mode 100755 index 44979c4..0000000 --- a/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.h +++ /dev/null @@ -1,48 +0,0 @@ -/*********************************************************************************** -* -* Copyright (c) 2016 Sebastian Hagedorn, Felix Lamouroux -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in -* all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -* THE SOFTWARE. -* -***********************************************************************************/ - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import - -// This category is only useful when NSURLSession is present -#if defined(__IPHONE_7_0) || defined(__MAC_10_9) - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - NSURLRequest+HTTPBodyTesting - -@interface NSURLRequest (HTTPBodyTesting) -/** - * Unfortunately, when sending POST requests (with a body) using NSURLSession, - * by the time the request arrives at OHHTTPStubs, the HTTPBody of the - * NSURLRequest has been reset to nil. - * - * You can use this method to retrieve the HTTPBody for testing and use it to - * conditionally stub your requests. - */ -- (NSData *)OHHTTPStubs_HTTPBody; -@end - -#endif /* __IPHONE_7_0 || __MAC_10_9 */ diff --git a/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.m b/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.m deleted file mode 100755 index a2ff7e8..0000000 --- a/Example/BNPayment-Example/NSURLSession/NSURLRequest+HTTPBodyTesting.m +++ /dev/null @@ -1,86 +0,0 @@ -/*********************************************************************************** -* -* Copyright (c) 2016 Sebastian Hagedorn, Felix Lamouroux -* -* Permission is hereby granted, free of charge, to any person obtaining a copy -* of this software and associated documentation files (the "Software"), to deal -* in the Software without restriction, including without limitation the rights -* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell -* copies of the Software, and to permit persons to whom the Software is -* furnished to do so, subject to the following conditions: -* -* The above copyright notice and this permission notice shall be included in -* all copies or substantial portions of the Software. -* -* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -* THE SOFTWARE. -* -***********************************************************************************/ - -#import "NSURLRequest+HTTPBodyTesting.h" - -#if defined(__IPHONE_7_0) || defined(__MAC_10_9) - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import "OHHTTPStubsMethodSwizzling.h" - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - NSURLRequest+CustomHTTPBody - -NSString * const OHHTTPStubs_HTTPBodyKey = @"HTTPBody"; - -@implementation NSURLRequest (HTTPBodyTesting) - -- (NSData*)OHHTTPStubs_HTTPBody -{ - return [NSURLProtocol propertyForKey:OHHTTPStubs_HTTPBodyKey inRequest:self]; -} - -@end - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - NSMutableURLRequest+HTTPBodyTesting - -typedef void(*OHHHTTPStubsSetterIMP)(id, SEL, id); -static OHHHTTPStubsSetterIMP orig_setHTTPBody; - -static void OHHTTPStubs_setHTTPBody(id self, SEL _cmd, NSData* HTTPBody) -{ - // store the http body via NSURLProtocol - if (HTTPBody) { - [NSURLProtocol setProperty:HTTPBody forKey:OHHTTPStubs_HTTPBodyKey inRequest:self]; - } else { - // unfortunately resetting does not work properly as the NSURLSession also uses this to reset the property - } - - orig_setHTTPBody(self, _cmd, HTTPBody); -} - -/** - * Swizzles setHTTPBody: in order to maintain a copy of the http body for later - * reference and calls the original implementation. - * - * @warning Should not be used in production, testing only. - */ -@interface NSMutableURLRequest (HTTPBodyTesting) @end - -@implementation NSMutableURLRequest (HTTPBodyTesting) - -+ (void)load -{ - orig_setHTTPBody = (OHHHTTPStubsSetterIMP)OHHTTPStubsReplaceMethod(@selector(setHTTPBody:), - (IMP)OHHTTPStubs_setHTTPBody, - [NSMutableURLRequest class], - NO); -} - -@end - -#endif /* __IPHONE_7_0 || __MAC_10_9 */ diff --git a/Example/BNPayment-Example/NSURLSession/OHHTTPStubs+NSURLSessionConfiguration.m b/Example/BNPayment-Example/NSURLSession/OHHTTPStubs+NSURLSessionConfiguration.m deleted file mode 100755 index 6e88515..0000000 --- a/Example/BNPayment-Example/NSURLSession/OHHTTPStubs+NSURLSessionConfiguration.m +++ /dev/null @@ -1,78 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - -#import - -#if defined(__IPHONE_7_0) || defined(__MAC_10_9) -#import "OHHTTPStubs.h" -#import "OHHTTPStubsMethodSwizzling.h" - -////////////////////////////////////////////////////////////////////////////////////////////////// - -/** - * This helper is used to swizzle NSURLSessionConfiguration constructor methods - * defaultSessionConfiguration and ephemeralSessionConfiguration to insert the private - * OHHTTPStubsProtocol into their protocolClasses array so that OHHTTPStubs is automagically - * supported when you create a new NSURLSession based on one of there configurations. - */ - -typedef NSURLSessionConfiguration*(*SessionConfigConstructor)(id,SEL); -static SessionConfigConstructor orig_defaultSessionConfiguration; -static SessionConfigConstructor orig_ephemeralSessionConfiguration; - -static NSURLSessionConfiguration* OHHTTPStubs_defaultSessionConfiguration(id self, SEL _cmd) -{ - NSURLSessionConfiguration* config = orig_defaultSessionConfiguration(self,_cmd); // call original method - [OHHTTPStubs setEnabled:YES forSessionConfiguration:config]; //OHHTTPStubsAddProtocolClassToNSURLSessionConfiguration(config); - return config; -} - -static NSURLSessionConfiguration* OHHTTPStubs_ephemeralSessionConfiguration(id self, SEL _cmd) -{ - NSURLSessionConfiguration* config = orig_ephemeralSessionConfiguration(self,_cmd); // call original method - [OHHTTPStubs setEnabled:YES forSessionConfiguration:config]; //OHHTTPStubsAddProtocolClassToNSURLSessionConfiguration(config); - return config; -} - -@interface NSURLSessionConfiguration(OHHTTPStubsSupport) @end - -@implementation NSURLSessionConfiguration(OHHTTPStubsSupport) - -+(void)load -{ - orig_defaultSessionConfiguration = (SessionConfigConstructor)OHHTTPStubsReplaceMethod(@selector(defaultSessionConfiguration), - (IMP)OHHTTPStubs_defaultSessionConfiguration, - [NSURLSessionConfiguration class], - YES); - orig_ephemeralSessionConfiguration = (SessionConfigConstructor)OHHTTPStubsReplaceMethod(@selector(ephemeralSessionConfiguration), - (IMP)OHHTTPStubs_ephemeralSessionConfiguration, - [NSURLSessionConfiguration class], - YES); -} - -@end - -#endif /* __IPHONE_7_0 || __MAC_10_9 */ - - diff --git a/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.h b/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.h deleted file mode 100755 index 443a680..0000000 --- a/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.h +++ /dev/null @@ -1,51 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon, 2016 Sebastian Hagedorn - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Method Swizzling Helpers - -/** - * Replaces the selector's associated method implementation with the - * given implementation (or adds it, if there was no existing one). - * - * @param selector The selector entry in the dispatch table. - * @param newImpl The implementation that will be associated with - * the given selector. - * @param affectedClass The class whose dispatch table will be altered. - * @param isClassMethod Set to YES if the selector denotes a class - * method, or NO if it is an instance method. - * @return The previous implementation associated with - * the swizzled selector. You should store the - * implementation and call it when overwriting - * the selector. - */ -__attribute__((warn_unused_result)) IMP OHHTTPStubsReplaceMethod(SEL selector, - IMP newImpl, - Class affectedClass, - BOOL isClassMethod); diff --git a/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.m b/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.m deleted file mode 100755 index 2aefcc7..0000000 --- a/Example/BNPayment-Example/NSURLSession/OHHTTPStubsMethodSwizzling.m +++ /dev/null @@ -1,47 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon, 2016 Sebastian Hagedorn - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import "OHHTTPStubsMethodSwizzling.h" - -////////////////////////////////////////////////////////////////////////////////////////////////// -#pragma mark - Method Swizzling Helpers - -IMP OHHTTPStubsReplaceMethod(SEL selector, - IMP newImpl, - Class affectedClass, - BOOL isClassMethod) -{ - Method origMethod = isClassMethod ? class_getClassMethod(affectedClass, selector) : class_getInstanceMethod(affectedClass, selector); - IMP origImpl = method_getImplementation(origMethod); - - if (!class_addMethod(isClassMethod ? object_getClass(affectedClass) : affectedClass, selector, newImpl, method_getTypeEncoding(origMethod))) - { - method_setImplementation(origMethod, newImpl); - } - - return origImpl; -} diff --git a/Example/BNPayment-Example/OHHTTPStubs.h b/Example/BNPayment-Example/OHHTTPStubs.h deleted file mode 100755 index 964ac7a..0000000 --- a/Example/BNPayment-Example/OHHTTPStubs.h +++ /dev/null @@ -1,219 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import - -#import "Compatibility.h" -#import "OHHTTPStubsResponse.h" - -NS_ASSUME_NONNULL_BEGIN - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Types - -typedef BOOL(^OHHTTPStubsTestBlock)(NSURLRequest* request); -typedef OHHTTPStubsResponse* __nonnull (^OHHTTPStubsResponseBlock)( NSURLRequest* request); - -/** - * This opaque type represents an installed stub and is used to uniquely - * identify a stub once it has been created. - * - * This type is returned by the `stubRequestsPassingTest:withStubResponse:` method - * so that you can later reference it and use this reference to remove the stub later. - * - * This type also let you add arbitrary metadata to a stub to differenciate it - * more easily when debugging. - */ -@protocol OHHTTPStubsDescriptor -/** - * An arbitrary name that you can set and get to describe your stub. - * Use it as your own convenience. - * - * This is especially useful if you dump all installed stubs using `allStubs` - * or if you want to log which stubs are being triggered using `onStubActivation:`. - */ -@property(nonatomic, strong, nullable) NSString* name; -@end - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Interface - -/** - * Stubs Manager. Use this class to add and remove stubs and stub your network requests. - */ -@interface OHHTTPStubs : NSObject - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Adding & Removing stubs - - - -/** - * Dedicated method to add a stub - * - * @param testBlock Block that should return `YES` if the request passed as parameter - * should be stubbed with the response block, and `NO` if it should - * hit the real world (or be managed by another stub). - * @param responseBlock Block that will return the `OHHTTPStubsResponse` (response to - * use for stubbing) corresponding to the given request - * - * @return a stub descriptor that uniquely identifies the stub and can be later used to remove it with `removeStub:`. - * - * @note The returned stub descriptor is retained (`__strong` reference) by `OHHTTPStubs` - * until it is removed (with one of the `removeStub:` / `removeAllStubs` - * methods); it is thus recommended to keep it in a `__weak` storage (and not `__strong`) - * in your app code, to let the stub descriptor be destroyed and let the variable go - * back to `nil` automatically when the stub is removed. - */ -+(id)stubRequestsPassingTest:(OHHTTPStubsTestBlock)testBlock - withStubResponse:(OHHTTPStubsResponseBlock)responseBlock; - -/** - * Remove a stub from the list of stubs - * - * @param stubDesc The stub descriptor that has been returned when adding the stub - * using `stubRequestsPassingTest:withStubResponse:` - * - * @return `YES` if the stub has been successfully removed, `NO` if the parameter was - * not a valid stub identifier - */ -+(BOOL)removeStub:(id)stubDesc; - -/** - * Remove all the stubs from the stubs list. - */ -+(void)removeAllStubs; - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Disabling & Re-Enabling stubs - -/** - * Enable or disable the stubs for the shared session or for `NSURLConnection` - * - * @param enabled If `YES`, enables the stubs. If `NO`, disable all the - * stubs and let all the requests hit the real world. - * - * @note OHHTTPStubs are enabled by default, so there is no need to call - * this method with `YES` for stubs to work, except if you explicitely - * disabled the stubs before. - * - * @note This only affects requests that are further made using `NSURLConnection` - * or using `[NSURLSession sharedSession]`. This does not affect requests - * sent on an `NSURLSession` created using an `NSURLSessionConfiguration`. - */ -+(void)setEnabled:(BOOL)enabled; - -/** - * Whether or not stubs are enabled for the shared session or for `NSURLConnection` - * - * @return If `YES` the stubs are enabled. If `NO` then the stubs are disabled - */ -+(BOOL)isEnabled; - -#if defined(__IPHONE_7_0) || defined(__MAC_10_9) -/** - * Enable or disable the stubs on a given `NSURLSessionConfiguration`. - * - * @param enabled If `YES`, enables the stubs for this `NSURLSessionConfiguration`. - * If `NO`, disable the stubs and let all the requests hit the real world - * @param sessionConfig The NSURLSessionConfiguration on which to enabled/disable the stubs - * - * @note OHHTTPStubs are enabled by default on newly created `defaultSessionConfiguration` - * and `ephemeralSessionConfiguration`, so there is no need to call this method with - * `YES` for stubs to work. You generally only use this if you want to disable - * `OHTTPStubs` per `NSURLSession` by calling it before building the `NSURLSession` - * with the `NSURLSessionConfiguration`. - * - * @note Important: As usual according to the way `NSURLSessionConfiguration` works, you - * MUST set this property BEFORE creating the `NSURLSession`. Once the `NSURLSession` - * object is created, they use a deep copy of the `NSURLSessionConfiguration` object - * used to create them, so changing the configuration later does not affect already - * created sessions. - */ -+ (void)setEnabled:(BOOL)enabled forSessionConfiguration:(NSURLSessionConfiguration *)sessionConfig; - -/** - * Whether stubs are enabled or disabled on a given `NSURLSessionConfiguration` - * - * @param sessionConfig The NSURLSessionConfiguration on which to enable/disable the stubs - * - * @return If `YES` the stubs are enabled for sessionConfig. If `NO` then the stubs are disabled - */ -+ (BOOL)isEnabledForSessionConfiguration:(NSURLSessionConfiguration *)sessionConfig; -#endif - -#pragma mark - Debug Methods - -/** - * List all the installed stubs - * - * @return An array of `id` objects currently installed. Useful for debug. - */ -+(NSArray*)allStubs; - -/** - * Setup a block to be called each time a stub is triggered. - * - * Useful if you want to log all your requests being stubbed for example and see which stub - * was used to respond to each request. - * - * @param block The block to call each time a request is being stubbed by OHHTTPStubs. - * Set it to `nil` to do nothing. Defaults is `nil`. - */ -+(void)onStubActivation:( nullable void(^)(NSURLRequest* request, id stub, OHHTTPStubsResponse* responseStub) )block; - -/** - * Setup a block to be called whenever OHHTTPStubs encounters a redirect request. - * - * @param block The block to call each time a redirect request is being stubbed by OHHTTPStubs. - * Set it to `nil` to do nothing. Defaults is `nil`. - */ -+(void)onStubRedirectResponse:( nullable void(^)(NSURLRequest* request, NSURLRequest* redirectRequest, id stub, OHHTTPStubsResponse* responseStub) )block; - -/** - * Setup a block to be called each time a stub finishes. Useful if stubs take an insignificant amount - * of time to execute (due to low bandwidth or delayed response time). This block may also be called - * if there are errors generated by OHHTTPStubs in the course of executing a network request. - * - * @param block The block to call each time a request is finished being stubbed by OHHTTPStubs. - * Set it to `nil` to do nothing. Defaults is `nil`. - */ -+(void)afterStubFinish:( nullable void(^)(NSURLRequest* request, id stub, OHHTTPStubsResponse* responseStub, NSError *error) )block; - -/** - * Setup a block to be called whenever OHHTTPStubs encounters a missing stub. - * - * @param block The block to call each time no stub for a request can be found. - * Set it to `nil` to do nothing. Defaults is `nil`. - */ -+(void)onStubMissing:( nullable void(^)(NSURLRequest* request) )block; - -@end - -NS_ASSUME_NONNULL_END - diff --git a/Example/BNPayment-Example/OHHTTPStubs.m b/Example/BNPayment-Example/OHHTTPStubs.m deleted file mode 100755 index ff21e64..0000000 --- a/Example/BNPayment-Example/OHHTTPStubs.m +++ /dev/null @@ -1,637 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - -#if ! __has_feature(objc_arc) -#error This file is expected to be compiled with ARC turned ON -#endif - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import "OHHTTPStubs.h" - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Types & Constants - -@interface OHHTTPStubsProtocol : NSURLProtocol @end - -static NSTimeInterval const kSlotTime = 0.25; // Must be >0. We will send a chunk of the data from the stream each 'slotTime' seconds - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Private Interfaces - -@interface OHHTTPStubs() -+ (instancetype)sharedInstance; -@property(atomic, copy) NSMutableArray* stubDescriptors; -@property(atomic, assign) BOOL enabledState; -@property(atomic, copy, nullable) void (^onStubActivationBlock)(NSURLRequest*, id, OHHTTPStubsResponse*); -@property(atomic, copy, nullable) void (^onStubRedirectBlock)(NSURLRequest*, NSURLRequest*, id, OHHTTPStubsResponse*); -@property(atomic, copy, nullable) void (^afterStubFinishBlock)(NSURLRequest*, id, OHHTTPStubsResponse*, NSError*); -@property(atomic, copy, nullable) void (^onStubMissingBlock)(NSURLRequest*); -@end - -@interface OHHTTPStubsDescriptor : NSObject -@property(atomic, copy) OHHTTPStubsTestBlock testBlock; -@property(atomic, copy) OHHTTPStubsResponseBlock responseBlock; -@end - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - OHHTTPStubsDescriptor Implementation - -@implementation OHHTTPStubsDescriptor - -@synthesize name = _name; - -+(instancetype)stubDescriptorWithTestBlock:(OHHTTPStubsTestBlock)testBlock - responseBlock:(OHHTTPStubsResponseBlock)responseBlock -{ - OHHTTPStubsDescriptor* stub = [OHHTTPStubsDescriptor new]; - stub.testBlock = testBlock; - stub.responseBlock = responseBlock; - return stub; -} - --(NSString*)description -{ - return [NSString stringWithFormat:@"<%@ %p : %@>", self.class, self, self.name]; -} - -@end - - - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - OHHTTPStubs Implementation - -@implementation OHHTTPStubs - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Singleton methods - -+ (instancetype)sharedInstance -{ - static OHHTTPStubs *sharedInstance = nil; - - static dispatch_once_t predicate; - dispatch_once(&predicate, ^{ - sharedInstance = [[self alloc] init]; - }); - - return sharedInstance; -} - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Setup & Teardown - -+ (void)initialize -{ - if (self == [OHHTTPStubs class]) - { - [self _setEnable:YES]; - } -} -- (instancetype)init -{ - self = [super init]; - if (self) - { - _stubDescriptors = [NSMutableArray array]; - _enabledState = YES; // assume initialize has already been run - } - return self; -} - -- (void)dealloc -{ - [self.class _setEnable:NO]; -} - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Public class methods - -#pragma mark > Adding & Removing stubs - -+(id)stubRequestsPassingTest:(OHHTTPStubsTestBlock)testBlock - withStubResponse:(OHHTTPStubsResponseBlock)responseBlock -{ - OHHTTPStubsDescriptor* stub = [OHHTTPStubsDescriptor stubDescriptorWithTestBlock:testBlock - responseBlock:responseBlock]; - [OHHTTPStubs.sharedInstance addStub:stub]; - return stub; -} - -+(BOOL)removeStub:(id)stubDesc -{ - return [OHHTTPStubs.sharedInstance removeStub:stubDesc]; -} - -+(void)removeAllStubs -{ - [OHHTTPStubs.sharedInstance removeAllStubs]; -} - -#pragma mark > Disabling & Re-Enabling stubs - -+(void)_setEnable:(BOOL)enable -{ - if (enable) - { - [NSURLProtocol registerClass:OHHTTPStubsProtocol.class]; - } - else - { - [NSURLProtocol unregisterClass:OHHTTPStubsProtocol.class]; - } -} - -+(void)setEnabled:(BOOL)enabled -{ - [OHHTTPStubs.sharedInstance setEnabled:enabled]; -} - -+(BOOL)isEnabled -{ - return OHHTTPStubs.sharedInstance.isEnabled; -} - -#if defined(__IPHONE_7_0) || defined(__MAC_10_9) -+ (void)setEnabled:(BOOL)enable forSessionConfiguration:(NSURLSessionConfiguration*)sessionConfig -{ - // Runtime check to make sure the API is available on this version - if ( [sessionConfig respondsToSelector:@selector(protocolClasses)] - && [sessionConfig respondsToSelector:@selector(setProtocolClasses:)]) - { - NSMutableArray * urlProtocolClasses = [NSMutableArray arrayWithArray:sessionConfig.protocolClasses]; - Class protoCls = OHHTTPStubsProtocol.class; - if (enable && ![urlProtocolClasses containsObject:protoCls]) - { - [urlProtocolClasses insertObject:protoCls atIndex:0]; - } - else if (!enable && [urlProtocolClasses containsObject:protoCls]) - { - [urlProtocolClasses removeObject:protoCls]; - } - sessionConfig.protocolClasses = urlProtocolClasses; - } - else - { - NSLog(@"[OHHTTPStubs] %@ is only available when running on iOS7+/OSX9+. " - @"Use conditions like 'if ([NSURLSessionConfiguration class])' to only call " - @"this method if the user is running iOS7+/OSX9+.", NSStringFromSelector(_cmd)); - } -} - -+ (BOOL)isEnabledForSessionConfiguration:(NSURLSessionConfiguration *)sessionConfig -{ - // Runtime check to make sure the API is available on this version - if ( [sessionConfig respondsToSelector:@selector(protocolClasses)] - && [sessionConfig respondsToSelector:@selector(setProtocolClasses:)]) - { - NSMutableArray * urlProtocolClasses = [NSMutableArray arrayWithArray:sessionConfig.protocolClasses]; - Class protoCls = OHHTTPStubsProtocol.class; - return [urlProtocolClasses containsObject:protoCls]; - } - else - { - NSLog(@"[OHHTTPStubs] %@ is only available when running on iOS7+/OSX9+. " - @"Use conditions like 'if ([NSURLSessionConfiguration class])' to only call " - @"this method if the user is running iOS7+/OSX9+.", NSStringFromSelector(_cmd)); - return NO; - } -} -#endif - -#pragma mark > Debug Methods - -+(NSArray*)allStubs -{ - return [OHHTTPStubs.sharedInstance stubDescriptors]; -} - -+(void)onStubActivation:( nullable void(^)(NSURLRequest* request, id stub, OHHTTPStubsResponse* responseStub) )block -{ - [OHHTTPStubs.sharedInstance setOnStubActivationBlock:block]; -} - -+(void)onStubRedirectResponse:( nullable void(^)(NSURLRequest* request, NSURLRequest* redirectRequest, id stub, OHHTTPStubsResponse* responseStub) )block -{ - [OHHTTPStubs.sharedInstance setOnStubRedirectBlock:block]; -} - -+(void)afterStubFinish:( nullable void(^)(NSURLRequest* request, id stub, OHHTTPStubsResponse* responseStub, NSError* error) )block -{ - [OHHTTPStubs.sharedInstance setAfterStubFinishBlock:block]; -} - -+(void)onStubMissing:( nullable void(^)(NSURLRequest* request) )block -{ - [OHHTTPStubs.sharedInstance setOnStubMissingBlock:block]; -} - - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Private instance methods - --(BOOL)isEnabled -{ - BOOL enabled = NO; - @synchronized(self) - { - enabled = _enabledState; - } - return enabled; -} - --(void)setEnabled:(BOOL)enable -{ - @synchronized(self) - { - _enabledState = enable; - [self.class _setEnable:_enabledState]; - } -} - --(void)addStub:(OHHTTPStubsDescriptor*)stubDesc -{ - @synchronized(_stubDescriptors) - { - [_stubDescriptors addObject:stubDesc]; - } -} - --(BOOL)removeStub:(id)stubDesc -{ - BOOL handlerFound = NO; - @synchronized(_stubDescriptors) - { - handlerFound = [_stubDescriptors containsObject:stubDesc]; - [_stubDescriptors removeObject:stubDesc]; - } - return handlerFound; -} - --(void)removeAllStubs -{ - @synchronized(_stubDescriptors) - { - [_stubDescriptors removeAllObjects]; - } -} - -- (OHHTTPStubsDescriptor*)firstStubPassingTestForRequest:(NSURLRequest*)request -{ - OHHTTPStubsDescriptor* foundStub = nil; - @synchronized(_stubDescriptors) - { - for(OHHTTPStubsDescriptor* stub in _stubDescriptors.reverseObjectEnumerator) - { - if (stub.testBlock(request)) - { - foundStub = stub; - break; - } - } - } - return foundStub; -} - -@end - - - - - - - - - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Private Protocol Class - -@interface OHHTTPStubsProtocol() -@property(assign) BOOL stopped; -@property(strong) OHHTTPStubsDescriptor* stub; -@property(assign) CFRunLoopRef clientRunLoop; -- (void)executeOnClientRunLoopAfterDelay:(NSTimeInterval)delayInSeconds block:(dispatch_block_t)block; -@end - -@implementation OHHTTPStubsProtocol - -+ (BOOL)canInitWithRequest:(NSURLRequest *)request -{ - BOOL found = ([OHHTTPStubs.sharedInstance firstStubPassingTestForRequest:request] != nil); - if (!found && OHHTTPStubs.sharedInstance.onStubMissingBlock) { - OHHTTPStubs.sharedInstance.onStubMissingBlock(request); - } - return found; -} - -- (id)initWithRequest:(NSURLRequest *)request cachedResponse:(NSCachedURLResponse *)response client:(id)client -{ - // Make super sure that we never use a cached response. - OHHTTPStubsProtocol* proto = [super initWithRequest:request cachedResponse:nil client:client]; - proto.stub = [OHHTTPStubs.sharedInstance firstStubPassingTestForRequest:request]; - return proto; -} - -+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request -{ - return request; -} - -- (NSCachedURLResponse *)cachedResponse -{ - return nil; -} - -- (void)startLoading -{ - self.clientRunLoop = CFRunLoopGetCurrent(); - NSURLRequest* request = self.request; - id client = self.client; - - if (!self.stub) - { - NSDictionary* userInfo = [NSDictionary dictionaryWithObjectsAndKeys: - @"It seems like the stub has been removed BEFORE the response had time to be sent.", - NSLocalizedFailureReasonErrorKey, - @"For more info, see https://github.com/AliSoftware/OHHTTPStubs/wiki/OHHTTPStubs-and-asynchronous-tests", - NSLocalizedRecoverySuggestionErrorKey, - request.URL, // Stop right here if request.URL is nil - NSURLErrorFailingURLErrorKey, - nil]; - NSError* error = [NSError errorWithDomain:@"OHHTTPStubs" code:500 userInfo:userInfo]; - [client URLProtocol:self didFailWithError:error]; - if (OHHTTPStubs.sharedInstance.afterStubFinishBlock) - { - OHHTTPStubs.sharedInstance.afterStubFinishBlock(request, self.stub, nil, error); - } - return; - } - - OHHTTPStubsResponse* responseStub = self.stub.responseBlock(request); - - if (OHHTTPStubs.sharedInstance.onStubActivationBlock) - { - OHHTTPStubs.sharedInstance.onStubActivationBlock(request, self.stub, responseStub); - } - - if (responseStub.error == nil) - { - NSHTTPURLResponse* urlResponse = [[NSHTTPURLResponse alloc] initWithURL:request.URL - statusCode:responseStub.statusCode - HTTPVersion:@"HTTP/1.1" - headerFields:responseStub.httpHeaders]; - - // Cookies handling - if (request.HTTPShouldHandleCookies && request.URL) - { - NSArray* cookies = [NSHTTPCookie cookiesWithResponseHeaderFields:responseStub.httpHeaders forURL:request.URL]; - if (cookies) - { - [NSHTTPCookieStorage.sharedHTTPCookieStorage setCookies:cookies forURL:request.URL mainDocumentURL:request.mainDocumentURL]; - } - } - - - NSString* redirectLocation = (responseStub.httpHeaders)[@"Location"]; - NSURL* redirectLocationURL; - if (redirectLocation) - { - redirectLocationURL = [NSURL URLWithString:redirectLocation]; - } - else - { - redirectLocationURL = nil; - } - [self executeOnClientRunLoopAfterDelay:responseStub.requestTime block:^{ - if (!self.stopped) - { - // Notify if a redirection occurred - if (((responseStub.statusCode > 300) && (responseStub.statusCode < 400)) && redirectLocationURL) - { - NSURLRequest *redirectRequest; - NSMutableURLRequest *mReq; - - switch (responseStub.statusCode) - { - case 301: - case 302: - case 307: - case 308: - //Preserve the original request method and body, and set the new location URL - mReq = [self.request mutableCopy]; - [mReq setURL:redirectLocationURL]; - redirectRequest = (NSURLRequest*)[mReq copy]; - break; - - default: - redirectRequest = [NSURLRequest requestWithURL:redirectLocationURL]; - break; - } - - [client URLProtocol:self wasRedirectedToRequest:redirectRequest redirectResponse:urlResponse]; - if (OHHTTPStubs.sharedInstance.onStubRedirectBlock) - { - OHHTTPStubs.sharedInstance.onStubRedirectBlock(request, redirectRequest, self.stub, responseStub); - } - } - - // Send the response (even for redirections) - [client URLProtocol:self didReceiveResponse:urlResponse cacheStoragePolicy:NSURLCacheStorageNotAllowed]; - if(responseStub.inputStream.streamStatus == NSStreamStatusNotOpen) - { - [responseStub.inputStream open]; - } - [self streamDataForClient:client - withStubResponse:responseStub - completion:^(NSError * error) - { - [responseStub.inputStream close]; - NSError *blockError = nil; - if (error==nil) - { - [client URLProtocolDidFinishLoading:self]; - } - else - { - [client URLProtocol:self didFailWithError:responseStub.error]; - blockError = responseStub.error; - } - if (OHHTTPStubs.sharedInstance.afterStubFinishBlock) - { - OHHTTPStubs.sharedInstance.afterStubFinishBlock(request, self.stub, responseStub, blockError); - } - }]; - } - }]; - } else { - // Send the canned error - [self executeOnClientRunLoopAfterDelay:responseStub.responseTime block:^{ - if (!self.stopped) - { - [client URLProtocol:self didFailWithError:responseStub.error]; - if (OHHTTPStubs.sharedInstance.afterStubFinishBlock) - { - OHHTTPStubs.sharedInstance.afterStubFinishBlock(request, self.stub, responseStub, responseStub.error); - } - } - }]; - } -} - -- (void)stopLoading -{ - self.stopped = YES; -} - -typedef struct { - NSTimeInterval slotTime; - double chunkSizePerSlot; - double cumulativeChunkSize; -} OHHTTPStubsStreamTimingInfo; - -- (void)streamDataForClient:(id)client - withStubResponse:(OHHTTPStubsResponse*)stubResponse - completion:(void(^)(NSError * error))completion -{ - if (!self.stopped) - { - if ((stubResponse.dataSize>0) && stubResponse.inputStream.hasBytesAvailable) - { - // Compute timing data once and for all for this stub - - OHHTTPStubsStreamTimingInfo timingInfo = { - .slotTime = kSlotTime, // Must be >0. We will send a chunk of data from the stream each 'slotTime' seconds - .cumulativeChunkSize = 0 - }; - - if(stubResponse.responseTime < 0) - { - // Bytes send each 'slotTime' seconds = Speed in KB/s * 1000 * slotTime in seconds - timingInfo.chunkSizePerSlot = (fabs(stubResponse.responseTime) * 1000) * timingInfo.slotTime; - } - else if (stubResponse.responseTime < kSlotTime) // includes case when responseTime == 0 - { - // We want to send the whole data quicker than the slotTime, so send it all in one chunk. - timingInfo.chunkSizePerSlot = stubResponse.dataSize; - timingInfo.slotTime = stubResponse.responseTime; - } - else - { - // Bytes send each 'slotTime' seconds = (Whole size in bytes / response time) * slotTime = speed in bps * slotTime in seconds - timingInfo.chunkSizePerSlot = ((stubResponse.dataSize/stubResponse.responseTime) * timingInfo.slotTime); - } - - [self streamDataForClient:client - fromStream:stubResponse.inputStream - timingInfo:timingInfo - completion:completion]; - } - else - { - [self executeOnClientRunLoopAfterDelay:stubResponse.responseTime block:^{ - if (completion && !self.stopped) - { - completion(nil); - } - }]; - } - } -} - -- (void) streamDataForClient:(id)client - fromStream:(NSInputStream*)inputStream - timingInfo:(OHHTTPStubsStreamTimingInfo)timingInfo - completion:(void(^)(NSError * error))completion -{ - NSParameterAssert(timingInfo.chunkSizePerSlot > 0); - - if (inputStream.hasBytesAvailable && (!self.stopped)) - { - // This is needed in case we computed a non-integer chunkSizePerSlot, to avoid cumulative errors - double cumulativeChunkSizeAfterRead = timingInfo.cumulativeChunkSize + timingInfo.chunkSizePerSlot; - NSUInteger chunkSizeToRead = floor(cumulativeChunkSizeAfterRead) - floor(timingInfo.cumulativeChunkSize); - timingInfo.cumulativeChunkSize = cumulativeChunkSizeAfterRead; - - if (chunkSizeToRead == 0) - { - // Nothing to read at this pass, but probably later - [self executeOnClientRunLoopAfterDelay:timingInfo.slotTime block:^{ - [self streamDataForClient:client fromStream:inputStream - timingInfo:timingInfo completion:completion]; - }]; - } else { - uint8_t* buffer = (uint8_t*)malloc(sizeof(uint8_t)*chunkSizeToRead); - NSInteger bytesRead = [inputStream read:buffer maxLength:chunkSizeToRead]; - if (bytesRead > 0) - { - NSData * data = [NSData dataWithBytes:buffer length:bytesRead]; - // Wait for 'slotTime' seconds before sending the chunk. - // If bytesRead < chunkSizePerSlot (because we are near the EOF), adjust slotTime proportionally to the bytes remaining - [self executeOnClientRunLoopAfterDelay:((double)bytesRead / (double)chunkSizeToRead) * timingInfo.slotTime block:^{ - [client URLProtocol:self didLoadData:data]; - [self streamDataForClient:client fromStream:inputStream - timingInfo:timingInfo completion:completion]; - }]; - } - else - { - if (completion) - { - // Note: We may also arrive here with no error if we were just at the end of the stream (EOF) - // In that case, hasBytesAvailable did return YES (because at the limit of OEF) but nothing were read (because EOF) - // But then in that case inputStream.streamError will be nil so that's cool, we won't return an error anyway - completion(inputStream.streamError); - } - } - free(buffer); - } - } - else - { - if (completion) - { - completion(nil); - } - } -} - -///////////////////////////////////////////// -// Delayed execution utility methods -///////////////////////////////////////////// - -- (void)executeOnClientRunLoopAfterDelay:(NSTimeInterval)delayInSeconds block:(dispatch_block_t)block -{ - dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC)); - dispatch_after(popTime, dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ - CFRunLoopPerformBlock(self.clientRunLoop, kCFRunLoopDefaultMode, block); - CFRunLoopWakeUp(self.clientRunLoop); - }); -} - -@end diff --git a/Example/BNPayment-Example/OHHTTPStubsResponse.h b/Example/BNPayment-Example/OHHTTPStubsResponse.h deleted file mode 100755 index f9995fc..0000000 --- a/Example/BNPayment-Example/OHHTTPStubsResponse.h +++ /dev/null @@ -1,301 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import - -#import "Compatibility.h" - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Defines & Constants - -// Non-standard download speeds -extern const double -OHHTTPStubsDownloadSpeed1KBPS, // 1.0 KB per second -OHHTTPStubsDownloadSpeedSLOW; // 1.5 KB per second - -// Standard download speeds. -extern const double -OHHTTPStubsDownloadSpeedGPRS, -OHHTTPStubsDownloadSpeedEDGE, -OHHTTPStubsDownloadSpeed3G, -OHHTTPStubsDownloadSpeed3GPlus, -OHHTTPStubsDownloadSpeedWifi; - - -NS_ASSUME_NONNULL_BEGIN - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Interface - -/** - * Stubs Response. This describes a stubbed response to be returned by the URL Loading System, - * including its HTTP headers, body, statusCode and response time. - */ -@interface OHHTTPStubsResponse : NSObject - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Properties - -/** - * The headers to use for the fake response - */ -@property(nonatomic, strong, nullable) NSDictionary* httpHeaders; -/** - * The HTTP status code to use for the fake response - */ -@property(nonatomic, assign) int statusCode; -/** - * The inputStream used when sending the response. - * @note You generally don't manipulate this directly. - */ -@property(nonatomic, strong, nullable) NSInputStream* inputStream; -/** - * The size of the fake response body, in bytes. - */ -@property(nonatomic, assign) unsigned long long dataSize; -/** - * The duration to wait before faking receiving the response headers. - * - * Defaults to 0.0. - */ -@property(nonatomic, assign) NSTimeInterval requestTime; -/** - * The duration to use to send the fake response body. - * - * @note if responseTime<0, it is interpreted as a download speed in KBps ( -200 => 200KB/s ) - */ -@property(nonatomic, assign) NSTimeInterval responseTime; -/** - * The fake error to generate to simulate a network error. - * - * If `error` is non-`nil`, the request will result in a failure and no response will be sent. - */ -@property(nonatomic, strong, nullable) NSError* error; - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Commodity Constructors -/*! @name Commodity */ - -/* -------------------------------------------------------------------------- */ -#pragma mark > Building response from NSData - -/** - * Builds a response given raw data. - * - * @note Internally calls `-initWithInputStream:dataSize:statusCode:headers:` with and inputStream built from the NSData. - * - * @param data The raw data to return in the response - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - */ -+(instancetype)responseWithData:(NSData*)data - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders; - - -/* -------------------------------------------------------------------------- */ -#pragma mark > Building response from a file - -/** - * Builds a response given a file path, the status code and headers. - * - * @param filePath The file path that contains the response body to return. - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note It is encouraged to use the OHPathHelpers functions & macros to build - * the filePath parameter easily - */ -+(instancetype)responseWithFileAtPath:(NSString *)filePath - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders; - - -/** - * Builds a response given a URL, the status code, and headers. - * - * @param fileURL The URL for the data to return in the response - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note This method applies only to URLs that represent file system resources - */ -+(instancetype)responseWithFileURL:(NSURL *)fileURL - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders; - -/* -------------------------------------------------------------------------- */ -#pragma mark > Building an error response - -/** - * Builds a response that corresponds to the given error - * - * @param error The error to use in the stubbed response. - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note For example you could use an error like `[NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil]` - */ -+(instancetype)responseWithError:(NSError*)error; - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Commotidy Setters - -/** - * Set the `responseTime` of the `OHHTTPStubsResponse` and return `self`. Useful for chaining method calls. - * - * _Usage example:_ - *
return [[OHHTTPStubsResponse responseWithData:data statusCode:200 headers:nil] responseTime:5.0];
- * - * @param responseTime If positive, the amount of time used to send the entire response. - * If negative, the rate in KB/s at which to send the response data. - * Useful to simulate slow networks for example. You may use the - * _OHHTTPStubsDownloadSpeed…_ constants here. - * - * @return `self` (= the same `OHHTTPStubsResponse` that was the target of this method). - * Returning `self` is useful for chaining method calls. - */ --(instancetype)responseTime:(NSTimeInterval)responseTime; - -/** - * Set both the `requestTime` and the `responseTime` of the `OHHTTPStubsResponse` at once. - * Useful for chaining method calls. - * - * _Usage example:_ - *
return [[OHHTTPStubsResponse responseWithData:data statusCode:200 headers:nil]
- *            requestTime:1.0 responseTime:5.0];
- * - * @param requestTime The time to wait before the response begins to send. This value must be greater than or equal to zero. - * @param responseTime If positive, the amount of time used to send the entire response. - * If negative, the rate in KB/s at which to send the response data. - * Useful to simulate slow networks for example. You may use the - * _OHHTTPStubsDownloadSpeed…_ constants here. - * - * @return `self` (= the same `OHHTTPStubsResponse` that was the target of this method). Useful for chaining method calls. - */ --(instancetype)requestTime:(NSTimeInterval)requestTime responseTime:(NSTimeInterval)responseTime; - - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Initializers -/*! @name Initializers */ - -/** - * Designated empty initializer - * - * @return An empty `OHHTTPStubsResponse` on which you need to set either an error or a statusCode, httpHeaders, inputStream and dataSize. - * - * @note This is not recommended to use this method directly. You should use `initWithInputStream:dataSize:statusCode:headers:` instead. - */ --(instancetype)init NS_DESIGNATED_INITIALIZER; - -/** - * Designed initializer. Initialize a response with the given input stream, dataSize, - * statusCode and headers. - * - * @param inputStream The input stream that will provide the data to return in the response - * @param dataSize The size of the data in the stream. - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note You will probably never need to call this method yourself. Prefer the other initializers (that will call this method eventually) - */ --(instancetype)initWithInputStream:(NSInputStream*)inputStream - dataSize:(unsigned long long)dataSize - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders NS_DESIGNATED_INITIALIZER; - - -/** - * Initialize a response with a given file path, statusCode and headers. - * - * @param filePath The file path of the data to return in the response - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note This method simply builds the NSInputStream, compute the file size, and then call `-initWithInputStream:dataSize:statusCode:headers:` - */ --(instancetype)initWithFileAtPath:(NSString*)filePath - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders; - - -/** - * Initialize a response with a given URL, statusCode and headers. - * - * @param fileURL The URL for the data to return in the response - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note This method applies only to URLs that represent file system resources - */ --(instancetype)initWithFileURL:(NSURL *)fileURL - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders; - -/** - * Initialize a response with the given data, statusCode and headers. - * - * @param data The raw data to return in the response - * @param statusCode The HTTP Status Code to use in the response - * @param httpHeaders The HTTP Headers to return in the response - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - */ --(instancetype)initWithData:(NSData*)data - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders; - - -/** - * Designed initializer. Initialize a response with the given error. - * - * @param error The error to use in the stubbed response. - * - * @return An `OHHTTPStubsResponse` describing the corresponding response to return by the stub - * - * @note For example you could use an error like `[NSError errorWithDomain:NSURLErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:nil]` - */ --(instancetype)initWithError:(NSError*)error NS_DESIGNATED_INITIALIZER; - -@end - -NS_ASSUME_NONNULL_END diff --git a/Example/BNPayment-Example/OHHTTPStubsResponse.m b/Example/BNPayment-Example/OHHTTPStubsResponse.m deleted file mode 100755 index c5d2a70..0000000 --- a/Example/BNPayment-Example/OHHTTPStubsResponse.m +++ /dev/null @@ -1,220 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - -#if ! __has_feature(objc_arc) -#error This file is expected to be compiled with ARC turned ON -#endif - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Imports - -#import "OHHTTPStubsResponse.h" - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Defines & Constants -const double OHHTTPStubsDownloadSpeed1KBPS =- 8 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeedSLOW =- 12 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeedGPRS =- 56 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeedEDGE =- 128 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeed3G =- 3200 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeed3GPlus =- 7200 / 8; // kbps -> KB/s -const double OHHTTPStubsDownloadSpeedWifi =- 12000 / 8; // kbps -> KB/s - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Implementation - -@implementation OHHTTPStubsResponse - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Commodity Constructors - - -#pragma mark > Building response from NSData - -+(instancetype)responseWithData:(NSData*)data - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders -{ - OHHTTPStubsResponse* response = [[self alloc] initWithData:data - statusCode:statusCode - headers:httpHeaders]; - return response; -} - - -#pragma mark > Building response from a file - -+(instancetype)responseWithFileAtPath:(NSString *)filePath - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders -{ - OHHTTPStubsResponse* response = [[self alloc] initWithFileAtPath:filePath - statusCode:statusCode - headers:httpHeaders]; - return response; -} - -+(instancetype)responseWithFileURL:(NSURL *)fileURL - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders -{ - OHHTTPStubsResponse* response = [[self alloc] initWithFileURL:fileURL - statusCode:statusCode - headers:httpHeaders]; - return response; -} - -#pragma mark > Building an error response - -+(instancetype)responseWithError:(NSError*)error -{ - OHHTTPStubsResponse* response = [[self alloc] initWithError:error]; - return response; -} - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Commotidy Setters - --(instancetype)responseTime:(NSTimeInterval)responseTime -{ - _responseTime = responseTime; - return self; -} - --(instancetype)requestTime:(NSTimeInterval)requestTime responseTime:(NSTimeInterval)responseTime -{ - _requestTime = requestTime; - _responseTime = responseTime; - return self; -} - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Initializers - --(instancetype)init -{ - self = [super init]; - return self; -} - --(instancetype)initWithInputStream:(NSInputStream*)inputStream - dataSize:(unsigned long long)dataSize - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders -{ - self = [super init]; - if (self) - { - _inputStream = inputStream; - _dataSize = dataSize; - _statusCode = statusCode; - NSMutableDictionary * headers = [NSMutableDictionary dictionaryWithDictionary:httpHeaders]; - static NSString *const ContentLengthHeader = @"Content-Length"; - if (!headers[ContentLengthHeader]) - { - headers[ContentLengthHeader] = [NSString stringWithFormat:@"%llu",_dataSize]; - } - _httpHeaders = [NSDictionary dictionaryWithDictionary:headers]; - } - return self; -} - --(instancetype)initWithFileAtPath:(NSString*)filePath - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders -{ - NSURL *fileURL = filePath ? [NSURL fileURLWithPath:filePath] : nil; - self = [self initWithFileURL:fileURL - statusCode:statusCode - headers:httpHeaders]; - return self; -} - --(instancetype)initWithFileURL:(NSURL *)fileURL - statusCode:(int)statusCode - headers:(nullable NSDictionary *)httpHeaders { - if (!fileURL) { - NSLog(@"%s: nil file path. Returning empty data", __PRETTY_FUNCTION__); - return [self initWithInputStream:[NSInputStream inputStreamWithData:[NSData data]] - dataSize:0 - statusCode:statusCode - headers:httpHeaders]; - } - - // [NSURL -isFileURL] is only available on iOS 8+ - NSAssert([fileURL.scheme isEqualToString:NSURLFileScheme], @"%s: Only file URLs may be passed to this method.",__PRETTY_FUNCTION__); - - NSNumber *fileSize; - NSError *error; - const BOOL success __unused = [fileURL getResourceValue:&fileSize forKey:NSURLFileSizeKey error:&error]; - - NSAssert(success && fileSize, @"%s Couldn't get the file size for URL. \ -The URL was: %@. \ -The operation to retrieve the file size was %@. \ -The error associated with that operation was: %@", - __PRETTY_FUNCTION__, fileURL, success ? @"successful" : @"unsuccessful", error); - - return [self initWithInputStream:[NSInputStream inputStreamWithURL:fileURL] - dataSize:[fileSize unsignedLongLongValue] - statusCode:statusCode - headers:httpHeaders]; -} - --(instancetype)initWithData:(NSData*)data - statusCode:(int)statusCode - headers:(nullable NSDictionary*)httpHeaders -{ - NSInputStream* inputStream = [NSInputStream inputStreamWithData:data?:[NSData data]]; - self = [self initWithInputStream:inputStream - dataSize:data.length - statusCode:statusCode - headers:httpHeaders]; - return self; -} - --(instancetype)initWithError:(NSError*)error -{ - self = [super init]; - if (self) { - _error = error; - } - return self; -} - --(NSString*)debugDescription -{ - return [NSString stringWithFormat:@"<%@ %p requestTime:%f responseTime:%f status:%d dataSize:%llu>", - self.class, self, self.requestTime, self.responseTime, self.statusCode, self.dataSize]; -} - -//////////////////////////////////////////////////////////////////////////////// -#pragma mark - Accessors - --(void)setRequestTime:(NSTimeInterval)requestTime -{ - NSAssert(requestTime >= 0, @"Invalid Request Time (%f) for OHHTTPStubResponse. Request time must be greater than or equal to zero",requestTime); - _requestTime = requestTime; -} - -@end diff --git a/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.h b/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.h deleted file mode 100755 index d924df4..0000000 --- a/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.h +++ /dev/null @@ -1,87 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -#import - -#import "Compatibility.h" - -NS_ASSUME_NONNULL_BEGIN - -/** - * Useful function to build a path given a file name and a class. - * - * @param fileName The name of the file to get the path to, including file extension - * @param inBundleForClass The class of the caller, used to determine the current bundle - * in which the file is supposed to be located. - * You should typically pass `self.class` (ObjC) or - * `self.dynamicType` (Swift < 3.0) or `type(of: self)` (Swift >= 3.0) when calling this function. - * - * @return The path of the given file in the same bundle as the inBundleForClass class - */ -NSString* __nullable OHPathForFile(NSString* fileName, Class inBundleForClass); - -/** - * Useful function to build a path given a file name and a bundle. - * - * @param fileName The name of the file to get the path to, including file extension - * @param bundle The bundle in which the file is supposed to be located. - * This parameter can't be null. - * - * @return The path of the given file in given bundle - * - * @note You should avoid using `[NSBundle mainBundle]` for the `bundle` parameter, - * as in the context of Unit Tests, this points to the Simulator's bundle, - * not the bundle of the app under test. That's why `nil` is not an acceptable - * value (so you won't expect it to default to the `mainBundle`). - * You should use `[NSBundle bundleForClass:]` instead. - */ -NSString* __nullable OHPathForFileInBundle(NSString* fileName, NSBundle* bundle); - -/** - * Useful function to build a path to a file in the Documents's directory in the - * app sandbox, used by iTunes File Sharing for example. - * - * @param fileName The name of the file to get the path to, including file extension - * - * @return The path of the file in the Documents directory in your App Sandbox - */ -NSString* __nullable OHPathForFileInDocumentsDir(NSString* fileName); - - - -/** - * Useful function to build an NSBundle located in the application's resources simply from its name - * - * @param bundleBasename The base name, without extension (extension is assumed to be ".bundle"). - * @param inBundleForClass The class of the caller, used to determine the current bundle - * in which the file is supposed to be located. - * You should typically pass `self.class` (ObjC) or - * `self.dynamicType` (Swift) when calling this function. - * - * @return The NSBundle object representing the bundle with the given basename located in your application's resources. - */ -NSBundle* __nullable OHResourceBundle(NSString* bundleBasename, Class inBundleForClass); - -NS_ASSUME_NONNULL_END diff --git a/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.m b/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.m deleted file mode 100755 index 89d1e05..0000000 --- a/Example/BNPayment-Example/OHPathHelpers/OHPathHelpers.m +++ /dev/null @@ -1,52 +0,0 @@ -/*********************************************************************************** - * - * Copyright (c) 2012 Olivier Halligon - * - * Permission is hereby granted, free of charge, to any person obtaining a copy - * of this software and associated documentation files (the "Software"), to deal - * in the Software without restriction, including without limitation the rights - * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell - * copies of the Software, and to permit persons to whom the Software is - * furnished to do so, subject to the following conditions: - * - * The above copyright notice and this permission notice shall be included in - * all copies or substantial portions of the Software. - * - * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - * THE SOFTWARE. - * - ***********************************************************************************/ - - -#import "OHPathHelpers.h" - -NSString* __nullable OHPathForFile(NSString* fileName, Class inBundleForClass) -{ - NSBundle* bundle = [NSBundle bundleForClass:inBundleForClass]; - return OHPathForFileInBundle(fileName, bundle); -} - -NSString* __nullable OHPathForFileInBundle(NSString* fileName, NSBundle* bundle) -{ - return [bundle pathForResource:[fileName stringByDeletingPathExtension] - ofType:[fileName pathExtension]]; -} - -NSString* __nullable OHPathForFileInDocumentsDir(NSString* fileName) -{ - NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); - NSString *basePath = (paths.count > 0) ? paths[0] : nil; - return [basePath stringByAppendingPathComponent:fileName]; -} - -NSBundle* __nullable OHResourceBundle(NSString* bundleBasename, Class inBundleForClass) -{ - NSBundle* classBundle = [NSBundle bundleForClass:inBundleForClass]; - return [NSBundle bundleWithPath:[classBundle pathForResource:bundleBasename - ofType:@"bundle"]]; -} diff --git a/Example/BNPayment-Example/ProductsViewController.swift b/Example/BNPayment-Example/ProductsViewController.swift deleted file mode 100644 index 96f9252..0000000 --- a/Example/BNPayment-Example/ProductsViewController.swift +++ /dev/null @@ -1,66 +0,0 @@ -// -// ProductsViewController.swift -// BNPayment-Example -// -// Created by Max Mattini on 27/03/2017. -// Copyright © 2017 Bambora. All rights reserved. -// - -import UIKit - -class ProductsViewController: UIViewController { - - @IBOutlet weak var vHeader: UIView! - @IBOutlet weak var lblTitle: UILabel! - @IBOutlet weak var btnPayYourBill: UIButton! - @IBOutlet weak var btnPaySimcard: UIButton! - @IBOutlet weak var btnOneYearPlan: UIButton! - @IBOutlet weak var btnTwoYearPlan: UIButton! - - @IBAction func btnPayYourBillAction(_ sender: Any) {registerOrSelectCard(amount: 12000, comment:"Pay Your Bill")} - @IBAction func btnPaySimcardAction(_ sender: Any) {registerOrSelectCard(amount: 5000, comment:"Pay Simcard")} - @IBAction func btnOneYearPlanAction(_ sender: Any) {registerOrSelectCard(amount: 1200, comment:"One Year Plan")} - @IBAction func btnTwoYearPlan(_ sender: Any) {registerOrSelectCard(amount: 1000, comment:"Two Year Plan")} - - func completeCardRegistration(p1:BNCCRegCompletion, p2:BNAuthorizedCreditCard?) ->Void - { - if let nav = self.navigationController { - nav.popViewController(animated: true) - } - } - - func registerOrSelectCard(amount:NSNumber, comment:String) -> Void{ - if let _ = BNPaymentHandler.sharedInstance().authorizedCards() { - - let parameters:[String:Any] = ["amount":amount, "comment":comment] - - self.performSegue(withIdentifier: "toCardView", sender: parameters) - } - } - - - override func prepare(for segue: UIStoryboardSegue, sender: Any?) { - if segue.identifier == "toCardView" { - if let cardVC = segue.destination as? CardsViewController { - let parameters = sender as! [String:Any] - cardVC.amount = parameters["amount"] as! NSNumber - cardVC.comment = parameters["comment"] as! String - } - } - } - - - - - override func viewDidLoad() { - super.viewDidLoad() - - // Do any additional setup after loading the view. - } - - override func didReceiveMemoryWarning() { - super.didReceiveMemoryWarning() - // Dispose of any resources that can be recreated. - } - -} diff --git a/Example/BNPayment-Example/TODO b/Example/BNPayment-Example/TODO deleted file mode 100644 index 5be8f40..0000000 --- a/Example/BNPayment-Example/TODO +++ /dev/null @@ -1,2 +0,0 @@ -- Remove hardcoded payment amount -- diff --git a/Example/BNPayment-Example/TestData/VisaCheckoutParams.json b/Example/BNPayment-Example/TestData/VisaCheckoutParams.json deleted file mode 100644 index 7326ac6..0000000 --- a/Example/BNPayment-Example/TestData/VisaCheckoutParams.json +++ /dev/null @@ -1,14 +0,0 @@ -{ - "apikey": "ZW06OP7C8MA8S1NM9J79136ZKOZs_hlr-SdJPOEax5Ri9eBb4", - "currencyCode": "AUD", - "subtotal": "11.00", - "externalClientId": "c182d487-d94b-4907-bd74-eaa107b05ec7", - "externalProfileId": "IPPMerchant147942", - "total": "11.00", - "locale": "en_AU", - "collectShipping": "true", - "message" : "Click to Pay Now", - "buttonAction": "Pay", - "buttonImageUrl": "https://sandbox.secure.checkout.visa.com/wallet-services-web/xo/button.png", - "jsLibraryUrl" : "https://sandbox-assets.secure.checkout.visa.com/checkout-widget/resources/js/integration/v1/sdk.js" -} diff --git a/Example/BNPayment-Example/TestData/VisaCheckoutTransaction.json b/Example/BNPayment-Example/TestData/VisaCheckoutTransaction.json deleted file mode 100644 index 9281298..0000000 --- a/Example/BNPayment-Example/TestData/VisaCheckoutTransaction.json +++ /dev/null @@ -1,19 +0,0 @@ -{ - "currency": "AUD", - "operations":null, - "payment": "217001832", - "captures": null, - "state": null, - "region": null, - "operationInProgress": "false", - "amount": 12000, - "refunds" : null, - "comment": null, - "merchant": "d7e4e8e4-8e44-4895-9731-c6031792e3a3", - "merchant": "02a4f74c-770c-48af-a51f-c67ffd58659e", - "receipt": "92055816", - "cardType": "", - "creditCardToken": "", - "cardHolderName" : "Mark", - "truncatedCard": "", -} diff --git a/Example/BNPayment-Example/ViewController.h b/Example/BNPayment-Example/ViewController.h deleted file mode 100644 index 932a562..0000000 --- a/Example/BNPayment-Example/ViewController.h +++ /dev/null @@ -1,14 +0,0 @@ -// -// BNViewController.h -// BNPayment -// -// Created by Bambora On Mobile AB on 11/12/2015. -// Copyright (c) 2015 Bambora On Mobile AB. All rights reserved. -// - -@import UIKit; - -@interface ViewController : UIViewController - -@end - diff --git a/Example/BNPayment-Example/ViewController.m b/Example/BNPayment-Example/ViewController.m deleted file mode 100644 index b392849..0000000 --- a/Example/BNPayment-Example/ViewController.m +++ /dev/null @@ -1,244 +0,0 @@ -// -// BNViewController.m -// BNPayment -// -// Created by Bambora On Mobile AB on 11/12/2015. -// Copyright (c) 2015 Bambora On Mobile AB. All rights reserved. -// - -#import "ViewController.h" -#import - -@interface ViewController () - -@end - -@implementation ViewController { - BNCCHostedRegistrationFormVC *ccHostedRegistrationVC; -} - -- (void)viewDidLoad { - [super viewDidLoad]; - // Do any additional setup after loading the view, typically from a nib. -} - -- (void)didReceiveMemoryWarning { - [super didReceiveMemoryWarning]; - // Dispose of any resources that can be recreated. -} - --(IBAction)registerCreditCard:(id)sender { - - BNCreditCardRegistrationVC *vc = [BNCreditCardRegistrationVC new]; - vc.completionBlock = ^(BNCCRegCompletion completion, BNAuthorizedCreditCard *card){ - [self.navigationController popViewControllerAnimated:YES]; - [self displaAliasAlertWithAuthorizedCard:card]; - }; - - [self.navigationController pushViewController:vc animated:YES]; -} - --(IBAction)registerCreditCardHostedForm:(id)sender { - UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 0, 50)]; - - ccHostedRegistrationVC = [[BNCCHostedRegistrationFormVC alloc] initWithHostedFormParams:[BNCCHostedFormParams mockObject]]; - ccHostedRegistrationVC.webviewDelegate = self; - [ccHostedRegistrationVC addHeaderView:headerView]; - - [self.navigationController pushViewController:ccHostedRegistrationVC animated:YES]; -} - --(IBAction)unregisterCreditCard:(id)sender { - NSArray *authorizedCards = [[BNPaymentHandler sharedInstance] authorizedCards]; - - if (authorizedCards.count > 0) { - - NSMutableArray *actions = [[NSMutableArray alloc] initWithCapacity:authorizedCards.count+1]; - - - [authorizedCards enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - __weak BNAuthorizedCreditCard *cc = obj; - NSString *actionTitle = cc.creditCardAlias ? cc.creditCardAlias : cc.creditCardNumber; - - UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * _Nonnull action) { - [[BNPaymentHandler sharedInstance] removeAuthorizedCreditCard:cc]; - }]; - [actions addObject:action]; - }]; - - UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel - handler:nil]; - [actions addObject:cancelAction]; - - [self displayAlertControllerWithStyle:UIAlertControllerStyleActionSheet - title:@"Choose credit card" - message:nil - action:actions]; - - } else { - UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault - handler:nil]; - [self displayAlertControllerWithStyle:UIAlertControllerStyleAlert - title:@"No credit card registered" - message:@"There is nothing to remove." - action:@[confirmAction]]; - } -} - --(IBAction)makePurchase:(id)sender { - NSArray *authorizedCards = [[BNPaymentHandler sharedInstance] authorizedCards]; - - if(authorizedCards.count > 0) { - - NSMutableArray *actions = [[NSMutableArray alloc] initWithCapacity:authorizedCards.count+1]; - - [authorizedCards enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { - __weak BNAuthorizedCreditCard *cc = obj; - NSString *actionTitle = cc.creditCardAlias ? cc.creditCardAlias : cc.creditCardNumber; - - UIAlertAction *action = [UIAlertAction actionWithTitle:actionTitle - style:UIAlertActionStyleDefault - handler:^(UIAlertAction * _Nonnull action) { - [self makePaymentWithCard:cc]; - }]; - [actions addObject:action]; - }]; - - UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleCancel - handler:nil]; - [actions addObject:cancelAction]; - - [self displayAlertControllerWithStyle:UIAlertControllerStyleActionSheet - title:@"Choose credit card" - message:nil - action:actions]; - - } else { - UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel - handler:nil]; - [self displayAlertControllerWithStyle:UIAlertControllerStyleAlert - title:@"No credit card registered" - message:@"Please register a credit card in order to make a purchase." - action:@[confirmAction]]; - } -} - -- (void)makePaymentWithCard:(BNAuthorizedCreditCard *)card { - BNPaymentParams *params = [BNPaymentParams mockObject]; - params.token = card.creditCardToken; - - [[BNPaymentHandler sharedInstance] makePaymentExtWithParams:params - result:^(NSDictionary* response, BNPaymentResult result, NSError *error) { - BOOL success = result == BNPaymentSuccess; - NSString *title = success ? @"Success" : @"Failure"; - - NSString* receipt = @"?"; - if (response){ - receipt = [response objectForKey:@"receipt"]; - } - - NSString *message = success ? - [NSString stringWithFormat:@"The payment succeeded. receipt= %@", receipt]: - [NSString stringWithFormat:@"The payment did not succeed."]; - - UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"Ok" - style:UIAlertActionStyleDefault - handler:nil]; - - [self displayAlertControllerWithStyle:UIAlertControllerStyleAlert - title:title - message:message - action:@[confirmAction]]; - }]; -} - - -- (void)displaAliasAlertWithAuthorizedCard:(BNAuthorizedCreditCard *) __weak card { - NSString *title = card ? @"Name" : @"No card"; - NSString *message = card ? @"Please name the credit card." : @"No credit card was registered!"; - - UIAlertController* alertController = [UIAlertController alertControllerWithTitle:title - message:message - preferredStyle:UIAlertControllerStyleAlert]; - - UIAlertAction *action = [UIAlertAction actionWithTitle:@"Ok" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - if(card) { - UITextField *aliasTextField = alertController.textFields.firstObject; - card.creditCardAlias = aliasTextField.text.length > 0 ? aliasTextField.text : card.creditCardNumber; - [[BNPaymentHandler sharedInstance] saveAuthorizedCreditCard:card]; - } - }]; - - if (card) { - [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { - textField.placeholder = @"Name"; - }]; - } - - [alertController addAction:action]; - - dispatch_async(dispatch_get_main_queue(), ^(){ - [self presentViewController:alertController animated:YES completion:nil]; - }); -} - -- (void)displayAlertControllerWithStyle:(UIAlertControllerStyle)style - title:(NSString *)title - message:(NSString *)message - action:(NSArray *)actions { - - UIAlertController* alert = [UIAlertController alertControllerWithTitle:title - message:message - preferredStyle:style]; - - for (UIAlertAction *action in actions) { - [alert addAction:action]; - } - - dispatch_async(dispatch_get_main_queue(), ^(){ - [self presentViewController:alert animated:YES completion:nil]; - }); -} - -#pragma mark - BNPaymentWebviewDelegate methods - -- (void)BNPaymentWebview:(BNPaymentWebview *)webview didRegisterAuthorizedCard:(BNAuthorizedCreditCard *)authorizedCard { - dispatch_async(dispatch_get_main_queue(), ^(){ - [self.navigationController popViewControllerAnimated:YES]; - [self displaAliasAlertWithAuthorizedCard:authorizedCard]; - }); -} - -- (void)BNPaymentWebview:(BNPaymentWebview *)webview didStartOperation:(BNPaymentWebviewOperation)operation { - if(operation == BNPWVOperationSubmitCCData) { - [ccHostedRegistrationVC setWebViewLoading:YES]; - } -} - -- (void)BNPaymentWebview:(BNPaymentWebview *)webview didFinishOperation:(BNPaymentWebviewOperation)operation { - if(operation == BNPWVOperationSubmitCCData) { - [ccHostedRegistrationVC setWebViewLoading:NO]; - } -} - -- (void)BNPaymentWebview:(BNPaymentWebview *)webview didFailOperation:(BNPaymentWebviewOperation)operation withError:(NSError *)error { - - if (error.code == EPAYSubmissionDeclined) { - [ccHostedRegistrationVC setWebViewLoading:NO]; - return; - } - - UIAlertAction* confirmAction = [UIAlertAction actionWithTitle:@"Ok" - style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { - dispatch_async(dispatch_get_main_queue(), ^(){ - [ccHostedRegistrationVC setWebViewLoading:NO]; - [self.navigationController popViewControllerAnimated:YES]; - }); - }]; - - [self displayAlertControllerWithStyle:UIAlertControllerStyleAlert title:@"Error" message:@"Error" action:@[confirmAction]]; -} - -@end diff --git a/Example/BNPayment-Example/main.m b/Example/BNPayment-Example/main.m deleted file mode 100644 index d0e2c87..0000000 --- a/Example/BNPayment-Example/main.m +++ /dev/null @@ -1,16 +0,0 @@ -// -// main.m -// BNPayment-Example -// -// Created by Oskar Henriksson on 07/04/2016. -// Copyright © 2016 Bambora. All rights reserved. -// - -#import -#import "AppDelegate.h" - -int main(int argc, char * argv[]) { - @autoreleasepool { - return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); - } -}