Skip to content

Commit

Permalink
Merge pull request #23 from chargebee/dev_v1.0.2
Browse files Browse the repository at this point in the history
Dev v1.0.2- changes
1.Made customerID optional
2.SDK key changes
3.Price - decimal change
4.Improved instrumentation
  • Loading branch information
cb-imayaselvan authored Dec 16, 2021
2 parents 381a9db + a0375cd commit 358937f
Show file tree
Hide file tree
Showing 15 changed files with 71 additions and 57 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.1'
s.version = '1.0.2'
s.summary = 'Chargebee iOS SDK'

# This description is used to generate tags and improve search results.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,8 @@ final class CBAuthenticationResource: CBAPIResource {
urlRequest.httpBody = bodyComponents.query?.data(using: .utf8)
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
urlRequest.addValue(authHeader!, forHTTPHeaderField: "Authorization")

urlRequest.addValue(sdkVersion, forHTTPHeaderField: "version")
urlRequest.addValue(platform, forHTTPHeaderField: "platform")
return urlRequest
}
}
Expand Down
8 changes: 4 additions & 4 deletions Chargebee/Classes/Configuration/CBEnvironment.swift
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,18 @@ import Foundation

class CBEnvironment {
static var site: String = ""
static var publishableApiKey: String = ""
static var apiKey: String = ""
static var encodedApiKey: String = ""
static var baseUrl: String = ""
static var allowErrorLogging: Bool = true
static var sdkKey : String = ""
static var version : CatalogVersion = .unknown

static func configure(site: String, publishableApiKey: String, allowErrorLogging: Bool, sdkKey: String? = nil) {
static func configure(site: String, apiKey: String, allowErrorLogging: Bool, sdkKey: String? = nil) {
CBEnvironment.site = site
CBEnvironment.publishableApiKey = publishableApiKey
CBEnvironment.apiKey = apiKey
CBEnvironment.allowErrorLogging = allowErrorLogging
CBEnvironment.encodedApiKey = CBEnvironment.publishableApiKey.data(using: .utf8)?.base64EncodedString() ?? ""
CBEnvironment.encodedApiKey = CBEnvironment.apiKey.data(using: .utf8)?.base64EncodedString() ?? ""
CBEnvironment.baseUrl = "https://\(CBEnvironment.site).chargebee.com/api"
CBEnvironment.version = .unknown

Expand Down
4 changes: 2 additions & 2 deletions Chargebee/Classes/Configuration/Chargebee.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ public class Chargebee {
public init() {
}

public static func configure(site: String, publishableApiKey: String, sdkKey: String? = nil, allowErrorLogging: Bool = true) {
CBEnvironment.configure(site: site, publishableApiKey: publishableApiKey, allowErrorLogging: allowErrorLogging, sdkKey: sdkKey)
public static func configure(site: String, apiKey: String, sdkKey: String? = nil, allowErrorLogging: Bool = true) {
CBEnvironment.configure(site: site, apiKey: apiKey, allowErrorLogging: allowErrorLogging, sdkKey: sdkKey)
}
}
2 changes: 2 additions & 0 deletions Chargebee/Classes/Network/CBAPIRequest.swift
Original file line number Diff line number Diff line change
Expand Up @@ -73,6 +73,8 @@ extension CBAPIResource {
header?.forEach({ (key, value) in
urlRequest.addValue(value, forHTTPHeaderField: key)
})
urlRequest.addValue(sdkVersion, forHTTPHeaderField: "version")
urlRequest.addValue(platform, forHTTPHeaderField: "platform")
return urlRequest
}
}
Expand Down
14 changes: 6 additions & 8 deletions Chargebee/Classes/Purchase/CBPurchaseManager.swift
Original file line number Diff line number Diff line change
Expand Up @@ -118,10 +118,10 @@ public extension CBPurchase {


//Buy the product
func purchaseProduct(product: CBProduct, customerId : String ,completion handler: @escaping ((_ result: Result<(status:Bool, subscription:CBSubscriptionStatus?), 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
customerID = customerId ?? ""
guard CBAuthenticationManager.isSDKKeyPresent() else {
handler(.failure(CBPurchaseError.cannotMakePayments))
return
Expand Down Expand Up @@ -192,11 +192,9 @@ extension CBPurchase: SKPaymentTransactionObserver {
case .purchased:
SKPaymentQueue.default().finishTransaction(transaction)
if let productId = activeProduct?.productIdentifier,
let price = activeProduct?.price,
let currencyCode = activeProduct?.priceLocale.currencyCode {
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)
let currencyCode = activeProduct?.priceLocale.currencyCode,
let price = activeProduct?.price {
validateReceipt(for: productId, name: activeProduct?.localizedTitle ?? productId, "\(price)", currencyCode: currencyCode, customerId:customerID,completion: buyProductHandler)
}
case .restored:
restoredPurchasesCount += 1
Expand Down Expand Up @@ -247,7 +245,7 @@ public extension CBPurchase {
// print("Receipt String is :\(receiptString)")
debugPrint("Apple Purchase - success")

CBReceiptValidationManager.validateReceipt(receipt: receiptString, productId: productID,name: name, 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 Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,17 +29,16 @@ class CBReceiptValidationManager {
name: String,
price: String,
currencyCode : String,
customerId : String,
customerId : String? = "",
completion handler: @escaping CBValidateReceiptHandler) {
let logger = CBLogger(name: "buy", action: "process_purchase_command")
logger.info()


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

let request = CBAPIRequest(resource: CBValidateReceiptResource(receipt: receipt, productId: productId,name: name,
price: price, currencyCode : currencyCode,
customerId : customerId))
customerId : customerId ?? ""))
request.create(withCompletion: { (res: CBValidateReceiptWrapper?) in
onSuccess(res!.inAppSubscription)
}, onError: onError)
Expand Down
22 changes: 12 additions & 10 deletions Chargebee/Classes/ReceiptValidation/CBValidateReceiptResource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,8 @@ class CBValidateReceiptResource: CBAPIResource {
header?.forEach({ (key, value) in
urlRequest.addValue(value, forHTTPHeaderField: key)
})
urlRequest.addValue(sdkVersion, forHTTPHeaderField: "version")
urlRequest.addValue(platform, forHTTPHeaderField: "platform")
return urlRequest
}

Expand All @@ -48,14 +50,16 @@ class CBValidateReceiptResource: CBAPIResource {
urlRequest.httpMethod = "post"
urlRequest.addValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
var bodyComponents = URLComponents()
bodyComponents.queryItems = requestBody?.toFormBody().map({ (key, value) -> URLQueryItem in
URLQueryItem(name: key,
value: value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!.replacingOccurrences(of: "+", with: "%2B"))
})

let bodyData = requestBody?.toFormBody().filter({!$0.value.isEmpty})
if let data = bodyData {
bodyComponents.queryItems = data.compactMap({ (key, value) -> URLQueryItem in
URLQueryItem(name: key,
value: value.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!.replacingOccurrences(of: "+", with: "%2B"))
})
}
urlRequest.httpBody = bodyComponents.query?.data(using: .utf8)
return urlRequest
}
}

init(receipt: String, productId: String, name: String,
price: String, currencyCode : String,
Expand All @@ -75,17 +79,15 @@ struct PayloadBody: URLEncodedRequestBody {
let price: String
let currencyCode : String
let customerId : String
let channel : String = "app_store"

func toFormBody() -> [String: String] {
[
"receipt" : receipt,
"product[id]" : productId,
"product[name]": name,
"product[price]" :price,
"product[price_in_decimal]" :price,
"product[currency_code]" :currencyCode,
"customer[id]" :customerId,
"channel": channel
"customer[id]" :customerId
]
}
}
Expand Down
10 changes: 8 additions & 2 deletions Chargebee/Classes/Subscription/CBSubscription.swift
Original file line number Diff line number Diff line change
Expand Up @@ -16,12 +16,18 @@ public struct CBSubscriptionData: Codable {
public let activatedAt: Double?
public let status: String?
public let planAmount: Double?


public let id: String?
public let currentTermEnd: Double?
public let currentTermStart: Double?

enum CodingKeys: String, CodingKey {
case activatedAt = "activated_at"
case status
case id
case planAmount = "plan_amount"
case currentTermEnd = "current_term_end"
case currentTermStart = "current_term_start"

}
}

Expand Down
2 changes: 2 additions & 0 deletions Chargebee/Classes/Subscription/CBSubscriptionResource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,8 @@ final class CBSubscriptionResource: CBAPIResource {
urlRequest.addValue(authHeader!, forHTTPHeaderField: "Authorization")
urlRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Content-Type")
urlRequest.addValue("application/json; charset=utf-8", forHTTPHeaderField: "Accept")
urlRequest.addValue(sdkVersion, forHTTPHeaderField: "version")
urlRequest.addValue(platform, forHTTPHeaderField: "platform")
return urlRequest
}
}
Expand Down
2 changes: 1 addition & 1 deletion Chargebee/Classes/Token/CBPaymentConfigResource.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ final class CBPaymentConfigResource: CBAPIResource {
var baseUrl: String
var authHeader: String? {
get {
"Basic \(CBEnvironment.publishableApiKey)"
"Basic \(CBEnvironment.apiKey)"
}
}
var methodPath: String = "/internal/component/retrieve_config"
Expand Down
2 changes: 1 addition & 1 deletion Example/Chargebee/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Override point for customization after application

Chargebee.configure(site: "Site Name",
publishableApiKey: "API Key",sdkKey: "ResourceID/SDK Key")
apiKey: "API Key- (full Access)",sdkKey: "ResourceID/SDK Key")
return true
}
}
2 changes: 1 addition & 1 deletion Example/Chargebee/CBSDKConfigurationViewController.swift
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ final class CBSDKConfigurationViewController: UIViewController {
@IBAction private func initializeClicked(_ sender: UIButton) {
// guard canInitialise() else { return }
Chargebee.configure(site: siteNameTextField.unwrappedText,
publishableApiKey: apiKeyTextField.unwrappedText,
apiKey: apiKeyTextField.unwrappedText,
sdkKey: sdkKeyTextField.unwrappedText,
allowErrorLogging: true)
}
Expand Down
40 changes: 20 additions & 20 deletions Example/Pods/Target Support Files/Chargebee/Chargebee-Info.plist

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

10 changes: 7 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,19 +40,19 @@ You can initialize the SDK during your app startup by including the following in
import Chargebee

Chargebee.configure(site: "your-site",
publishableApiKey: "api_key",
apiKey: "api_key",
sdkKey: "sdk_key")
}

```

### Configuration for using tokenization only
If you want to use the Chargebee iOS SDK only for tokenizing credit card details, you can initialize the SDK with your Chargebee Site and Publishable API key alone. You can initialize the SDK during your app startup by including the following in your app delegate.
If you want to use the Chargebee iOS SDK only for tokenizing credit card details, you can initialize the SDK with your Chargebee Site and API key alone. You can initialize the SDK during your app startup by including the following in your app delegate.

```swift
import Chargebee

Chargebee.configure(site: "your-site", publishableApiKey: "api_key")
Chargebee.configure(site: "your-site", apiKey: "api_key")

```

Expand Down Expand Up @@ -86,6 +86,7 @@ The above function will determine your product catalog version in Chargebee and

You can then convert these to Apple IAP Product objects with the following function.


```swift
CBPurchase.shared.retrieveProducts(withProductID : ["Product ID from Apple"],completion: { result in
switch result {
Expand All @@ -104,6 +105,9 @@ You can present any of the above products to your users for them to purchase.

When the user chooses the product to purchase, pass in the product and customer identifiers to the following function.

customer id - optional Parameter
We need the unique ID of your customer for customer_id. If your unique list of customers is maintained in your database or a 3rd party system , send us the unique ID from there. If you rely on Chargebee for the unique list of customers, then you can send us a random unique string for this ID.

```swift

CBPurchase.shared.purchaseProduct(product: "CBProduct",customerId: "CustomerID") { result in
Expand Down

0 comments on commit 358937f

Please sign in to comment.