Skip to content

Commit

Permalink
Merge pull request #22 from chargebee/dev_v1.0.1
Browse files Browse the repository at this point in the history
Chargebee's iOS SDK will return subscription details when purchaseProduct function is invoked
CBProduct - Improvements
  • Loading branch information
cb-imayaselvan authored Nov 19, 2021
2 parents c9fdaff + 801d885 commit 381a9db
Show file tree
Hide file tree
Showing 12 changed files with 101 additions and 147 deletions.
2 changes: 1 addition & 1 deletion Chargebee.podspec
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@

Pod::Spec.new do |s|
s.name = 'Chargebee'
s.version = '1.0.0'
s.version = '1.0.1'
s.summary = 'Chargebee iOS SDK'

# This description is used to generate tags and improve search results.
Expand Down
6 changes: 3 additions & 3 deletions Chargebee/Classes/Configuration/CBEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -18,15 +18,16 @@ class CBEnvironment {
CBEnvironment.publishableApiKey = publishableApiKey
CBEnvironment.allowErrorLogging = allowErrorLogging
CBEnvironment.encodedApiKey = CBEnvironment.publishableApiKey.data(using: .utf8)?.base64EncodedString() ?? ""
// CBEnvironment.baseUrl = "https://\(CBEnvironment.site).chargebee.com/api"
CBEnvironment.baseUrl = "https://\(CBEnvironment.site).chargebee.com/api"
CBEnvironment.version = .unknown

if let sdkKey = sdkKey {
CBEnvironment.sdkKey = sdkKey
// Verify SDK Key
/// Verify SDK Key and Setup the Environment
CBAuthenticationManager.authenticate(forSDKKey: CBEnvironment.sdkKey) { result in
switch result {
case .success(let status):
print("Environment Setup - Completed")
CBEnvironment.version = status.details.version ?? .unknown
case .error(let error):
print(error)
Expand All @@ -35,7 +36,6 @@ class CBEnvironment {
}
}


}

}
80 changes: 50 additions & 30 deletions Chargebee/Classes/Purchase/CBPurchaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,8 @@ public class CBPurchase: NSObject {

private var productIDs: [String] = []
public var receiveProductsHandler: ((_ result: Result<[CBProduct], CBPurchaseError>) -> Void)?
public var buyProductHandler: ((Result<Bool, Error>) -> Void)?
public var buyProductHandler: ((Result<(status:Bool, subscription:CBSubscriptionStatus?), Error>) -> Void)?

private var restoredPurchasesCount = 0
var datasource: CBPurchaseDataSource?
private var activeProduct: SKProduct?
Expand All @@ -32,6 +33,9 @@ public class CBPurchase: NSObject {

public struct CBProduct {
public let product: SKProduct
init(product: SKProduct) {
self.product = product
}
}

extension Array where Element == SKProduct {
Expand All @@ -53,7 +57,6 @@ public extension CBPurchase {
func retrieveProducts(withProductID productIDs: [String], completion receiveProductsHandler: @escaping (_ result: Result<[CBProduct], CBPurchaseError>) -> Void) {
self.receiveProductsHandler = receiveProductsHandler

// To Be commented for Local testing of Get Products
var _productIDs: [String] = []
if productIDs.count > 0 {
_productIDs = productIDs
Expand All @@ -67,40 +70,55 @@ public extension CBPurchase {
}

let request = SKProductsRequest(productIdentifiers: Set(_productIDs))
// End of To Be Commented region for Local testing of Get Products

// To Be uncommented for Local testing of Get Products
//let request = SKProductsRequest(productIdentifiers: Set(["Chargebee02","Chargebee03","Chargebee04", "Chargebee05", "Chargebee06"]))
// End of To Be uncommented for Local testing of Get Products
request.delegate = self
request.start()
}

//Get the products without Product ID's
///Get the products without Product ID's
func retrieveProductIdentifers(queryParams : [String:String]? = nil, completion handler: @escaping ((_ result: Result<CBProductIDWrapper, Error>) -> Void)) {
var params = queryParams ?? [String:String]()
params["channel[is]"] = "app_store"
switch CBEnvironment.version {
case .v1:
CBProductsV1.getProducts(queryParams: params) { wrapper in
handler(.success(wrapper))
/// Based on user Cataloge version Plan will fetch from chargebee system

func retrieveProducts() {
switch CBEnvironment.version {
case .v1:
CBProductsV1.getProducts(queryParams: params) { wrapper in
handler(.success(wrapper))
return
}
case .v2:
CBProductsV2.getProducts(queryParams: params) { wrapper in
handler(.success(wrapper))
return
}
case .unknown:

handler(.failure(CBPurchaseError.invalidCatalogVersion))
return
}
case .v2:
CBProductsV2.getProducts(queryParams: params) { wrapper in
handler(.success(wrapper))
return
}
/// Check the Environment Version

if CBEnvironment.version == .unknown {
CBAuthenticationManager.authenticate(forSDKKey: CBEnvironment.sdkKey) { result in
switch result {
case .success(let status):
CBEnvironment.version = status.details.version ?? .unknown
retrieveProducts()
case .error(let error):
print(error)
handler(.failure(CBPurchaseError.invalidCatalogVersion))
}
}
case .unknown:
handler(.failure(CBPurchaseError.invalidCatalogVersion))
return
}else {
retrieveProducts()
}

}


//Buy the product
func purchaseProduct(product: CBProduct, customerId : String ,completion handler: @escaping ((_ result: Result<Bool, Error>) -> Void)) {
func purchaseProduct(product: CBProduct, customerId : String ,completion handler: @escaping ((_ result: Result<(status:Bool, subscription:CBSubscriptionStatus?), Error>) -> Void)) {
buyProductHandler = handler
activeProduct = product.product
customerID = customerId
Expand All @@ -125,7 +143,7 @@ public extension CBPurchase {
}

//Restore the purchase
func restorePurchases(completion handler: @escaping ((_ result: Result<Bool, Error>) -> Void)) {
func restorePurchases(completion handler: @escaping ((_ result: Result<(status:Bool, subscription:CBSubscriptionStatus?), Error>) -> Void)) {
buyProductHandler = handler
restoredPurchasesCount = 0
SKPaymentQueue.default().restoreCompletedTransactions()
Expand Down Expand Up @@ -176,8 +194,9 @@ extension CBPurchase: SKPaymentTransactionObserver {
if let productId = activeProduct?.productIdentifier,
let price = activeProduct?.price,
let currencyCode = activeProduct?.priceLocale.currencyCode {
let priceValue : Int = Int((price.doubleValue) * Double(100))
validateReceipt(for: productId, String(priceValue), currencyCode: currencyCode, customerId:customerID,completion: buyProductHandler)
let priceValue : Int = Int((price.doubleValue) * Double(100))
let name = activeProduct?.localizedTitle ?? productId
validateReceipt(for: productId, name: name, String(priceValue), currencyCode: currencyCode, customerId:customerID,completion: buyProductHandler)
}
case .restored:
restoredPurchasesCount += 1
Expand All @@ -200,7 +219,7 @@ extension CBPurchase: SKPaymentTransactionObserver {

public func paymentQueueRestoreCompletedTransactionsFinished(_ queue: SKPaymentQueue) {
if restoredPurchasesCount != 0 {
buyProductHandler?(.success(true))
buyProductHandler?(.success((true, nil)))
} else {
buyProductHandler?(.failure(CBPurchaseError.noProductToRestore))
}
Expand All @@ -215,7 +234,7 @@ extension CBPurchase: SKPaymentTransactionObserver {

//chargebee methods
public extension CBPurchase {
func validateReceipt(for productID: String, _ price: String, currencyCode: String, customerId :String,completion: ((Result<Bool, Error>) -> Void)?) {
func validateReceipt(for productID: String,name:String, _ price: String, currencyCode: String, customerId :String,completion: ((Result<(status:Bool, subscription:CBSubscriptionStatus?), Error>) -> Void)?) {
guard let appStoreReceiptURL = Bundle.main.appStoreReceiptURL,
FileManager.default.fileExists(atPath: appStoreReceiptURL.path) else {
debugPrint("No receipt Exist")
Expand All @@ -227,7 +246,8 @@ public extension CBPurchase {
let receiptString = receiptData.base64EncodedString(options: [])
// print("Receipt String is :\(receiptString)")
debugPrint("Apple Purchase - success")
CBReceiptValidationManager.validateReceipt(receipt: receiptString, productId: productID, price: price, currencyCode: currencyCode, customerId: customerID ) {

CBReceiptValidationManager.validateReceipt(receipt: receiptString, productId: productID,name: name, price: price, currencyCode: currencyCode, customerId: customerID ) {
(receiptResult) in DispatchQueue.main.async {
switch receiptResult {
case .success(let receipt):
Expand All @@ -240,15 +260,15 @@ public extension CBPurchase {
DispatchQueue.main.asyncAfter(deadline: .now() + 0.5) {
CBSubscription.retrieveSubscription(forID: receipt.subscriptionId) { subscriptionStatusResult in
switch subscriptionStatusResult {
case .success:
completion?(.success(true))
case let .success(statusResult):
completion?(.success((true, statusResult)))
case .error(let error):
completion?(.failure(error))
}
}
}
case .error(let error):
debugPrint("Chargebee - Receipt Upload - Failure")
debugPrint(" Chargebee - Receipt Upload - Failure")
completion?(.failure(error))
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ struct CBValidateReceipt: Decodable {
class CBReceiptValidationManager {
public static func validateReceipt(receipt: String,
productId: String,
name: String,
price: String,
currencyCode : String,
customerId : String,
Expand All @@ -36,7 +37,7 @@ class CBReceiptValidationManager {

let (onSuccess, onError) = CBResult.buildResultHandlers(handler,nil)

let request = CBAPIRequest(resource: CBValidateReceiptResource(receipt: receipt, productId: productId,
let request = CBAPIRequest(resource: CBValidateReceiptResource(receipt: receipt, productId: productId,name: name,
price: price, currencyCode : currencyCode,
customerId : customerId))
request.create(withCompletion: { (res: CBValidateReceiptWrapper?) in
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -57,11 +57,11 @@ class CBValidateReceiptResource: CBAPIResource {
return urlRequest
}

init(receipt: String, productId: String,
init(receipt: String, productId: String, name: String,
price: String, currencyCode : String,
customerId : String) {
self.baseUrl = CBEnvironment.baseUrl
self.requestBody = PayloadBody(receipt: receipt, productId: productId,
self.requestBody = PayloadBody(receipt: receipt, productId: productId,name: name,
price: price, currencyCode : currencyCode,
customerId : customerId)
}
Expand All @@ -71,6 +71,7 @@ class CBValidateReceiptResource: CBAPIResource {
struct PayloadBody: URLEncodedRequestBody {
let receipt: String
let productId: String
let name: String
let price: String
let currencyCode : String
let customerId : String
Expand All @@ -80,6 +81,7 @@ struct PayloadBody: URLEncodedRequestBody {
[
"receipt" : receipt,
"product[id]" : productId,
"product[name]": name,
"product[price]" :price,
"product[currency_code]" :currencyCode,
"customer[id]" :customerId,
Expand Down
4 changes: 0 additions & 4 deletions Example/Chargebee.xcodeproj/project.pbxproj
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,6 @@
607FACDD1AFB9204008FA782 /* Images.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 607FACDC1AFB9204008FA782 /* Images.xcassets */; };
607FACE01AFB9204008FA782 /* LaunchScreen.xib in Resources */ = {isa = PBXBuildFile; fileRef = 607FACDE1AFB9204008FA782 /* LaunchScreen.xib */; };
62B3F4F6713321E11E4A68BB /* Pods_Chargebee_Example.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = 2172435AB6EDB8C0EB2804F6 /* Pods_Chargebee_Example.framework */; };
72CD6DE82662856000E17CFE /* CBSDKPurchaseViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 854BE17C2653A5E100A9190D /* CBSDKPurchaseViewController.swift */; };
851009C0265BDA4B00B6A12E /* CBSDKProductTableViewCell.swift in Sources */ = {isa = PBXBuildFile; fileRef = 851009BE265BDA4B00B6A12E /* CBSDKProductTableViewCell.swift */; };
851009C1265BDA4B00B6A12E /* CBSDKProductTableViewCell.xib in Resources */ = {isa = PBXBuildFile; fileRef = 851009BF265BDA4B00B6A12E /* CBSDKProductTableViewCell.xib */; };
851009CB265BE7E000B6A12E /* CBSDKConfigurationViewController.swift in Sources */ = {isa = PBXBuildFile; fileRef = 851009CA265BE7E000B6A12E /* CBSDKConfigurationViewController.swift */; };
Expand Down Expand Up @@ -53,7 +52,6 @@
851009BE265BDA4B00B6A12E /* CBSDKProductTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CBSDKProductTableViewCell.swift; sourceTree = "<group>"; };
851009BF265BDA4B00B6A12E /* CBSDKProductTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = CBSDKProductTableViewCell.xib; sourceTree = "<group>"; };
851009CA265BE7E000B6A12E /* CBSDKConfigurationViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CBSDKConfigurationViewController.swift; sourceTree = "<group>"; };
854BE17C2653A5E100A9190D /* CBSDKPurchaseViewController.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CBSDKPurchaseViewController.swift; sourceTree = "<group>"; };
880524BD03DBC913F225A876 /* Pods-Chargebee_Example.debug.xcconfig */ = {isa = PBXFileReference; includeInIndex = 1; lastKnownFileType = text.xcconfig; name = "Pods-Chargebee_Example.debug.xcconfig"; path = "Target Support Files/Pods-Chargebee_Example/Pods-Chargebee_Example.debug.xcconfig"; sourceTree = "<group>"; };
90C8D07B26A9C7980004EE81 /* CBSDKItemTableViewCell.xib */ = {isa = PBXFileReference; lastKnownFileType = file.xib; path = CBSDKItemTableViewCell.xib; sourceTree = "<group>"; };
90C8D07D26A9CB260004EE81 /* CBSDKItemTableViewCell.swift */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = CBSDKItemTableViewCell.swift; sourceTree = "<group>"; };
Expand Down Expand Up @@ -100,7 +98,6 @@
607FACD71AFB9204008FA782 /* CBSDKOptionsViewController.swift */,
FA3ECF3424B6FA6C00643E63 /* CBSDKTokenViewController.swift */,
FA3ECF3824B6FDED00643E63 /* CBSDKAddonViewController.swift */,
854BE17C2653A5E100A9190D /* CBSDKPurchaseViewController.swift */,
20CCB492265ACAAD003E7AAD /* CBSDKProductsTableViewController.swift */,
20CCB4B4265BB090003E7AAD /* CBSDKSubscriptionStatusViewController.swift */,
851009CA265BE7E000B6A12E /* CBSDKConfigurationViewController.swift */,
Expand Down Expand Up @@ -347,7 +344,6 @@
isa = PBXSourcesBuildPhase;
buildActionMask = 2147483647;
files = (
72CD6DE82662856000E17CFE /* CBSDKPurchaseViewController.swift in Sources */,
D4FAC01426EA7BCC00577895 /* CBSDKPlansViewController.swift in Sources */,
FA3ECF3924B6FDED00643E63 /* CBSDKAddonViewController.swift in Sources */,
851009C0265BDA4B00B6A12E /* CBSDKProductTableViewCell.swift in Sources */,
Expand Down
Loading

0 comments on commit 381a9db

Please sign in to comment.