苹果内购IAP记录-2 StoreKit新版

苹果内购新版的StoreKit2只支持iOS15以上,新的nsync同步接口,简单的使用如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
@available(iOS 15.0, *)
public class MXLiveIAPStoreV2 {
     
    static let shared: MXLiveIAPStoreV2 = MXLiveIAPStoreV2()
    typealias Transaction = StoreKit.Transaction
     
    private(set) var fuel: [Product] = []
     
    var updateListenerTask: Task<Void, Error>? = nil
     
//    var statusChanged:(MXLiveIAPStatus) -> Void = {_ in
//
//    }
 
    private var currentTransaction:Transaction?
    private var currentOrder: MXLiveIAPOrder?
     
    private init() {
         
    }
    weak var delegate: MXLiveIAPDelegate?
    func install(delegate:MXLiveIAPDelegate){
        currentOrder = MXLiveIAPOrder.getLastOrderForKeychain()
        //Start a transaction listener as close to app launch as possible so you don't miss any transactions.
        self.updateListenerTask = listenForTransactions()
    }
     
    deinit {
        updateListenerTask?.cancel()
    }
     
    func getCurrentOrder()->MXLiveIAPOrder?{
        return currentOrder
    }
    func canStartNewIAP() -> Bool{
        return currentOrder == nil
    }
    func finishCurrentOrder(){
        MXLiveIAPPayment.shared.finishCurrentOrder()
        currentOrder?.deleteKeychainOrderRecord()
        currentOrder = nil
        guard let tran = currentTransaction else {
            return
        }
        currentTransaction = nil
        Task{
            await tran.finish()
        }
    }
     
    private func listenForTransactions() -> Task<Void, Error> {
        return Task.detached {
            //Iterate through any transactions that don't come from a direct call to `purchase()`.
            for await result in Transaction.updates {
                do {
                    _ = try self.checkVerified(result)
//                    transaction.appAccountToken?.uuidString
                     
                    //Always finish a transaction.
                    self.finishCurrentOrder()
                    //MARK: - update gems
                    self.delegate?.orderStatusChanged(order: self.currentOrder, status: .complete)
                } catch {
                    self.delegate?.orderStatusChanged(order: self.currentOrder, status: .failed(error))
                    self.finishCurrentOrder()
                    //StoreKit has a transaction that fails verification. Don't deliver content to the user.
                    print("Transaction failed verification")
                }
            }
        }
    }
 
    func startIAPPayment(ids:[String], order:MXLiveIAPOrder){
         
        self.currentOrder = order
        currentOrder?.saveToKeyChain()
        Task {
             
            if let pro = await requestProducts(ids:ids)?.last{
                 
                _ = try? await  purchase(pro)
            }
            
        }
         
    }
     
    private func requestProducts(ids:[String]) async -> [Product]?{
         
         
            //During store initialization, request products from the App Store.
            do {
                //Request products from the App Store using the identifiers that the Products.plist file defines.
                 
                let storeProducts = try await Product.products(for: ids)
 
                var newFuel: [Product] = []
 
                //Filter the products into categories based on their type.
                for product in storeProducts {
                    switch product.type {
                    case .consumable:
                        newFuel.append(product)
                         
                    case .nonConsumable:
                        break
                    case .autoRenewable:
                        break
                    case .nonRenewable:
                        break
                    default:
                        //Ignore this product.
                        print("Unknown product")
                    }
                }
 
                //Sort each product category by price, lowest to highest, to update the store.
                fuel = newFuel
                return newFuel
            } catch let error{
                self.delegate?.orderStatusChanged(order: currentOrder, status: .failed(MXLiveIAPError(reason: "get product faile", code: -1)))
                finishCurrentOrder()
                print("Failed product request from the App Store server: \(error)")
                return nil
            }
         
         
         
    }
     
    private func purchase(_ product: Product) async throws -> Transaction? {
        /*
         UUID 是苹果定义的接口 UUID().uuidString 获取,格式如:4713AE2D-11A5-40EA-B836-CBCD1EC96A76。如果需要关联 用户ID 和开发者订单号,需要开发者自动映射,或者服务器端生成返回等
         */
        //Begin purchasing the `Product` the user selects.
                                          //6e738162-133f-4d11-b446-4293709529799328312
        let uuidString = UUID().uuidString//367E28C7-CF53-438A-98C3-24DFA11706BF
        print("------uuid ------: \(uuidString)")
        let uuid = Product.PurchaseOption.appAccountToken(UUID.init(uuidString: uuidString)!)
        let result = try await product.purchase(options: [uuid])//options: Set<Product.PurchaseOption>([.appAccountToken(UUID(uuidString: "uid1")!)]))
         
        switch result {
             
        case .success(let verification):
            //Check whether the transaction is verified. If it isn't,
            //this function rethrows the verification error.
            let transaction = try checkVerified(verification)
            self.currentTransaction = transaction
            //The transaction is verified. Deliver content to the user.
            currentOrder?.transactionId = "\(transaction.id)"
            currentOrder?.updateTokeyChain()
            self.delegate?.orderStatusChanged(order: currentOrder, status: .complete)
            print(transaction.debugDescription)
            //Always finish a transaction.
//            await transaction.finish()
 
            return transaction
        case .userCancelled, .pending:
            self.delegate?.orderStatusChanged(order: currentOrder, status: .failed(MXLiveIAPError(reason: "user Cancelled", code: -1)))
            self.finishCurrentOrder()
            return nil
        default:
            return nil
        }
    }
     
    //Check whether the JWS passes StoreKit verification.
    func checkVerified<T>(_ result: VerificationResult<T>) throws -> T {
        switch result {
        case .unverified:
            //StoreKit parses the JWS, but it fails verification.
            throw StoreError.failedVerification
        case .verified(let safe):
            //The result is verified. Return the unwrapped value.
            return safe
        }
    }
     
    /*All transactions:全部的购买交易订单
     Latest transactions:最新的购买交易订单。(分为订阅品项和除订阅品项外的所有类型二种)
     Current entitlements:当前用户有购买的权限。(全部的订阅品项、和非消耗品项)
    */
    func allTransaction() async -> [Transaction] {
        var all = [Transaction]()
         
        for await result in  Transaction.all {
            do {
                let tran = try checkVerified(result)
                all.append(tran)
                 
            } catch let error {
             
                print("error:----\(error)")
            }
             
        }
        return all
         
        //Transaction.latest(for: "pid")
         
    }
    //获取推广内购商品
    func Promotion() async -> [SKProduct]?{
        let promotion = SKProductStorePromotionController()
         
        let prodicts = try? await promotion.promotionOrder()
        return prodicts
    }
     
     
}

 代码地址:https://github.com/duzhaoquan/DQIAPTool

posted @   不停奔跑的蜗牛  阅读(368)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· SQL Server 2025 AI相关能力初探
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
历史上的今天:
2022-01-17 WKWebView 白屏问题,WKWebView request body丢失问题
点击右上角即可分享
微信分享提示