美文网首页
【iOS】StoreKit2的currencyCode获取方案

【iOS】StoreKit2的currencyCode获取方案

作者: 谦言忘语 | 来源:发表于2023-01-09 11:51 被阅读0次

StoreKit2的currencyCode获取问题

我们在内购的时候,需要将countryCode、currencyCode、price这几个参数读取后发给后台,用于货币校验、价格校验及统计。
StoreKit2有个坑爹的地方,就是在21年出来的时候,苹果没有提供currencyCode的API。

新的API可以直接获取currencyCode

22年的时候终于出了一个API,可以通过下面的方式读取countryCode

let products = try await Product.products(for: [productId])
let currencyCode = products.last?.priceFormatStyle.currencyCode

但是,这个新出的API并不能在Xcode13上编译通过,只能在Xcode14及以上版本编译通过。而目前开发使用的是Xcode13。
并且,苹果提示这个API如果在iOS16之前使用(就是iOS15)在某些情况下可能出现一些问题(主要是StoreKit Testing和出现严重的服务器错误时)。

Product {

    /// The format style to use when formatting numbers derived from the price for the product.
    ///
    /// Use `displayPrice` when possible. Use `priceFormatStyle` only for localizing numbers
    /// derived from the `price` property, such as "2 products for $(`price * 2`)".
    /// - Important: When using `priceFormatStyle` on systems earlier than iOS 16.0,
    ///              macOS 13.0, tvOS 16.0 or watchOS 9.0, the property may return a format style
    ///              with a sentinel locale with identifier "xx\_XX" in some uncommon cases:
    ///              (1) StoreKit Testing in Xcode (workaround: test your app on a device running a
    ///              more recent OS) or (2) a critical server error.
    @available(iOS 15.0, macOS 12.0, tvOS 15.0, watchOS 8.0, *)
    public var priceFormatStyle: Decimal.FormatStyle.Currency { get }

总的来说,因为目前开发的Xcode版本较低导致的编译无法通过,所以我们需要尝试寻找另外的方法来获取currencyCode。

从Product的jsonRepresentation里面获取currencyCode

其实苹果本身是可以拿到currencyCode的,因为获取商品信息成功之后,我们直接打印可以看到一个json,里面有我们需要的currencyCode。

let products = try await Product.products(for: [productId])
print("product=\(products.last!)")

以下为打印出来的内容(已脱敏处理):

product={
  "attributes" : {
    "description" : {
      "standard" : "구매성공,800원보 획득"
    },
    "icuLocale" : "en_TW@currency=TWD",
    "isFamilyShareable" : 0,
    "isMerchandisedEnabled" : 0,
    "isMerchandisedVisibleByDefault" : 0,
    "isSubscription" : 0,
    "kind" : "Consumable",
    "name" : "800원보",
    "offerName" : "kr.app.gold1",
    "offers" : [
      {
        "assets" : [

        ],
        "buyParams" : "productType=A&price=330000&salableAdamId=1531111111&pricingParameters=STDQ&pg=default",
        "currencyCode" : "TWD",
        "price" : 330,
        "priceFormatted" : "NT$330.00",
        "type" : "buy"
      }
    ],
    "releaseDate" : "2009-06-17",
    "url" : "https://sandbox.itunes.apple.com/tw/app/800%EC%9B%90%EB%B3%B4/id1531111111?l=en"
  },
  "href" : "/v1/catalog/tw/in-apps/153111111?l=en-GB",
  "id" : "153111111",
  "type" : "in-apps"
}

可以看到1. icuLocale的值里面有currency相关内容,2. offers数组里面也有一个currencyCode参数。
那么,我们拿到这个json之后,再去读取里面相关的内容,不就可以获取到我们想要的currencyCode了?
这个json其实在product的jsonRepresentation属性里面,我们转化一下就可以拿到。
于是,我们通过下面的代码可以拿到我们想要的currencyCode

let products = try await Product.products(for: [productId])
let product = products.last

// data->JSON->Dictionry
let decoded = try? JSONSerialization.jsonObject(with: product!.jsonRepresentation, options: [])
let jsonDict = decoded as? [String: Any] ?? [:]

let attributes = jsonDict["attributes"] as? [String: Any]
let offers = attributes?["offers"] as? [[String: Any]]

// 直接获取currencyCode(目前采用了这种方案)
let currencyCode = offers?.first?["currencyCode"] as? String
print("currencyCode=\(currencyCode)")

// 获取icuLocale字符串,然后截取字符串拿到currencyCode(略,目前未采用这种方案)
let icuLocale = attributes?["icuLocale"]
print("icuLocale=\(icuLocale)")

目前我们就是使用这种方案来获取currencyCode的。目前已上线,并没有出现什么问题,后续会继续进行观察。
但是这种方案毕竟不是官方提供的,里面的JSON格式可能会出现改变,所以,这种方案其实是有风险的。但是,以目前的情况来说,不失为一种好方案。

使用Storekit1来获取currencyCode

StoreKit2获取不到,但是StoreKit1肯定是可以拿到的,所以,有些人会使用StoreKit1来获取currencyCode。
这种不失为一个好方案,但是这个API需要走一个网络请求,相对较为耗时。

//获取商品信息
NSSet *pidSets = [NSSet setWithObject:productId];
SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:pidSets];
request.delegate = self;
[request start];

#pragma mark - 获取商品信息成功后回调
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response
{
    SKProduct *product = [response.products lastObject];
    NSLocale *priceLocale = product.priceLocale;
    //获取本地货币简码
    NSString *currencyCode = nil;
    if (@available(iOS 10.0,*)) {
        currencyCode = priceLocale.currencyCode;
    } else {
        currencyCode = [[priceLocale.localeIdentifier componentsSeparatedByString:@"="] lastObject];
    }
    NSLog(@"currencyCode=%@",currencyCode);
}

总结

总的来说,StoreKit2获取货币码currencyCode的方案有3个:

1.使用priceFormatStyle.currencyCode进行获取。官方API,但是需要Xcode14才能编译通过。在2023.4之后推荐使用(那时候最低使用Xcode14)。
2.使用product的jsonRepresentation属性,通过解析json的方式获取。适配Xcode13和iOS15,如果未更新Xcode到14及以上,是较好的方案。缺点是非官方推荐方式,后续json里面的内容可能会有改动导致出错。
3.使用StoreKit1的API获取。好处是方案比较成熟,缺点是较为耗时,而且在StoreKit2里面使用,不太和谐。

推荐方案:
使用Xcode14的开发建议直接使用方案一。
目前不少开发仍在使用Xcode13,所以使用Xcode13的开发建议使用方案二。
另外可以尝试iOS15使用方案二,iOS16及以上使用方案一(对于这样做是否更好,未验证过)。

参考链接

Missing currencyCode in StoreKit2
purchases-ios库--github

相关文章

网友评论

      本文标题:【iOS】StoreKit2的currencyCode获取方案

      本文链接:https://www.haomeiwen.com/subject/doipcdtx.html