IOSIAP.ts 3.9 KB

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