tauri-plugin-iap 0.9.1

A Tauri v2 plugin that enables In-App Purchases (IAP)
Documentation
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
use base64::Engine;
use base64::engine::general_purpose::URL_SAFE_NO_PAD;
use serde::de::DeserializeOwned;
use serde::{Deserialize, Serialize};
use tauri::Emitter;
use tauri::Manager;
use tauri::{AppHandle, Runtime, plugin::PluginApi};
use windows::core::{HSTRING, Interface};
use windows::{
    Foundation::DateTime,
    Services::Store::{
        StoreConsumableStatus, StoreContext, StoreLicense, StoreProduct, StorePurchaseProperties,
        StorePurchaseStatus,
    },
    Win32::UI::Shell::IInitializeWithWindow,
};
use windows_collections::IIterable;

use crate::error::{ErrorResponse, PluginInvokeError};
use crate::models::{
    GetProductsResponse, PricingPhase, Product, ProductStatus, Purchase, PurchaseRequest,
    PurchaseStateValue, RestorePurchasesResponse, SubscriptionOffer,
};
use std::sync::{Arc, RwLock};

/// Microsoft Store has no native per-transaction token, but our cross-platform API
/// exposes `purchase_token: String` for every purchase. We synthesize one by encoding
/// the data needed to consume the purchase later (`product_id` for
/// `ReportConsumableFulfillmentAsync`) into a versioned base64-JSON envelope.
/// The token is opaque to the developer; only `consume_purchase()` decodes it.
#[derive(Serialize, Deserialize)]
struct WindowsPurchaseTokenV1 {
    v: u8,
    product_id: String,
    purchase_time: i64,
    nonce: u32,
}

impl WindowsPurchaseTokenV1 {
    fn encode(&self) -> crate::Result<String> {
        let bytes = serde_json::to_vec(self).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to encode purchase token: {e}")),
                data: (),
            }))
        })?;
        Ok(URL_SAFE_NO_PAD.encode(&bytes))
    }

    fn decode(s: &str) -> crate::Result<Self> {
        let invalid = || {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("invalidPurchaseToken".to_string()),
                message: Some("Invalid Windows purchase token".to_string()),
                data: (),
            }))
        };
        let bytes = URL_SAFE_NO_PAD.decode(s).map_err(|_| invalid())?;
        let env: Self = serde_json::from_slice(&bytes).map_err(|_| invalid())?;
        if env.v != 1 {
            return Err(invalid());
        }
        Ok(env)
    }
}

#[allow(clippy::unnecessary_wraps)]
pub fn init<R: Runtime, C: DeserializeOwned>(
    app: &AppHandle<R>,
    _api: &PluginApi<R, C>,
) -> crate::Result<Iap<R>> {
    Ok(Iap {
        app_handle: app.clone(),
        store_context: Arc::new(RwLock::new(None)),
    })
}

/// Access to the iap APIs.
pub struct Iap<R: Runtime> {
    app_handle: AppHandle<R>,
    store_context: Arc<RwLock<Option<StoreContext>>>,
}

impl<R: Runtime> Iap<R> {
    /// Get or create the `StoreContext` instance
    fn get_store_context(&self) -> crate::Result<StoreContext> {
        let mut context_guard = self.store_context.write().map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("internalError".to_string()),
                message: Some(format!("Failed to acquire write lock: {e:?}")),
                data: (),
            }))
        })?;

        if context_guard.is_none() {
            // Get the default store context for the current user
            let context = StoreContext::GetDefault()?;

            let window = self.app_handle.get_webview_window("main").ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("windowError".to_string()),
                    message: Some("Failed to get main window".to_string()),
                    data: (),
                }))
            })?;
            let hwnd = window.hwnd().map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("windowError".to_string()),
                    message: Some(format!("Failed to get window handle: {e:?}")),
                    data: (),
                }))
            })?;

            // Cast the WinRT object to IInitializeWithWindow and initialize it with your HWND
            let init = context.cast::<IInitializeWithWindow>()?;
            unsafe {
                init.Initialize(hwnd)?;
            }

            *context_guard = Some(context);
        }

        Ok(context_guard
            .as_ref()
            .ok_or_else(|| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("storeNotInitialized".to_string()),
                    message: Some("Store context not initialized".to_string()),
                    data: (),
                }))
            })?
            .clone())
    }

    /// Convert Windows `DateTime` to Unix timestamp in milliseconds
    const fn datetime_to_unix_millis(datetime: DateTime) -> i64 {
        // Windows DateTime is in 100-nanosecond intervals since January 1, 1601
        // Convert to Unix timestamp (milliseconds since January 1, 1970)
        const WINDOWS_TICK: i64 = 10_000_000;
        const SEC_TO_UNIX_EPOCH: i64 = 11_644_473_600;

        let windows_ticks = datetime.UniversalTime;
        let seconds_since_1601 = windows_ticks / WINDOWS_TICK;
        let unix_seconds = seconds_since_1601 - SEC_TO_UNIX_EPOCH;
        unix_seconds * 1000 // Convert to milliseconds
    }

    /// Emit an event to the frontend (equivalent to `iOS`/Android `trigger` method).
    fn trigger<S: serde::Serialize + Clone>(&self, event: &str, payload: S) {
        let _ = self.app_handle.emit(event, payload);
    }

    #[allow(clippy::unused_async)]
    pub async fn get_products(
        &self,
        product_ids: Vec<String>,
        product_type: String,
    ) -> crate::Result<GetProductsResponse> {
        let context = self.get_store_context()?;

        // Convert product IDs to HSTRING
        let store_ids: Vec<HSTRING> = product_ids
            .iter()
            .map(|id| HSTRING::from(id.as_str()))
            .collect();

        // Determine product kinds based on type
        let product_kinds: Vec<HSTRING> = match product_type.as_str() {
            "inapp" => vec![
                HSTRING::from("Consumable"),
                HSTRING::from("UnmanagedConsumable"),
            ],
            "subs" => vec![HSTRING::from("Subscription"), HSTRING::from("Durable")],
            _ => vec![
                HSTRING::from("Consumable"),
                HSTRING::from("UnmanagedConsumable"),
                HSTRING::from("Durable"),
                HSTRING::from("Subscription"),
            ],
        };

        let store_ids: IIterable<HSTRING> = store_ids.into();
        let product_kinds: IIterable<HSTRING> = product_kinds.into();

        // Query products from the store
        let query_result = context
            .GetStoreProductsAsync(&product_kinds, &store_ids)
            .and_then(|async_op| async_op.get())?;

        // Check for any errors
        let extended_error = query_result.ExtendedError()?;
        if extended_error.is_err() {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("storeQueryFailed".to_string()),
                    message: Some(format!(
                        "Store query failed with error: {:?}",
                        extended_error.message()
                    )),
                    data: (),
                }),
            ));
        }

        let products_map = query_result.Products()?;
        let mut products = Vec::new();

        // Iterate through the products
        let iterator = products_map.First()?;
        while iterator.HasCurrent()? {
            let item = iterator.Current()?;
            let store_product = item.Value()?;

            let product = Self::convert_store_product_to_product(&store_product, &product_type)?;
            products.push(product);

            iterator.MoveNext()?;
        }

        Ok(GetProductsResponse { products })
    }

    fn convert_store_product_to_product(
        store_product: &StoreProduct,
        product_type: &str,
    ) -> crate::Result<Product> {
        let product_id = store_product.StoreId()?.to_string();

        let title = store_product.Title()?.to_string();

        let description = store_product.Description()?.to_string();

        let price = store_product.Price()?;

        let formatted_price = price.FormattedPrice()?.to_string();

        let currency_code = price.CurrencyCode()?.to_string();

        // Get the raw price value
        let formatted_base_price = price.FormattedBasePrice()?.to_string();

        // Parse price to get numeric value (remove currency symbols)
        let price_value = formatted_base_price
            .chars()
            .filter(|c| c.is_numeric() || *c == '.')
            .collect::<String>()
            .parse::<f64>()
            .unwrap_or(0.0);

        #[allow(
            clippy::cast_possible_truncation,
            clippy::cast_sign_loss,
            clippy::cast_precision_loss
        )]
        let price_amount_micros = (price_value * 1_000_000.0) as i64;

        // Handle subscription offers if this is a subscription product
        let subscription_offer_details = if product_type == "subs" {
            let mut offers = Vec::new();

            // Get SKUs for subscription details
            let skus = store_product.Skus()?;
            let sku_count = skus.Size()?;

            for i in 0..sku_count {
                let sku = skus.GetAt(i)?;

                let sku_id = sku.StoreId()?.to_string();
                sku.StoreId()?.to_string();

                let sku_price = sku.Price()?;

                // Check if this SKU has subscription info
                let subscription_info = sku.SubscriptionInfo();

                if let Ok(info) = subscription_info {
                    let billing_period = info.BillingPeriod()?;
                    let billing_period_unit = info.BillingPeriodUnit()?;

                    let billing_period_str = format!(
                        "P{}{}",
                        billing_period,
                        match billing_period_unit.0 {
                            0 => "D", // Day
                            1 => "W", // Week
                            3 => "Y", // Year
                            _ => "M", // Month (default)
                        }
                    );

                    let pricing_phase = PricingPhase {
                        formatted_price: sku_price.FormattedPrice()?.to_string(),
                        price_currency_code: currency_code.clone(),
                        price_amount_micros,
                        billing_period: billing_period_str,
                        billing_cycle_count: 0, // Windows doesn't provide this directly
                        recurrence_mode: 1,     // Infinite recurring
                    };

                    let offer = SubscriptionOffer {
                        offer_token: sku_id.clone(),
                        base_plan_id: sku_id,
                        offer_id: None,
                        pricing_phases: vec![pricing_phase],
                    };

                    offers.push(offer);
                }
            }

            if offers.is_empty() {
                None
            } else {
                Some(offers)
            }
        } else {
            None
        };

        Ok(Product {
            product_id,
            title,
            description,
            product_type: product_type.to_string(),
            formatted_price: Some(formatted_price),
            price_currency_code: Some(currency_code),
            price_amount_micros: Some(price_amount_micros),
            subscription_offer_details,
        })
    }

    #[allow(clippy::too_many_lines)]
    pub async fn purchase(&self, payload: PurchaseRequest) -> crate::Result<Purchase> {
        let context = self.get_store_context()?;

        // Get the product first to ensure it exists
        let products_response = self
            .get_products(
                vec![payload.product_id.clone()],
                payload.product_type.clone(),
            )
            .await?;

        if products_response.products.is_empty() {
            return Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("productNotFound".to_string()),
                    message: Some("Product not found".to_string()),
                    data: (),
                }),
            ));
        }

        let product = &products_response.products[0];
        let product_title = product.title.clone();

        let store_id = HSTRING::from(&payload.product_id);

        // Create purchase properties if we have an offer token (for subscriptions)
        let offer_token = payload.options.and_then(|opts| opts.offer_token);
        let purchase_result = if let Some(token) = offer_token {
            let properties = StorePurchaseProperties::Create(&HSTRING::from(&payload.product_id))?;

            // Set the SKU ID for subscription offers
            properties.SetExtendedJsonData(&HSTRING::from(format!(r#"{{"skuId":"{token}"}}"#)))?;

            context
                .RequestPurchaseWithPurchasePropertiesAsync(&store_id, &properties)
                .and_then(|async_op| async_op.get())?
        } else {
            // Simple purchase without properties
            context
                .RequestPurchaseAsync(&store_id)
                .and_then(|async_op| async_op.get())?
        };

        // Check purchase status
        let status = purchase_result.Status()?;

        let purchase_state = match status {
            StorePurchaseStatus::Succeeded | StorePurchaseStatus::AlreadyPurchased => {
                PurchaseStateValue::Purchased
            }
            StorePurchaseStatus::NotPurchased => {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("purchaseNotCompleted".to_string()),
                        message: Some("Purchase was not completed".to_string()),
                        data: (),
                    }),
                ));
            }
            StorePurchaseStatus::NetworkError => {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("networkError".to_string()),
                        message: Some("Network error during purchase".to_string()),
                        data: (),
                    }),
                ));
            }
            StorePurchaseStatus::ServerError => {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("serverError".to_string()),
                        message: Some("Server error during purchase".to_string()),
                        data: (),
                    }),
                ));
            }
            _ => {
                return Err(crate::Error::PluginInvoke(
                    PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("purchaseFailed".to_string()),
                        message: Some("Purchase failed".to_string()),
                        data: (),
                    }),
                ));
            }
        };

        // Get extended error info if available
        let error_message = purchase_result
            .ExtendedError()
            .ok()
            .map_or_else(String::new, windows::core::HRESULT::message);

        // Generate purchase details
        let purchase_time_ms = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("systemTimeError".to_string()),
                    message: Some(format!("Failed to get system time: {e:?}")),
                    data: (),
                }))
            })?
            .as_millis();
        let purchase_time = i64::try_from(purchase_time_ms).map_err(|e| {
            crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                code: Some("systemTimeError".to_string()),
                message: Some(format!("System time out of i64 range: {e}")),
                data: (),
            }))
        })?;

        // Sub-millisecond entropy so two purchases in the same `purchase_time` ms still differ.
        let nonce = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map_or(0, |d| d.subsec_nanos());
        let purchase_token = WindowsPurchaseTokenV1 {
            v: 1,
            product_id: product.product_id.clone(),
            purchase_time,
            nonce,
        }
        .encode()?;

        let purchase = Purchase {
            order_id: Some(purchase_token.clone()),
            package_name: product_title,
            product_id: product.product_id.clone(),
            purchase_time,
            purchase_token,
            purchase_state,
            is_auto_renewing: product.product_type == "subs",
            is_acknowledged: true, // Windows Store handles acknowledgment
            original_json: format!(
                r#"{{"status":{},"message":"{}","productId":"{}"}}"#,
                status.0, error_message, product.product_id
            ),
            signature: String::new(), // Windows doesn't provide signatures like Android
            original_id: None, // Windows doesn't have original transaction IDs like iOS/macOS
            jws_representation: None, // Windows doesn't have JWS like iOS/macOS
        };

        // Emit event for purchase state change
        self.trigger("purchaseUpdated", purchase.clone());

        Ok(purchase)
    }

    #[allow(clippy::unused_async)]
    pub async fn restore_purchases(
        &self,
        product_type: String,
    ) -> crate::Result<RestorePurchasesResponse> {
        let context = self.get_store_context()?;

        // Get app license info
        let app_license = context
            .GetAppLicenseAsync()
            .and_then(|async_op| async_op.get())?;

        let mut purchases = Vec::new();

        // Get add-on licenses (in-app purchases)
        let addon_licenses = app_license.AddOnLicenses()?;

        let iterator = addon_licenses.First()?;
        while iterator.HasCurrent()? {
            let item = iterator.Current()?;
            let license = item.Value()?;

            let purchase = self.convert_license_to_purchase(&license, &product_type)?;

            if purchase.purchase_state == PurchaseStateValue::Purchased {
                purchases.push(purchase);
            }

            iterator.MoveNext()?;
        }

        Ok(RestorePurchasesResponse { purchases })
    }

    fn convert_license_to_purchase(
        &self,
        license: &StoreLicense,
        product_type: &str,
    ) -> crate::Result<Purchase> {
        let product_id = license.InAppOfferToken()?.to_string();

        let sku_store_id = license.SkuStoreId()?.to_string();

        let is_active = license.IsActive()?;

        let expiration_date = license.ExpirationDate()?;
        let expiration_millis = Self::datetime_to_unix_millis(expiration_date);

        // Estimate purchase time (30 days before expiration for monthly subs)
        let purchase_time = if product_type == "subs" && expiration_millis > 0 {
            expiration_millis - (30 * 24 * 60 * 60 * 1000)
        } else {
            let now_ms = std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .map_err(|e| {
                    crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                        code: Some("systemTimeError".to_string()),
                        message: Some(format!("Failed to get system time: {e:?}")),
                        data: (),
                    }))
                })?
                .as_millis();
            i64::try_from(now_ms).map_err(|e| {
                crate::Error::PluginInvoke(PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("systemTimeError".to_string()),
                    message: Some(format!("System time out of i64 range: {e}")),
                    data: (),
                }))
            })?
        };

        let purchase_state = if is_active {
            PurchaseStateValue::Purchased
        } else {
            PurchaseStateValue::Canceled
        };

        Ok(Purchase {
            order_id: Some(sku_store_id.clone()),
            package_name: self.app_handle.package_info().name.clone(),
            product_id,
            purchase_time,
            purchase_token: sku_store_id,
            purchase_state,
            is_auto_renewing: product_type == "subs" && is_active,
            is_acknowledged: true,
            original_json: format!(
                r#"{{"isActive":{is_active},"expirationDate":{expiration_millis}}}"#
            ),
            signature: String::new(),
            original_id: None,
            jws_representation: None, // Windows doesn't have JWS like iOS/macOS
        })
    }

    /// No-op: Microsoft Store auto-acknowledges purchases. Method exists for API parity.
    #[allow(clippy::unused_async, clippy::unused_self)]
    pub async fn acknowledge_purchase(&self, _purchase_token: String) -> crate::Result<()> {
        Ok(())
    }

    #[allow(clippy::unused_async)]
    pub async fn consume_purchase(&self, purchase_token: String) -> crate::Result<()> {
        let envelope = WindowsPurchaseTokenV1::decode(&purchase_token)?;
        let context = self.get_store_context()?;
        let store_id = HSTRING::from(&envelope.product_id);
        let tracking_id = windows::core::GUID::new()?;

        let result = context
            .ReportConsumableFulfillmentAsync(&store_id, 1u32, tracking_id)
            .and_then(|async_op| async_op.get())?;

        let status = result.Status()?;
        match status {
            StoreConsumableStatus::Succeeded => Ok(()),
            StoreConsumableStatus::InsufficentQuantity => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("insufficientQuantity".to_string()),
                    message: Some("Not enough balance remaining to consume".to_string()),
                    data: (),
                }),
            )),
            StoreConsumableStatus::NetworkError => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("networkError".to_string()),
                    message: Some("Network error during consume".to_string()),
                    data: (),
                }),
            )),
            StoreConsumableStatus::ServerError => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("serverError".to_string()),
                    message: Some("Server error during consume".to_string()),
                    data: (),
                }),
            )),
            _ => Err(crate::Error::PluginInvoke(
                PluginInvokeError::InvokeRejected(ErrorResponse {
                    code: Some("consumeFailed".to_string()),
                    message: Some("Failed to consume purchase".to_string()),
                    data: (),
                }),
            )),
        }
    }

    #[allow(clippy::unused_async)]
    pub async fn get_product_status(
        &self,
        product_id: String,
        product_type: String,
    ) -> crate::Result<ProductStatus> {
        let context = self.get_store_context()?;

        // Get app license to check ownership
        let app_license = context
            .GetAppLicenseAsync()
            .and_then(|async_op| async_op.get())?;

        let addon_licenses = app_license.AddOnLicenses()?;

        // Look for the specific product license
        let product_key = HSTRING::from(&product_id);
        let has_license = addon_licenses.HasKey(&product_key)?;

        if has_license {
            let license = addon_licenses.Lookup(&product_key)?;

            let is_active = license.IsActive()?;
            let expiration_date = license.ExpirationDate()?;
            let expiration_time = Self::datetime_to_unix_millis(expiration_date);

            let purchase_time = if product_type == "subs" && expiration_time > 0 {
                expiration_time - (30 * 24 * 60 * 60 * 1000)
            } else {
                expiration_time
            };

            let purchase_state = if is_active {
                Some(PurchaseStateValue::Purchased)
            } else {
                Some(PurchaseStateValue::Canceled)
            };

            let sku_store_id = license.SkuStoreId()?.to_string();

            Ok(ProductStatus {
                product_id,
                is_owned: is_active,
                purchase_state,
                purchase_time: Some(purchase_time),
                expiration_time: if expiration_time > 0 {
                    Some(expiration_time)
                } else {
                    None
                },
                is_auto_renewing: Some(product_type == "subs" && is_active),
                is_acknowledged: Some(true),
                purchase_token: Some(sku_store_id),
            })
        } else {
            Ok(ProductStatus {
                product_id,
                is_owned: false,
                purchase_state: None,
                purchase_time: None,
                expiration_time: None,
                is_auto_renewing: None,
                is_acknowledged: None,
                purchase_token: None,
            })
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_datetime_to_unix_millis_epoch() {
        // Unix epoch: January 1, 1970 00:00:00 UTC
        // In Windows ticks: 116444736000000000 (100-nanosecond intervals since Jan 1, 1601)
        let datetime = DateTime {
            UniversalTime: 116_444_736_000_000_000,
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        assert_eq!(result, 0);
    }

    #[test]
    fn test_datetime_to_unix_millis_known_date() {
        // November 14, 2023 00:00:00 UTC
        // Unix timestamp: 1699920000000 ms
        // Windows ticks: 133445856000000000
        let datetime = DateTime {
            UniversalTime: 133_445_856_000_000_000,
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        assert_eq!(result, 1_699_920_000_000);
    }

    #[test]
    fn test_datetime_to_unix_millis_before_epoch() {
        // Date before Unix epoch should give negative result
        // January 1, 1969 00:00:00 UTC
        // Windows ticks: 116413200000000000
        let datetime = DateTime {
            UniversalTime: 116_413_200_000_000_000,
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        assert!(result < 0);
    }

    #[test]
    fn test_datetime_to_unix_millis_year_2000() {
        // January 1, 2000 00:00:00 UTC
        // Unix timestamp: 946684800000 ms
        // Windows ticks: 125911584000000000
        let datetime = DateTime {
            UniversalTime: 125_911_584_000_000_000,
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        assert_eq!(result, 946_684_800_000);
    }

    #[test]
    fn test_datetime_to_unix_millis_precision() {
        // Test that sub-second precision is handled correctly (truncated to seconds then converted to ms)
        // The function converts to seconds first, losing sub-second precision
        let datetime = DateTime {
            UniversalTime: 116_444_736_000_000_000 + 5_000_000, // epoch + 500ms in 100-ns ticks
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        // Since we divide by WINDOWS_TICK (10_000_000), we truncate sub-second values
        assert_eq!(result, 0);
    }

    #[test]
    fn test_datetime_to_unix_millis_one_second_after_epoch() {
        // 1 second after Unix epoch
        let datetime = DateTime {
            UniversalTime: 116_444_736_000_000_000 + 10_000_000, // epoch + 1 second in 100-ns ticks
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        assert_eq!(result, 1000);
    }

    #[test]
    fn test_datetime_to_unix_millis_far_future() {
        // January 1, 2100 00:00:00 UTC
        // Windows ticks: 157766880000000000
        let datetime = DateTime {
            UniversalTime: 157_766_880_000_000_000,
        };
        let result = Iap::<tauri::Wry>::datetime_to_unix_millis(datetime);
        // Should be approximately 4102444800000 ms
        assert!(result > 4_000_000_000_000);
    }

    fn sample_envelope(product_id: &str) -> WindowsPurchaseTokenV1 {
        WindowsPurchaseTokenV1 {
            v: 1,
            product_id: product_id.to_string(),
            purchase_time: 1_714_387_200_000,
            nonce: 42,
        }
    }

    fn assert_envelope_eq(a: &WindowsPurchaseTokenV1, b: &WindowsPurchaseTokenV1) {
        assert_eq!(a.v, b.v);
        assert_eq!(a.product_id, b.product_id);
        assert_eq!(a.purchase_time, b.purchase_time);
        assert_eq!(a.nonce, b.nonce);
    }

    #[test]
    fn test_envelope_round_trip_typical() {
        let original = sample_envelope("9MSPC6MP8FM4");
        let encoded = original.encode().expect("encode must succeed");
        let decoded =
            WindowsPurchaseTokenV1::decode(&encoded).expect("just-encoded token must decode");
        assert_envelope_eq(&original, &decoded);
    }

    #[test]
    fn test_envelope_round_trip_empty_product_id() {
        let original = sample_envelope("");
        let encoded = original.encode().expect("encode must succeed");
        let decoded =
            WindowsPurchaseTokenV1::decode(&encoded).expect("just-encoded token must decode");
        assert_envelope_eq(&original, &decoded);
    }

    #[test]
    fn test_envelope_round_trip_long_product_id() {
        let original = sample_envelope(&"x".repeat(512));
        let encoded = original.encode().expect("encode must succeed");
        let decoded =
            WindowsPurchaseTokenV1::decode(&encoded).expect("just-encoded token must decode");
        assert_envelope_eq(&original, &decoded);
    }

    #[test]
    fn test_envelope_encoded_uses_url_safe_alphabet() {
        let encoded = sample_envelope("9MSPC6MP8FM4")
            .encode()
            .expect("encode must succeed");
        for ch in encoded.chars() {
            assert!(
                ch.is_ascii_alphanumeric() || ch == '-' || ch == '_',
                "encoded token contains non-URL-safe char: {ch:?}"
            );
        }
    }

    #[test]
    fn test_envelope_encoding_is_stable() {
        let env = sample_envelope("9MSPC6MP8FM4");
        let a = env.encode().expect("encode must succeed");
        let b = env.encode().expect("encode must succeed");
        assert_eq!(a, b);
    }

    #[test]
    fn test_envelope_decode_rejects_malformed_base64() {
        assert!(WindowsPurchaseTokenV1::decode("!!!not-base64!!!").is_err());
    }

    #[test]
    fn test_envelope_decode_rejects_non_json_payload() {
        // Valid base64 of "hello world" (not JSON).
        let bogus = URL_SAFE_NO_PAD.encode(b"hello world");
        assert!(WindowsPurchaseTokenV1::decode(&bogus).is_err());
    }

    #[test]
    fn test_envelope_decode_rejects_unknown_version() {
        let bytes = serde_json::to_vec(&serde_json::json!({
            "v": 99,
            "product_id": "9MSPC6MP8FM4",
            "purchase_time": 1_714_387_200_000_i64,
            "nonce": 42,
        }))
        .expect("static JSON must serialize");
        let encoded = URL_SAFE_NO_PAD.encode(&bytes);
        assert!(WindowsPurchaseTokenV1::decode(&encoded).is_err());
    }

    #[test]
    fn test_envelope_decode_rejects_missing_product_id() {
        let bytes = serde_json::to_vec(&serde_json::json!({
            "v": 1,
            "purchase_time": 1_714_387_200_000_i64,
            "nonce": 42,
        }))
        .expect("static JSON must serialize");
        let encoded = URL_SAFE_NO_PAD.encode(&bytes);
        assert!(WindowsPurchaseTokenV1::decode(&encoded).is_err());
    }
}