IOSIAP.ts 3.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. import { native } from 'cc';
  2. import { IAPImpl, IAPProductsResult, IAPResult } from './IAPImpl';
  3. export class IOSIAP extends IAPImpl {
  4. private seed = 0;
  5. private listening = false;
  6. private pending = new Map<string, { resolve: (data: any) => void; reject: (error: Error) => void; timer: ReturnType<typeof setTimeout> }>();
  7. private listeners = new Set<(transaction: IAPResult) => void>();
  8. private listen(): void {
  9. if (this.listening) return;
  10. native.jsbBridgeWrapper.addNativeEventListener('iap.response', payload => {
  11. let response: any;
  12. try { response = JSON.parse(payload); } catch { return; }
  13. if (response.method === 'transaction') {
  14. for (const listener of this.listeners) {
  15. try { listener(response.data); } catch (error) { console.error('[IAP] Transaction listener failed', error); }
  16. }
  17. return;
  18. }
  19. const pending = this.pending.get(response.requestId);
  20. if (!pending) return;
  21. clearTimeout(pending.timer);
  22. this.pending.delete(response.requestId);
  23. if (response.success) pending.resolve(response.data);
  24. else pending.reject(new Error(response.error || 'IAP request failed'));
  25. });
  26. this.listening = true;
  27. }
  28. private request<T>(method: string, params: object = {}): Promise<T> {
  29. this.listen();
  30. const requestId = `${Date.now()}-${++this.seed}`;
  31. return new Promise<T>((resolve, reject) => {
  32. const timer = setTimeout(() => {
  33. this.pending.delete(requestId);
  34. reject(new Error('IAP 请求超时;不代表支付失败,请查询未完成交易,勿直接重复购买。'));
  35. }, 180000);
  36. this.pending.set(requestId, { resolve, reject, timer });
  37. try { native.jsbBridgeWrapper.dispatchEventToNative('iap.request', JSON.stringify({ requestId, method, params })); }
  38. catch (error) { clearTimeout(timer); this.pending.delete(requestId); reject(error); }
  39. });
  40. }
  41. init(productIds: string[]): Promise<IAPProductsResult> {
  42. if (!productIds.length || productIds.some(id => typeof id !== 'string' || !id.trim())) {
  43. return Promise.reject(new Error('商品 ID 不能为空。'));
  44. }
  45. return this.request('init', { productIds: [...new Set(productIds)] });
  46. }
  47. purchase(productId: string): Promise<IAPResult> { return this.request('purchase', { productId }); }
  48. restore(): Promise<IAPResult[]> { return this.request('restore'); }
  49. getPendingTransactions(): Promise<IAPResult[]> { return this.request('pending'); }
  50. async finishTransaction(transactionId: string): Promise<void> {
  51. if (!transactionId) throw new Error('交易 ID 不能为空。');
  52. await this.request('finish', { transactionId });
  53. }
  54. onTransaction(listener: (transaction: IAPResult) => void): () => void {
  55. this.listen();
  56. this.listeners.add(listener);
  57. return () => { this.listeners.delete(listener); };
  58. }
  59. }