diff --git a/.github/workflows/package-size-check.js b/.github/workflows/package-size-check.js index 8f30f2e809..6bf365bd8c 100644 --- a/.github/workflows/package-size-check.js +++ b/.github/workflows/package-size-check.js @@ -11,7 +11,7 @@ const features = []; files.forEach(file => { const filePath = ps.join(exportsDir, file); const feature = ps.parse(ps.basename(filePath)).name; - if (feature !== 'vendor') { + if (feature !== 'vendor-google') { features.push(feature); } }); diff --git a/@types/jsb.d.ts b/@types/jsb.d.ts index 418b3ec839..69251386de 100644 --- a/@types/jsb.d.ts +++ b/@types/jsb.d.ts @@ -358,22 +358,18 @@ declare namespace jsb { onThermalStatusChanged?: (previousStatus: number, newStatus: number, statusMin: number, statusMax: number) => void; } | undefined; - /** - * @en Params containing the response code and the debug message from In-app Billing API response. - * @zh 包含应用内结算 API 响应代码和调试信息的参数 - */ - export interface BillingResult { - /** - * @en Debug message returned in In-app Billing API calls. - * @zh 应用内结算 API 调用中返回的调试消息。 - */ - readonly debugMessage: string; - /** - * @en Code returned in In-app Billing API calls. - * @zh 应用内结算 API 调用中返回的响应代码。 - */ - readonly responseCode: string; - readonly toStr: string; + export interface UserChoiceDetailsProduct { + hashCode(): number; + getId(): string; + getOfferToken(): string; + getType(): string; + toString(): string; + equals(product: UserChoiceDetailsProduct): boolean; + } + export class UserChoiceDetails { + getExternalTransactionToken(): string; + getOriginalExternalTransactionId(): string; + getProducts(): UserChoiceDetailsProduct[]; } /** @@ -385,17 +381,17 @@ declare namespace jsb { * @en The price for the payment in micro-units, where 1,000,000 micro-units equal one unit of the currency. * @zh 以微单位返回支付价格,其中 1,000,000 个微单位等于 1 个货币单位。 */ - readonly priceAmountMicros: number; + getPriceAmountMicros(): number; /** * @en Formatted price for the payment, including its currency sign. * @zh 支付的格式化价格,包括其货币单位。 */ - readonly formattedPrice: string; + getFormattedPrice(): string; /** * @en ISO 4217 currency code for price. * @zh 价格的 ISO 4217 货币代码。 */ - readonly priceCurrencyCode: string; + getPriceCurrencyCode(): string; } /** @@ -407,12 +403,12 @@ declare namespace jsb { * @en Committed payments count after a user signs up for this subscription plan. * @zh 用户注册此订阅计划后承诺的付款数量。 */ - readonly installmentPlanCommitmentPaymentsCount: number; + getInstallmentPlanCommitmentPaymentsCount(): number; /** * @en Subsequent committed payments count after this subscription plan renews. * @zh 此订阅计划续订后的后续承诺付款数量。 */ - readonly subsequentInstallmentPlanCommitmentPaymentsCount: number; + getSubsequentInstallmentPlanCommitmentPaymentsCount(): number; } /** @@ -424,32 +420,44 @@ declare namespace jsb { * @en Number of cycles for which the billing period is applied. * @zh 计费周期适用的周期数。 */ - readonly billingCycleCount: number; + getBillingCycleCount(): number; /** * @en The price for the payment cycle in micro-units, where 1,000,000 micro-units equal one unit of the currency. * @zh 微单位付款周期的价格,其中 1,000,000 个微单位等于 1 个货币单位。 */ - readonly priceAmountMicros: number; + getPriceAmountMicros(): number; /** * @en RecurrenceMode for the pricing phase. * @zh 定价阶段的RecurrenceMode。 */ - readonly recurrenceMode: number; + getRecurrenceMode(): number; /** * @en Billing period for which the given price applies, specified in ISO 8601 format. * @zh 给定价格适用的计费期,以 ISO 8601 格式指定。 */ - readonly billingPeriod: string; + getBillingPeriod(): string; /** * @en Formatted price for the payment cycle, including its currency sign. * @zh 付款周期的格式化价格,包括其货币符号。 */ - readonly formattedPrice: string; + getFormattedPrice(): string; /** * @en Returns ISO 4217 currency code for price. * @zh 返回价格的 ISO 4217 货币代码。 */ - readonly priceCurrencyCode: string; + getPriceCurrencyCode(): string; + } + + /** + * @en Represents a pricing phase, describing how a user pays at a point in time. + * @zh 表示定价阶段,描述用户在某个时间点如何付款。 + */ + export interface PricingPhases { + /** + * @en Returns ISO 4217 currency code for price. + * @zh 返回价格的 ISO 4217 货币代码。 + */ + getPricingPhaseList(): PricingPhase[]; } /** @@ -461,83 +469,86 @@ declare namespace jsb { * @en The base plan id associated with the subscription product. * @zh 与订阅产品相关的基本计划 ID。 */ - readonly basePlanId: string; + getBasePlanId(): string; /** * @en The offer id associated with the subscription product. * @zh 与订阅产品相关的优惠 ID。 */ - readonly offerId: string; + getOfferId(): string; /** * @en The offer tags associated with this Subscription Offer. * @zh 与此订阅优惠相关的优惠标签。 */ - readonly offerTags: string[]; + getOfferTags(): string[]; /** * @en The offer token required to pass in launchBillingFlow to purchase the subscription product with these pricing phases. * @zh 在 launchBillingFlow 中传递以使用这些定价阶段购买订阅产品所需的优惠令牌。 */ - readonly offerToken: string; + getOfferToken(): string; /** * @en The pricing phases for the subscription product. * @zh 订阅产品的定价区间。 */ - readonly pricingPhaseList: PricingPhase[]; + getPricingPhases(): PricingPhases; /** * @en The additional details of an installment plan. * @zh 分期付款计划的附加详细信息。 */ - readonly installmentPlanDetails: InstallmentPlanDetails; + getInstallmentPlanDetails(): InstallmentPlanDetails; } /** * @en Represents the details of a one time or subscription product. * @zh 代表一次性或订阅产品的详细信息。 */ - export interface ProductDetails { + export class ProductDetails { + static RecurrenceMode: typeof jsb.RecurrenceMode; + + equals(other: ProductDetails): boolean; /** * @en Hash code * @zh hash值 */ - readonly hashCode: number; + hashCode(): number; /** * @en The description of the product. * @zh 产品的描述。 */ - readonly description: string; + getDescription(): string; /** * @en The name of the product being sold. * @zh 所售产品的名称。 */ - readonly name: string; + getName(): string; /** * @en The product's Id. * @zh 产品的 ID。 */ - readonly productId: string; + getProductId(): string; /** * @en The ProductType of the product. * @zh ProductType产品的。 */ - readonly productType: string; + getProductType(): string; /** * @en The title of the product being sold. * @zh 所售产品的标题。 */ - readonly title: string; + getTitle(): string; /** * @en To string * @zh 转换成字符串 */ - readonly toStr: string; + toString(): string; /** * @en The offer details of an one-time purchase product. * @zh 代表一次性购买产品的报价详情。 */ - readonly oneTimePurchaseOfferDetails: OneTimePurchaseOfferDetails; + getOneTimePurchaseOfferDetails(): OneTimePurchaseOfferDetails; /** * @en A list containing all available offers to purchase a subscription product. * @zh 返回包含购买订阅产品的所有可用优惠的列表。 */ - readonly subscriptionOfferDetails: SubscriptionOfferDetails[]; + getSubscriptionOfferDetails(): SubscriptionOfferDetails[]; } /** @@ -549,12 +560,12 @@ declare namespace jsb { * @en The obfuscated account id specified in setObfuscatedAccountId. * @zh 在setObfuscatedAccountId中设置的混淆账户id */ - readonly obfuscatedAccountId: string; + getObfuscatedAccountId(): string; /** * @en The obfuscated profile id specified in setObfuscatedProfileId. * @zh 在setObfuscatedProfileId中设置的混淆profile id */ - readonly obfuscatedProfileId: string; + getObfuscatedProfileId(): string; } /** @@ -566,101 +577,135 @@ declare namespace jsb { * @en A token that uniquely identifies this pending transaction. * @zh 唯一标识此待处理交易的令牌。 */ - readonly purchaseToken: string; + getPurchaseToken(): string; /** * @en The product ids. * @zh 产品 ID。 */ - readonly products: string[]; + getProducts(): string[]; } + /** + * @en + * Possible purchase states. + * + * @zh + * 可能的购买状态。 + */ + export enum PurchaseState { + /** + * @en + * Purchase is pending and not yet completed to be processed by your app. + * + * @zh + * 购买处于待处理状态且尚未完成,无法由您的应用程序处理。 + */ + PENDING = 2, + /** + * @en + * Purchase is completed.. + * + * @zh + * 购买完成。 + */ + PURCHASED = 1, + /** + * @en + * Purchase with unknown state. + * + * @zh + * 未知状态 + */ + UNSPECIFIED_STATE = 0, + } /** * @en Represents an in-app billing purchase. * @zh 代表应用内billing购买。 */ - export interface Purchase { + export class Purchase { + static PurchaseState: typeof jsb.PurchaseState; /** * @en One of PurchaseState indicating the state of the purchase. * @zh PurchaseState表示购买状态的其中一个值。 */ - readonly purchaseState: number; + getPurchaseState(): number; /** * @en The time the product was purchased, in milliseconds since the epoch (Jan 1, 1970). * @zh 产品购买的时间,以纪元(1970 年 1 月 1 日)以来的毫秒数表示。 */ - readonly purchaseTime: number; + getPurchaseTime(): number; /** * @en Indicates whether the purchase has been acknowledged. * @zh 表示是否已确认购买。 */ - readonly isAcknowledged: number; + isAcknowledged(): number; /** * @en Indicates whether the subscription renews automatically. * @zh 指示订阅是否自动续订。 */ - readonly isAutoRenewing: number; + isAutoRenewing(): number; /** * @en Hash code * @zh hash值 */ - readonly hashCode: number; + hashCode(): number; /** * @en The quantity of the purchased product. * @zh 购买产品的数量。 */ - readonly quantity: number; + getQuantity(): number; /** * @en The payload specified when the purchase was acknowledged or consumed. * @zh 确认或消费购买时指定的有效负载。 */ - readonly developerPayload: string; + getDeveloperPayload(): string; /** * @en Returns a unique order identifier for the transaction. * @zh 交易的唯一订单标识符。 */ - readonly orderId: string; + getOrderId(): string; /** * @en Returns a String in JSON format that contains details about the purchase order. * @zh 包含有关采购订单详细信息的 JSON 格式的字符串。 */ - readonly originalJson: string; + getOriginalJson(): string; /** * @en The application package from which the purchase originated. * @zh 购买来源的应用程序包。 */ - readonly packageName: string; + getPackageName(): string; /** * @en A token that uniquely identifies a purchase for a given item and user pair. * @zh 唯一标识给定商品和用户对的购买的令牌。 */ - readonly purchaseToken: string; + getPurchaseToken(): string; /** * @en String containing the signature of the purchase data that was signed with the private key of the developer. * @zh 包含使用开发者私钥签名的购买数据签名的字符串。 */ - readonly signature: string; + getSignature(): string; /** * @en To string * @zh 转换成字符串 */ - readonly toStr: string; + toString(): string; /** * @en Returns account identifiers that were provided when the purchase was made. * @zh 返回购买时提供的帐户标识符。 */ - readonly accountIdentifiers: AccountIdentifiers; + getAccountIdentifiers(): AccountIdentifiers; /** * @en The PendingPurchaseUpdate for an uncommitted transaction. * @zh 返回PendingPurchaseUpdate未提交的事务。 */ - readonly pendingPurchaseUpdate: PendingPurchaseUpdate; + getPendingPurchaseUpdate(): PendingPurchaseUpdate; /** * @en the product Ids. * @zh 产品 ID。 */ - readonly products: string[]; + getProducts(): string[]; } export interface BillingConfig { @@ -668,7 +713,7 @@ declare namespace jsb { * @en The customer's country code. * @zh 客户的国家代码。 */ - readonly countryCode: string; + getCountryCode(): string; } /** @@ -681,7 +726,7 @@ declare namespace jsb { * without user choice to use Google Play billing. * @zh 返回一个外部交易令牌,该令牌可用于报告通过替代付款方式进行的交易,而无需用户选择使用 Google Play 付款方式。 */ - readonly externalTransactionToken: string; + getExternalTransactionToken(): string; } /** @@ -693,149 +738,683 @@ declare namespace jsb { * @en An external transaction token that can be used to report a transaction made via external offer. * @zh 可用于报告通过外部报价进行的交易的外部交易令牌。 */ - readonly externalTransactionToken: string; + getExternalTransactionToken(): string; } /** * @en Results related to in-app messaging. * @zh 与应用程序内消息相关的结果。 */ - export interface InAppMessageResult { + export class InAppMessageResult { + static InAppMessageResponseCode: typeof InAppMessageResponseCode; /** * @en Response code for the in-app messaging API call. * @zh 应用内消息传递 API 调用的响应代码。 */ - readonly responseCode: number; + getResponseCode(): number; /** * @en Token that identifies the purchase to be acknowledged, if any. * @zh 返回标识需要确认的购买的令牌。 */ - readonly purchaseToken: string; + getPurchaseToken(): string; + } + + export interface BillingResultBuilder { + setDebugMessage(productType: string): BillingResultBuilder; + setResponseCode(productType: number): BillingResultBuilder; + build(): BillingResult; + } + export class BillingResult { + private constructor(); + static Builder: BillingResultBuilder; + getResponseCode(): number; + getDebugMessage(): string; + toString(): string; + public static newBuilder(): BillingResultBuilder; + } + + export namespace BillingResult { + type Builder = BillingResultBuilder; + } + + export interface UserChoiceBillingListener { + userSelectedAlternativeBilling(userChoiceDetails: UserChoiceDetails): void; + } + export interface PurchasesUpdatedListener { + onPurchasesUpdated(billingResult: BillingResult, purchases: Purchase[]): void; + } + export interface BillingClientStateListener { + onBillingServiceDisconnected(): void; + onBillingSetupFinished( + billingResult: BillingResult, + ): void; + } + + export interface PendingPurchasesParamsBuilder { + enableOneTimeProducts: () => PendingPurchasesParamsBuilder; + enablePrepaidPlans: () => PendingPurchasesParamsBuilder; + build: () => PendingPurchasesParams; + } + + export class PendingPurchasesParams { + private constructor(); + public static newBuilder(): PendingPurchasesParamsBuilder; + } + + export interface QueryProductDetailsParamsProductBuilder { + setProductId: (productID: string) => QueryProductDetailsParamsProductBuilder; + setProductType: (productType: string) => QueryProductDetailsParamsProductBuilder; + build: () => QueryProductDetailsParamsProduct; + } + export class QueryProductDetailsParamsProduct { + private constructor(); + public static newBuilder(): QueryProductDetailsParamsProductBuilder; + } + + export interface QueryProductDetailsParamsBuilder { + setProductList: (products: QueryProductDetailsParamsProduct[]) => QueryProductDetailsParamsBuilder; + build: () => QueryProductDetailsParams; + } + export class QueryProductDetailsParams { + static Product: typeof jsb.QueryProductDetailsParamsProduct; + private constructor(); + public static newBuilder(): QueryProductDetailsParamsBuilder; + } + + export interface ProductDetailsResponseListener { + onProductDetailsResponse(billingResult: BillingResult, productDetailsList: ProductDetails[]): void; + } + + export interface ConsumeResponseListener { + onConsumeResponse(billingResult: BillingResult, token: string): void + } + + export interface AcknowledgePurchaseResponseListener { + onAcknowledgePurchaseResponse( + billingResult: BillingResult + ): void + } + + export interface BillingClientBuilder { + enableAlternativeBillingOnly: () => BillingClientBuilder; + enableExternalOffer: () => BillingClientBuilder; + enablePendingPurchases: (params: PendingPurchasesParams) => BillingClientBuilder; + enableUserChoiceBilling: (userChoiceBillingListener: UserChoiceBillingListener) => BillingClientBuilder; + setListener: (listener: PurchasesUpdatedListener) => BillingClientBuilder; + build: () => BillingClient; + } + + export interface PurchasesResponseListener { + onQueryPurchasesResponse( + billingResult: BillingResult, + purchase: Purchase[] + ): void + } + + export interface BillingConfigResponseListener { + onBillingConfigResponse( + billingResult: BillingResult, + billingConfig: BillingConfig + ): void + } + export interface AlternativeBillingOnlyReportingDetailsListener { + onAlternativeBillingOnlyTokenResponse( + billingResult: BillingResult, + alternativeBillingOnlyReportingDetails: AlternativeBillingOnlyReportingDetails + ): void + } + + export interface ExternalOfferReportingDetailsListener { + onExternalOfferReportingDetailsResponse( + billingResult: BillingResult, + externalOfferReportingDetails: ExternalOfferReportingDetails + ): void + } + + export interface AlternativeBillingOnlyAvailabilityListener { + onAlternativeBillingOnlyAvailabilityResponse( + billingResult: BillingResult + ): void + } + + export interface ExternalOfferAvailabilityListener { + onExternalOfferAvailabilityResponse( + billingResult: BillingResult + ): void + } + export interface AlternativeBillingOnlyInformationDialogListener { + onAlternativeBillingOnlyInformationDialogResponse( + billingResult: BillingResult + ): void + } + export interface ExternalOfferInformationDialogListener { + onExternalOfferInformationDialogResponse( + billingResult: BillingResult + ): void + } + export interface InAppMessageResponseListener { + onInAppMessageResponse( + inAppMessageResult: InAppMessageResult + ): void } /** - * @en Main interface for communication between the Google Play library and user application code. - * @zh 产品 ID。 + * @en + * Connection state of billing client. + * + * @zh + * Billing client的连接状态 */ - const googleBilling: { + export enum ConnectionState { /** - * @en Starts up BillingClient setup process asynchronously. - * @zh 异步启动 BillingClient 设置过程。 + * @en + * This client was not yet connected to billing service or was already closed. + * + * @zh + * 此客户端尚未连接到Billing服务或已关闭。 */ - startConnection(): void; + DISCONNECTED = 0, + /** + * @en + * This client is currently in process of connecting to billing service. + * + * @zh + * 此客户端目前正在连接到Billing服务。 + */ + CONNECTING = 1, + /** + * @en + * This client is currently connected to billing service. + * + * @zh + * 此客户端当前已连接到Billing服务。 + */ + CONNECTED = 2, + /** + * @en + * This client was already closed and shouldn't be used again. + * + * @zh + * 该客户端已关闭,不应再次使用。 + */ + CLOSED = 3, + } + /** + * @en + * Possible response codes. + * + * @zh + * 可能的响应代码。 + */ + export enum BillingResponseCode { + /** + * @en + * This field is deprecated. + * See SERVICE_UNAVAILABLE which will be used instead of this code. + * + * @zh + * 这个字段已经废弃。 + * 看看SERVICE_UNAVAILABLE将使用哪一个来代替此代码。 + */ + SERVICE_TIMEOUT = -3, + /** + * @en + * The requested feature is not supported by the Play Store on the current device. + * + * @zh + * 当前设备上的 Play Store 不支持所请求的功能。 + */ + FEATURE_NOT_SUPPORTED = -2, + /** + * @en + * The app is not connected to the Play Store service via the Google Play Billing Library. + * + * @zh + * 该应用未通过 Google Play Billing库连接到 Play Store 服务。 + */ + SERVICE_DISCONNECTED = -1, + /** + * @en + * Success. + * + * @zh + * 成功。 + */ + OK = 0, + /** + * @en + * Transaction was canceled by the user. + * + * @zh + * 交易已被用户取消。 + */ + USER_CANCELED = 1, + /** + * @en + * The service is currently unavailable. + * + * @zh + * 当前设备上的 Play Store 不支持所请求的功能。 + */ + SERVICE_UNAVAILABLE = 2, + /** + * @en + * A user billing error occurred during processing. + * + * @zh + * 处理过程中出现用户billing错误。 + */ + BILLING_UNAVAILABLE = 3, + /** + * @en + * The requested product is not available for purchase. + * + * @zh + * 所请求的产品无法购买。 + */ + ITEM_UNAVAILABLE = 4, + /** + * @en + * Error resulting from incorrect usage of the API. + * + * @zh + * 由于错误使用 API 而导致的错误。 + */ + DEVELOPER_ERROR = 5, + /** + * @en + * Fatal error during the API action. + * + * @zh + * API 操作期间发生致命错误。 + */ + ERROR = 6, + /** + * @en + * The purchase failed because the item is already owned. + * + * @zh + * 购买失败,因为该物品已被拥有。 + */ + ITEM_ALREADY_OWNED = 7, + /** + * @en + * Requested action on the item failed since it is not owned by the user. + * + * @zh + * 由于该项目不属于用户,因此对该项目请求的操作失败。 + */ + ITEM_NOT_OWNED = 8, + /** + * @en + * A network error occurred during the operation. + * + * @zh + * 操作期间发生网络错误。 + */ + NETWORK_ERROR = 12, + } + /** + * @en + * Features/capabilities supported by isFeatureSupported. + * + * @zh + * 支持的特性/能力isFeatureSupported。 + */ + export enum FeatureType { + /** + * @en + * Purchase/query for subscriptions. + * + * @zh + * 购买/查询订阅。 + */ + SUBSCRIPTIONS = 'subscriptions', + /** + * @en + * Subscriptions update/replace. + * + * @zh + * 订阅更新/替换。 + */ + SUBSCRIPTIONS_UPDATE = 'subscriptionsUpdate', + /** + * @en + * Launch a price change confirmation flow. + * + * @zh + * 启动价格变动确认流程。 + */ + PRICE_CHANGE_CONFIRMATION = 'priceChangeConfirmation', + /** + * @en + * Show in-app messages. + * + * @zh + * 显示应用内消息。 + */ + IN_APP_MESSAGING = 'bbb', + /** + * @en + * Play billing library support for querying and purchasing. + * + * @zh + * Play Billing库支持查询、购买。 + */ + PRODUCT_DETAILS = 'fff', + /** + * @en + * Get billing config. + * + * @zh + * 获取计费配置。 + */ + BILLING_CONFIG = 'ggg', + /** + * @en + * Alternative billing only. + * + * @zh + * 仅限替代Billing。 + */ + ALTERNATIVE_BILLING_ONLY = 'jjj', /** - * @en Closes the connection and releases all held resources such as service connections. - * @zh 关闭连接并释放所有持有的资源,例如服务连接。 + * @en + * Play billing library support for external offer. + * + * @zh + * Play billing库支持外部报价。 */ - endConnection(): void; + EXTERNAL_OFFER = 'kkk', + } + /** + * @en + * Supported Product types. + * + * @zh + * 支持的产品类型。 + */ + export enum ProductType { /** - * @en Get the current billing client connection state. - * @zh 获取当前计费客户端连接状态。 + * @en + * A Product type for Android apps in-app products. + * + * @zh + * Android 应用内产品的产品类型。 */ - getConnectionState(): number; + INAPP = 'inapp', + /** + * @en + * A Product type for Android apps subscriptions. + * + * @zh + * Android 应用程序订阅的产品类型。 + */ + SUBS = 'subs' + } + /** + * @en + * A high-level category of the in-app message. + * One category can be mapped to multiple in-app messages. + * + * @zh + * 应用程序内信息的高级类别。 + * 一个类别可映射到多个应用程序内信息。 + */ + export enum InAppMessageCategoryId { /** - * @en Checks if the client is currently connected to the service, so that requests to other methods will succeed. - Returns true if the client is currently connected to the service, false otherwise. - * @zh 检查客户端当前是否连接到服务,以便对其他方法的请求能够成功。 - 如果客户端当前已连接到服务,则返回 true,否则返回 false。 + * @en + * A Product type for Android apps in-app products. + * + * @zh + * 应用程序中未知的消息类别 ID */ - isReady(): boolean; + UNKNOWN_IN_APP_MESSAGE_CATEGORY_ID = 0, + /** + * @en + * The in-app messages of this category are for transactional purpose, such as payment issues. + * + * @zh + * 这类应用内信息用于交易目的,如支付问题。 + */ + TRANSACTIONAL = 2 + } + /** + * @en + * Supported replacement modes to replace an existing subscription with a new one. + * + * @zh + * 支持替换模式,可将现有订购替换为新订购。 + */ + export enum ReplacementMode { /** - * @en Performs a network query the details of products available for sale in your app. - * @zh 执行网络查询您的应用中可供销售的产品的详细信息。 + * @en + * Unknown replacement mode. + * + * @zh + * 未知替换模式 */ - queryProductDetailsParams(productId: string[], productType: string): void; + UNKNOWN_REPLACEMENT_MODE = 0, /** - * @en Initiates the billing flow for an in-app purchase or subscription. - * @zh 启动应用内购买或订阅的计费流程。 + * @en + * The new plan takes effect immediately, and the remaining time will be prorated and credited to the user. + * + * @zh + * 新计划立即生效,剩余时间将按比例计入用户贷方。 */ - launchBillingFlow(productDetails: ProductDetails[], selectedOfferToken: string | null): void; + WITH_TIME_PRORATION = 1, /** - * @en Consumes a given in-app product. - * @zh 消费指定的应用内产品。 + * @en + * The new plan takes effect immediately, and the billing cycle remains the same. + * + * @zh + * 新计划立即生效,计费周期保持不变。 */ - consumePurchases(purchases: Purchase[]): void; + CHARGE_PRORATED_PRICE = 2, /** - * @en Returns purchases details for currently owned items bought within your app. - * @zh 返回您应用内当前拥有的购买商品的购买详情。 + * @en + * The new plan takes effect immediately, and the new price will be charged on next recurrence time. + * + * @zh + * 新计划立即生效,新价格将在下次复诊时收取。 */ - queryPurchasesAsync(productType: string): void; + WITHOUT_PRORATION = 3, /** - * @en Acknowledges in-app purchases.. - * @zh 确认应用内购买。 + * @en + * Replacement takes effect immediately, and the user is charged full price of new plan and + * is given a full billing cycle of subscription, plus remaining prorated time from the old plan. + * + * @zh + * 替换立即生效,用户将被收取新计划的全额费用,并获得一个完整的计费周期,加上旧计划按比例计算的剩余时间。 */ - acknowledgePurchase(purchases: Purchase[]): void; + CHARGE_FULL_PRICE = 5, /** - * @en Gets the billing config, which stores configuration used to perform billing operations. - * @zh 获取计费配置,其中存储用于执行计费操作的配置。 + * @en + * The new purchase takes effect immediately, the new plan will take effect when the old item expires. + * + * @zh + * 新购买立即生效,新计划将在旧项目到期时生效。 */ - getBillingConfigAsync(): void; + DEFERRED = 6, + } + /** + * @en + * Possible response codes. + * + * @zh + * 可能的响应代码。 + */ + export enum InAppMessageResponseCode { /** - * @en Creates alternative billing only purchase details that can be used to report a transaction made via alternative billing without user choice to use Google Play billing. - * @zh 创建仅限替代结算的购买详情,可用于报告通过替代结算进行的交易,而无需用户选择使用 Google Play Billing。 + * @en + * The flow has finished and there is no action needed from developers. + * + * @zh + * 流程已经结束,开发人员无需采取任何行动。 */ - createAlternativeBillingOnlyReportingDetailsAsync(): void; + NO_ACTION_NEEDED = 0, /** - * @en Checks the availability of offering alternative billing without user choice to use Google Play Billing. - * @zh 检查是否可以提供替代结算方式,而无需用户选择使用 Google Play Billing方式。 + * @en + * The subscription status changed. + * + * @zh + * 订阅状态已更改。 */ - isAlternativeBillingOnlyAvailableAsync(): void; + SUBSCRIPTION_STATUS_UPDATED = 1 + } + /** + * @en + * Recurrence mode of the pricing phase. + * + * @zh + * 定价阶段的复现模式。 + */ + export enum RecurrenceMode { /** - * @en Creates purchase details that can be used to report a transaction made via external offer. - * @zh 创建可用于报告通过外部报价进行的交易的购买详情。 + * @en + * The billing plan payment recurs for infinite billing periods unless cancelled. + * + * @zh + * 除非取消,否则billing计划付款将无限期地重复。 */ - createExternalOfferReportingDetailsAsync(): void; + INFINITE_RECURRING = 1, /** - * @en Checks the availability of providing external offer. - * @zh 检查提供外部报价的可用性。 + * @en + * The billing plan payment recurs for a fixed number of billing period set in billingCycleCount. + * + * @zh + * Billing计划付款将在 billingCycleCount 中设置的固定计费周期内重复发生。 */ - isExternalOfferAvailableAsync(): void; + FINITE_RECURRING = 2, + /** + * @en + * The billing plan payment is a one time charge that does not repeat. + * + * @zh + * Billing计划付款是一次性费用,不会重复。 + */ + NON_RECURRING = 3, + } - /** - * @en Checks if the specified feature or capability is supported by the Play Store. - * @zh 检查 Play Store 是否支持指定的功能。 - */ - isFeatureSupported(feature: string): BillingResult; + export interface ProductDetailsParamsBuilder { + setOfferToken: (offerToken: string) => ProductDetailsParamsBuilder; + setProductDetails: (productDetails: ProductDetails) => ProductDetailsParamsBuilder; + build: () => ProductDetailsParams; + } + export class ProductDetailsParams { + private constructor(); + static Builder: ProductDetailsParamsBuilder; + static newBuilder: () => ProductDetailsParamsBuilder; + } - /** - * @en Shows the alternative billing only information dialog on top of the calling app. - * @zh 在调用应用程序顶部显示仅显示备用计费信息对话框。 - */ - showAlternativeBillingOnlyInformationDialog(): BillingResult; + export interface SubscriptionUpdateParamsBuilder { + setOldPurchaseToken: (purchaseToken: string) => SubscriptionUpdateParamsBuilder; + setOriginalExternalTransactionId: (externalTransactionId: string) => SubscriptionUpdateParamsBuilder; + setSubscriptionReplacementMode: (subscriptionReplacementMode: number) => SubscriptionUpdateParamsBuilder; + build: () => SubscriptionUpdateParams; + } + export class SubscriptionUpdateParams { + private constructor(); + static Builder: SubscriptionUpdateParamsBuilder; + static newBuilder: () => SubscriptionUpdateParamsBuilder; + static ReplacementMode: typeof jsb.ReplacementMode; + } - /** - * @en Shows the external offer information dialog on top of the calling app. - * @zh 在调用应用程序顶部显示外部优惠信息对话框。 - */ - showExternalOfferInformationDialog(): BillingResult; + export class BillingFlowParams { + static ProductDetailsParams: typeof jsb.ProductDetailsParams; + static SubscriptionUpdateParams: typeof jsb.SubscriptionUpdateParams; + static Builder: BillingFlowParamsBuilder; + private constructor(); + public static newBuilder(): BillingFlowParamsBuilder; + } - /** - * @en Overlays billing related messages on top of the calling app. - * @zh 在调用应用程序上叠加与计费相关的消息。 - */ - showInAppMessages(): BillingResult; - } | undefined; - export let onBillingSetupFinished: (result: BillingResult) => void | undefined; - export let onBillingServiceDisconnected: () => void | undefined; - export let onProductDetailsResponse: (result: BillingResult, productDetailsList: ProductDetails[]) => void | undefined; - export let onPurchasesUpdated: (result: BillingResult, purchaseList: Purchase[]) => void | undefined; - export let onConsumeResponse: (result: BillingResult, purchaseToken: string) => void | undefined; - export let onAcknowledgePurchaseResponse: (result: BillingResult) => void | undefined; - export let onQueryPurchasesResponse: (result: BillingResult, purchaseList: Purchase[]) => void | undefined; - export let onBillingConfigResponse: (result: BillingResult, config: BillingConfig) => void | undefined; - export let onAlternativeBillingOnlyTokenResponse: (result: BillingResult, details: AlternativeBillingOnlyReportingDetails) => void | undefined; - export let onExternalOfferReportingDetailsResponse: (result: BillingResult, details: ExternalOfferReportingDetails) => void | undefined; - export let onAlternativeBillingOnlyAvailabilityResponse: (result: BillingResult) => void | undefined; - export let onExternalOfferAvailabilityResponse: (result: BillingResult) => void | undefined; - export let onAlternativeBillingOnlyInformationDialogResponse: (result: BillingResult) => void | undefined; - export let onExternalOfferInformationDialogResponse: (result: BillingResult) => void | undefined; - export let onInAppMessageResponse: (result: InAppMessageResult) => void | undefined; + export interface BillingFlowParamsBuilder { + setIsOfferPersonalized: (isOfferPersonalized: boolean) => BillingFlowParamsBuilder; + setObfuscatedAccountId: (obfuscatedAccountid: string) => BillingFlowParamsBuilder; + setObfuscatedProfileId: (obfuscatedProfileId: string) => BillingFlowParamsBuilder; + setProductDetailsParamsList: (userChoiceBillingListener: ProductDetailsParams[]) => BillingFlowParamsBuilder; + setSubscriptionUpdateParams: (userChoiceBillingListener: SubscriptionUpdateParams) => BillingFlowParamsBuilder; + build: () => BillingFlowParams; + } + + export interface ConsumeParamsBuilder { + setPurchaseToken: (purchaseToken: string) => ConsumeParamsBuilder; + build: () => ConsumeParams; + } + export class ConsumeParams { + private constructor(); + public static newBuilder(): ConsumeParamsBuilder; + } + export interface AcknowledgePurchaseParamsBuilder { + setPurchaseToken: (purchaseToken: string) => AcknowledgePurchaseParamsBuilder; + build: () => AcknowledgePurchaseParams; + } + export class AcknowledgePurchaseParams { + private constructor(); + public static newBuilder(): AcknowledgePurchaseParamsBuilder; + } + + export interface QueryPurchasesParamsBuilder { + setProductType: (productType: string) => QueryPurchasesParamsBuilder; + build: () => QueryPurchasesParams; + } + export class QueryPurchasesParams { + private constructor(); + public static newBuilder(): QueryPurchasesParamsBuilder; + } + + export interface InAppMessageParamsBuilder { + addAllInAppMessageCategoriesToShow: () => InAppMessageParamsBuilder; + addInAppMessageCategoryToShow: (inAppMessageCategoryId: number) => InAppMessageParamsBuilder; + build: () => InAppMessageParams; + } + export class InAppMessageParams { + private constructor(); + public static newBuilder(): InAppMessageParamsBuilder; + static InAppMessageCategoryId: typeof InAppMessageCategoryId; + } + + export interface GetBillingConfigParamsBuilder { + build: () => GetBillingConfigParams; + } + export class GetBillingConfigParams { + private constructor(); + public static newBuilder(): GetBillingConfigParamsBuilder; + } + export class BillingClient { + private constructor(); + static Builder: BillingFlowParamsBuilder; + static ConnectionState: typeof jsb.ConnectionState; + static BillingResponseCode: typeof jsb.BillingResponseCode; + static FeatureType: typeof jsb.FeatureType; + static ProductType: typeof jsb.ProductType; + public static newBuilder(): BillingClientBuilder; + startConnection: (listener: BillingClientStateListener) => void; + endConnection: () => void; + getConnectionState: () => number; + isReady: () => void; + queryProductDetailsAsync: (params: QueryProductDetailsParams, listener: ProductDetailsResponseListener) => void; + launchBillingFlow: (params: BillingFlowParams) => void; + consumeAsync: (params: ConsumeParams, listener: ConsumeResponseListener) => void; + acknowledgePurchase: (params: AcknowledgePurchaseParams, listener: AcknowledgePurchaseResponseListener) => void; + queryPurchasesAsync: (params: QueryPurchasesParams, listener: PurchasesResponseListener) => void; + getBillingConfigAsync: (params: GetBillingConfigParams, listener: BillingConfigResponseListener) => void; + createAlternativeBillingOnlyReportingDetailsAsync: (listener: AlternativeBillingOnlyReportingDetailsListener) => void; + isAlternativeBillingOnlyAvailableAsync: (listener: AlternativeBillingOnlyAvailabilityListener) => void; + createExternalOfferReportingDetailsAsync: (listener: ExternalOfferReportingDetailsListener) => void; + isExternalOfferAvailableAsync: (listener: ExternalOfferAvailabilityListener) => void; + + isFeatureSupported: (productType: string) => BillingResult; + showAlternativeBillingOnlyInformationDialog: (listener: AlternativeBillingOnlyInformationDialogListener) => void; + showExternalOfferInformationDialog: (listener: ExternalOfferInformationDialogListener) => void; + showInAppMessages: (params: InAppMessageParams, listener: InAppMessageResponseListener) => void; + } } declare namespace ns { diff --git a/cc.config.json b/cc.config.json index c998707946..86f8cd9328 100644 --- a/cc.config.json +++ b/cc.config.json @@ -159,7 +159,7 @@ "modules": ["tiled-map"], "dependentModules": ["2d"] }, - "vendor": { + "vendor-google": { "modules": ["vendor-google"] }, "spine": { diff --git a/cocos/2d/renderer/render-data.ts b/cocos/2d/renderer/render-data.ts index e8578db0a2..c6de48b3fb 100644 --- a/cocos/2d/renderer/render-data.ts +++ b/cocos/2d/renderer/render-data.ts @@ -484,7 +484,9 @@ export class RenderData extends BaseRenderData { // Hack Do not update pre frame if (JSB && this.multiOwner === false) { if (DEBUG) { - assert(this._renderDrawInfo.render2dBuffer.length === this._floatStride * this._data.length, 'Vertex count doesn\'t match.'); + if (this._renderDrawInfo && this._renderDrawInfo.render2dBuffer) { + assert(this._renderDrawInfo.render2dBuffer.length === this._floatStride * this._data.length, 'Vertex count doesn\'t match.'); + } } // sync shared buffer to native this._renderDrawInfo.fillRender2dBuffer(this._data); diff --git a/cocos/2d/renderer/render-draw-info.ts b/cocos/2d/renderer/render-draw-info.ts index df0546389d..45a0402cb6 100644 --- a/cocos/2d/renderer/render-draw-info.ts +++ b/cocos/2d/renderer/render-draw-info.ts @@ -90,7 +90,7 @@ export class RenderDrawInfo { protected declare _uint32SharedBuffer: Uint32Array; // SharedBuffer of pos/uv/color - protected declare _render2dBuffer: Float32Array; + protected _render2dBuffer: Float32Array | null = null; constructor (nativeDrawInfo?: NativeRenderDrawInfo) { this.init(nativeDrawInfo); @@ -107,7 +107,7 @@ export class RenderDrawInfo { return this._nativeObj; } - get render2dBuffer (): Float32Array { + get render2dBuffer (): Float32Array | null { return this._render2dBuffer; } @@ -301,6 +301,9 @@ export class RenderDrawInfo { public fillRender2dBuffer (vertexDataArr: IRenderData[]): void { if (JSB) { + if (!this._render2dBuffer) { + return; + } const fillLength = Math.min(this._vbCount, vertexDataArr.length); let bufferOffset = 0; for (let i = 0; i < fillLength; i++) { diff --git a/cocos/native-binding/impl.ts b/cocos/native-binding/impl.ts index c8f6b63958..71f72d7652 100644 --- a/cocos/native-binding/impl.ts +++ b/cocos/native-binding/impl.ts @@ -35,6 +35,8 @@ if (NATIVE) { globalJsb.__bridge = new globalThis.JavascriptJavaBridge(); } else if (globalThis.JavaScriptObjCBridge && (sys.os === sys.OS.IOS || sys.os === sys.OS.OSX)) { globalJsb.__bridge = new globalThis.JavaScriptObjCBridge(); + } else if (globalThis.JavaScriptArkTsBridge && (sys.os === sys.OS.OPENHARMONY)) { + globalJsb.__bridge = new globalThis.JavaScriptArkTsBridge(); } else { globalJsb.__bridge = null; } diff --git a/cocos/native-binding/index.ts b/cocos/native-binding/index.ts index ec3b93cfc1..94fcf4c42e 100644 --- a/cocos/native-binding/index.ts +++ b/cocos/native-binding/index.ts @@ -1262,10 +1262,31 @@ export declare namespace native { * @en call Objective-C/Java static methods * @zh 调用 Objective-C/Java 静态方法 * - * @param className : @en the class name of the Objective-C/Java class @zh Objective-C/Java 类的类名 - * @param methodName : @en the method name of the Objective-C/Java class @zh Objective-C/Java 类的方法名 - * @param methodSignature : @en the method signature of the Objective-C/Java class @zh Objective-C/Java 方法签名 - * @param parameters : @en the parameters of the Objective-C/Java class to translate @zh 传递至该 Objective-C/Java 方法的参数 + * @param className : @en the class name of the Objective-C/Java/ArkTs class @zh Objective-C/Java/ArkTs 类的类名 + * @param methodName : @en the method name of the Objective-C/Java/ArkT class @zh Objective-C/Java/ArkT 类的方法名 + * @param methodSignature : + * @en + * - On the Android platform: Represents the method signature of the Java class. + * - On the Mac/iOS platform: Represents the first parameter of the Objective-C method. + * - On the HarmonyOS Next platform: Represents all parameters of the ArkTs method. + * If multiple parameters are required, can be converted into a JSON string. + * @zh + * - 在 Android 平台:表示 Java 方法的签名。 + * - 在 Mac 或 iOS 平台:表示 Objective-C 方法的第一个参数。 + * - 在 HarmonyOS Next 平台:表示 ArkTs 方法的所有参数。如果需要传入多个参数,可以将它们转换为 JSON 字符串。 + * + * @param parameters : + * @en + * - On the Android platform: Represents the parameters passed to the Java method. + * - On the Mac/iOS platform: Represents the second or subsequent parameters of the Objective-C method. + * - On the HarmonyOS Next platform: Indicates whether the ArkTs method is synchronous or asynchronous. + * The default is `true`, meaning the ArkTs method is called synchronously. + * Note that calling asynchronous ArkTs methods may block while waiting for results. + * @zh + * - 在 Android 平台:传递到 Java 方法的参数。 + * - 在 Mac 或 iOS 平台:传递到 Objective-C 方法的第二个或更多参数。 + * - 在 HarmonyOS Next 平台:表示调用 ArkTs 方法是同步还是异步。 + * 默认值为 `true`,表示调用ArkTs的同步方法。注意,调用异步方法可能会阻塞以等待结果。 */ export function callStaticMethod(className: string, methodName: string, methodSignature: string, ...parameters: any): any; } diff --git a/cocos/primitive/primitive.ts b/cocos/primitive/primitive.ts index 9455de2455..84a09ad892 100644 --- a/cocos/primitive/primitive.ts +++ b/cocos/primitive/primitive.ts @@ -26,7 +26,7 @@ import { ccclass, type, serializable, editable } from 'cc.decorator'; import { createMesh } from '../3d/misc'; import { Mesh } from '../3d/assets/mesh'; import * as primitives from '.'; -import { ccenum, cclegacy } from '../core'; +import { Enum, cclegacy } from '../core'; enum PrimitiveType { BOX = 0, @@ -38,7 +38,7 @@ enum PrimitiveType { PLANE = 6, QUAD = 7, } -ccenum(PrimitiveType); +Enum(PrimitiveType); // Need reversed keys in Primitive.onLoaded, so use Enum to generate reversed keys. /** * @en @@ -81,7 +81,8 @@ export class Primitive extends Mesh { * 根据`type`和`info`构建相应的网格。 */ public onLoaded (): void { - createMesh(primitives[PrimitiveType[this.type].toLowerCase()](this.info), this); + const factory = primitives[PrimitiveType[this.type].toLowerCase()] as (arg: typeof this.info) => primitives.IGeometry; + createMesh(factory(this.info), this); } } diff --git a/cocos/scene-graph/node.jsb.ts b/cocos/scene-graph/node.jsb.ts index a6585a8ba4..14bef97039 100644 --- a/cocos/scene-graph/node.jsb.ts +++ b/cocos/scene-graph/node.jsb.ts @@ -265,6 +265,9 @@ nodeProto.on = function (type, callback, target, useCapture: any = false) { this._registeredNodeEventTypeMask |= REGISTERED_EVENT_MASK_TRANSFORM_CHANGED; } break; + case NodeEventType.ACTIVE_CHANGED: + this._eventMask |= ACTIVE_ON; + break; case NodeEventType.PARENT_CHANGED: if (!(this._registeredNodeEventTypeMask & REGISTERED_EVENT_MASK_PARENT_CHANGED)) { this._registerOnParentChanged(); @@ -311,6 +314,9 @@ nodeProto.off = function (type: string, callback?, target?, useCapture = false) case NodeEventType.TRANSFORM_CHANGED: this._eventMask &= ~TRANSFORM_ON; break; + case NodeEventType.ACTIVE_CHANGED: + this._eventMask &= ~ACTIVE_ON; + break; default: break; } @@ -339,6 +345,10 @@ nodeProto.targetOff = function (target: string | unknown) { if ((this._eventMask & TRANSFORM_ON) && !this._eventProcessor.hasEventListener(NodeEventType.TRANSFORM_CHANGED)) { this._eventMask &= ~TRANSFORM_ON; } + + if ((this._eventMask & ACTIVE_ON) && !this._eventProcessor.hasEventListener(NodeEventType.ACTIVE_CHANGED)) { + this._eventMask &= ~ACTIVE_ON; + } }; nodeProto.pauseSystemEvents = function pauseSystemEvents(recursive: boolean): void { @@ -503,6 +513,10 @@ nodeProto._onActivateNode = function (shouldActiveNow) { }; nodeProto._onPostActivated = function (active: boolean) { + if (this._eventMask & ACTIVE_ON) { + this.emit(NodeEventType.ACTIVE_CHANGED, this, active); + } + const eventProcessor = this._eventProcessor; if (eventProcessor.isEnabled === active) { NodeEventProcessor.callbacksInvoker.emit(DispatcherEventType.MARK_LIST_DIRTY); @@ -1272,6 +1286,12 @@ nodeProto._onActiveNode = function (shouldActiveNow: boolean) { }; nodeProto._onBatchCreated = function (dontSyncChildPrefab: boolean) { + if (this._eventMask & ACTIVE_ON) { + if (!this._activeInHierarchy) { + this.emit(NodeEventType.ACTIVE_CHANGED, this, false); + } + } + this.hasChangedFlags = TRANSFORMBIT_TRS; const children = this._children; const len = children.length; diff --git a/cocos/spine/skeleton.ts b/cocos/spine/skeleton.ts index 6811fb184b..4f9f1e5547 100644 --- a/cocos/spine/skeleton.ts +++ b/cocos/spine/skeleton.ts @@ -22,7 +22,7 @@ THE SOFTWARE. */ import { EDITOR_NOT_IN_PREVIEW, JSB } from 'internal:constants'; -import { ccclass, executeInEditMode, help, menu, serializable, type, displayName, override, displayOrder, editable, tooltip } from 'cc.decorator'; +import { ccclass, executeInEditMode, help, menu, serializable, type, override, displayOrder, editable, visible } from 'cc.decorator'; import { Material, Texture2D } from '../asset/assets'; import { error, logID, warn } from '../core/platform/debug'; import { Enum, EnumType, ccenum } from '../core/value-types/enum'; @@ -370,6 +370,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal */ + @visible(true) @type(DefaultSkinsEnum) get _defaultSkinIndex (): number { if (this.skeletonData) { @@ -419,6 +420,7 @@ export class Skeleton extends UIRenderer { /** * @engineInternal */ + @visible(true) @type(SpineDefaultAnimsEnum) get _animationIndex (): number { const animationName = EDITOR_NOT_IN_PREVIEW ? this.defaultAnimation : this.animation; @@ -495,6 +497,7 @@ export class Skeleton extends UIRenderer { * @en Whether play animations in loop mode. * @zh 是否循环播放当前骨骼动画。 */ + @visible(true) @serializable public loop = true; diff --git a/editor/engine-features/render-config.json b/editor/engine-features/render-config.json index 11fb294988..59845f6600 100644 --- a/editor/engine-features/render-config.json +++ b/editor/engine-features/render-config.json @@ -312,10 +312,10 @@ "2d" ] }, - "vendor": { + "vendor-google": { "default": false, - "label": "i18n:ENGINE.features.vendor.label", - "description": "i18n:ENGINE.features.vendor.description", + "label": "i18n:ENGINE.features.vendor_google.label", + "description": "i18n:ENGINE.features.vendor_google.description", "enginePlugin": false, "isNativeModule": true, "cmakeConfig": "USE_VENDOR", diff --git a/editor/i18n/en/localization.js b/editor/i18n/en/localization.js index bfbb09859e..ad6e95257e 100755 --- a/editor/i18n/en/localization.js +++ b/editor/i18n/en/localization.js @@ -1043,8 +1043,8 @@ module.exports = link(mixin({ label: "Tiled Map", description: "Tiled map support.", }, - vendor: { - label: "Vendor", + vendor_google: { + label: "Vendor Google", description: "Vendor support.", }, spine: { diff --git a/editor/i18n/zh/localization.js b/editor/i18n/zh/localization.js index 92675fffe6..f8f4170e5e 100755 --- a/editor/i18n/zh/localization.js +++ b/editor/i18n/zh/localization.js @@ -1021,9 +1021,9 @@ module.exports = link(mixin({ label: "Tiled 地图", description: "Tiled 地图支持。", }, - vendor: { - label: "Vendor", - description: "Vendor 支持.", + vendor_google: { + label: "Vendor Google", + description: "Vendor Google 支持.", }, spine: { label: "Spine 动画", diff --git a/native/CMakeLists.txt b/native/CMakeLists.txt index 2cbbd620e4..aeee3884be 100644 --- a/native/CMakeLists.txt +++ b/native/CMakeLists.txt @@ -764,8 +764,32 @@ if(USE_GOOGLE_BILLING) cocos_source_files( vendor/google/billing/GoogleBilling.cpp vendor/google/billing/GoogleBilling.h + vendor/google/billing/GoogleBillingManager.h vendor/google/billing/GoogleBillingHelper.cpp vendor/google/billing/GoogleBillingHelper.h + vendor/google/billing/JniBilling.cpp + vendor/google/billing/JniBilling.h + + vendor/google/billing/build-params/AcknowledgePurchaseParams.h + vendor/google/billing/build-params/BillingFlowParams.h + vendor/google/billing/build-params/ConsumeParams.h + vendor/google/billing/build-params/GetBillingConfigParams.h + vendor/google/billing/build-params/InAppMessageParams.h + vendor/google/billing/build-params/PendingPurchasesParams.h + vendor/google/billing/build-params/QueryProductDetailsParams.h + vendor/google/billing/build-params/QueryPurchasesParams.h + + vendor/google/billing/result-values/AccountIdentifiers.h + vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h + vendor/google/billing/result-values/BillingConfig.h + vendor/google/billing/result-values/BillingResult.h + vendor/google/billing/result-values/ExternalOfferReportingDetails.h + vendor/google/billing/result-values/InAppMessageResult.h + vendor/google/billing/result-values/Purchase.h + vendor/google/billing/result-values/Purchase.cpp + vendor/google/billing/result-values/ProductDetails.h + vendor/google/billing/result-values/ProductDetails.cpp + vendor/google/billing/result-values/UserChoiceDetails.h ) endif() @@ -1074,6 +1098,9 @@ set(SWIG_OUTPUT_ROOT ${CMAKE_CURRENT_BINARY_DIR}/generated) set(SWIG_OUTPUT ${SWIG_OUTPUT_ROOT}/cocos/bindings/auto) cc_gen_swig_files(${CMAKE_CURRENT_LIST_DIR}/tools/swig-config ${SWIG_OUTPUT}) +if(USE_GOOGLE_BILLING) + cc_gen_swig_files(${CMAKE_CURRENT_LIST_DIR}/tools/swig-config/android ${SWIG_OUTPUT}) +endif() ##### platform cocos_source_files( @@ -2235,6 +2262,13 @@ if(USE_WEBVIEW) ) endif() +if(USE_GOOGLE_BILLING) + cocos_source_files( + NO_WERROR NO_UBUILD ${SWIG_OUTPUT}/jsb_google_billing_auto.cpp + ${SWIG_OUTPUT}/jsb_google_billing_auto.h + ) +endif() + if(USE_XR_REMOTE_PREVIEW) cocos_source_files( NO_WERROR cocos/xr/XRRemotePreviewManager.h @@ -2608,13 +2642,6 @@ if(USE_ADPF) ) endif() -if(USE_GOOGLE_BILLING) - cocos_source_files( - cocos/bindings/manual/jsb_google_billing.cpp - ) - -endif() - if(ANDROID) cocos_source_files( cocos/bindings/manual/jsb_platform_android.cpp @@ -3146,7 +3173,7 @@ function(cc_apply_definations target) $<$:SCRIPT_ENGINE_TYPE=5> $<$:SCRIPT_ENGINE_TYPE=6> $<$,$>:CC_DEBUG=1> - $,CC_USE_APDF=1,CC_USE_APDF=0> + $,CC_USE_ADPF=1,CC_USE_ADPF=0> $,CC_USE_GOOGLE_BILLING=1,CC_USE_GOOGLE_BILLING=0> ) endfunction() diff --git a/native/cocos/audio/openharmony/PcmAudioService.cpp b/native/cocos/audio/openharmony/PcmAudioService.cpp index 3844eb717f..e9f2e999cc 100644 --- a/native/cocos/audio/openharmony/PcmAudioService.cpp +++ b/native/cocos/audio/openharmony/PcmAudioService.cpp @@ -31,7 +31,7 @@ THE SOFTWARE. #include "audio/android/utils/Compat.h" namespace cc { -static ccstd::vector __silenceData;//NOLINT(bugprone-reserved-identifier, readability-identifier-naming) +static ccstd::vector __silenceData; //NOLINT(bugprone-reserved-identifier, readability-identifier-naming) PcmAudioService::PcmAudioService() : _controller(nullptr) { @@ -149,4 +149,4 @@ void PcmAudioService::resume() { OH_AudioRenderer_Start(_audioRenderer); } } -} // namespace cocos2d \ No newline at end of file +} // namespace cc \ No newline at end of file diff --git a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h index 9f6e5bf059..c3b5c4b5ef 100644 --- a/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h +++ b/native/cocos/bindings/jswrapper/jsvm/CommonHeader.h @@ -48,27 +48,26 @@ } while (0) // Returns nullptr if the_call doesn't return JSVM_OK. -#define NODE_API_CALL(status, env, the_call) \ - status = the_call; \ - if (status != JSVM_OK) { \ - bool isPending = false; \ - if (JSVM_OK == OH_JSVM_IsExceptionPending((env), &isPending) && isPending) { \ - JSVM_Value error; \ - if (JSVM_OK == OH_JSVM_GetAndClearLastException((env), &error)) { \ - JSVM_Value stack; \ - OH_JSVM_GetNamedProperty((env), error, "stack", &stack); \ - JSVM_Value message; \ - OH_JSVM_GetNamedProperty((env), error, "message", &message); \ - char stackstr[256]; \ - OH_JSVM_GetValueStringUtf8(env, stack, stackstr, 256, nullptr); \ - SE_LOGE("JSVM error stack: %{public}s", stackstr); \ - char messagestr[256]; \ - OH_JSVM_GetValueStringUtf8(env, message, messagestr, 256, nullptr); \ - SE_LOGE("JSVM error message: %{public}s", messagestr); \ - } \ - } \ - } \ - NODE_API_CALL_BASE(env, status, nullptr) +#define NODE_API_CALL(status, env, the_call) \ + status = the_call; \ + if (status != JSVM_OK) { \ + bool isPending = false; \ + if (JSVM_OK == OH_JSVM_IsExceptionPending((env), &isPending) && isPending) { \ + JSVM_Value error; \ + if (JSVM_OK == OH_JSVM_GetAndClearLastException((env), &error)) { \ + JSVM_Value stack; \ + OH_JSVM_GetNamedProperty((env), error, "stack", &stack); \ + JSVM_Value message; \ + OH_JSVM_GetNamedProperty((env), error, "message", &message); \ + char stackstr[256]; \ + OH_JSVM_GetValueStringUtf8(env, stack, stackstr, 256, nullptr); \ + SE_LOGE("JSVM error stack: %s", stackstr); \ + char messagestr[256]; \ + OH_JSVM_GetValueStringUtf8(env, message, messagestr, 256, nullptr); \ + SE_LOGE("JSVM error message: %s", messagestr); \ + } \ + } \ + } // Returns empty if the_call doesn't return JSVM_OK. #define NODE_API_CALL_RETURN_VOID(env, the_call) \ @@ -80,10 +79,10 @@ #define DECLARE_NODE_API_GETTER(name, func) \ { (name), nullptr, nullptr, (func), nullptr, nullptr, JSVM_DEFAULT, nullptr } -void add_returned_status(JSVM_Env env, +void add_returned_status(JSVM_Env env, const char* key, - JSVM_Value object, - char* expected_message, + JSVM_Value object, + char* expected_message, JSVM_Status expected_status, JSVM_Status actual_status); diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.cpp b/native/cocos/bindings/jswrapper/jsvm/Object.cpp index 02560a20aa..e859f07851 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.cpp +++ b/native/cocos/bindings/jswrapper/jsvm/Object.cpp @@ -46,13 +46,13 @@ Object::~Object() { Object* Object::createObjectWithClass(Class* cls) { JSVM_Value jsobj = Class::_createJSObjectWithClass(cls); - Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), jsobj, cls); + Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), jsobj, cls); return obj; } bool Object::setProperty(const char* name, const Value& data) { JSVM_Status status; - JSVM_Value jsVal; + JSVM_Value jsVal; internal::seToJsValue(data, &jsVal); NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), name, jsVal)); return status == JSVM_OK; @@ -60,8 +60,8 @@ bool Object::setProperty(const char* name, const Value& data) { bool Object::getProperty(const char* name, Value* d) { JSVM_Status status; - JSVM_Value jsVal; - Value data; + JSVM_Value jsVal; + Value data; NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, _objRef.getValue(_env), name, &jsVal)); if (status == JSVM_OK) { internal::jsToSeValue(jsVal, &data); @@ -93,7 +93,7 @@ void Object::setPrivateObject(PrivateObjectBase* data) { }); } #endif - + if (data) { _privateData = data->getRaw(); _privateObject = data; @@ -104,36 +104,35 @@ void Object::setPrivateObject(PrivateObjectBase* data) { auto tmpThis = _objRef.getValue(_env); JSVM_Ref result = nullptr; NODE_API_CALL(status, _env, - OH_JSVM_Wrap(_env, tmpThis, this, sendWeakCallback, - (void*)this /* finalize_hint */, &result)); + OH_JSVM_Wrap(_env, tmpThis, this, weakCallback, + (void*)this /* finalize_hint */, &result)); //_objRef.setWeakref(_env, result); setProperty("__native_ptr__", se::Value(static_cast(reinterpret_cast(data)))); return; } - -bool Object::deleteProperty(const char *name) { +bool Object::deleteProperty(const char* name) { JSVM_Status status; JSVM_Value key; NODE_API_CALL(status, _env, OH_JSVM_GetNamedProperty(_env, _objRef.getValue(_env), name, &key)); if (status != JSVM_OK) { return false; } - bool ret = false; + bool ret = false; NODE_API_CALL(status, _env, OH_JSVM_DeleteProperty(_env, _objRef.getValue(_env), key, &ret)); return ret; } bool Object::isArray() const { JSVM_Status status; - bool ret = false; + bool ret = false; NODE_API_CALL(status, _env, OH_JSVM_IsArray(_env, _objRef.getValue(_env), &ret)); return ret; } bool Object::getArrayLength(uint32_t* length) const { JSVM_Status status; - uint32_t len = 0; + uint32_t len = 0; NODE_API_CALL(status, _env, OH_JSVM_GetArrayLength(_env, _objRef.getValue(_env), &len)); if (length) { *length = len; @@ -143,7 +142,7 @@ bool Object::getArrayLength(uint32_t* length) const { bool Object::getArrayElement(uint32_t index, Value* data) const { JSVM_Status status; - JSVM_Value val; + JSVM_Value val; NODE_API_CALL(status, _env, OH_JSVM_GetElement(_env, _objRef.getValue(_env), index, &val)); internal::jsToSeValue(val, data); return true; @@ -151,7 +150,7 @@ bool Object::getArrayElement(uint32_t index, Value* data) const { bool Object::setArrayElement(uint32_t index, const Value& data) { JSVM_Status status; - JSVM_Value val; + JSVM_Value val; internal::seToJsValue(data, &val); NODE_API_CALL(status, _env, OH_JSVM_SetElement(_env, _objRef.getValue(_env), index, val)); return true; @@ -159,7 +158,7 @@ bool Object::setArrayElement(uint32_t index, const Value& data) { bool Object::isTypedArray() const { JSVM_Status status; - bool ret = false; + bool ret = false; NODE_API_CALL(status, _env, OH_JSVM_IsTypedarray(_env, _objRef.getValue(_env), &ret)); return ret; } @@ -171,11 +170,11 @@ bool Object::isProxy() const { } Object::TypedArrayType Object::getTypedArrayType() const { - JSVM_Status status; + JSVM_Status status; JSVM_TypedarrayType type; - JSVM_Value inputBuffer; - size_t byteOffset; - size_t length; + JSVM_Value inputBuffer; + size_t byteOffset; + size_t length; NODE_API_CALL(status, _env, OH_JSVM_GetTypedarrayInfo(_env, _objRef.getValue(_env), &type, &length, NULL, &inputBuffer, &byteOffset)); TypedArrayType ret = TypedArrayType::NONE; @@ -220,33 +219,33 @@ Object::TypedArrayType Object::getTypedArrayType() const { } bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { - JSVM_Status status; + JSVM_Status status; JSVM_TypedarrayType type; - JSVM_Value inputBuffer; - size_t byteOffset; - size_t arrayLength; - void* data = nullptr; + JSVM_Value inputBuffer; + size_t byteOffset; + size_t arrayLength; + void* data = nullptr; NODE_API_CALL(status, _env, OH_JSVM_GetTypedarrayInfo(_env, _objRef.getValue(_env), &type, &arrayLength, &data, &inputBuffer, &byteOffset)); *ptr = (uint8_t*)(data); if (length) { size_t bytesOfElement = 1; switch (type) { - case JSVM_INT16_ARRAY: - case JSVM_UINT16_ARRAY: - bytesOfElement = 2; - break; - case JSVM_INT32_ARRAY: - case JSVM_UINT32_ARRAY: - case JSVM_FLOAT32_ARRAY: - bytesOfElement = 4; - break; - case JSVM_FLOAT64_ARRAY: - case JSVM_BIGINT64_ARRAY: - case JSVM_BIGUINT64_ARRAY: - bytesOfElement = 8; - break; - default: - break; + case JSVM_INT16_ARRAY: + case JSVM_UINT16_ARRAY: + bytesOfElement = 2; + break; + case JSVM_INT32_ARRAY: + case JSVM_UINT32_ARRAY: + case JSVM_FLOAT32_ARRAY: + bytesOfElement = 4; + break; + case JSVM_FLOAT64_ARRAY: + case JSVM_BIGINT64_ARRAY: + case JSVM_BIGUINT64_ARRAY: + bytesOfElement = 8; + break; + default: + break; } *length = arrayLength * bytesOfElement; } @@ -254,7 +253,7 @@ bool Object::getTypedArrayData(uint8_t** ptr, size_t* length) const { } bool Object::isArrayBuffer() const { - bool ret = false; + bool ret = false; JSVM_Status status; NODE_API_CALL(status, _env, OH_JSVM_IsArraybuffer(_env, _objRef.getValue(_env), &ret)); return ret; @@ -262,7 +261,7 @@ bool Object::isArrayBuffer() const { bool Object::getArrayBufferData(uint8_t** ptr, size_t* length) const { JSVM_Status status; - size_t len = 0; + size_t len = 0; NODE_API_CALL(status, _env, OH_JSVM_GetArraybufferInfo(_env, _objRef.getValue(_env), reinterpret_cast(ptr), &len)); if (length) { *length = len; @@ -277,9 +276,9 @@ Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, return nullptr; } - JSVM_TypedarrayType jsvmType; - JSVM_Value outputBuffer; - void* outputPtr = nullptr; + JSVM_TypedarrayType jsvmType; + JSVM_Value outputBuffer; + void* outputPtr = nullptr; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &outputPtr, &outputBuffer)); if (outputPtr && data && byteLength > 0) { memcpy(outputPtr, data, byteLength); @@ -287,11 +286,11 @@ Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, size_t sizeOfEle = 0; switch (type) { case TypedArrayType::INT8: - jsvmType = JSVM_INT8_ARRAY; + jsvmType = JSVM_INT8_ARRAY; sizeOfEle = 1; break; case TypedArrayType::UINT8: - jsvmType = JSVM_UINT8_ARRAY; + jsvmType = JSVM_UINT8_ARRAY; sizeOfEle = 1; break; case TypedArrayType::UINT8_CLAMPED: @@ -299,42 +298,42 @@ Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, sizeOfEle = 1; break; case TypedArrayType::INT16: - jsvmType = JSVM_INT16_ARRAY; + jsvmType = JSVM_INT16_ARRAY; sizeOfEle = 2; break; case TypedArrayType::UINT16: - jsvmType = JSVM_UINT16_ARRAY; + jsvmType = JSVM_UINT16_ARRAY; sizeOfEle = 2; break; case TypedArrayType::INT32: - jsvmType = JSVM_INT32_ARRAY; + jsvmType = JSVM_INT32_ARRAY; sizeOfEle = 4; break; case TypedArrayType::UINT32: - jsvmType = JSVM_UINT32_ARRAY; + jsvmType = JSVM_UINT32_ARRAY; sizeOfEle = 4; break; case TypedArrayType::FLOAT32: - jsvmType = JSVM_FLOAT32_ARRAY; + jsvmType = JSVM_FLOAT32_ARRAY; sizeOfEle = 4; break; case TypedArrayType::FLOAT64: - jsvmType = JSVM_FLOAT64_ARRAY; + jsvmType = JSVM_FLOAT64_ARRAY; sizeOfEle = 8; break; case TypedArrayType::BIGINT64: - jsvmType = JSVM_BIGINT64_ARRAY; + jsvmType = JSVM_BIGINT64_ARRAY; sizeOfEle = 8; break; case TypedArrayType::BIGUINT64: - jsvmType = JSVM_BIGUINT64_ARRAY; + jsvmType = JSVM_BIGUINT64_ARRAY; sizeOfEle = 8; break; default: assert(false); // Should never go here. break; } - size_t eleCounts = byteLength / sizeOfEle; + size_t eleCounts = byteLength / sizeOfEle; JSVM_Value outputArray; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateTypedarray(ScriptEngine::getEnv(), jsvmType, eleCounts, outputBuffer, 0, &outputArray)); @@ -342,13 +341,13 @@ Object* Object::createTypedArray(Object::TypedArrayType type, const void* data, return obj; } -Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj) { +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object* obj) { return Object::createTypedArrayWithBuffer(type, obj, 0); } -Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset) { +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object* obj, size_t offset) { size_t byteLength{0}; - uint8_t *skip{nullptr}; + uint8_t* skip{nullptr}; if (obj->getArrayBufferData(&skip, &byteLength)) { return Object::createTypedArrayWithBuffer(type, obj, offset, byteLength - offset); @@ -358,13 +357,12 @@ Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *ob return nullptr; } -Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *obj, size_t offset, size_t byteLength) { +Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object* obj, size_t offset, size_t byteLength) { if (type == TypedArrayType::NONE) { SE_LOGE("Don't pass se::Object::TypedArrayType::NONE to createTypedArray API!"); return nullptr; } - assert(obj->isArrayBuffer()); JSVM_Status status; JSVM_Value outputBuffer = obj->_getJSObject(); @@ -373,47 +371,50 @@ Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *ob size_t sizeOfEle = 0; switch (type) { case TypedArrayType::INT8: - jsvmType = JSVM_INT8_ARRAY; + jsvmType = JSVM_INT8_ARRAY; sizeOfEle = 1; break; case TypedArrayType::UINT8: - jsvmType = JSVM_UINT8_ARRAY; + jsvmType = JSVM_UINT8_ARRAY; sizeOfEle = 1; break; case TypedArrayType::INT16: - jsvmType = JSVM_INT8_ARRAY; + jsvmType = JSVM_INT8_ARRAY; sizeOfEle = 2; + break; case TypedArrayType::UINT16: - jsvmType = JSVM_UINT8_ARRAY; + jsvmType = JSVM_UINT8_ARRAY; sizeOfEle = 2; break; case TypedArrayType::INT32: - jsvmType = JSVM_INT32_ARRAY; + jsvmType = JSVM_INT32_ARRAY; sizeOfEle = 4; + break; case TypedArrayType::UINT32: - jsvmType = JSVM_UINT32_ARRAY; + jsvmType = JSVM_UINT32_ARRAY; sizeOfEle = 4; + break; case TypedArrayType::FLOAT32: - jsvmType = JSVM_FLOAT32_ARRAY; + jsvmType = JSVM_FLOAT32_ARRAY; sizeOfEle = 4; break; case TypedArrayType::FLOAT64: - jsvmType = JSVM_FLOAT64_ARRAY; + jsvmType = JSVM_FLOAT64_ARRAY; sizeOfEle = 8; break; case TypedArrayType::BIGINT64: - jsvmType = JSVM_BIGINT64_ARRAY; + jsvmType = JSVM_BIGINT64_ARRAY; sizeOfEle = 8; break; case TypedArrayType::BIGUINT64: - jsvmType = JSVM_BIGUINT64_ARRAY; + jsvmType = JSVM_BIGUINT64_ARRAY; sizeOfEle = 8; break; default: assert(false); // Should never go here. break; } - size_t eleCounts = byteLength / sizeOfEle; + size_t eleCounts = byteLength / sizeOfEle; JSVM_Value outputArray; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateTypedarray(ScriptEngine::getEnv(), jsvmType, eleCounts, outputBuffer, offset, &outputArray)); @@ -423,33 +424,21 @@ Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object *ob Object* Object::createExternalArrayBufferObject(void* contents, size_t byteLength, BufferContentsFreeFunc freeFunc, void* freeUserData) { JSVM_Status status; JSVM_Value result; - if (freeFunc) { - struct ExternalArrayBufferCallbackParams* param = new (struct ExternalArrayBufferCallbackParams); - param->func = freeFunc; - param->contents = contents; - param->byteLength = byteLength; - param->userData = freeUserData; - NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &contents, &result)); - param->func(param->contents, param->byteLength, param->userData); - delete param; - } else { - NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &contents, &result)); - } - + // JSVM does not support the napi_create_external_arraybuffer interface like in NAPI. + NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArrayBufferFromBackingStoreData(ScriptEngine::getEnv(), contents, byteLength, 0, byteLength, &result)); Object* obj = Object::_createJSObject(ScriptEngine::getEnv(), result, nullptr); return obj; } - bool Object::isFunction() const { JSVM_ValueType valuetype0; - JSVM_Status status; + JSVM_Status status; NODE_API_CALL(status, _env, OH_JSVM_Typeof(_env, _objRef.getValue(_env), &valuetype0)); return (valuetype0 == JSVM_ValueType::JSVM_FUNCTION); } bool Object::defineFunction(const char* funcName, JSVM_Callback func) { - JSVM_Value fn; + JSVM_Value fn; JSVM_Status status; NODE_API_CALL(status, _env, OH_JSVM_CreateFunction(_env, funcName, JSVM_AUTO_LENGTH, func, &fn)); NODE_API_CALL(status, _env, OH_JSVM_SetNamedProperty(_env, _objRef.getValue(_env), funcName, fn)); @@ -457,7 +446,7 @@ bool Object::defineFunction(const char* funcName, JSVM_Callback func) { } bool Object::defineProperty(const char* name, JSVM_Callback getter, JSVM_Callback setter) { - JSVM_Status status; + JSVM_Status status; JSVM_PropertyDescriptor properties[] = {{name, nullptr, nullptr, getter, setter, 0, JSVM_DEFAULT}}; status = OH_JSVM_DefineProperties(_env, _objRef.getValue(_env), sizeof(properties) / sizeof(JSVM_PropertyDescriptor), properties); if (status == JSVM_OK) { @@ -476,7 +465,7 @@ Object* Object::_createJSObject(JSVM_Env env, JSVM_Value js_object, Class* cls) } Object* Object::createPlainObject() { - JSVM_Value result; + JSVM_Value result; JSVM_Status status; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateObject(ScriptEngine::getEnv(), &result)); Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); @@ -484,7 +473,7 @@ Object* Object::createPlainObject() { } Object* Object::createArrayObject(size_t length) { - JSVM_Value result; + JSVM_Value result; JSVM_Status status; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArrayWithLength(ScriptEngine::getEnv(), length, &result)); Object* obj = _createJSObject(ScriptEngine::getEnv(), result, nullptr); @@ -492,10 +481,10 @@ Object* Object::createArrayObject(size_t length) { } Object* Object::createArrayBufferObject(const void* data, size_t byteLength) { - JSVM_Value result; + JSVM_Value result; JSVM_Status status; - void* retData; - Object* obj = nullptr; + void* retData; + Object* obj = nullptr; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateArraybuffer(ScriptEngine::getEnv(), byteLength, &retData, &result)); if (status == JSVM_OK) { if (data) { @@ -508,7 +497,7 @@ Object* Object::createArrayBufferObject(const void* data, size_t byteLength) { bool Object::getAllKeys(std::vector* allKeys) const { JSVM_Status status; - JSVM_Value names; + JSVM_Value names; NODE_API_CALL(status, _env, OH_JSVM_GetPropertyNames(_env, _objRef.getValue(_env), &names)); if (status != JSVM_OK) { @@ -520,7 +509,7 @@ bool Object::getAllKeys(std::vector* allKeys) const { JSVM_Value val; NODE_API_CALL(status, _env, OH_JSVM_GetElement(_env, names, i, &val)); if (status == JSVM_OK) { - char buffer[MAX_STRING_LEN]; + char buffer[MAX_STRING_LEN]; size_t result = 0; NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, val, buffer, MAX_STRING_LEN, &result)); if (result > 0) { @@ -546,12 +535,12 @@ bool Object::init(JSVM_Env env, JSVM_Value js_object, Class* cls) { } bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { - size_t argc = 0; + size_t argc = 0; std::vector argv; argv.reserve(10); argc = args.size(); internal::seToJsArgs(_env, args, &argv); - JSVM_Value return_val; + JSVM_Value return_val; JSVM_Status status; assert(isFunction()); JSVM_Value thisObj = thisObject ? thisObject->_getJSObject() : ({ @@ -560,7 +549,7 @@ bool Object::call(const ValueArray& args, Object* thisObject, Value* rval) { undefinedValue; }); NODE_API_CALL(status, _env, - OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val)); + OH_JSVM_CallFunction(_env, thisObj, _getJSObject(), argc, argv.data(), &return_val)); if (rval) { internal::jsToSeValue(return_val, rval); } @@ -588,7 +577,7 @@ void Object::_setFinalizeCallback(JSVM_Finalize finalizeCb) { // setProperty("__native_ptr__", se::Value(static_cast(reinterpret_cast(data)))); // } -void* Object::getPrivateData() const{ +void* Object::getPrivateData() const { return _privateData; } @@ -596,7 +585,7 @@ bool Object::attachObject(Object* obj) { assert(obj); Object* global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) { return false; } @@ -619,7 +608,7 @@ bool Object::detachObject(Object* obj) { assert(obj); Object* global = ScriptEngine::getInstance()->getGlobalObject(); - Value jsbVal; + Value jsbVal; if (!global->getProperty("jsb", &jsbVal)) { return false; } @@ -644,7 +633,7 @@ std::string Object::toString() const { if (isFunction() || isArray() || isTypedArray()) { JSVM_Value result; NODE_API_CALL(status, _env, OH_JSVM_CoerceToString(_env, _objRef.getValue(_env), &result)); - char buffer[MAX_STRING_LEN]; + char buffer[MAX_STRING_LEN]; size_t result_t = 0; NODE_API_CALL(status, _env, OH_JSVM_GetValueStringUtf8(_env, result, buffer, MAX_STRING_LEN, &result_t)); ret = buffer; @@ -684,8 +673,8 @@ Class* Object::_getClass() const { } Object* Object::getObjectWithPtr(void* ptr) { - Object* obj = nullptr; - auto iter = NativePtrToObjectMap::find(ptr); + Object* obj = nullptr; + auto iter = NativePtrToObjectMap::find(ptr); if (iter != NativePtrToObjectMap::end()) { obj = iter->second; obj->incRef(); @@ -707,12 +696,9 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint / if (nativeObject == nullptr) { return; } - void *rawPtr = reinterpret_cast(finalizeHint)->_privateData; + void* rawPtr = reinterpret_cast(finalizeHint)->_privateData; Object* seObj = reinterpret_cast(finalizeHint); Object* rawPtrObj = reinterpret_cast(rawPtr); - if(rawPtrObj->getRefCount() == 0) { - return; - } if (seObj->_onCleaingPrivateData) { //called by cleanPrivateData, not release seObj; return; } @@ -726,11 +712,11 @@ void Object::weakCallback(JSVM_Env env, void* nativeObject, void* finalizeHint / } if (seObj->_finalizeCb != nullptr) { - seObj->_finalizeCb(env, rawPtr, rawPtr); + seObj->_finalizeCb(env, finalizeHint, finalizeHint); } else { assert(seObj->_getClass() != nullptr); if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { - seObj->_getClass()->_getFinalizeFunction()(env, rawPtr, rawPtr); + seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint); } } seObj->decRef(); @@ -742,14 +728,14 @@ void Object::setup() { } void Object::cleanup() { - void* nativeObj = nullptr; - Object* obj = nullptr; - Class* cls = nullptr; + void* nativeObj = nullptr; + Object* obj = nullptr; + Class* cls = nullptr; const auto& nativePtrToObjectMap = NativePtrToObjectMap::instance(); for (const auto& e : nativePtrToObjectMap) { nativeObj = e.first; - obj = e.second; + obj = e.second; if (obj->_finalizeCb != nullptr) { obj->_finalizeCb(ScriptEngine::getEnv(), nativeObj, nullptr); @@ -770,7 +756,6 @@ void Object::cleanup() { obj = e.first; cls = obj->_getClass(); obj->_rootCount = 0; - } } @@ -799,14 +784,14 @@ Object* Object::createJSONObject(const std::string& jsonStr) { // 调用js中的JSON.parse将jsJsonStr转换成js对象 JSVM_Value jsObj; - NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr ,&jsObj)); + NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr, &jsObj)); - Object *obj = nullptr; + Object* obj = nullptr; obj = Object::_createJSObject(_env, jsObj, nullptr); return obj; } -Object *Object::createJSONObject(std::u16string &&jsonStr) { +Object* Object::createJSONObject(std::u16string&& jsonStr) { auto _env = ScriptEngine::getEnv(); JSVM_Status status; JSVM_Value global; @@ -828,9 +813,9 @@ Object *Object::createJSONObject(std::u16string &&jsonStr) { // 调用js中的JSON.parse将jsJsonStr转换成js对象 JSVM_Value jsObj; - NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr ,&jsObj)); + NODE_API_CALL(status, _env, OH_JSVM_CallFunction(_env, globalJsonObj, parseFunc, 1, &jsJsonStr, &jsObj)); - Object *obj = nullptr; + Object* obj = nullptr; obj = Object::_createJSObject(_env, jsObj, nullptr); return obj; } @@ -860,7 +845,7 @@ void Object::clearPrivateData(bool clearMapping) { } } -Object* Object::createUTF8String(const std::string& str) { +Object* Object::createUTF8String(const std::string& str) { JSVM_Status status; JSVM_Value result; NODE_API_CALL(status, ScriptEngine::getEnv(), OH_JSVM_CreateStringUtf8(ScriptEngine::getEnv(), str.c_str(), JSVM_AUTO_LENGTH, &result)); diff --git a/native/cocos/bindings/jswrapper/jsvm/Object.h b/native/cocos/bindings/jswrapper/jsvm/Object.h index c6238130d3..35a4258281 100644 --- a/native/cocos/bindings/jswrapper/jsvm/Object.h +++ b/native/cocos/bindings/jswrapper/jsvm/Object.h @@ -25,32 +25,32 @@ #pragma once #include +#include "../PrivateObject.h" #include "../RefCounter.h" #include "../Value.h" #include "../config.h" #include "CommonHeader.h" #include "HelperMacros.h" -#include "../PrivateObject.h" namespace se { class Class; - namespace internal { - struct PrivateData; - } +namespace internal { +struct PrivateData; +} class ObjectRef { private: - JSVM_Ref _ref = nullptr; - int _refCounts = 0; - JSVM_Env _env = nullptr; - JSVM_Value _obj = nullptr; + JSVM_Ref _ref = nullptr; + int _refCounts = 0; + JSVM_Env _env = nullptr; + JSVM_Value _obj = nullptr; public: ~ObjectRef() { deleteRef(); } JSVM_Value getValue(JSVM_Env env) const { - JSVM_Value result; + JSVM_Value result; JSVM_Status status; NODE_API_CALL(status, env, OH_JSVM_GetReferenceValue(env, _ref, &result)); assert(status == JSVM_OK); @@ -70,7 +70,7 @@ public: void initStrongRef(JSVM_Env env, JSVM_Value obj) { assert(_ref == nullptr); _refCounts = 1; - _obj = obj; + _obj = obj; OH_JSVM_CreateReference(env, obj, _refCounts, &_ref); _env = env; } @@ -78,7 +78,7 @@ public: assert(_refCounts == 0); if (_refCounts == 0) { uint32_t result = 0; - _refCounts = 1; + _refCounts = 1; OH_JSVM_ReferenceRef(env, _ref, &result); } } @@ -88,7 +88,7 @@ public: if (_refCounts > 0) { _refCounts--; if (_refCounts == 0) { - OH_JSVM_ReferenceUnref(env, _ref, &result); + OH_JSVM_ReferenceUnref(env, _ref, &result); } } } @@ -100,7 +100,7 @@ public: OH_JSVM_DeleteReference(_env, _ref); _ref = nullptr; } -}; +}; class Object; @@ -128,7 +128,7 @@ public: void *contents{nullptr}; size_t byteLength{0}; void *userData{0}; - }; + }; Object(); ~Object(); @@ -159,7 +159,7 @@ public: inline bool getProperty(const std::string &name, Value *value) { return getProperty(name.c_str(), value); } - + void setPrivateObject(PrivateObjectBase *data); PrivateObjectBase *getPrivateObject() const; @@ -187,19 +187,18 @@ public: return static_cast *>(_privateObject)->getData(); } - /** - * @brief Delete a property of an object. - * @param[in] name A utf-8 string containing the property's name. - * @return true if the property is deleted successfully, otherwise false. - */ + * @brief Delete a property of an object. + * @param[in] name A utf-8 string containing the property's name. + * @return true if the property is deleted successfully, otherwise false. + */ bool deleteProperty(const char *name); /** * @brief Gets an object's private data. * @return A void* that is the object's private data, if the object has private data, otherwise nullptr. */ - void* getPrivateData() const; + void *getPrivateData() const; /** * @brief Sets a pointer to private data on an object. @@ -256,7 +255,6 @@ public: */ void clearPrivateData(bool clearMapping = true); - /** * @brief Sets whether to clear the mapping of native object & se::Object in finalizer */ @@ -467,9 +465,9 @@ public: */ static Object *getObjectWithPtr(void *ptr); - Class * _getClass() const; // NOLINT(readability-identifier-naming) + Class *_getClass() const; // NOLINT(readability-identifier-naming) JSVM_Value _getJSObject() const; - void _setFinalizeCallback(JSVM_Finalize finalizeCb); // NOLINT(readability-identifier-naming) + void _setFinalizeCallback(JSVM_Finalize finalizeCb); // NOLINT(readability-identifier-naming) /** * @brief Returns the string for describing current object. * @return The string for describing current object. @@ -478,27 +476,27 @@ public: bool init(JSVM_Env env, JSVM_Value js_object, Class *cls); - static Object *createUTF8String(const std::string& str); + static Object *createUTF8String(const std::string &str); private: -// Object(); -// virtual ~Object(); + // Object(); + // virtual ~Object(); static void sendWeakCallback(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); static void weakCallback(JSVM_Env env, void *nativeObject, void * /*finalize_hint*/); static void setup(); static void cleanup(); private: - ObjectRef _objRef; - JSVM_Finalize _finalizeCb = nullptr; + ObjectRef _objRef; + JSVM_Finalize _finalizeCb = nullptr; bool _clearMappingInFinalizer = true; - void* _privateData = nullptr; - PrivateObjectBase *_privateObject = nullptr; - JSVM_Env _env = nullptr; - Class * _cls = nullptr; - uint32_t _rootCount = 0; - bool _onCleaingPrivateData = false; - internal::PrivateData* _internalData; + void *_privateData = nullptr; + PrivateObjectBase *_privateObject = nullptr; + JSVM_Env _env = nullptr; + Class *_cls = nullptr; + uint32_t _rootCount = 0; + bool _onCleaingPrivateData = false; + internal::PrivateData *_internalData; friend class ScriptEngine; }; diff --git a/native/cocos/bindings/jswrapper/napi/Object.cpp b/native/cocos/bindings/jswrapper/napi/Object.cpp index 732d140357..3bb98f596d 100644 --- a/native/cocos/bindings/jswrapper/napi/Object.cpp +++ b/native/cocos/bindings/jswrapper/napi/Object.cpp @@ -287,7 +287,6 @@ Object* Object::createTypedArrayWithBuffer(TypedArrayType type, const Object* ob return nullptr; } - CC_ASSERT(obj->isArrayBuffer()); napi_status status; napi_value outputBuffer = obj->_getJSObject(); @@ -662,11 +661,11 @@ void Object::weakCallback(napi_env env, void* nativeObject, void* finalizeHint / } if (seObj->_finalizeCb != nullptr) { - seObj->_finalizeCb(env, rawPtr, rawPtr); + seObj->_finalizeCb(env, finalizeHint, finalizeHint); } else { assert(seObj->_getClass() != nullptr); if (seObj->_getClass()->_getFinalizeFunction() != nullptr) { - seObj->_getClass()->_getFinalizeFunction()(env, rawPtr, rawPtr); + seObj->_getClass()->_getFinalizeFunction()(env, finalizeHint, finalizeHint); } } seObj->decRef(); diff --git a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp index 8d8e253afb..6b5f6b7158 100644 --- a/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp +++ b/native/cocos/bindings/manual/JavaScriptArkTsBridge.cpp @@ -24,9 +24,9 @@ #include "cocos/bindings/manual/JavaScriptArkTsBridge.h" #include #include "bundle/native_interface_bundle.h" -#include "cocos/platform/openharmony/napi/NapiHelper.h" #include "cocos/bindings/jswrapper/SeApi.h" #include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/platform/openharmony/napi/NapiHelper.h" #define JSA_ERR_OK (0) #define JSA_ERR_TYPE_NOT_SUPPORT (-1) @@ -85,7 +85,8 @@ char* JavaScriptArkTsBridge::__getModuleInfo(const char* module_name) { se::Value convertToSeValue(const cc::CallbackParamType& value) { return std::visit([](auto&& arg) -> se::Value { return se::Value(arg); - }, value); + }, + value); } bool JavaScriptArkTsBridge::CallInfo::execute(se::Value& rval) { @@ -203,24 +204,27 @@ static bool JavaScriptArkTsBridge_callStaticMethod(se::State& s) { const auto& args = s.args(); int argc = (int)args.size(); - if (argc == 4) { + if (argc == 3 || argc == 4) { bool ok = false; - bool isSyn; + bool isSync = true; std::string clsPath, methodName, paramStr; - isSyn = seval_to_type(args[0], ok); - SE_PRECONDITION2(ok, false, "Converting isSyn failed!"); - - clsPath = seval_to_type(args[1], ok); + clsPath = seval_to_type(args[0], ok); SE_PRECONDITION2(ok, false, "Converting clsPath failed!"); - methodName = seval_to_type(args[2], ok); + methodName = seval_to_type(args[1], ok); SE_PRECONDITION2(ok, false, "Converting methodName failed!"); - paramStr = seval_to_type(args[3], ok); + paramStr = seval_to_type(args[2], ok); SE_PRECONDITION2(ok, false, "Converting paramStr failed!"); - JavaScriptArkTsBridge::CallInfo call(isSyn, clsPath.c_str(), methodName.c_str(), paramStr.c_str()); + if (argc == 4) { + ok = args[3].isBoolean(); + SE_PRECONDITION2(ok, false, "isSync must be boolean type"); + isSync = args[3].toBoolean(); + } + + JavaScriptArkTsBridge::CallInfo call(isSync, clsPath.c_str(), methodName.c_str(), paramStr.c_str()); ok = call.execute(s.rval()); if (!ok) { s.rval().setUndefined(); diff --git a/native/cocos/bindings/manual/jsb_global.cpp b/native/cocos/bindings/manual/jsb_global.cpp index 41685fb68e..27ea121651 100644 --- a/native/cocos/bindings/manual/jsb_global.cpp +++ b/native/cocos/bindings/manual/jsb_global.cpp @@ -979,7 +979,7 @@ static bool jsb_createExternalArrayBuffer(se::State &s) { // NOLINT SE_PRECONDITION2(ok, false, "Error processing arguments"); if (byteLength > 0) { // NOTE: Currently V8 use shared_ptr which has different abi on win64-debug and win64-release -#if CC_PLATFORM == CC_PLATFORM_WINDOWS && SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8 +#if (CC_PLATFORM == CC_PLATFORM_WINDOWS && SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_V8) || (SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_JSVM) se::HandleObject arrayBuffer{se::Object::createArrayBufferObject(nullptr, byteLength)}; #else void *buffer = malloc(byteLength); @@ -1336,12 +1336,12 @@ static bool js_TextDecoder_constructor(se::State &s) // NOLINT(readability-ident // https://developer.mozilla.org/en-US/docs/Web/API/Encoding_API/Encodings // NOTE: We only support utf-8 and utf-16 encoding now. auto label = args[0].toString(); - + // Convert to lowercase to support 'UTF-8', 'UTF-16' - std::transform(label.begin(), label.end(), label.begin(), [](char c){ + std::transform(label.begin(), label.end(), label.begin(), [](char c) { return ::tolower(c); }); - + if (label == "unicode-1-1-utf-8" || label == "utf-8" || label == "utf8") { encoding = "utf-8"; } else if (label == "utf-16" || label == "utf-16le") { @@ -1575,7 +1575,7 @@ bool jsb_register_global_variables(se::Object *global) { // NOLINT __jsbObj->defineFunction("copyTextToClipboard", _SE(JSB_copyTextToClipboard)); __jsbObj->defineFunction("setPreferredFramesPerSecond", _SE(JSB_setPreferredFramesPerSecond)); __jsbObj->defineFunction("destroyImage", _SE(js_destroyImage)); - + #if CC_USE_EDITBOX __jsbObj->defineFunction("showInputBox", _SE(JSB_showInputBox)); __jsbObj->defineFunction("hideInputBox", _SE(JSB_hideInputBox)); diff --git a/native/cocos/bindings/manual/jsb_google_billing.cpp b/native/cocos/bindings/manual/jsb_google_billing.cpp deleted file mode 100644 index 9321269fbb..0000000000 --- a/native/cocos/bindings/manual/jsb_google_billing.cpp +++ /dev/null @@ -1,1497 +0,0 @@ -/**************************************************************************** - Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated documentation files (the "Software"), to deal - in the Software without restriction, including without limitation the rights to - use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies - of the Software, and to permit persons to whom the Software is furnished to do so, - subject to the following conditions: - - The above copyright notice and this permission notice shall be included in - all copies or substantial portions of the Software. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -*****************************************************************************/ - -#include "application/ApplicationManager.h" -#include "bindings/jswrapper/SeApi.h" - -#if CC_PLATFORM == CC_PLATFORM_ANDROID - #include "bindings/jswrapper/SeApi.h" - #include "bindings/manual/jsb_conversions.h" - #include "bindings/manual/jsb_global.h" - #include "vendor/google/billing/GoogleBilling.h" -JSB_REGISTER_OBJECT_TYPE(cc::BillingResult); -JSB_REGISTER_OBJECT_TYPE(cc::OneTimePurchaseOfferDetails); -JSB_REGISTER_OBJECT_TYPE(cc::InstallmentPlanDetails); -JSB_REGISTER_OBJECT_TYPE(cc::PricingPhase); -JSB_REGISTER_OBJECT_TYPE(cc::SubscriptionOfferDetails); -JSB_REGISTER_OBJECT_TYPE(cc::ProductDetails); -JSB_REGISTER_OBJECT_TYPE(cc::AccountIdentifiers); -JSB_REGISTER_OBJECT_TYPE(cc::PendingPurchaseUpdate); -JSB_REGISTER_OBJECT_TYPE(cc::Purchase); -JSB_REGISTER_OBJECT_TYPE(cc::BillingConfig); -JSB_REGISTER_OBJECT_TYPE(cc::GoogleBilling); - -#endif - -#if CC_PLATFORM == CC_PLATFORM_ANDROID -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_BillingResult) -static bool js_cc_BillingResult_debugMessage_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* arg1 = (cc::BillingResult*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->debugMessage; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_BillingResult_debugMessage_get) - -static bool js_cc_BillingResult_responseCode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* arg1 = (cc::BillingResult*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->responseCode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - return true; -} -SE_BIND_PROP_GET(js_cc_BillingResult_responseCode_get) - -static bool js_cc_BillingResult_toString_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* arg1 = (cc::BillingResult*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->toString; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - return true; -} -SE_BIND_PROP_GET(js_cc_BillingResult_toString_get) - -static bool js_delete_cc_BillingResult(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_BillingResult) - -bool js_register_cc_BillingResult(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("BillingResult", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("debugMessage", _SE(js_cc_BillingResult_debugMessage_get), nullptr); - cls->defineProperty("responseCode", _SE(js_cc_BillingResult_responseCode_get), nullptr); - cls->defineProperty("toStr", _SE(js_cc_BillingResult_toString_get), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_BillingResult)); - - cls->install(); - JSBClassType::registerClass(cls); - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_OneTimePurchaseOfferDetails) - -static bool js_cc_OneTimePurchaseOfferDetails_formattedPrice_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::OneTimePurchaseOfferDetails* arg1 = (cc::OneTimePurchaseOfferDetails*)NULL; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->formattedPrice, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(arg1->formattedPrice, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_OneTimePurchaseOfferDetails_formattedPrice_get) - -static bool js_cc_OneTimePurchaseOfferDetails_priceAmountMicros_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::OneTimePurchaseOfferDetails* arg1 = (cc::OneTimePurchaseOfferDetails*)NULL; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->priceAmountMicros, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_OneTimePurchaseOfferDetails_priceAmountMicros_get) - -static bool js_cc_OneTimePurchaseOfferDetails_priceCurrencyCode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::OneTimePurchaseOfferDetails* arg1 = (cc::OneTimePurchaseOfferDetails*)NULL; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= nativevalue_to_se(arg1->priceCurrencyCode, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(arg1->priceCurrencyCode, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_OneTimePurchaseOfferDetails_priceCurrencyCode_get) - -static bool js_delete_cc_OneTimePurchaseOfferDetails(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_OneTimePurchaseOfferDetails) - -bool js_register_cc_OneTimePurchaseOfferDetails(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("OneTimePurchaseOfferDetails", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("formattedPrice", _SE(js_cc_OneTimePurchaseOfferDetails_formattedPrice_get), nullptr); - cls->defineProperty("priceAmountMicros", _SE(js_cc_OneTimePurchaseOfferDetails_priceAmountMicros_get), nullptr); - cls->defineProperty("priceCurrencyCode", _SE(js_cc_OneTimePurchaseOfferDetails_priceCurrencyCode_get), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_OneTimePurchaseOfferDetails)); - - cls->install(); - JSBClassType::registerClass(cls); - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_InstallmentPlanDetails) -static bool js_cc_InstallmentPlanDetails_installmentPlanCommitmentPaymentsCount_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::InstallmentPlanDetails* arg1 = (cc::InstallmentPlanDetails*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->installmentPlanCommitmentPaymentsCount; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_InstallmentPlanDetails_installmentPlanCommitmentPaymentsCount_get) - -static bool js_cc_InstallmentPlanDetails_subsequentInstallmentPlanCommitmentPaymentsCount_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::InstallmentPlanDetails* arg1 = (cc::InstallmentPlanDetails*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->subsequentInstallmentPlanCommitmentPaymentsCount; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_InstallmentPlanDetails_subsequentInstallmentPlanCommitmentPaymentsCount_get) - -static bool js_delete_cc_InstallmentPlanDetails(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_InstallmentPlanDetails) - -bool js_register_cc_InstallmentPlanDetails(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("InstallmentPlanDetails", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("installmentPlanCommitmentPaymentsCount", _SE(js_cc_InstallmentPlanDetails_installmentPlanCommitmentPaymentsCount_get), nullptr); - cls->defineProperty("subsequentInstallmentPlanCommitmentPaymentsCount", _SE(js_cc_InstallmentPlanDetails_subsequentInstallmentPlanCommitmentPaymentsCount_get), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_InstallmentPlanDetails)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_PricingPhase) - -static bool js_cc_PricingPhase_billingCycleCount_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->billingCycleCount; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_billingCycleCount_get) - -static bool js_cc_PricingPhase_priceAmountMicros_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - long result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->priceAmountMicros; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_priceAmountMicros_get) - -static bool js_cc_PricingPhase_recurrenceMode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->recurrenceMode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_recurrenceMode_get) - -static bool js_cc_PricingPhase_billingPeriod_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->billingPeriod; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_billingPeriod_get) - -static bool js_cc_PricingPhase_formattedPrice_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->formattedPrice; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_formattedPrice_get) - -static bool js_cc_PricingPhase_priceCurrencyCode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PricingPhase* arg1 = (cc::PricingPhase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->priceCurrencyCode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhase_priceCurrencyCode_get) - -static bool js_delete_cc_PricingPhase(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_PricingPhase) - -bool js_register_cc_PricingPhase(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("PricingPhase", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("billingCycleCount", _SE(js_cc_PricingPhase_billingCycleCount_get), nullptr); - cls->defineProperty("priceAmountMicros", _SE(js_cc_PricingPhase_priceAmountMicros_get), nullptr); - cls->defineProperty("recurrenceMode", _SE(js_cc_PricingPhase_recurrenceMode_get), nullptr); - cls->defineProperty("billingPeriod", _SE(js_cc_PricingPhase_billingPeriod_get), nullptr); - cls->defineProperty("formattedPrice", _SE(js_cc_PricingPhase_formattedPrice_get), nullptr); - cls->defineProperty("priceCurrencyCode", _SE(js_cc_PricingPhase_priceCurrencyCode_get), nullptr); - cls->defineFinalizeFunction(_SE(js_delete_cc_PricingPhase)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_PricingPhases) -static bool js_cc_PricingPhases_pricingPhaseList_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - cc::PricingPhases* result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->pricingPhases.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PricingPhases_pricingPhaseList_get) -static bool js_delete_cc_PricingPhases(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_PricingPhases) -bool js_register_cc_PricingPhases(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("PricingPhases", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("pricingPhaseList", _SE(js_cc_PricingPhases_pricingPhaseList_get), nullptr); - cls->defineFinalizeFunction(_SE(js_delete_cc_PricingPhases)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_SubscriptionOfferDetails) - -static bool js_cc_SubscriptionOfferDetails_basePlanId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->basePlanId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_basePlanId_get) - -static bool js_cc_SubscriptionOfferDetails_installmentPlanDetails_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - cc::InstallmentPlanDetails* result = 0; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->installmentPlanDetails.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_installmentPlanDetails_get) - -static bool js_cc_SubscriptionOfferDetails_offerId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->offerId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_offerId_get) - -static bool js_cc_SubscriptionOfferDetails_offerTags_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - std::vector result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->offerTags; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_offerTags_get) - -static bool js_cc_SubscriptionOfferDetails_offerToken_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->offerToken; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_offerToken_get) - -static bool js_cc_SubscriptionOfferDetails_pricingPhases_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::SubscriptionOfferDetails* arg1 = (cc::SubscriptionOfferDetails*)NULL; - cc::PricingPhases* result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->pricingPhases.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_SubscriptionOfferDetails_pricingPhases_get) - -static bool js_delete_cc_SubscriptionOfferDetails(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_SubscriptionOfferDetails) - -bool js_register_cc_SubscriptionOfferDetails(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("SubscriptionOfferDetails", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("basePlanId", _SE(js_cc_SubscriptionOfferDetails_basePlanId_get), nullptr); - cls->defineProperty("installmentPlanDetails", _SE(js_cc_SubscriptionOfferDetails_installmentPlanDetails_get), nullptr); - cls->defineProperty("offerId", _SE(js_cc_SubscriptionOfferDetails_offerId_get), nullptr); - cls->defineProperty("offerTags", _SE(js_cc_SubscriptionOfferDetails_offerTags_get), nullptr); - cls->defineProperty("offerToken", _SE(js_cc_SubscriptionOfferDetails_offerToken_get), nullptr); - cls->defineProperty("pricingPhases", _SE(js_cc_SubscriptionOfferDetails_pricingPhases_get), nullptr); - cls->defineFinalizeFunction(_SE(js_delete_cc_SubscriptionOfferDetails)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_ProductDetails) - -static bool js_cc_ProductDetails_equals(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - cc::ProductDetails* arg2 = (cc::ProductDetails*)NULL; - bool result; - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &arg2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - result = (bool)((cc::ProductDetails const*)arg1)->equals(*arg2); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - return true; -} -SE_BIND_FUNC(js_cc_ProductDetails_equals) - -static bool js_cc_ProductDetails_hashCode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->hashCode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_hashCode_get) - -static bool js_cc_ProductDetails_description_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->description; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_description_get) - -static bool js_cc_ProductDetails_name_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->name; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_name_get) - -static bool js_cc_ProductDetails_oneTimePurchaseOfferDetails_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - cc::OneTimePurchaseOfferDetails* result = 0; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->oneTimePurchaseOfferDetails.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_oneTimePurchaseOfferDetails_get) - -static bool js_cc_ProductDetails_productId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->productId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_productId_get) - -static bool js_cc_ProductDetails_productType_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->productType; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_productType_get) - -static bool js_cc_ProductDetails_title_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->title; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_title_get) - -static bool js_cc_ProductDetails_toString_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->toString; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_toString_get) - -static bool js_cc_ProductDetails_subscriptionOfferDetails_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::ProductDetails* arg1 = (cc::ProductDetails*)NULL; - std::vector result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->subscriptionOfferDetails; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_ProductDetails_subscriptionOfferDetails_get) - -static bool js_delete_cc_ProductDetails(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_ProductDetails) - -bool js_register_cc_ProductDetails(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("ProductDetails", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("hashCode", _SE(js_cc_ProductDetails_hashCode_get), nullptr); - cls->defineProperty("description", _SE(js_cc_ProductDetails_description_get), nullptr); - cls->defineProperty("name", _SE(js_cc_ProductDetails_name_get), nullptr); - cls->defineProperty("oneTimePurchaseOfferDetails", _SE(js_cc_ProductDetails_oneTimePurchaseOfferDetails_get), nullptr); - cls->defineProperty("productId", _SE(js_cc_ProductDetails_productId_get), nullptr); - cls->defineProperty("productType", _SE(js_cc_ProductDetails_productType_get), nullptr); - cls->defineProperty("title", _SE(js_cc_ProductDetails_title_get), nullptr); - cls->defineProperty("toStr", _SE(js_cc_ProductDetails_toString_get), nullptr); - cls->defineProperty("subscriptionOfferDetails", _SE(js_cc_ProductDetails_subscriptionOfferDetails_get), nullptr); - - cls->defineFunction("equals", _SE(js_cc_ProductDetails_equals)); - - cls->defineFinalizeFunction(_SE(js_delete_cc_ProductDetails)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_AccountIdentifiers) - -static bool js_cc_AccountIdentifiers_obfuscatedAccountId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::AccountIdentifiers* arg1 = (cc::AccountIdentifiers*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->obfuscatedAccountId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_AccountIdentifiers_obfuscatedAccountId_get) - -static bool js_cc_AccountIdentifiers_obfuscatedProfileId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::AccountIdentifiers* arg1 = (cc::AccountIdentifiers*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->obfuscatedProfileId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_AccountIdentifiers_obfuscatedProfileId_get) - -static bool js_delete_cc_AccountIdentifiers(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_AccountIdentifiers) - -bool js_register_cc_AccountIdentifiers(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("AccountIdentifiers", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("obfuscatedAccountId", _SE(js_cc_AccountIdentifiers_obfuscatedAccountId_get), nullptr); - cls->defineProperty("obfuscatedProfileId", _SE(js_cc_AccountIdentifiers_obfuscatedProfileId_get), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_AccountIdentifiers)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_PendingPurchaseUpdate) - -static bool js_cc_PendingPurchaseUpdate_products_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PendingPurchaseUpdate* arg1 = (cc::PendingPurchaseUpdate*)NULL; - std::vector result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->products; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PendingPurchaseUpdate_products_get) - -static bool js_cc_PendingPurchaseUpdate_purchaseToken_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::PendingPurchaseUpdate* arg1 = (cc::PendingPurchaseUpdate*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->purchaseToken; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_PendingPurchaseUpdate_purchaseToken_get) - -static bool js_delete_cc_PendingPurchaseUpdate(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_PendingPurchaseUpdate) - -bool js_register_cc_PendingPurchaseUpdate(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("PendingPurchaseUpdate", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("products", _SE(js_cc_PendingPurchaseUpdate_products_get), nullptr); - cls->defineProperty("purchaseToken", _SE(js_cc_PendingPurchaseUpdate_purchaseToken_get), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_PendingPurchaseUpdate)); - - cls->install(); - JSBClassType::registerClass(cls); - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_Purchase) - -static bool js_cc_Purchase_equals(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - cc::Purchase* arg1 = (cc::Purchase*)NULL; - cc::Purchase* arg2 = 0; - cc::Purchase temp2; - bool result; - - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - result = (bool)((cc::Purchase const*)arg1)->equals((cc::Purchase const&)*arg2); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_FUNC(js_cc_Purchase_equals) - -static bool js_cc_Purchase_accountIdentifiers_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - cc::AccountIdentifiers* result = 0; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->accountIdentifiers.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_accountIdentifiers_get) - -static bool js_cc_Purchase_developerPayload_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->developerPayload; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_developerPayload_get) - -static bool js_cc_Purchase_orderId_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->orderId; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_orderId_get) - -static bool js_cc_Purchase_originalJson_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->originalJson; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_originalJson_get) - -static bool js_cc_Purchase_packageName_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->packageName; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_packageName_get) - -static bool js_cc_Purchase_pendingPurchaseUpdate_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - cc::PendingPurchaseUpdate* result = 0; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->pendingPurchaseUpdate.get(); - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_pendingPurchaseUpdate_get) - -static bool js_cc_Purchase_products_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::vector result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->products; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_products_get) - -static bool js_cc_Purchase_purchaseState_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->purchaseState; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_purchaseState_get) - -static bool js_cc_Purchase_purchaseTime_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - long result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = (long)arg1->purchaseTime; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_purchaseTime_get) - -static bool js_cc_Purchase_purchaseToken_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->purchaseToken; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_purchaseToken_get) - -static bool js_cc_Purchase_quantity_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->quantity; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_quantity_get) - -static bool js_cc_Purchase_signature_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->signature; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_signature_get) - -static bool js_cc_Purchase_hashCode_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - int result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->hashCode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_hashCode_get) - -static bool js_cc_Purchase_isAcknowledged_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - bool result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->isAcknowledged; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_isAcknowledged_get) - -static bool js_cc_Purchase_isAutoRenewing_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - bool result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->isAutoRenewing; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_isAutoRenewing_get) - -static bool js_cc_Purchase_toString_get(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::Purchase* arg1 = (cc::Purchase*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->toString; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_Purchase_toString_get) - -static bool js_delete_cc_Purchase(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_Purchase) - -bool js_register_cc_Purchase(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("Purchase", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - cls->defineProperty("accountIdentifiers", _SE(js_cc_Purchase_accountIdentifiers_get), nullptr); - cls->defineProperty("developerPayload", _SE(js_cc_Purchase_developerPayload_get), nullptr); - cls->defineProperty("orderId", _SE(js_cc_Purchase_orderId_get), nullptr); - cls->defineProperty("originalJson", _SE(js_cc_Purchase_originalJson_get), nullptr); - cls->defineProperty("packageName", _SE(js_cc_Purchase_packageName_get), nullptr); - cls->defineProperty("pendingPurchaseUpdate", _SE(js_cc_Purchase_pendingPurchaseUpdate_get), nullptr); - cls->defineProperty("products", _SE(js_cc_Purchase_products_get), nullptr); - cls->defineProperty("purchaseState", _SE(js_cc_Purchase_purchaseState_get), nullptr); - cls->defineProperty("purchaseTime", _SE(js_cc_Purchase_purchaseTime_get), nullptr); - cls->defineProperty("purchaseToken", _SE(js_cc_Purchase_purchaseToken_get), nullptr); - cls->defineProperty("quantity", _SE(js_cc_Purchase_quantity_get), nullptr); - cls->defineProperty("signature", _SE(js_cc_Purchase_signature_get), nullptr); - cls->defineProperty("hashCode", _SE(js_cc_Purchase_hashCode_get), nullptr); - cls->defineProperty("isAcknowledged", _SE(js_cc_Purchase_isAcknowledged_get), nullptr); - cls->defineProperty("isAutoRenewing", _SE(js_cc_Purchase_isAutoRenewing_get), nullptr); - cls->defineProperty("toStr", _SE(js_cc_Purchase_toString_get), nullptr); - - cls->defineFunction("equals", _SE(js_cc_Purchase_equals)); - - cls->defineFinalizeFunction(_SE(js_delete_cc_Purchase)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -static bool js_cc_BillingConfig_countryCode(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingConfig* arg1 = (cc::BillingConfig*)NULL; - std::string result; - - arg1 = SE_THIS_OBJECT(s); - if (nullptr == arg1) return true; - result = arg1->countryCode; - - ok &= nativevalue_to_se(result, s.rval(), s.thisObject() /*ctx*/); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - SE_HOLD_RETURN_VALUE(result, s.thisObject(), s.rval()); - - return true; -} -SE_BIND_PROP_GET(js_cc_BillingConfig_countryCode) - -static bool js_delete_cc_BillingConfig(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_BillingConfig) - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_BillingConfig) - -bool js_register_cc_BillingConfig(se::Object* obj) { // NOLINT - auto* cls = se::Class::create("BillingConfig", obj, nullptr, nullptr); - - cls->defineStaticProperty("__isJSB", se::Value(true), se::PropertyAttribute::READ_ONLY | se::PropertyAttribute::DONT_ENUM | se::PropertyAttribute::DONT_DELETE); - - cls->defineProperty("countryCode", _SE(js_cc_BillingConfig_countryCode), nullptr); - - cls->defineFinalizeFunction(_SE(js_delete_cc_BillingConfig)); - - cls->install(); - JSBClassType::registerClass(cls); - - se::ScriptEngine::getInstance()->clearException(); - return true; -} - -SE_DECLARE_FINALIZE_FUNC(js_delete_cc_Google_Billing) - -static bool js_cc_Google_Billing_startConnection(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().startConnection(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_startConnection) - -static bool js_cc_Google_Billing_endConnection(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().endConnection(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_endConnection) - -static bool js_cc_Google_Billing_getConnectionState(se::State& s) { // NOLINT - int connectionState = cc::GoogleBilling::getInstance().getConnectionState(); - s.rval().setFloat(connectionState); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_getConnectionState) - -static bool js_cc_Google_Billing_isReady(se::State& s) { - int isReady = cc::GoogleBilling::getInstance().isReady(); - s.rval().setFloat(isReady); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_isReady) - -static bool js_cc_Google_Billing_queryProductDetailsParams(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - std::vector* arg2 = 0; - std::string* arg3 = 0; - std::vector temp2; - std::string temp3; - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - ok &= sevalue_to_native(args[1], &temp3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg3 = &temp3; - - cc::GoogleBilling::getInstance().queryProductDetailsParams((std::vector const&)*arg2, (std::string const&)*arg3); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_queryProductDetailsParams) - -static bool js_cc_Google_Billing_launchBillingFlow(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - - std::vector* arg2 = 0; - std::string* arg3 = 0; - std::vector temp2; - std::string temp3; - - if (argc != 2) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 2); - return false; - } - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - ok &= sevalue_to_native(args[1], &temp3, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg3 = &temp3; - - cc::GoogleBilling::getInstance().launchBillingFlow((std::vector const&)*arg2, (std::string const&)*arg3); - - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_launchBillingFlow) - -static bool js_cc_Google_Billing_consumePurchases(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - std::vector* arg2 = 0; - std::vector temp2; - - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - cc::GoogleBilling::getInstance().consumePurchases((std::vector const&)*arg2); - - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_consumePurchases) - -static bool js_cc_Google_Billing_acknowledgePurchase(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - std::vector* arg1 = 0; - std::vector temp2; - - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg1 = &temp2; - - cc::GoogleBilling::getInstance().acknowledgePurchase((std::vector const&)*arg1); - - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_acknowledgePurchase) - -static bool js_cc_Google_Billing_queryPurchasesAsync(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - std::string* arg2 = 0; - std::string temp2; - - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - arg2 = &temp2; - - cc::GoogleBilling::getInstance().queryPurchasesAsync((std::string const&)*arg2); - - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_queryPurchasesAsync) - -static bool js_cc_Google_Billing_getBillingConfigAsync(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().getBillingConfigAsync(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_getBillingConfigAsync) - -static bool js_cc_Google_Billing_createAlternativeBillingOnlyReportingDetailsAsync(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().createAlternativeBillingOnlyReportingDetailsAsync(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_createAlternativeBillingOnlyReportingDetailsAsync) - -static bool js_cc_Google_Billing_isAlternativeBillingOnlyAvailableAsync(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().isAlternativeBillingOnlyAvailableAsync(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_isAlternativeBillingOnlyAvailableAsync) - -static bool js_cc_Google_Billing_createExternalOfferReportingDetailsAsync(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().createExternalOfferReportingDetailsAsync(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_createExternalOfferReportingDetailsAsync) - -static bool js_cc_Google_Billing_isExternalOfferAvailableAsync(se::State& s) { // NOLINT - cc::GoogleBilling::getInstance().isExternalOfferAvailableAsync(); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_isExternalOfferAvailableAsync) - -static bool js_cc_Google_Billing_isFeatureSupported(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - const auto& args = s.args(); - size_t argc = args.size(); - std::string temp2; - - if (argc != 1) { - SE_REPORT_ERROR("wrong number of arguments: %d, was expecting %d", (int)argc, 1); - return false; - } - - ok &= sevalue_to_native(args[0], &temp2, s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - - cc::BillingResult* result = cc::GoogleBilling::getInstance().isFeatureSupported(temp2); - - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_isFeatureSupported) - -static bool js_cc_Google_Billing_showAlternativeBillingOnlyInformationDialog(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* result = cc::GoogleBilling::getInstance().showAlternativeBillingOnlyInformationDialog(); - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_showAlternativeBillingOnlyInformationDialog) - -static bool js_cc_Google_Billing_showExternalOfferInformationDialog(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* result = cc::GoogleBilling::getInstance().showExternalOfferInformationDialog(); - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_showExternalOfferInformationDialog) - -static bool js_cc_Google_Billing_showInAppMessages(se::State& s) { // NOLINT - CC_UNUSED bool ok = true; - cc::BillingResult* result = cc::GoogleBilling::getInstance().showInAppMessages(); - ok &= nativevalue_to_se(*result, s.rval(), s.thisObject()); - SE_PRECONDITION2(ok, false, "Error processing arguments"); - return true; -} -SE_BIND_FUNC(js_cc_Google_Billing_showInAppMessages) - -static bool js_delete_cc_Google_Billing(se::State& s) { // NOLINT - return true; -} -SE_BIND_FINALIZE_FUNC(js_delete_cc_Google_Billing) - -bool js_register_cc_Google_Billing(se::Object* obj) { // NOLINT - se::Value googleBillingVal{se::Object::createPlainObject()}; - auto* cls = googleBillingVal.toObject(); - - cls->defineFunction("startConnection", _SE(js_cc_Google_Billing_startConnection)); - cls->defineFunction("endConnection", _SE(js_cc_Google_Billing_endConnection)); - cls->defineFunction("getConnectionState", _SE(js_cc_Google_Billing_getConnectionState)); - cls->defineFunction("isReady", _SE(js_cc_Google_Billing_isReady)); - cls->defineFunction("queryProductDetailsParams", _SE(js_cc_Google_Billing_queryProductDetailsParams)); - - cls->defineFunction("launchBillingFlow", _SE(js_cc_Google_Billing_launchBillingFlow)); - cls->defineFunction("consumePurchases", _SE(js_cc_Google_Billing_consumePurchases)); - cls->defineFunction("acknowledgePurchase", _SE(js_cc_Google_Billing_acknowledgePurchase)); - cls->defineFunction("queryPurchasesAsync", _SE(js_cc_Google_Billing_queryPurchasesAsync)); - cls->defineFunction("getBillingConfigAsync", _SE(js_cc_Google_Billing_getBillingConfigAsync)); - - cls->defineFunction("createAlternativeBillingOnlyReportingDetailsAsync", _SE(js_cc_Google_Billing_createAlternativeBillingOnlyReportingDetailsAsync)); - cls->defineFunction("isAlternativeBillingOnlyAvailableAsync", _SE(js_cc_Google_Billing_isAlternativeBillingOnlyAvailableAsync)); - cls->defineFunction("createExternalOfferReportingDetailsAsync", _SE(js_cc_Google_Billing_createExternalOfferReportingDetailsAsync)); - cls->defineFunction("isExternalOfferAvailableAsync", _SE(js_cc_Google_Billing_isExternalOfferAvailableAsync)); - - cls->defineFunction("isFeatureSupported", _SE(js_cc_Google_Billing_isFeatureSupported)); - - cls->defineFunction("showAlternativeBillingOnlyInformationDialog", _SE(js_cc_Google_Billing_showAlternativeBillingOnlyInformationDialog)); - cls->defineFunction("showExternalOfferInformationDialog", _SE(js_cc_Google_Billing_showExternalOfferInformationDialog)); - cls->defineFunction("showInAppMessages", _SE(js_cc_Google_Billing_showInAppMessages)); - - obj->setProperty("googleBilling", googleBillingVal); - - return true; -} - -bool jsb_register_all_billing(se::Object* obj) { // NOLINT - se::Value nsVal; - if (!obj->getProperty("jsb", &nsVal, true)) { - se::HandleObject jsobj(se::Object::createPlainObject()); - nsVal.setObject(jsobj); - obj->setProperty("jsb", nsVal); - } - se::Object* ns = nsVal.toObject(); - /* Register classes */ - js_register_cc_BillingResult(ns); - js_register_cc_OneTimePurchaseOfferDetails(ns); - js_register_cc_InstallmentPlanDetails(ns); - js_register_cc_PricingPhases(ns); - js_register_cc_PricingPhase(ns); - - js_register_cc_SubscriptionOfferDetails(ns); - js_register_cc_ProductDetails(ns); - js_register_cc_AccountIdentifiers(ns); - js_register_cc_PendingPurchaseUpdate(ns); - js_register_cc_Purchase(ns); - js_register_cc_BillingConfig(ns); - js_register_cc_Google_Billing(ns); - return true; -} - -#else -void jsb_register_all_billing(se::Object *ns) {} // NOLINT - -#endif // CC_PLATFORM_ANDROID diff --git a/native/cocos/bindings/manual/jsb_module_register.cpp b/native/cocos/bindings/manual/jsb_module_register.cpp index 0e0c7ee52f..cd9d0af6d2 100644 --- a/native/cocos/bindings/manual/jsb_module_register.cpp +++ b/native/cocos/bindings/manual/jsb_module_register.cpp @@ -84,7 +84,7 @@ #include "cocos/bindings/manual/JavaScriptArkTsBridge.h" #endif -#if(CC_PLATFORM == CC_PLATFORM_OPENHARMONY) +#if (CC_PLATFORM == CC_PLATFORM_OPENHARMONY) #if CC_USE_WEBVIEW #include "cocos/bindings/auto/jsb_webview_auto.h" #endif @@ -125,7 +125,9 @@ #include "cocos/bindings/auto/jsb_physics_auto.h" #endif -extern bool jsb_register_all_billing(se::Object *); // NOLINT +#if CC_USE_GOOGLE_BILLING + #include "cocos/bindings/auto/jsb_google_billing_auto.h" +#endif bool jsb_register_all_modules() { se::ScriptEngine *se = se::ScriptEngine::getInstance(); @@ -193,7 +195,7 @@ bool jsb_register_all_modules() { #endif #if CC_USE_GOOGLE_BILLING - se->addRegisterCallback(jsb_register_all_billing); + se->addRegisterCallback(register_all_billing); #endif #if CC_USE_MIDDLEWARE diff --git a/native/cocos/editor-support/spine/SpineString.cpp b/native/cocos/editor-support/spine/SpineString.cpp index c86cfc439f..d9a924bfe5 100644 --- a/native/cocos/editor-support/spine/SpineString.cpp +++ b/native/cocos/editor-support/spine/SpineString.cpp @@ -29,7 +29,6 @@ #include - // Required for sprintf on MSVC #ifdef _MSC_VER #pragma warning(disable : 4996) @@ -55,7 +54,8 @@ String::String(const char *chars, size_t len, bool own) { } } -String::String(const char *chars, bool own/* = false*/): String(chars, strlen(chars), own) { +String::String(const char *chars, bool own /* = false*/) +: String(chars, (chars ? strlen(chars) : 0), own) { } String::String(const String &other) { @@ -189,4 +189,3 @@ String::~String() { } } // namespace spine - diff --git a/native/cocos/platform/android/adpf_manager.cpp b/native/cocos/platform/android/adpf_manager.cpp index 32c5a97cad..dc80b397b9 100644 --- a/native/cocos/platform/android/adpf_manager.cpp +++ b/native/cocos/platform/android/adpf_manager.cpp @@ -19,8 +19,8 @@ #if CC_PLATFORM == CC_PLATFORM_ANDROID && __ANDROID_API__ >= 30 - #include #include + #include #include #include #include @@ -175,11 +175,11 @@ float ADPFManager::updateThermalStatusHeadRoom() { // Initialize JNI calls for the PowerHintManager. bool ADPFManager::initializePerformanceHintManager() { -#if __ANDROID_API__ >= 33 - if ( hint_manager_ == nullptr ) { + #if __ANDROID_API__ >= 33 + if (hint_manager_ == nullptr) { hint_manager_ = APerformanceHint_getManager(); } - if ( hint_session_ == nullptr && hint_manager_ != nullptr ) { + if (hint_session_ == nullptr && hint_manager_ != nullptr) { int32_t tid = gettid(); thread_ids_.push_back(tid); int32_t tids[1]; @@ -187,7 +187,7 @@ bool ADPFManager::initializePerformanceHintManager() { hint_session_ = APerformanceHint_createSession(hint_manager_, tids, 1, last_target_); } return true; -#else + #elif __ANDROID_API__ >= 31 JNIEnv *env = cc::JniHelper::getEnv(); auto *applicationContext = cc::JniHelper::getContext(); @@ -243,7 +243,7 @@ bool ADPFManager::initializePerformanceHintManager() { set_threads_ = env->GetMethodID( cls_perfhint_session, "setThreads", "([I)V"); check = env->ExceptionCheck(); - if ( check ) { + if (check) { env->ExceptionDescribe(); env->ExceptionClear(); set_threads_ = nullptr; @@ -264,7 +264,9 @@ bool ADPFManager::initializePerformanceHintManager() { } return true; -#endif + #else + return false; + #endif } thermalStateChangeListener ADPFManager::thermalListener = NULL; @@ -290,13 +292,13 @@ void ADPFManager::beginPerfHintSession() { } void ADPFManager::endPerfHintSession(jlong target_duration_ns) { -#if __ANDROID_API__ >= 33 + #if __ANDROID_API__ >= 33 auto perf_end = std::chrono::steady_clock::now(); auto dur = std::chrono::duration_cast(perf_end - perf_start_).count(); int64_t actual_duration_ns = static_cast(dur); APerformanceHint_reportActualWorkDuration(hint_session_, actual_duration_ns); APerformanceHint_updateTargetWorkDuration(hint_session_, target_duration_ns); -#else + #else auto perf_end = std::chrono::steady_clock::now(); auto dur = std::chrono::duration_cast(perf_end - perf_start_).count(); jlong actual_duration_ns = static_cast(dur); @@ -309,7 +311,7 @@ void ADPFManager::endPerfHintSession(jlong target_duration_ns) { env->CallVoidMethod(obj_perfhint_session_, update_target_work_duration_, target_duration_ns); } -#endif + #endif } void ADPFManager::addThreadIdToHintSession(int32_t tid) { thread_ids_.push_back(tid); @@ -324,27 +326,27 @@ void ADPFManager::removeThreadIdFromHintSession(int32_t tid) { } void ADPFManager::registerThreadIdsToHintSession() { -#if __ANDROID_API__ >= 34 + #if __ANDROID_API__ >= 34 auto data = thread_ids_.data(); std::size_t size = thread_ids_.size(); APerformanceHint_setThreads(hint_session_, data, size); -#elif __ANDROID_API__ >= 33 + #elif __ANDROID_API__ >= 33 auto data = thread_ids_.data(); std::size_t size = thread_ids_.size(); - if ( hint_session_ != nullptr ) { + if (hint_session_ != nullptr) { APerformanceHint_closeSession(hint_session_); } hint_session_ = APerformanceHint_createSession(hint_manager_, data, size, last_target_); -#else + #elif __ANDROID_API__ >= 31 JNIEnv *env = cc::JniHelper::getEnv(); std::size_t size = thread_ids_.size(); jintArray array = env->NewIntArray(size); auto data = thread_ids_.data(); env->SetIntArrayRegion(array, 0, size, data); - if ( set_threads_ == nullptr ) { + if (set_threads_ == nullptr) { // we have to recreate the hint session - if ( obj_perfhint_session_ ) { - env->DeleteGlobalRef(obj_perfhint_session_ ); + if (obj_perfhint_session_) { + env->DeleteGlobalRef(obj_perfhint_session_); } const jlong DEFAULT_TARGET_NS = 16666666; jobject obj_hintsession = env->CallObjectMethod(obj_perfhint_service_, create_hint_session_, array, DEFAULT_TARGET_NS); @@ -353,12 +355,12 @@ void ADPFManager::registerThreadIdsToHintSession() { // API Level 34 env->CallVoidMethod(obj_perfhint_session_, set_threads_, array); jboolean check = env->ExceptionCheck(); - if ( check ) { + if (check) { env->ExceptionDescribe(); env->ExceptionClear(); } } -#endif + #endif } #endif diff --git a/native/cocos/platform/android/adpf_manager.h b/native/cocos/platform/android/adpf_manager.h index 7ba133aad8..015051fa5d 100644 --- a/native/cocos/platform/android/adpf_manager.h +++ b/native/cocos/platform/android/adpf_manager.h @@ -16,14 +16,14 @@ #pragma once -#if CC_PLATFORM == CC_PLATFORM_ANDROID && __ANDROID_API__ >= 30 +#if CC_PLATFORM == CC_PLATFORM_ANDROID && __ANDROID_API__ >= 30 && CC_USE_ADPF #include #include #include -#if __ANDROID_API__ >= 33 - #include - #include -#endif + #if __ANDROID_API__ >= 33 + #include + #include + #endif #include #include @@ -68,7 +68,7 @@ public: } // clean all hint sessions - for ( const auto& kv : map_hint_sessions ) { + for (const auto &kv : map_hint_sessions) { jobject global_hint_session = kv.second; env->DeleteGlobalRef(global_hint_session); } @@ -114,7 +114,7 @@ public: AThermalManager *getThermalManager() { return thermal_manager_; } void initialize(); - void destroy(); + void destroy(); private: // Update thermal headroom each sec. @@ -173,15 +173,14 @@ private: std::vector thread_ids_; std::chrono::time_point perf_start_; -#if __ANDROID_API__ >= 33 + #if __ANDROID_API__ >= 33 APerformanceHintManager *hint_manager_ = nullptr; APerformanceHintSession *hint_session_ = nullptr; int64_t last_target_ = 16666666; -#endif + #endif }; #define CC_SUPPORT_ADPF 1 // NOLINT #else #define CC_SUPPORT_ADPF 0 // NOLINT #endif // ADPF_MANAGER_H_ - diff --git a/native/cocos/platform/android/java/vendor/google/billing/GoogleBilling.java b/native/cocos/platform/android/java/vendor/google/billing/GoogleBilling.java index 9cd1bc853d..40f08200a2 100644 --- a/native/cocos/platform/android/java/vendor/google/billing/GoogleBilling.java +++ b/native/cocos/platform/android/java/vendor/google/billing/GoogleBilling.java @@ -28,84 +28,116 @@ import android.util.Log; import androidx.annotation.NonNull; import androidx.annotation.Nullable; -import com.android.billingclient.api.BillingConfig; + import com.android.billingclient.api.BillingResult; -import com.android.billingclient.api.InAppMessageResult; import com.android.billingclient.api.ProductDetails; import com.android.billingclient.api.Purchase; import com.android.billingclient.api.AcknowledgePurchaseParams; import com.android.billingclient.api.AcknowledgePurchaseResponseListener; import com.android.billingclient.api.BillingClient; -import com.android.billingclient.api.BillingClientStateListener; + import com.android.billingclient.api.BillingFlowParams; import com.android.billingclient.api.ConsumeParams; import com.android.billingclient.api.ConsumeResponseListener; import com.android.billingclient.api.AlternativeBillingOnlyReportingDetailsListener; import com.android.billingclient.api.ProductDetailsResponseListener; import com.android.billingclient.api.PurchasesResponseListener; -import com.android.billingclient.api.PurchasesUpdatedListener; import com.android.billingclient.api.QueryProductDetailsParams; import com.android.billingclient.api.QueryPurchasesParams; import com.android.billingclient.api.GetBillingConfigParams; import com.android.billingclient.api.BillingConfigResponseListener; -import com.android.billingclient.api.AlternativeBillingOnlyReportingDetails; import com.android.billingclient.api.AlternativeBillingOnlyAvailabilityListener; import com.android.billingclient.api.AlternativeBillingOnlyInformationDialogListener; import com.android.billingclient.api.ExternalOfferReportingDetailsListener; -import com.android.billingclient.api.ExternalOfferReportingDetails; import com.android.billingclient.api.ExternalOfferAvailabilityListener; import com.android.billingclient.api.ExternalOfferInformationDialogListener; import com.android.billingclient.api.InAppMessageParams; import com.android.billingclient.api.InAppMessageResponseListener; +import com.android.billingclient.api.BillingClientStateListener; import com.cocos.lib.GlobalObject; -import com.cocos.lib.CocosHelper; + import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; -public class GoogleBilling implements BillingClientStateListener, - PurchasesUpdatedListener, ProductDetailsResponseListener, PurchasesResponseListener, - ConsumeResponseListener, AcknowledgePurchaseResponseListener, BillingConfigResponseListener, - AlternativeBillingOnlyReportingDetailsListener, AlternativeBillingOnlyAvailabilityListener,AlternativeBillingOnlyInformationDialogListener, - ExternalOfferReportingDetailsListener, ExternalOfferAvailabilityListener,ExternalOfferInformationDialogListener, InAppMessageResponseListener { +public final class GoogleBilling { private static final String TAG = GoogleBilling.class.getSimpleName(); private Map _productDetails = new HashMap<>(); private Map _purchase = new HashMap<>(); private int _productDetailsNextID = 0; private int _purchaseNextID = 0; - + private int _tag = 0; /** * The billing client. */ private BillingClient _billingClient; - public GoogleBilling() { - _billingClient = BillingClient.newBuilder(GlobalObject.getActivity()) - .setListener(this) - .enablePendingPurchases() - .build(); + public GoogleBilling(int tag, BillingClient.Builder builder) { + assert tag >= 0 && builder != null; + this._tag = tag; + try { + _billingClient = builder.build(); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); + } } - public void removeProductDetails(int productDetailsID) { - if (_productDetails.containsKey(productDetailsID)) { - _productDetails.remove(productDetailsID); + public void removeProductDetails(int productDetailsId) { + if (_productDetails.containsKey(productDetailsId)) { + _productDetails.remove(productDetailsId); + Log.w(TAG, "removeProductDetails"); } else { Log.w(TAG, "Remove invalid product details id"); } } + public int pushProductDetails(List productDetailsList) { + int startID = _productDetailsNextID; + for (ProductDetails productDetails: productDetailsList) { + _productDetails.put(_productDetailsNextID++, productDetails); + Log.w(TAG, "pushProductDetails"); + } + return startID; + } - public void removePurchase(int purchaseID) { - if (_purchase.containsKey(purchaseID)) { - _purchase.remove(purchaseID); + public ProductDetails getProductDetails(int productDetailsId) { + if (_productDetails.containsKey(productDetailsId)) { + return _productDetails.get(productDetailsId); + } else { + Log.w(TAG, "Remove invalid product details id"); + } + return null; + } + + public int pushPurchases(List purchaseList) { + int startID = _purchaseNextID; + if(purchaseList != null) { + for (Purchase purchase: purchaseList) { + _purchase.put(_purchaseNextID++, purchase); + } + } + return startID; + } + public void removePurchase(int purchaseId) { + if (_purchase.containsKey(purchaseId)) { + _purchase.remove(purchaseId); } else { Log.w(TAG, "Remove invalid purchase id"); } } - public void startConnection() { - _billingClient.startConnection(this); + public Purchase getPurchase(int purchaseId) { + if (_purchase.containsKey(purchaseId)) { + return _purchase.get(purchaseId); + } else { + Log.w(TAG, "Remove invalid product details id"); + } + return null; + } + + public void startConnection(@NonNull BillingClientStateListener listener) { + _billingClient.startConnection(listener); } public void endConnection() { _billingClient.endConnection(); @@ -123,96 +155,60 @@ public class GoogleBilling implements BillingClientStateListener, return _billingClient.isReady(); } - public boolean isConnected() { - return getConnectionState() == BillingClient.ConnectionState.CONNECTED; + public void createAlternativeBillingOnlyReportingDetailsAsync(@NonNull AlternativeBillingOnlyReportingDetailsListener listener) { + _billingClient.createAlternativeBillingOnlyReportingDetailsAsync(listener); } - public void createAlternativeBillingOnlyReportingDetailsAsync() { - _billingClient.createAlternativeBillingOnlyReportingDetailsAsync(this); + public void isAlternativeBillingOnlyAvailableAsync(@NonNull AlternativeBillingOnlyAvailabilityListener listener) { + _billingClient.isAlternativeBillingOnlyAvailableAsync(listener); } - public void isAlternativeBillingOnlyAvailableAsync() { - _billingClient.isAlternativeBillingOnlyAvailableAsync(this); + public void createExternalOfferReportingDetailsAsync(@NonNull ExternalOfferReportingDetailsListener listener) { + _billingClient.createExternalOfferReportingDetailsAsync(listener); } - public void createExternalOfferReportingDetailsAsync() { - _billingClient.createExternalOfferReportingDetailsAsync(this); + public void isExternalOfferAvailableAsync(@NonNull ExternalOfferAvailabilityListener listener) { + _billingClient.isExternalOfferAvailableAsync(listener); } - public void isExternalOfferAvailableAsync() { - _billingClient.isExternalOfferAvailableAsync(this); - } - - public void queryProductDetailsParams(String[] productIds, String type) { - if(!isConnected()) { - Log.e(TAG, "Must be connected before use this interface"); - return; - } + public void queryProductDetailsAsync(String[] productIds, String[] productTypes, + ProductDetailsResponseListener listener) { if(productIds.length == 0) { - Log.e(TAG, "Product ID cannot be empty"); + Log.e(TAG, "Product id must be provided."); return; } - String inputType; - if(type.equals(BillingClient.ProductType.INAPP)) { - inputType = BillingClient.ProductType.INAPP; - } else if(type.equals(BillingClient.ProductType.SUBS)) { - inputType = BillingClient.ProductType.SUBS; - } else { - Log.e(TAG, "Undefined product types."); + if(productIds.length != productTypes.length) { + Log.e(TAG, "Product ID does not match the number of product types"); return; } - List products = new ArrayList<>(); - for(String productId: productIds) { - products.add( - QueryProductDetailsParams.Product.newBuilder() - .setProductId(productId) - .setProductType(inputType) - .build()); - } - QueryProductDetailsParams params = - QueryProductDetailsParams.newBuilder().setProductList(products).build(); - _billingClient.queryProductDetailsAsync(params, this); - } - - public void launchBillingFlow(int[] productDetailsHashs, String selectedOfferToken) { - if(!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - List productDetailsParamsList = new ArrayList<>(); - for (int productDetailsHash: productDetailsHashs) { - if(_productDetails.containsKey(productDetailsHash)) { - if(selectedOfferToken.isEmpty()) { - productDetailsParamsList.add( - BillingFlowParams.ProductDetailsParams.newBuilder().setProductDetails(_productDetails.get(productDetailsHash)).build() - ); - } else { - productDetailsParamsList.add( - BillingFlowParams.ProductDetailsParams.newBuilder() - .setProductDetails(_productDetails.get(productDetailsHash)) - .setOfferToken(selectedOfferToken) - .build() - ); + try { + List products = new ArrayList<>(); + for(int i = 0; i < productIds.length; ++i) { + String inputType = ""; + if(productTypes[i].equals(BillingClient.ProductType.INAPP)) { + inputType = BillingClient.ProductType.INAPP; + } else if(productTypes[i].equals(BillingClient.ProductType.SUBS)) { + inputType = BillingClient.ProductType.SUBS; } - } else { - Log.w(TAG, "Purchased product ID does not exist"); + products.add( + QueryProductDetailsParams.Product.newBuilder() + .setProductId(productIds[i]) + .setProductType(inputType) + .build()); } - + QueryProductDetailsParams params = + QueryProductDetailsParams.newBuilder().setProductList(products).build(); + _billingClient.queryProductDetailsAsync(params, listener); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); } - if(productDetailsParamsList.isEmpty()) { - Log.w(TAG, "Purchased product ID does not exist"); - return; - } - BillingFlowParams params = BillingFlowParams.newBuilder().setProductDetailsParamsList(productDetailsParamsList).build(); - _billingClient.launchBillingFlow(GlobalObject.getActivity(), params); + } + public BillingResult launchBillingFlow(BillingFlowParams params) { + return _billingClient.launchBillingFlow(GlobalObject.getActivity(), params); } - public void queryPurchasesAsync(String type) { - if(!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - String inputType; + public void queryPurchasesAsync(String type, @NonNull PurchasesResponseListener listener) { + String inputType = ""; if(type.equals(BillingClient.ProductType.INAPP)) { inputType = BillingClient.ProductType.INAPP; } else if(type.equals(BillingClient.ProductType.SUBS)) { @@ -221,276 +217,52 @@ public class GoogleBilling implements BillingClientStateListener, Log.w(TAG, "Undefined product types."); return; } - _billingClient.queryPurchasesAsync(QueryPurchasesParams.newBuilder() - .setProductType(inputType) - .build(), this); + try { + _billingClient.queryPurchasesAsync(QueryPurchasesParams.newBuilder() + .setProductType(inputType) + .build(), listener); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); + } } - public void consumePurchase(@Nullable Purchase purchase) { - if(!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - if(purchase != null && purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { + public void consumeAsync(String purchaseToken, ConsumeResponseListener listener) { + try { _billingClient.consumeAsync(ConsumeParams.newBuilder() - .setPurchaseToken(purchase.getPurchaseToken()).build(), - this); + .setPurchaseToken(purchaseToken).build(), + listener); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); } } - private void consumePurchases(@NonNull List purchases) { - if(!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - for (Purchase purchase : purchases) { - consumePurchase(purchase); + public void acknowledgePurchase(@Nullable String purchaseToken, AcknowledgePurchaseResponseListener listener) { + try { + _billingClient.acknowledgePurchase( + AcknowledgePurchaseParams.newBuilder().setPurchaseToken(purchaseToken).build(), + listener); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); } } - public void consumePurchases(@NonNull int[] purchaseHashs) { - if(purchaseHashs.length == 0) { - return; - } - List purchases = new ArrayList<>(); - for (int purchaseHash: purchaseHashs) { - if(_purchase.containsKey(purchaseHash)) { - purchases.add(_purchase.get(purchaseHash)); - } else { - Log.w(TAG, "Purchase id for consumption does not exist"); - } - } - if (!isConnected()) { - startConnection(); - return; - } - consumePurchases(purchases); - } - - private void acknowledgePurchase(@Nullable Purchase purchase) { - if (!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - - if (purchase != null && purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED) { - //if (!purchase.isAcknowledged()) { - _billingClient.acknowledgePurchase(AcknowledgePurchaseParams.newBuilder() - .setPurchaseToken(purchase.getPurchaseToken()).build(), - this); - //} + public void getBillingConfigAsync( @NonNull BillingConfigResponseListener listener) { + try { + GetBillingConfigParams getBillingConfigParams = GetBillingConfigParams.newBuilder().build(); + _billingClient.getBillingConfigAsync(getBillingConfigParams, listener); + } catch (RuntimeException e) { + Log.e(TAG, e.getMessage()); } } - private void acknowledgePurchases(@Nullable List purchases) { - if (!isConnected()) { - Log.w(TAG, "Must be connected before use this interface"); - return; - } - if(purchases != null) { - for (Purchase purchase : purchases) { - acknowledgePurchase(purchase); - } - } + public BillingResult showAlternativeBillingOnlyInformationDialog(@NonNull AlternativeBillingOnlyInformationDialogListener listener) { + return _billingClient.showAlternativeBillingOnlyInformationDialog(GlobalObject.getActivity(), listener); } - public void acknowledgePurchases(@NonNull int[] purchaseHashs) { - List purchases = new ArrayList<>(); - for (int purchaseHash: purchaseHashs) { - if(_purchase.containsKey(purchaseHash)) { - purchases.add(_purchase.get(purchaseHash)); - } else { - Log.w(TAG, "Purchase id for acknowledge does not exist"); - } - } - acknowledgePurchases(purchases); + public BillingResult showExternalOfferInformationDialog(@NonNull ExternalOfferInformationDialogListener listener) { + return _billingClient.showExternalOfferInformationDialog(GlobalObject.getActivity(), listener); } - - public void getBillingConfigAsync() { - GetBillingConfigParams getBillingConfigParams = GetBillingConfigParams.newBuilder().build(); - _billingClient.getBillingConfigAsync(getBillingConfigParams, this); - } - - public BillingResult showAlternativeBillingOnlyInformationDialog() { - return _billingClient.showAlternativeBillingOnlyInformationDialog(GlobalObject.getActivity(), this); - } - - public BillingResult showExternalOfferInformationDialog() { - return _billingClient.showExternalOfferInformationDialog(GlobalObject.getActivity(), this); - } - public BillingResult showInAppMessages() { - return _billingClient.showInAppMessages(GlobalObject.getActivity(), InAppMessageParams.newBuilder().build(), this); - } - - @Override - public void onBillingSetupFinished(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onBillingSetupFinished(billingResult); - } - }); - } - - public void onBillingServiceDisconnected() { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onBillingServiceDisconnected(); - } - }); - } - - @Override - public void onProductDetailsResponse(@NonNull BillingResult billingResult, - @NonNull List productDetailsList) { - int startID = _productDetailsNextID; - for (ProductDetails productDetails: productDetailsList) { - _productDetails.put(_productDetailsNextID++, productDetails); - } - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onProductDetailsResponse(billingResult, productDetailsList, startID); - } - }); - } - - @Override - public void onPurchasesUpdated(@NonNull BillingResult billingResult, - @Nullable List purchaseList) { - int startID = _purchaseNextID; - if(purchaseList != null) { - for (Purchase purchase: purchaseList) { - _purchase.put(_purchaseNextID++, purchase); - } - } - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onPurchasesUpdated(billingResult, purchaseList, startID); - } - }); - } - - @Override - public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, - @NonNull List purchaseList) { - int startID = _purchaseNextID; - for (Purchase purchase: purchaseList) { - _purchase.put(_purchaseNextID++, purchase); - } - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onQueryPurchasesResponse(billingResult, purchaseList, startID); - } - }); - } - - @Override - public void onConsumeResponse(@NonNull BillingResult billingResult, - @NonNull String purchaseToken) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onConsumeResponse(billingResult, purchaseToken); - } - }); - } - - @Override - public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onAcknowledgePurchaseResponse(billingResult); - } - }); - } - - @Override - public void onBillingConfigResponse(@NonNull BillingResult billingResult, @Nullable BillingConfig billingConfig) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onBillingConfigResponse(billingResult, billingConfig); - } - }); - } - - @Override - public void onAlternativeBillingOnlyTokenResponse( - @NonNull BillingResult billingResult, - @Nullable AlternativeBillingOnlyReportingDetails alternativeBillingOnlyReportingDetails) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onAlternativeBillingOnlyTokenResponse(billingResult, alternativeBillingOnlyReportingDetails); - } - }); - } - - @Override - public void onAlternativeBillingOnlyAvailabilityResponse(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onAlternativeBillingOnlyAvailabilityResponse(billingResult); - } - }); - } - - @Override - public void onExternalOfferReportingDetailsResponse( - @NonNull BillingResult billingResult, - @Nullable ExternalOfferReportingDetails externalOfferReportingDetails - ) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onExternalOfferReportingDetailsResponse(billingResult, externalOfferReportingDetails); - } - }); - } - - @Override - public void onExternalOfferAvailabilityResponse(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onExternalOfferAvailabilityResponse(billingResult); - } - }); - } - - @Override - public void onExternalOfferInformationDialogResponse(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onExternalOfferInformationDialogResponse(billingResult); - } - }); - } - - @Override - public void onAlternativeBillingOnlyInformationDialogResponse(@NonNull BillingResult billingResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onAlternativeBillingOnlyInformationDialogResponse(billingResult); - } - }); - } - - @Override - public void onInAppMessageResponse(@NonNull InAppMessageResult inAppMessageResult) { - CocosHelper.runOnGameThread(new Runnable() { - @Override - public void run() { - GoogleBillingHelper.onInAppMessageResponse(inAppMessageResult); - } - }); + public BillingResult showInAppMessages(InAppMessageParams params, @NonNull InAppMessageResponseListener listener) { + return _billingClient.showInAppMessages(GlobalObject.getActivity(), params, listener); } } diff --git a/native/cocos/platform/android/java/vendor/google/billing/GoogleBillingHelper.java b/native/cocos/platform/android/java/vendor/google/billing/GoogleBillingHelper.java index 2cef42b49e..2ba775d8c9 100644 --- a/native/cocos/platform/android/java/vendor/google/billing/GoogleBillingHelper.java +++ b/native/cocos/platform/android/java/vendor/google/billing/GoogleBillingHelper.java @@ -24,191 +24,475 @@ THE SOFTWARE. package google.billing; -import android.annotation.SuppressLint; - import androidx.annotation.NonNull; import androidx.annotation.Nullable; +import com.android.billingclient.api.AcknowledgePurchaseResponseListener; +import com.android.billingclient.api.AlternativeBillingOnlyAvailabilityListener; +import com.android.billingclient.api.AlternativeBillingOnlyInformationDialogListener; import com.android.billingclient.api.AlternativeBillingOnlyReportingDetails; +import com.android.billingclient.api.AlternativeBillingOnlyReportingDetailsListener; +import com.android.billingclient.api.BillingClient; import com.android.billingclient.api.BillingConfig; +import com.android.billingclient.api.BillingConfigResponseListener; +import com.android.billingclient.api.BillingFlowParams; import com.android.billingclient.api.BillingResult; +import com.android.billingclient.api.ConsumeResponseListener; +import com.android.billingclient.api.ExternalOfferAvailabilityListener; +import com.android.billingclient.api.ExternalOfferInformationDialogListener; import com.android.billingclient.api.ExternalOfferReportingDetails; +import com.android.billingclient.api.ExternalOfferReportingDetailsListener; +import com.android.billingclient.api.InAppMessageParams; +import com.android.billingclient.api.InAppMessageResponseListener; import com.android.billingclient.api.InAppMessageResult; import com.android.billingclient.api.ProductDetails; +import com.android.billingclient.api.ProductDetailsResponseListener; import com.android.billingclient.api.Purchase; import java.util.List; + +import com.android.billingclient.api.PurchasesResponseListener; +import com.android.billingclient.api.PurchasesUpdatedListener; +import com.android.billingclient.api.UserChoiceBillingListener; +import com.android.billingclient.api.UserChoiceDetails; +import com.cocos.lib.CocosHelper; import com.cocos.lib.GlobalObject; -import google.billing.GoogleBilling; +import android.util.Log; +import android.util.SparseArray; +import com.android.billingclient.api.BillingClientStateListener; -public class GoogleBillingHelper { - public static native void onBillingSetupFinished(@NonNull BillingResult billingResult); - public static native void onBillingServiceDisconnected(); - public static native void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List productDetailsList, int startID); - public static native void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List purchasesList, int startID); - public static native void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List purchasesList, int startID); - public static native void onConsumeResponse(@NonNull BillingResult billingResult, @NonNull String purchaseToken); - public static native void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult); - public static native void onBillingConfigResponse(@NonNull BillingResult billingResult, @Nullable BillingConfig billingConfig); +public final class GoogleBillingHelper { + private static final String TAG = GoogleBillingHelper.class.getSimpleName(); + private static SparseArray googleBillings = new SparseArray(); + private static int billingTag = 0; - public static native void onAlternativeBillingOnlyTokenResponse(@NonNull BillingResult billingResult, + public static int newTag() { + return billingTag++; + } + public static void createGoogleBilling(int tag, BillingClient.Builder builder) { + GoogleBilling billing = new GoogleBilling(tag, builder); + googleBillings.put(tag, billing); + } + + public static void removeGoogleBilling(int tag) { + googleBillings.remove(tag); + } + + public static final class BillingClientPurchasesUpdatedListener implements PurchasesUpdatedListener { + private int _tag; + BillingClientPurchasesUpdatedListener(int tag) { + this._tag = tag; + } + @Override + public void onPurchasesUpdated(@NonNull BillingResult billingResult, @Nullable List purchaseList) { + int tag = this._tag; + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + int startID = billing.pushPurchases(purchaseList); + GoogleBillingHelper.onPurchasesUpdated(tag, billingResult, purchaseList, startID); + } + } + }); + } + } + + public static final class BillingClientUserChoiceBillingListener implements UserChoiceBillingListener { + private int _tag; + BillingClientUserChoiceBillingListener(int tag) { + this._tag = tag; + } + @Override + public void userSelectedAlternativeBilling(@NonNull UserChoiceDetails userChoiceDetails) { + int tag = this._tag; + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + GoogleBillingHelper.userSelectedAlternativeBilling(tag, userChoiceDetails); + } + } + }); + } + } + + private static native void onBillingSetupFinished(int tag, int callbackId, @NonNull BillingResult billingResult); + private static native void onBillingServiceDisconnected(int tag, int callbackId); + private static native void onProductDetailsResponse(int tag, int callbackId, @NonNull BillingResult billingResult, @NonNull List productDetailsList, int startID); + private static native void onPurchasesUpdated(int tag, @NonNull BillingResult billingResult, @Nullable List purchasesList, int startID); + private static native void userSelectedAlternativeBilling(int tag, @NonNull UserChoiceDetails userChoiceDetails); + private static native void onQueryPurchasesResponse(int tag, int callbackId, @NonNull BillingResult billingResult, @NonNull List purchasesList, int startID); + private static native void onConsumeResponse(int tag, int callbackId, @NonNull BillingResult billingResult, @NonNull String purchaseToken); + private static native void onAcknowledgePurchaseResponse(int tag, int callbackId, @NonNull BillingResult billingResult); + private static native void onBillingConfigResponse(int tag, int callbackId, @NonNull BillingResult billingResult, @Nullable BillingConfig billingConfig); + + private static native void onAlternativeBillingOnlyTokenResponse(int tag, int callbackId, @NonNull BillingResult billingResult, @Nullable AlternativeBillingOnlyReportingDetails alternativeBillingOnlyReportingDetails); - public static native void onAlternativeBillingOnlyAvailabilityResponse(@NonNull BillingResult billingResult); + private static native void onAlternativeBillingOnlyAvailabilityResponse(int tag, int callbackId, @NonNull BillingResult billingResult); - public static native void onExternalOfferReportingDetailsResponse( + private static native void onExternalOfferReportingDetailsResponse( + int tag, + int callbackId, @NonNull BillingResult billingResult, @Nullable ExternalOfferReportingDetails externalOfferReportingDetails ); - public static native void onExternalOfferAvailabilityResponse(@NonNull BillingResult billingResult); - public static native void onExternalOfferInformationDialogResponse(@NonNull BillingResult billingResult); - public static native void onAlternativeBillingOnlyInformationDialogResponse(@NonNull BillingResult billingResult); - public static native void onInAppMessageResponse(@NonNull InAppMessageResult inAppMessageResult); + private static native void onExternalOfferAvailabilityResponse(int tag, int callbackId, @NonNull BillingResult billingResult); + private static native void onExternalOfferInformationDialogResponse(int tag, int callbackId, @NonNull BillingResult billingResult); + private static native void onAlternativeBillingOnlyInformationDialogResponse(int tag, int callbackId, @NonNull BillingResult billingResult); + private static native void onInAppMessageResponse(int tag, int callbackId, @NonNull InAppMessageResult inAppMessageResult); - @SuppressLint("StaticFieldLeak") - private static GoogleBilling instance; - - public static GoogleBilling getInstance() { - if (instance == null) { - instance = new GoogleBilling(); + public static ProductDetails getProductDetailsObject(int tag, int productDetailsID) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + return billing.getProductDetails(productDetailsID); } - return instance; + return null; } - public static void removeProductDetails(int productDetailsID) { - getInstance().removeProductDetails(productDetailsID); + public static void removeProductDetails(int tag, int productDetailsId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + billing.removeProductDetails(productDetailsId); + } } - public static void removePurchase(int purchaseID) { - getInstance().removeProductDetails(purchaseID); + public static void removePurchase(int tag, int purchaseID) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + billing.removePurchase(purchaseID); + } } - public static void startConnection() { - GlobalObject.runOnUiThread(new Runnable() { + public static Purchase getPurchase(int tag, int purchaseId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + return billing.getPurchase(purchaseId); + } + return null; + } + + + public static void startConnection(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.startConnection( + new BillingClientStateListener() { + @Override + public void onBillingSetupFinished(BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onBillingSetupFinished(tag, callbackId, billingResult); + } + }); + } + + @Override + public void onBillingServiceDisconnected() { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onBillingServiceDisconnected(tag, callbackId); + } + }); + + } + }); + } + + public static void endConnection(int tag) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + billing.endConnection(); + } + } + + public static int getConnectionState(int tag) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + return billing.getConnectionState(); + } + return 0; + } + + public static BillingResult isFeatureSupported(int tag, String feature) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + return billing.isFeatureSupported(feature); + } + return BillingResult.newBuilder().build(); + } + + public static boolean isReady(int tag) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + return billing.isReady(); + } + return false; + } + + public static void createAlternativeBillingOnlyReportingDetailsAsync(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.createAlternativeBillingOnlyReportingDetailsAsync( + new AlternativeBillingOnlyReportingDetailsListener() { + @Override + public void onAlternativeBillingOnlyTokenResponse(@NonNull BillingResult var1, @Nullable AlternativeBillingOnlyReportingDetails var2) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onAlternativeBillingOnlyTokenResponse(tag, callbackId, var1, var2); + } + }); + } + } + ); + } + + public static void isAlternativeBillingOnlyAvailableAsync(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.isAlternativeBillingOnlyAvailableAsync( + new AlternativeBillingOnlyAvailabilityListener() { + @Override + public void onAlternativeBillingOnlyAvailabilityResponse(@NonNull BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onAlternativeBillingOnlyAvailabilityResponse(tag, callbackId, billingResult); + } + }); + } + } + ); + } + + public static void createExternalOfferReportingDetailsAsync(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.createExternalOfferReportingDetailsAsync( + new ExternalOfferReportingDetailsListener() { + @Override + public void onExternalOfferReportingDetailsResponse(@NonNull BillingResult billingResult, @Nullable ExternalOfferReportingDetails externalOfferReportingDetails) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onExternalOfferReportingDetailsResponse(tag, callbackId, billingResult, externalOfferReportingDetails); + } + }); + } + } + ); + } + + public static void isExternalOfferAvailableAsync(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.isExternalOfferAvailableAsync( + new ExternalOfferAvailabilityListener() { + @Override + public void onExternalOfferAvailabilityResponse(@NonNull BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onExternalOfferAvailabilityResponse(tag, callbackId, billingResult); + } + }); + } + } + ); + } + + public static void queryProductDetailsAsync(int tag, int callbackId, String[] productIds, String[] productTypes) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.queryProductDetailsAsync(productIds, productTypes, + new ProductDetailsResponseListener() { + @Override + public void onProductDetailsResponse(@NonNull BillingResult billingResult, @NonNull List list) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + int startID = billing.pushProductDetails(list); + GoogleBillingHelper.onProductDetailsResponse(tag, callbackId, billingResult, list, startID); + } + }); + } + }); + } + + public static void launchBillingFlow(int tag, BillingFlowParams params) { + GoogleBilling billing = googleBillings.get(tag); + if (billing != null) { + GlobalObject.runOnUiThread(new Runnable() { + @Override + public void run() { + BillingResult res = billing.launchBillingFlow(params); + Log.i(TAG, String.format("BillingResult: ResponseCode : %d, DebugMessage : %s, ToString: %s", res.getResponseCode(), res.getDebugMessage(), res.toString())); + } + }); + } + } + + public static void queryPurchasesAsync(int tag, int callbackId, String type) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.queryPurchasesAsync(type, new PurchasesResponseListener() { @Override - public void run() { - getInstance().startConnection(); + public void onQueryPurchasesResponse(@NonNull BillingResult billingResult, @NonNull List list) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + int startID = billing.pushPurchases(list); + GoogleBillingHelper.onQueryPurchasesResponse(tag, callbackId, billingResult, list, startID); + } + }); } }); } - public static void endConnection() { - GlobalObject.runOnUiThread(new Runnable() { + public static void consumeAsync(int tag, int callbackId, String purchaseToken) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.consumeAsync(purchaseToken, new ConsumeResponseListener() { @Override - public void run() { - getInstance().endConnection(); + public void onConsumeResponse(@NonNull BillingResult billingResult, @NonNull String s) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onConsumeResponse(tag, callbackId, billingResult, s); + } + }); } }); } - public static int getConnectionState() { - return getInstance().getConnectionState(); - } - - public static BillingResult isFeatureSupported(String feature) { - return getInstance().isFeatureSupported(feature); - } - - public static boolean isReady() { - return getInstance().isReady(); - } - - public static void createAlternativeBillingOnlyReportingDetailsAsync() { - GlobalObject.runOnUiThread(new Runnable() { + public static void acknowledgePurchase(int tag, int callbackId, String purchaseToken) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.acknowledgePurchase(purchaseToken, new AcknowledgePurchaseResponseListener() { @Override - public void run() { - getInstance().createAlternativeBillingOnlyReportingDetailsAsync(); + public void onAcknowledgePurchaseResponse(@NonNull BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onAcknowledgePurchaseResponse(tag, callbackId, billingResult); + } + }); } }); } - public static void isAlternativeBillingOnlyAvailableAsync() { - GlobalObject.runOnUiThread(new Runnable() { + public static void getBillingConfigAsync(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + billing.getBillingConfigAsync(new BillingConfigResponseListener() { @Override - public void run() { - getInstance().isAlternativeBillingOnlyAvailableAsync(); + public void onBillingConfigResponse(@NonNull BillingResult billingResult, @Nullable BillingConfig billingConfig) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onBillingConfigResponse(tag, callbackId, billingResult, billingConfig); + } + }); } }); } - public static void createExternalOfferReportingDetailsAsync() { + public static void showAlternativeBillingOnlyInformationDialog(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } GlobalObject.runOnUiThread(new Runnable() { @Override public void run() { - getInstance().createExternalOfferReportingDetailsAsync(); + BillingResult res = billing.showAlternativeBillingOnlyInformationDialog(new AlternativeBillingOnlyInformationDialogListener() { + @Override + public void onAlternativeBillingOnlyInformationDialogResponse(@NonNull BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onAlternativeBillingOnlyInformationDialogResponse(tag, callbackId, billingResult); + } + }); + } + }); + Log.i(TAG, String.format("BillingResult: ResponseCode : %d, DebugMessage : %s, ToString: %s", res.getResponseCode(), res.getDebugMessage(), res.toString())); } }); } - public static void isExternalOfferAvailableAsync() { + public static void showExternalOfferInformationDialog(int tag, int callbackId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } + GlobalObject.runOnUiThread(new Runnable() { + @Override + public void run() { + BillingResult res = billing.showExternalOfferInformationDialog(new ExternalOfferInformationDialogListener() { + @Override + public void onExternalOfferInformationDialogResponse(@NonNull BillingResult billingResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onExternalOfferInformationDialogResponse(tag, callbackId, billingResult); + } + }); + } + }); + Log.i(TAG, String.format("BillingResult: ResponseCode : %d, DebugMessage : %s, ToString: %s", res.getResponseCode(), res.getDebugMessage(), res.toString())); + } + }); + } + public static void showInAppMessages(int tag, int callbackId, int[] inAppMessageCategoryId) { + GoogleBilling billing = googleBillings.get(tag); + if (billing == null) { + return; + } GlobalObject.runOnUiThread(new Runnable() { @Override public void run() { - getInstance().isExternalOfferAvailableAsync(); + InAppMessageParams.Builder builder = InAppMessageParams.newBuilder(); + for(int i = 0; i < inAppMessageCategoryId.length; ++i) { + builder.addInAppMessageCategoryToShow(inAppMessageCategoryId[i]); + } + BillingResult res = billing.showInAppMessages(builder.build(), new InAppMessageResponseListener() { + @Override + public void onInAppMessageResponse(@NonNull InAppMessageResult inAppMessageResult) { + CocosHelper.runOnGameThread(new Runnable() { + @Override + public void run() { + GoogleBillingHelper.onInAppMessageResponse(tag, callbackId, inAppMessageResult); + } + }); + } + }); + Log.i(TAG, String.format("BillingResult: ResponseCode : %d, DebugMessage : %s, ToString: %s", res.getResponseCode(), res.getDebugMessage(), res.toString())); } }); } - - public static void queryProductDetailsParams(String[] productIds, String type) { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().queryProductDetailsParams(productIds, type); - } - }); - } - - public static void launchBillingFlow(int[] productDetailsHashs, String selectedOfferToken) { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().launchBillingFlow(productDetailsHashs, selectedOfferToken); - } - }); - } - - public static void queryPurchasesAsync(String type) { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().queryPurchasesAsync(type); - } - }); - } - - public static void consumePurchases(@NonNull int[] purchaseHashs) { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().consumePurchases(purchaseHashs); - } - }); - } - - public static void acknowledgePurchases(@NonNull int[] purchaseHashs) { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().acknowledgePurchases(purchaseHashs); - } - }); - } - - public static void getBillingConfigAsync() { - GlobalObject.runOnUiThread(new Runnable() { - @Override - public void run() { - getInstance().getBillingConfigAsync(); - } - }); - } - - public static BillingResult showAlternativeBillingOnlyInformationDialog() { - return getInstance().showAlternativeBillingOnlyInformationDialog(); - } - - public static BillingResult showExternalOfferInformationDialog() { - return getInstance().showExternalOfferInformationDialog(); - } - public static BillingResult showInAppMessages() { - return getInstance().showInAppMessages(); - } } diff --git a/native/cocos/platform/android/libcocos2dx/proguard-rules.pro b/native/cocos/platform/android/libcocos2dx/proguard-rules.pro index 031a158bb4..60c0ad5c56 100644 --- a/native/cocos/platform/android/libcocos2dx/proguard-rules.pro +++ b/native/cocos/platform/android/libcocos2dx/proguard-rules.pro @@ -9,6 +9,8 @@ # Add any project specific keep options here: -keep public class com.google.** { *; } +-keep public class com.android.** { *; } +-keep public class google.billing.** { *; } -keep public class androidx.** { *; } -keep class com.cocos.lib.CocosActivity { public ; diff --git a/native/cocos/platform/java/jni/JniGoogleBillingHandler.cpp b/native/cocos/platform/java/jni/JniGoogleBillingHandler.cpp index a27ce9f0aa..1a53b6d9bf 100644 --- a/native/cocos/platform/java/jni/JniGoogleBillingHandler.cpp +++ b/native/cocos/platform/java/jni/JniGoogleBillingHandler.cpp @@ -22,91 +22,98 @@ THE SOFTWARE. ****************************************************************************/ -#include "platform/java/jni/JniHelper.h" #include +#include "platform/java/jni/JniHelper.h" #include "vendor/google/billing/GoogleBillingHelper.h" - +#include "vendor/google/billing/GoogleBillingManager.h" extern "C" { // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingSetupFinished(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onBillingSetupFinished(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingSetupFinished(JNIEnv *env, jclass clazz, jint tag, jint callbackID, jobject billingResultObj) { + cc::GoogleBillingHelper::onBillingSetupFinished(env, clazz, tag, callbackID, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingServiceDisconnected(JNIEnv *env, jclass clazz) { - cc::GoogleBillingHelper::onBillingServiceDisconnected(env, clazz); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingServiceDisconnected(JNIEnv *env, jclass clazz, jint tag, jint callbackID) { + cc::GoogleBillingHelper::onBillingServiceDisconnected(env, clazz, tag, callbackID); } // NOLINTNEXTLINE JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onProductDetailsResponse(JNIEnv *env, jclass clazz, - jobject billingResultObj, - jobject productDetailsListObj, - jint startID) { - cc::GoogleBillingHelper::onProductDetailsResponse(env, clazz, billingResultObj, productDetailsListObj, startID); + jint tag, jint callbackID, + jobject billingResultObj, + jobject productDetailsListObj, + jint startID) { + cc::GoogleBillingHelper::onProductDetailsResponse(env, clazz, tag, callbackID, billingResultObj, productDetailsListObj, startID); } // NOLINTNEXTLINE JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onPurchasesUpdated(JNIEnv *env, jclass clazz, - jobject billingResultObj, - jobject purchaseListObj, - jint startID) { - cc::GoogleBillingHelper::onPurchasesUpdated(env, clazz, billingResultObj, purchaseListObj, startID); + jint tag, + jobject billingResultObj, + jobject purchaseListObj, + jint startID) { + cc::GoogleBillingHelper::onPurchasesUpdated(env, clazz, tag, billingResultObj, purchaseListObj, startID); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onConsumeResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jstring purchaseToken) { - cc::GoogleBillingHelper::onConsumeResponse(env, clazz, billingResultObj, purchaseToken); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onConsumeResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jstring purchaseToken) { + cc::GoogleBillingHelper::onConsumeResponse(env, clazz, tag, callbackId, billingResultObj, purchaseToken); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onQueryPurchasesResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, - jobject purchaseListObj, jint startID) { - cc::GoogleBillingHelper::onQueryPurchasesResponse(env, clazz, billingResultObj, purchaseListObj, startID); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onQueryPurchasesResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, + jobject purchaseListObj, jint startID) { + cc::GoogleBillingHelper::onQueryPurchasesResponse(env, clazz, tag, callbackId, billingResultObj, purchaseListObj, startID); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAcknowledgePurchaseResponse(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onAcknowledgePurchaseResponse(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAcknowledgePurchaseResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + cc::GoogleBillingHelper::onAcknowledgePurchaseResponse(env, clazz, tag, callbackId, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingConfigResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject billingConfigObj) { - cc::GoogleBillingHelper::onBillingConfigResponse(env, clazz, billingResultObj, billingConfigObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onBillingConfigResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject billingConfigObj) { + cc::GoogleBillingHelper::onBillingConfigResponse(env, clazz, tag, callbackId, billingResultObj, billingConfigObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyTokenResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj) { - cc::GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(env, clazz, billingResultObj, alternativeBillingOnlyReportingDetailsObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyTokenResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj) { + cc::GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(env, clazz, tag, callbackId, billingResultObj, alternativeBillingOnlyReportingDetailsObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferReportingDetailsResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject externalOfferReportingDetailsObj) { - cc::GoogleBillingHelper::onExternalOfferReportingDetailsResponse(env, clazz, billingResultObj, externalOfferReportingDetailsObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferReportingDetailsResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject externalOfferReportingDetailsObj) { + cc::GoogleBillingHelper::onExternalOfferReportingDetailsResponse(env, clazz, tag, callbackId, billingResultObj, externalOfferReportingDetailsObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyAvailabilityResponse(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onAlternativeBillingOnlyAvailabilityResponse(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyAvailabilityResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + cc::GoogleBillingHelper::onAlternativeBillingOnlyAvailabilityResponse(env, clazz, tag, callbackId, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferAvailabilityResponse(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onExternalOfferAvailabilityResponse(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferAvailabilityResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + cc::GoogleBillingHelper::onExternalOfferAvailabilityResponse(env, clazz, tag, callbackId, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyInformationDialogResponse(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onAlternativeBillingOnlyInformationDialogResponse(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onAlternativeBillingOnlyInformationDialogResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + cc::GoogleBillingHelper::onAlternativeBillingOnlyInformationDialogResponse(env, clazz, tag, callbackId, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferInformationDialogResponse(JNIEnv *env, jclass clazz, jobject billingResultObj) { - cc::GoogleBillingHelper::onExternalOfferInformationDialogResponse(env, clazz, billingResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onExternalOfferInformationDialogResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + cc::GoogleBillingHelper::onExternalOfferInformationDialogResponse(env, clazz, tag, callbackId, billingResultObj); } // NOLINTNEXTLINE -JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onInAppMessageResponse(JNIEnv *env, jclass clazz, jobject inAppMessageResultObj) { - cc::GoogleBillingHelper::onInAppMessageResponse(env, clazz, inAppMessageResultObj); +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_onInAppMessageResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject inAppMessageResultObj) { + cc::GoogleBillingHelper::onInAppMessageResponse(env, clazz, tag, callbackId, inAppMessageResultObj); +} + +// NOLINTNEXTLINE +JNIEXPORT void JNICALL Java_google_billing_GoogleBillingHelper_userSelectedAlternativeBilling(JNIEnv *env, jclass clazz, jint tag, jobject userChoiceDetailsObj) { + cc::GoogleBillingHelper::userSelectedAlternativeBilling(env, clazz, tag, userChoiceDetailsObj); } } diff --git a/native/cocos/platform/openharmony/modules/Screen.cpp b/native/cocos/platform/openharmony/modules/Screen.cpp index fb41452209..56f39e4f75 100644 --- a/native/cocos/platform/openharmony/modules/Screen.cpp +++ b/native/cocos/platform/openharmony/modules/Screen.cpp @@ -53,14 +53,14 @@ Screen::Orientation Screen::getDeviceOrientation() const { value = dpi.As().Int32Value(); } - if(value == 0) { + if (value == 0) { return Orientation::PORTRAIT; - } else if(value == 1) { - return Orientation::LANDSCAPE_RIGHT; - } else if(value == 2) { - return Orientation::PORTRAIT_UPSIDE_DOWN; - } else if(value == 3) { + } else if (value == 1) { return Orientation::LANDSCAPE_LEFT; + } else if (value == 2) { + return Orientation::PORTRAIT_UPSIDE_DOWN; + } else if (value == 3) { + return Orientation::LANDSCAPE_RIGHT; } CC_ASSERT(false); return Orientation::PORTRAIT; @@ -89,5 +89,4 @@ void Screen::setDisplayStats(bool isShow) { se::ScriptEngine::getInstance()->evalString(commandBuf); } - } // namespace cc \ No newline at end of file diff --git a/native/cocos/platform/openharmony/napi/NapiHelper.cpp b/native/cocos/platform/openharmony/napi/NapiHelper.cpp index 8099b517b1..e453dcfea1 100644 --- a/native/cocos/platform/openharmony/napi/NapiHelper.cpp +++ b/native/cocos/platform/openharmony/napi/NapiHelper.cpp @@ -26,11 +26,11 @@ #include +#include "bindings/jswrapper/SeApi.h" +#include "platform/interfaces//modules/IScreen.h" +#include "platform/openharmony/FileUtils-OpenHarmony.h" #include "platform/openharmony/OpenHarmonyPlatform.h" #include "platform/openharmony/modules/SystemWindow.h" -#include "platform/openharmony/FileUtils-OpenHarmony.h" -#include "platform/interfaces//modules/IScreen.h" -#include "bindings/jswrapper/SeApi.h" #if CC_USE_EDITBOX #include "ui/edit-box/EditBox-openharmony.h" @@ -52,7 +52,6 @@ enum ContextType { ENGINE_UTILS, EDITBOX_UTILS, WEBVIEW_UTILS, - SYSTEM_UTILS, DISPLAY_UTILS, UV_ASYNC_SEND, VIDEO_UTILS @@ -61,31 +60,31 @@ enum ContextType { #define KEYCODE_BACK_OH 6 static Napi::Env gWorkerEnv(nullptr); -static Napi::FunctionReference* gPostMessageToUIThreadFunc = nullptr; -static Napi::FunctionReference* gPostSyncMessageToUIThreadFunc = nullptr; +static Napi::FunctionReference *gPostMessageToUIThreadFunc = nullptr; +static Napi::FunctionReference *gPostSyncMessageToUIThreadFunc = nullptr; -#define DEFINE_FUNCTION_CALLBACK(functionName, cachedFunctionRefPtr) \ -static void functionName(const Napi::CallbackInfo &info) { \ - Napi::Env env = info.Env(); \ - if (info.Length() != 1) { \ - Napi::Error::New(env, "setPostMessageFunction, 1 argument expected").ThrowAsJavaScriptException(); \ - return; \ - } \ - \ - if (!info[0].IsFunction()) { \ - Napi::TypeError::New(env, "setPostMessageFunction, function expected").ThrowAsJavaScriptException(); \ - return; \ - } \ - \ - delete cachedFunctionRefPtr; \ - cachedFunctionRefPtr = new Napi::FunctionReference(Napi::Persistent(info[0].As())); \ -} +#define DEFINE_FUNCTION_CALLBACK(functionName, cachedFunctionRefPtr) \ + static void functionName(const Napi::CallbackInfo &info) { \ + Napi::Env env = info.Env(); \ + if (info.Length() != 1) { \ + Napi::Error::New(env, "setPostMessageFunction, 1 argument expected").ThrowAsJavaScriptException(); \ + return; \ + } \ + \ + if (!info[0].IsFunction()) { \ + Napi::TypeError::New(env, "setPostMessageFunction, function expected").ThrowAsJavaScriptException(); \ + return; \ + } \ + \ + delete cachedFunctionRefPtr; \ + cachedFunctionRefPtr = new Napi::FunctionReference(Napi::Persistent(info[0].As())); \ + } DEFINE_FUNCTION_CALLBACK(js_set_PostMessage2UIThreadCallback, gPostMessageToUIThreadFunc) DEFINE_FUNCTION_CALLBACK(js_set_PostSyncMessage2UIThreadCallback, gPostSyncMessageToUIThreadFunc) /* static */ -void NapiHelper::postMessageToUIThread(const std::string& type, Napi::Value param) { +void NapiHelper::postMessageToUIThread(const std::string &type, Napi::Value param) { if (gPostMessageToUIThreadFunc == nullptr) { CC_LOG_ERROR("callback was not set %s, type: %s", __FUNCTION__, type.c_str()); return; @@ -94,7 +93,7 @@ void NapiHelper::postMessageToUIThread(const std::string& type, Napi::Value para } /* static */ -Napi::Value NapiHelper::postSyncMessageToUIThread(const std::string& type, Napi::Value param) { +Napi::Value NapiHelper::postSyncMessageToUIThread(const std::string &type, Napi::Value param) { if (gPostSyncMessageToUIThreadFunc == nullptr) { CC_LOG_ERROR("callback was not set %s, type: %s", __FUNCTION__, type.c_str()); return getWorkerEnv().Undefined(); @@ -105,7 +104,7 @@ Napi::Value NapiHelper::postSyncMessageToUIThread(const std::string& type, Napi: } /* static */ -Napi::Value NapiHelper::napiCallFunction(const char* functionName) { +Napi::Value NapiHelper::napiCallFunction(const char *functionName) { auto env = getWorkerEnv(); auto funcVal = env.Global().Get(functionName); if (!funcVal.IsFunction()) { @@ -121,7 +120,7 @@ Napi::Value NapiHelper::napiCallFunction(const char *functionName, float duratio if (!funcVal.IsFunction()) { return {}; } - const std::initializer_list args = { Napi::Number::New(env, duration) }; + const std::initializer_list args = {Napi::Number::New(env, duration)}; return funcVal.As().Call(env.Global(), args); } @@ -133,7 +132,7 @@ static bool exportFunctions(Napi::Object exports) { return false; } - auto* nativeXComponent = Napi::ObjectWrap::Unwrap(xcomponentObject.As()); + auto *nativeXComponent = Napi::ObjectWrap::Unwrap(xcomponentObject.As()); if (nativeXComponent == nullptr) { CC_LOG_ERROR("nativeXComponent is nullptr"); return false; @@ -155,7 +154,6 @@ static void napiOnShow(const Napi::CallbackInfo &info) { CC_LOG_INFO("napiOnShow"); cc::WorkerMessageData data{cc::MessageType::WM_APP_SHOW, nullptr, nullptr}; OpenHarmonyPlatform::getInstance()->enqueue(data); - } static void napiOnHide(const Napi::CallbackInfo &info) { @@ -188,9 +186,9 @@ static void napiOnPageHide(const Napi::CallbackInfo &info) { } static void napiNativeEngineInit(const Napi::CallbackInfo &info) { - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI - se::ScriptEngine::setEnv(info.Env()); - #endif +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI + se::ScriptEngine::setEnv(info.Env()); +#endif CC_LOG_INFO("napiNativeEngineInit before run"); OpenHarmonyPlatform::getInstance()->run(0, nullptr); CC_LOG_INFO("napiNativeEngineInit after run"); @@ -203,7 +201,7 @@ static void napiNativeEngineStart(const Napi::CallbackInfo &info) { static void napiWorkerInit(const Napi::CallbackInfo &info) { CC_LOG_INFO("napiWorkerInit ..."); Napi::Env env = info.Env(); - uv_loop_t* loop = nullptr; + uv_loop_t *loop = nullptr; napi_status status = napi_get_uv_event_loop(napi_env(env), &loop); if (status != napi_ok) { CC_LOG_ERROR("napi_get_uv_event_loop failed!"); @@ -218,22 +216,22 @@ static void napiOnDisplayChange(const Napi::CallbackInfo &info) { return; } - int32_t rotation = info[0].As().Int32Value(); + int32_t rotation = info[0].As().Int32Value(); int orientation = static_cast(cc::IScreen::Orientation::PORTRAIT); switch (rotation) { case 0: // ROTATION_0 orientation = static_cast(cc::IScreen::Orientation::PORTRAIT); - break; + break; case 1: // ROTATION_90 - orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_RIGHT); - break; + orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_LEFT); + break; case 2: // ROTATION_180 orientation = static_cast(cc::IScreen::Orientation::PORTRAIT_UPSIDE_DOWN); - break; + break; case 3: // ROTATION_270 - orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_LEFT); - break; + orientation = static_cast(cc::IScreen::Orientation::LANDSCAPE_RIGHT); + break; } cc::events::Orientation::broadcast(orientation); } @@ -263,21 +261,21 @@ static void napiWritablePathInit(const Napi::CallbackInfo &info) { static void registerFunction(const Napi::CallbackInfo &info) { Napi::Env env = info.Env(); - if(info.Length() != 2) { + if (info.Length() != 2) { Napi::Error::New(info.Env(), "2 argument expected").ThrowAsJavaScriptException(); return; } std::string functionName = info[0].As().Utf8Value(); - if(!info[1].IsFunction()) { + if (!info[1].IsFunction()) { Napi::Error::New(info.Env(), "Function expected").ThrowAsJavaScriptException(); return; } Napi::Function jsFunction = info[1].As(); napi_ref fucRef; napi_create_reference(env, jsFunction, 1, &fucRef); - char* name = new char[functionName.length() + 1]; + char *name = new char[functionName.length() + 1]; strcpy(name, functionName.c_str()); - JSFunction* jsFunctionPtr = new JSFunction(name, env, fucRef); + JSFunction *jsFunctionPtr = new JSFunction(name, env, fucRef); JSFunction::addFunction(name, jsFunctionPtr); return; } @@ -347,16 +345,15 @@ static Napi::Value getContext(const Napi::CallbackInfo &info) { exports["onPageHide"] = Napi::Function::New(env, napiOnPageHide); } break; case XCOMPONENT_REGISTER_LIFECYCLE_CALLBACK: { - } break; case NATIVE_RENDER_API: { exports["nativeEngineInit"] = Napi::Function::New(env, napiNativeEngineInit); exports["nativeEngineStart"] = Napi::Function::New(env, napiNativeEngineStart); } break; case WORKER_INIT: { - #if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI - se::ScriptEngine::setEnv(env); - #endif +#if SCRIPT_ENGINE_TYPE == SCRIPT_ENGINE_NAPI + se::ScriptEngine::setEnv(env); +#endif gWorkerEnv = env; exports["workerInit"] = Napi::Function::New(env, napiWorkerInit); @@ -370,27 +367,27 @@ static Napi::Value getContext(const Napi::CallbackInfo &info) { exports["registerFunction"] = Napi::Function::New(env, registerFunction); } break; case EDITBOX_UTILS: { - #if CC_USE_EDITBOX +#if CC_USE_EDITBOX exports["onTextChange"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnTextChange); exports["onComplete"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnComplete); exports["onConfirm"] = Napi::Function::New(env, OpenHarmonyEditBox::napiOnConfirm); - #endif +#endif } break; case WEBVIEW_UTILS: { - #if CC_USE_WEBVIEW +#if CC_USE_WEBVIEW exports["shouldStartLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiShouldStartLoading); exports["finishLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiFinishLoading); exports["failLoading"] = Napi::Function::New(env, OpenHarmonyWebView::napiFailLoading); exports["jsCallback"] = Napi::Function::New(env, OpenHarmonyWebView::napiJsCallback); - #endif +#endif } break; - case DISPLAY_UTILS: { + case DISPLAY_UTILS: { exports["onDisplayChange"] = Napi::Function::New(env, napiOnDisplayChange); } break; case UV_ASYNC_SEND: { exports["send"] = Napi::Function::New(env, napiASend); } break; - case VIDEO_UTILS: { + case VIDEO_UTILS: { exports["onVideoEvent"] = Napi::Function::New(env, napiOnVideoEvent); } break; default: diff --git a/native/tools/swig-config/android/google_billing.i b/native/tools/swig-config/android/google_billing.i new file mode 100644 index 0000000000..96c333127b --- /dev/null +++ b/native/tools/swig-config/android/google_billing.i @@ -0,0 +1,71 @@ +// Define module +// target_namespace means the name exported to JS, could be same as which in other modules +// audio at the last means the suffix of binding function name, different modules should use unique name +// Note: doesn't support number prefix +%module(target_namespace="jsb") billing + +// Disable some swig warnings, find warning number reference here ( https://www.swig.org/Doc4.1/Warnings.html ) +#pragma SWIG nowarn=503,302,401,317,402 + +// Insert code at the beginning of generated header file (.h) +%insert(header_file) %{ +#pragma once +#include "bindings/jswrapper/SeApi.h" +#include "bindings/manual/jsb_conversions.h" +#include "vendor/google/billing/GoogleBilling.h" +#include "vendor/google/billing/build-params/AcknowledgePurchaseParams.h" +#include "vendor/google/billing/build-params/BillingFlowParams.h" +#include "vendor/google/billing/build-params/ConsumeParams.h" +#include "vendor/google/billing/build-params/GetBillingConfigParams.h" +#include "vendor/google/billing/build-params/InAppMessageParams.h" +#include "vendor/google/billing/build-params/PendingPurchasesParams.h" +#include "vendor/google/billing/build-params/QueryProductDetailsParams.h" +#include "vendor/google/billing/build-params/QueryPurchasesParams.h" + +#include "vendor/google/billing/result-values/AccountIdentifiers.h" +#include "vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h" +#include "vendor/google/billing/result-values/BillingConfig.h" +#include "vendor/google/billing/result-values/BillingResult.h" +#include "vendor/google/billing/result-values/ExternalOfferReportingDetails.h" +#include "vendor/google/billing/result-values/InAppMessageResult.h" +#include "vendor/google/billing/result-values/Purchase.h" +#include "vendor/google/billing/result-values/ProductDetails.h" +#include "vendor/google/billing/result-values/UserChoiceDetails.h" +%} + +// Insert code at the beginning of generated source file (.cpp) +%{ +#include "bindings/auto/jsb_google_billing_auto.h" +%} + +// ----- Import Section ------ +// Brief: Import header files which are depended by 'Include Section' +// Note: +// %import "your_header_file.h" will not generate code for that header file +// +%import "base/Macros.h" + +// ----- Include Section ------ +// Brief: Include header files in which classes and methods will be bound +%include "vendor/google/billing/result-values/AccountIdentifiers.h" +%include "vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h" +%include "vendor/google/billing/result-values/BillingConfig.h" +%include "vendor/google/billing/result-values/BillingResult.h" +%include "vendor/google/billing/result-values/ExternalOfferReportingDetails.h" +%include "vendor/google/billing/result-values/InAppMessageResult.h" +%include "vendor/google/billing/result-values/Purchase.h" +%include "vendor/google/billing/result-values/ProductDetails.h" +%include "vendor/google/billing/result-values/UserChoiceDetails.h" + +%include "vendor/google/billing/build-params/AcknowledgePurchaseParams.h" +%include "vendor/google/billing/build-params/BillingFlowParams.h" +%include "vendor/google/billing/build-params/ConsumeParams.h" +%include "vendor/google/billing/build-params/GetBillingConfigParams.h" +%include "vendor/google/billing/build-params/InAppMessageParams.h" +%include "vendor/google/billing/build-params/PendingPurchasesParams.h" +%include "vendor/google/billing/build-params/QueryProductDetailsParams.h" +%include "vendor/google/billing/build-params/QueryPurchasesParams.h" + +%include "vendor/google/billing/GoogleBilling.h" + + diff --git a/native/vendor/google/billing/GoogleBilling.cpp b/native/vendor/google/billing/GoogleBilling.cpp index 04155f2ebb..b945f0402a 100644 --- a/native/vendor/google/billing/GoogleBilling.cpp +++ b/native/vendor/google/billing/GoogleBilling.cpp @@ -23,94 +23,243 @@ ****************************************************************************/ #include "vendor/google/billing/GoogleBilling.h" -#include "vendor/google/billing/GoogleBillingHelper.h" +#include "cocos/bindings/jswrapper/SeApi.h" #include "platform/java/jni/JniHelper.h" #include "platform/java/jni/JniImp.h" +#include "vendor/google/billing/GoogleBillingHelper.h" +#include "vendor/google/billing/GoogleBillingManager.h" +#include "vendor/google/billing/build-params/AcknowledgePurchaseParams.h" +#include "vendor/google/billing/build-params/BillingFlowParams.h" +#include "vendor/google/billing/build-params/ConsumeParams.h" +#include "vendor/google/billing/build-params/GetBillingConfigParams.h" +#include "vendor/google/billing/build-params/InAppMessageParams.h" +#include "vendor/google/billing/build-params/PendingPurchasesParams.h" +#include "vendor/google/billing/build-params/QueryProductDetailsParams.h" +#include "vendor/google/billing/build-params/QueryPurchasesParams.h" +#include "vendor/google/billing/result-values/BillingResult.h" namespace cc { - -ProductDetails::~ProductDetails() { - for (auto* ptr : subscriptionOfferDetails) { - delete ptr; +BillingClient::scopedListener::scopedListener(se::Object* obj) : _obj(obj) { + if (_obj) { + _obj->root(); + _obj->incRef(); } - subscriptionOfferDetails.clear(); - GoogleBillingHelper::removeProductDetails(_id); } -Purchase::~Purchase() { - GoogleBillingHelper::removePurchase(_id); +BillingClient::scopedListener::~scopedListener() { + if (_obj) { + _obj->unroot(); + _obj->decRef(); + } } -void GoogleBilling::startConnection() { - GoogleBillingHelper::startConnection(); +void BillingClient::scopedListener::reset(se::Object* obj) { + if (_obj) { + _obj->unroot(); + _obj->decRef(); + } + _obj = obj; + if (_obj) { + _obj->root(); + _obj->incRef(); + } } -void GoogleBilling::endConnection() { - GoogleBillingHelper::endConnection(); +BillingClient::Builder& BillingClient::Builder::enableUserChoiceBilling(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Can't set an empty listener."); + return *this; + } + + _userChoiceBillingListener.reset(listener); + return *this; } -int GoogleBilling::getConnectionState() const { - return GoogleBillingHelper::getConnectionState(); +BillingClient::Builder& BillingClient::Builder::setListener(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Can't set an empty listener."); + return *this; + } + _purchasesUpdatedListener.reset(listener); + return *this; } -bool GoogleBilling::isReady() const { - return GoogleBillingHelper::isReady(); +BillingClient::BillingClient(Builder* builder) { + this->_enableAlternativeBillingOnly = builder->_enableAlternativeBillingOnly; + this->_enableExternalOffer = builder->_enableExternalOffer; + this->_pendingPurchasesParams = builder->_pendingPurchasesParams; + + _purchasesUpdatedListener.reset(builder->_purchasesUpdatedListener.get()); + _userChoiceBillingListener.reset(builder->_userChoiceBillingListener.get()); + + _tag = GoogleBillingHelper::createGoogleBilling(builder); + + CC_ASSERT(_tag >= 0); + GoogleBillingManager::getInstance()->pushBillingClient(_tag, this); + delete builder; } -void GoogleBilling::queryProductDetailsParams(const std::vector& productIds, const std::string& type) { - GoogleBillingHelper::queryProductDetailsParams(productIds, type); +BillingClient::~BillingClient() { + CC_ASSERT(_tag >= 0); + GoogleBillingHelper::removeGoogleBilling(_tag); + GoogleBillingManager::getInstance()->removeGoogleBilling(_tag); + _listeners.clear(); } -void GoogleBilling::launchBillingFlow(const std::vector& productDetailsList, const std::string& selectedOfferToken) { - GoogleBillingHelper::launchBillingFlow(productDetailsList, selectedOfferToken); +int BillingClient::getNextListenerId() { + return _nextListnerId++; } -void GoogleBilling::consumePurchases(const std::vector& purchases) { - GoogleBillingHelper::consumePurchases(purchases); +int BillingClient::addListener(se::Object* listener) { + int listenerId = getNextListenerId(); + _listeners[listenerId].reset(listener); + return listenerId; } -void GoogleBilling::acknowledgePurchase(const std::vector& purchases) { - GoogleBillingHelper::acknowledgePurchase(purchases); +void BillingClient::startConnection(se::Object* listener) { + int listenerId = addListener(listener); + GoogleBillingHelper::startConnection(_tag, listenerId); } -void GoogleBilling::queryPurchasesAsync(const std::string& productType) { - GoogleBillingHelper::queryPurchasesAsync(productType); +void BillingClient::endConnection() { + GoogleBillingHelper::endConnection(_tag); } -void GoogleBilling::getBillingConfigAsync() { - GoogleBillingHelper::getBillingConfigAsync(); +int BillingClient::getConnectionState() const { + return GoogleBillingHelper::getConnectionState(_tag); } -BillingResult* GoogleBilling::isFeatureSupported(const std::string& feature) { - return GoogleBillingHelper::isFeatureSupported(feature); +bool BillingClient::isReady() const { + return GoogleBillingHelper::isReady(_tag); } -void GoogleBilling::createAlternativeBillingOnlyReportingDetailsAsync() { - GoogleBillingHelper::createAlternativeBillingOnlyReportingDetailsAsync(); +void BillingClient::queryProductDetailsAsync(QueryProductDetailsParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("QueryProductDetailsParams or listener can't be null"); + return; + } + int listenerId = addListener(listener); + std::vector productIds; + std::vector productTypes; + size_t size = params->_productList.size(); + productIds.reserve(size); + productTypes.reserve(size); + for (auto product : params->_productList) { + productIds.push_back(product->_productId); + productTypes.push_back(product->_productType); + } + GoogleBillingHelper::queryProductDetailsAsync(_tag, listenerId, productIds, productTypes); } -void GoogleBilling::isAlternativeBillingOnlyAvailableAsync() { - GoogleBillingHelper::isAlternativeBillingOnlyAvailableAsync(); +void BillingClient::launchBillingFlow(BillingFlowParams* params) { + if (!params) { + CC_LOG_WARNING("BillingFlowParams can't be null"); + return; + } + GoogleBillingHelper::launchBillingFlow(_tag, params); } -void GoogleBilling::createExternalOfferReportingDetailsAsync() { - GoogleBillingHelper::createExternalOfferReportingDetailsAsync(); +void BillingClient::consumeAsync(ConsumeParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("ConsumeParams or listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::consumeAsync(_tag, listenerId, params); } -void GoogleBilling::isExternalOfferAvailableAsync() { - GoogleBillingHelper::isExternalOfferAvailableAsync(); +void BillingClient::acknowledgePurchase(AcknowledgePurchaseParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("AcknowledgePurchaseParams or listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::acknowledgePurchase(_tag, listenerId, params); } -BillingResult* GoogleBilling::showAlternativeBillingOnlyInformationDialog() { - return GoogleBillingHelper::showAlternativeBillingOnlyInformationDialog(); +void BillingClient::queryPurchasesAsync(QueryPurchasesParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("QueryPurchasesParams or listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::queryPurchasesAsync(_tag, listenerId, params->_productType); } -BillingResult* GoogleBilling::showExternalOfferInformationDialog() { - return GoogleBillingHelper::showExternalOfferInformationDialog(); +void BillingClient::getBillingConfigAsync(GetBillingConfigParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("GetBillingConfigParams or listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::getBillingConfigAsync(_tag, listenerId); } -BillingResult* GoogleBilling::showInAppMessages() { - return GoogleBillingHelper::showInAppMessages(); +BillingResult* BillingClient::isFeatureSupported(const std::string& feature) { + return GoogleBillingHelper::isFeatureSupported(_tag, feature); +} + +void BillingClient::createAlternativeBillingOnlyReportingDetailsAsync(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::createAlternativeBillingOnlyReportingDetailsAsync(_tag, listenerId); +} + +void BillingClient::isAlternativeBillingOnlyAvailableAsync(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::isAlternativeBillingOnlyAvailableAsync(_tag, listenerId); +} + +void BillingClient::createExternalOfferReportingDetailsAsync(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::createExternalOfferReportingDetailsAsync(_tag, listenerId); +} + +void BillingClient::isExternalOfferAvailableAsync(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::isExternalOfferAvailableAsync(_tag, listenerId); +} + +void BillingClient::showAlternativeBillingOnlyInformationDialog(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::showAlternativeBillingOnlyInformationDialog(_tag, listenerId); +} + +void BillingClient::showExternalOfferInformationDialog(se::Object* listener) { + if (!listener) { + CC_LOG_WARNING("Listener can't be null"); + return; + } + int listenerId = addListener(listener); + return GoogleBillingHelper::showExternalOfferInformationDialog(_tag, listenerId); +} + +void BillingClient::showInAppMessages(InAppMessageParams* params, se::Object* listener) { + if (!params || !listener) { + CC_LOG_WARNING("InAppMessageParams and listener can't be null"); + return; + } + int listenerId = addListener(listener); + GoogleBillingHelper::showInAppMessages(_tag, listenerId, params->_inAppMessageCategoryIds); } } // namespace cc diff --git a/native/vendor/google/billing/GoogleBilling.h b/native/vendor/google/billing/GoogleBilling.h index b394775f2f..00613f7c43 100644 --- a/native/vendor/google/billing/GoogleBilling.h +++ b/native/vendor/google/billing/GoogleBilling.h @@ -24,169 +24,121 @@ #pragma once +#include #include - #include "base/Macros.h" #include "base/RefCounted.h" +namespace se { +class Object; +} + namespace cc { +class PendingPurchasesParams; +class QueryProductDetailsParams; +class BillingFlowParams; +class ConsumeParams; +class AcknowledgePurchaseParams; +class QueryPurchasesParams; +class GetBillingConfigParams; +class InAppMessageParams; +class BillingResult; -class CC_DLL BillingResult : public cc::RefCounted { -public: - int responseCode{0}; - std::string debugMessage; - std::string toString; -}; - -class CC_DLL OneTimePurchaseOfferDetails { -public: - long priceAmountMicros; - std::string formattedPrice; - std::string priceCurrencyCode; -}; - -class CC_DLL InstallmentPlanDetails { -public: - int installmentPlanCommitmentPaymentsCount; - int subsequentInstallmentPlanCommitmentPaymentsCount; -}; - -class CC_DLL PricingPhase { -public: - int billingCycleCount; - long priceAmountMicros; - int recurrenceMode; - std::string billingPeriod; - std::string formattedPrice; - std::string priceCurrencyCode; -}; - -class CC_DLL PricingPhases { -public: - ~PricingPhases() { - for (auto* pricingPhase : pricingPhaseList) { - delete pricingPhase; +class CC_DLL BillingClient : public cc::RefCounted { +private: + class scopedListener { + public: + scopedListener() = default; + scopedListener(se::Object* obj); + ~scopedListener(); + se::Object* get() const { + return _obj; + } + void reset(se::Object* obj); + operator bool() const { + return _obj != nullptr; } - pricingPhaseList.clear(); - } - std::vector pricingPhaseList; -}; -class CC_DLL SubscriptionOfferDetails { + private: + se::Object* _obj{nullptr}; + }; + public: - std::string basePlanId; - std::string offerId; - std::string offerToken; - std::vector offerTags; - std::unique_ptr pricingPhases; - std::unique_ptr installmentPlanDetails; -}; + class Builder { + public: + Builder& enableAlternativeBillingOnly() { + this->_enableAlternativeBillingOnly = true; + return *this; + } -class CC_DLL ProductDetails : public cc::RefCounted { -public: - ~ProductDetails() override; - bool equals(const ProductDetails& other) const { - return hashCode == other.hashCode; - } - int _id; // This is an ID that is not visible to ts and is used to free the java object. - int hashCode; - std::string description; - std::string name; - std::string productId; - std::string productType; - std::string title; - std::string toString; - std::unique_ptr oneTimePurchaseOfferDetails; - std::vector subscriptionOfferDetails; -}; + Builder& enableExternalOffer() { + this->_enableExternalOffer = true; + return *this; + } + Builder& enablePendingPurchases(PendingPurchasesParams* pendingPurchasesParams) { + this->_pendingPurchasesParams = pendingPurchasesParams; + return *this; + } -class CC_DLL AccountIdentifiers { -public: - std::string obfuscatedAccountId; - std::string obfuscatedProfileId; -}; + Builder& enableUserChoiceBilling(se::Object* listener); + Builder& setListener(se::Object* listener); -class CC_DLL PendingPurchaseUpdate { -public: - std::string purchaseToken; - std::vector products; -}; + BillingClient* build() { + return new BillingClient(this); + } -class CC_DLL Purchase : public cc::RefCounted { -public: - ~Purchase() override; - bool equals(const Purchase& other) const { - return hashCode == other.hashCode; - } - int _id; // This is an ID that is not visible to ts and is used to free the java object. - bool isAcknowledged; - bool isAutoRenewing; - int purchaseState; - int hashCode; - int quantity; - long purchaseTime; - std::string developerPayload; - std::string orderId; - std::string originalJson; - std::string packageName; - std::string purchaseToken; - std::string signature; - std::string toString; - std::unique_ptr accountIdentifiers; - std::unique_ptr pendingPurchaseUpdate; - std::vector products; -}; + private: + friend class BillingClient; + friend class JniBilling; + bool _enableAlternativeBillingOnly{false}; + bool _enableExternalOffer{false}; + PendingPurchasesParams* _pendingPurchasesParams{nullptr}; + scopedListener _purchasesUpdatedListener; + scopedListener _userChoiceBillingListener; + }; -class CC_DLL BillingConfig : public cc::RefCounted { -public: - std::string countryCode; -}; - -class AlternativeBillingOnlyReportingDetails : public cc::RefCounted{ -public: - std::string externalTransactionToken; -}; - -class ExternalOfferReportingDetails : public cc::RefCounted{ -public: - std::string externalTransactionToken; -}; - -class InAppMessageResult : public cc::RefCounted{ -public: - int responseCode; - std::string purchaseToken; -}; - -class CC_DLL GoogleBilling { -public: - static GoogleBilling &getInstance() { - static GoogleBilling instance; - return instance; + static Builder* newBuilder() { + return new Builder(); } - void startConnection(); + void startConnection(se::Object* listener); void endConnection(); int getConnectionState() const; bool isReady() const; - void queryProductDetailsParams(const std::vector& productIds, const std::string& type); - void launchBillingFlow(const std::vector& productDetails, const std::string& selectedOfferToken); - void consumePurchases(const std::vector& purchase); - void acknowledgePurchase(const std::vector& purchase); - void queryPurchasesAsync(const std::string& productType); - void getBillingConfigAsync(); - - void createAlternativeBillingOnlyReportingDetailsAsync(); - void isAlternativeBillingOnlyAvailableAsync(); - void createExternalOfferReportingDetailsAsync(); - void isExternalOfferAvailableAsync(); + void queryProductDetailsAsync(QueryProductDetailsParams* params, se::Object* listener); + void launchBillingFlow(BillingFlowParams* params); + void consumeAsync(ConsumeParams* params, se::Object* listener); + void acknowledgePurchase(AcknowledgePurchaseParams* params, se::Object* listener); + void queryPurchasesAsync(QueryPurchasesParams* parmas, se::Object* listener); + void getBillingConfigAsync(GetBillingConfigParams* params, se::Object* listener); + void createAlternativeBillingOnlyReportingDetailsAsync(se::Object* listener); + void isAlternativeBillingOnlyAvailableAsync(se::Object* listener); + void createExternalOfferReportingDetailsAsync(se::Object* listener); + void isExternalOfferAvailableAsync(se::Object* listener); BillingResult* isFeatureSupported(const std::string& feature); - BillingResult* showAlternativeBillingOnlyInformationDialog(); - BillingResult* showExternalOfferInformationDialog(); - BillingResult* showInAppMessages(); + void showAlternativeBillingOnlyInformationDialog(se::Object* listener); + void showExternalOfferInformationDialog(se::Object* listener); + void showInAppMessages(InAppMessageParams* params, se::Object* listener); + private: - GoogleBilling() = default; + BillingClient(Builder* builder); + ~BillingClient(); + int getNextListenerId(); + int addListener(se::Object* listener); + +private: + friend class GoogleBillingHelper; + int _tag{-1}; + bool _enableAlternativeBillingOnly{false}; + bool _enableExternalOffer{false}; + PendingPurchasesParams* _pendingPurchasesParams{nullptr}; + + scopedListener _purchasesUpdatedListener; + scopedListener _userChoiceBillingListener; + + int _nextListnerId{0}; + std::unordered_map _listeners; }; } // namespace cc diff --git a/native/vendor/google/billing/GoogleBillingHelper.cpp b/native/vendor/google/billing/GoogleBillingHelper.cpp index fc34a726e3..825f7c164a 100644 --- a/native/vendor/google/billing/GoogleBillingHelper.cpp +++ b/native/vendor/google/billing/GoogleBillingHelper.cpp @@ -22,7 +22,7 @@ THE SOFTWARE. ****************************************************************************/ #include "vendor/google/billing/GoogleBillingHelper.h" -#include "vendor/google/billing/GoogleBilling.h" + #include "platform/java/jni/JniHelper.h" #include @@ -33,7 +33,13 @@ #include "cocos/bindings/jswrapper/Value.h" #include "cocos/bindings/manual/jsb_conversions.h" #include "cocos/bindings/manual/jsb_global_init.h" - +#include "vendor/google/billing/GoogleBilling.h" +#include "vendor/google/billing/GoogleBillingManager.h" +#include "vendor/google/billing/JniBilling.h" +#include "vendor/google/billing/build-params/AcknowledgePurchaseParams.h" +#include "vendor/google/billing/build-params/ConsumeParams.h" +#include "vendor/google/billing/result-values/ProductDetails.h" +#include "vendor/google/billing/result-values/Purchase.h" namespace { #ifndef JCLS_BILLING @@ -43,38 +49,21 @@ namespace { namespace cc { namespace { -std::string callStringMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { - jmethodID methodId = env->GetMethodID(clazz, methodName, "()Ljava/lang/String;"); - jobject jStringObj = env->CallObjectMethod(obj, methodId); - if (jStringObj != nullptr) { - return cc::StringUtils::getStringUTFCharsJNI(env, static_cast(jStringObj)); +void invokeJsCallback(se::Object* obj, const char* jsFunctionName, const se::ValueArray& args) { + if (!obj) { + return; } - return ""; -} -jobject callObjectMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName, const char* returnType) { - std::string returnSign = cc::StringUtils::format("()L%s", returnType); - jmethodID methodId = env->GetMethodID(clazz, methodName, returnSign.c_str()); - return env->CallObjectMethod(obj, methodId); -} -int callIntMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { - jmethodID methodId = env->GetMethodID(clazz, methodName, "()I"); - return env->CallIntMethod(obj, methodId); + se::Value funcVal; + if (!obj->getProperty(jsFunctionName, &funcVal) || !funcVal.isObject()) { + return; + } + se::Value rval; + funcVal.toObject()->call(args, obj, &rval); } -bool callBooleanMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { - jmethodID methodId = env->GetMethodID(clazz, methodName, "()Z"); - return env->CallBooleanMethod(obj, methodId); -} - -long callLongMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { - jmethodID methodId = env->GetMethodID(clazz, methodName, "()J"); - return env->CallLongMethod(obj, methodId); -} -} // namespace - template -void callJSfunc(const char* jsFunctionName, Args&&... inargs) { // NOLINT(readability-identifier-naming) +void callJSfunc(se::Object* obj, const char* jsFunctionName, Args&&... inargs) { // NOLINT(readability-identifier-naming) if (!se::ScriptEngine::getInstance()->isValid()) { return; } @@ -82,515 +71,316 @@ void callJSfunc(const char* jsFunctionName, Args&&... inargs) { // NOLINT(readab se::ValueArray args; args.resize(sizeof...(Args)); nativevalue_to_se_args_v(args, inargs...); - se::Value func; - __jsbObj->getProperty(jsFunctionName, &func); - if (func.isObject() && func.toObject()->isFunction()) { - func.toObject()->call(args, nullptr); - } - return; + invokeJsCallback(obj, jsFunctionName, args); } -void callJSfunc(const char* jsFunctionName) { // NOLINT(readability-identifier-naming) +void callJSfunc(se::Object* obj, const char* jsFunctionName) { // NOLINT(readability-identifier-naming) if (!se::ScriptEngine::getInstance()->isValid()) { return; } se::AutoHandleScope scope; - se::ValueArray args; - se::Value func; - __jsbObj->getProperty(jsFunctionName, &func); - if (func.isObject() && func.toObject()->isFunction()) { - func.toObject()->call(args, nullptr); - } + invokeJsCallback(obj, jsFunctionName, se::ValueArray()); } -template void callJSfunc(const char*, BillingResult*&&); -template void callJSfunc(const char*, BillingResult*&&, const std::vector&); -template void callJSfunc(const char*, BillingResult*&&, const std::vector&); -template void callJSfunc(const char*, BillingResult*&&, const std::string&); -template void callJSfunc(const char*, BillingResult*&&, BillingConfig*&&); -template void callJSfunc(const char*, BillingResult*&&, AlternativeBillingOnlyReportingDetails*&&); -template void callJSfunc(const char*, BillingResult*&&, ExternalOfferReportingDetails*&&); -template void callJSfunc(const char*, InAppMessageResult*&&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, const std::vector&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, const std::vector&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, const std::string&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, BillingConfig*&&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, AlternativeBillingOnlyReportingDetails*&&); +template void callJSfunc(se::Object* obj, const char*, BillingResult*&&, ExternalOfferReportingDetails*&&); +template void callJSfunc(se::Object* obj, const char*, InAppMessageResult*&&); +} // namespace -void GoogleBillingHelper::removeProductDetails(int productDetailsID) { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "removeProductDetails", productDetailsID); -} +int GoogleBillingHelper::createGoogleBilling(BillingClient::Builder* builder) { + int tag = JniHelper::callStaticIntMethod(JCLS_BILLING, "newTag"); + jobject buildObj = JniBilling::newBillingClientBuilderObject(tag, builder); -void GoogleBillingHelper::removePurchase(int purchaseID) { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "removePurchase", purchaseID); -} - - -void GoogleBillingHelper::startConnection() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "startConnection"); -} - -void GoogleBillingHelper::endConnection() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "endConnection"); -} - -int GoogleBillingHelper::getConnectionState() { - return JniHelper::callStaticIntMethod(JCLS_BILLING, "getConnectionState"); -} - -bool GoogleBillingHelper::isReady() { - return JniHelper::callStaticBooleanMethod(JCLS_BILLING, "isReady"); -} - -void GoogleBillingHelper::queryProductDetailsParams(const std::vector& productIds, const std::string& type) { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "queryProductDetailsParams", productIds, type); -} - -void GoogleBillingHelper::queryPurchasesAsync(const std::string& productType) { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "queryPurchasesAsync", productType); -} - -void GoogleBillingHelper::getBillingConfigAsync() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "getBillingConfigAsync"); -} - -void GoogleBillingHelper::createAlternativeBillingOnlyReportingDetailsAsync() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "createAlternativeBillingOnlyReportingDetailsAsync"); -} - -void GoogleBillingHelper::isAlternativeBillingOnlyAvailableAsync() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "isAlternativeBillingOnlyAvailableAsync"); -} - -void GoogleBillingHelper::createExternalOfferReportingDetailsAsync() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "createExternalOfferReportingDetailsAsync"); -} - -void GoogleBillingHelper::isExternalOfferAvailableAsync() { - JniHelper::callStaticVoidMethod(JCLS_BILLING, "isExternalOfferAvailableAsync"); -} - -BillingResult* GoogleBillingHelper::showAlternativeBillingOnlyInformationDialog() { - return callFunctionAndReturnBillingResult("showAlternativeBillingOnlyInformationDialog"); -} - -BillingResult* GoogleBillingHelper::showExternalOfferInformationDialog() { - return callFunctionAndReturnBillingResult("showExternalOfferInformationDialog"); -} - -BillingResult* GoogleBillingHelper::showInAppMessages() { - return callFunctionAndReturnBillingResult("showInAppMessages"); -} - -void GoogleBillingHelper::launchBillingFlow(const std::vector& productDetailsList, const std::string& selectedOfferToken) { - if (productDetailsList.empty()) { - return; - } - auto* env = JniHelper::getEnv(); - const int size = productDetailsList.size(); - jintArray result = env->NewIntArray(size); - jint* buf = new jint[size]; - for (int i = 0; i < size; ++i) { - buf[i] = productDetailsList[i]->_id; - } - env->SetIntArrayRegion(result, 0, size, buf); - delete[] buf; cc::JniMethodInfo t; - cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "launchBillingFlow", "([ILjava/lang/String;)V"); - jstring offerToken = env->NewStringUTF(selectedOfferToken.c_str()); - t.env->CallStaticVoidMethod(t.classID, t.methodID, result, offerToken); + cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "createGoogleBilling", "(ILcom/android/billingclient/api/BillingClient$Builder;)V"); + t.env->CallStaticVoidMethod(t.classID, t.methodID, tag, buildObj); + + return tag; } -void GoogleBillingHelper::consumePurchases(const std::vector& purchases) { - if (purchases.empty()) { - return; - } - auto* env = JniHelper::getEnv(); - const int size = purchases.size(); - jintArray result = env->NewIntArray(size); - jint* buf = new jint[size]; - for (int i = 0; i < size; ++i) { - buf[i] = purchases[i]->_id; - } - env->SetIntArrayRegion(result, 0, size, buf); - delete[] buf; - cc::JniMethodInfo t; - cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "consumePurchases", "([I)V"); - t.env->CallStaticVoidMethod(t.classID, t.methodID, result); +void GoogleBillingHelper::removeGoogleBilling(int tag) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "removeGoogleBilling", tag); } -void GoogleBillingHelper::acknowledgePurchase(const std::vector& purchases) { - if (purchases.empty()) { - return; - } - auto* env = JniHelper::getEnv(); - const int size = purchases.size(); - jintArray result = env->NewIntArray(size); - jint* buf = new jint[size]; - for (int i = 0; i < size; ++i) { - buf[i] = purchases[i]->_id; - } - env->SetIntArrayRegion(result, 0, size, buf); - delete[] buf; - cc::JniMethodInfo t; - cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "acknowledgePurchases", "([I)V"); - t.env->CallStaticVoidMethod(t.classID, t.methodID, result); +void GoogleBillingHelper::removeProductDetails(int tag, int productDetailsID) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "removeProductDetails", tag, productDetailsID); } -BillingResult* GoogleBillingHelper::callFunctionAndReturnBillingResult(const std::string& functionName) { +void GoogleBillingHelper::removePurchase(int tag, int purchaseID) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "removePurchase", tag, purchaseID); +} + +void GoogleBillingHelper::startConnection(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "startConnection", tag, callbackId); +} + +void GoogleBillingHelper::endConnection(int tag) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "endConnection", tag); +} + +int GoogleBillingHelper::getConnectionState(int tag) { + return JniHelper::callStaticIntMethod(JCLS_BILLING, "getConnectionState", tag); +} + +bool GoogleBillingHelper::isReady(int tag) { + return JniHelper::callStaticBooleanMethod(JCLS_BILLING, "isReady", tag); +} + +void GoogleBillingHelper::queryProductDetailsAsync(int tag, int callbackId, const std::vector& productIds, const std::vector& productTypes) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "queryProductDetailsAsync", tag, callbackId, productIds, productTypes); +} + +void GoogleBillingHelper::queryPurchasesAsync(int tag, int callbackId, const std::string& productType) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "queryPurchasesAsync", tag, callbackId, productType); +} + +void GoogleBillingHelper::getBillingConfigAsync(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "getBillingConfigAsync", tag, callbackId); +} + +void GoogleBillingHelper::createAlternativeBillingOnlyReportingDetailsAsync(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "createAlternativeBillingOnlyReportingDetailsAsync", tag, callbackId); +} + +void GoogleBillingHelper::isAlternativeBillingOnlyAvailableAsync(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "isAlternativeBillingOnlyAvailableAsync", tag, callbackId); +} + +void GoogleBillingHelper::createExternalOfferReportingDetailsAsync(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "createExternalOfferReportingDetailsAsync", tag, callbackId); +} + +void GoogleBillingHelper::isExternalOfferAvailableAsync(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "isExternalOfferAvailableAsync", tag, callbackId); +} + +void GoogleBillingHelper::showAlternativeBillingOnlyInformationDialog(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "showAlternativeBillingOnlyInformationDialog", tag, callbackId); +} + +void GoogleBillingHelper::showExternalOfferInformationDialog(int tag, int callbackId) { + JniHelper::callStaticVoidMethod(JCLS_BILLING, "showExternalOfferInformationDialog", tag, callbackId); +} + +void GoogleBillingHelper::showInAppMessages(int tag, int callbackId, const std::vector& inAppMessageCategoryId) { auto* env = JniHelper::getEnv(); cc::JniMethodInfo t; - if (cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, functionName.c_str(), "()Lcom/android/billingclient/api/BillingResult;")) { - jobject obj = t.env->CallStaticObjectMethod(t.classID, t.methodID); - return toBillingResult(env, obj); + if (cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "showInAppMessages", "(II[I)V")) { + const int size = inAppMessageCategoryId.size(); + jintArray result = env->NewIntArray(size); + env->SetIntArrayRegion(result, 0, inAppMessageCategoryId.size(), inAppMessageCategoryId.data()); + t.env->CallStaticVoidMethod(t.classID, t.methodID, tag, callbackId, result); } - return nullptr; } -BillingResult* GoogleBillingHelper::isFeatureSupported(const std::string& feature) { +void GoogleBillingHelper::launchBillingFlow(int tag, BillingFlowParams* params) { + cc::JniMethodInfo t1; + cc::JniHelper::getStaticMethodInfo(t1, JCLS_BILLING, "launchBillingFlow", "(ILcom/android/billingclient/api/BillingFlowParams;)V"); + t1.env->CallStaticVoidMethod(t1.classID, t1.methodID, tag, JniBilling::newBillingFlowParamsObject(tag, params)); +} + +void GoogleBillingHelper::consumeAsync(int tag, int callbackId, ConsumeParams* purchase) { + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "consumeAsync", "(IILjava/lang/String;)V"); + jstring purchaseToken = cc::StringUtils::newStringUTFJNI(t.env, purchase->getPurchaseToken()); + t.env->CallStaticVoidMethod(t.classID, t.methodID, tag, callbackId, purchaseToken); +} + +void GoogleBillingHelper::acknowledgePurchase(int tag, int callbackId, AcknowledgePurchaseParams* purchase) { + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "acknowledgePurchase", "(IILjava/lang/String;)V"); + jstring purchaseToken = cc::StringUtils::newStringUTFJNI(t.env, purchase->getPurchaseToken()); + t.env->CallStaticVoidMethod(t.classID, t.methodID, tag, callbackId, purchaseToken); +} + +BillingResult* GoogleBillingHelper::isFeatureSupported(int tag, const std::string& feature) { auto* env = JniHelper::getEnv(); cc::JniMethodInfo t; - if (cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "isFeatureSupported", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingResult;")) { + if (cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, "isFeatureSupported", "(ILjava/lang/String;)Lcom/android/billingclient/api/BillingResult;")) { jstring jFeature = cc::StringUtils::newStringUTFJNI(env, feature); - jobject obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, jFeature); - return toBillingResult(env, obj); + jobject obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, tag, jFeature); + return cc::JniBilling::toBillingResult(env, obj); } return nullptr; } -void GoogleBillingHelper::onBillingSetupFinished(JNIEnv* env, jclass clazz, jobject billingResultObj) { - cc::callJSfunc("onBillingSetupFinished", toBillingResult(env, billingResultObj)); +void GoogleBillingHelper::onBillingSetupFinished(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onBillingSetupFinished", env, clazz, tag, callbackId, billingResultObj); } -void GoogleBillingHelper::onBillingServiceDisconnected(JNIEnv* env, jclass clazz) { - cc::callJSfunc("onBillingServiceDisconnected"); +void GoogleBillingHelper::onBillingServiceDisconnected(JNIEnv* env, jclass clazz, jint tag, jint callbackId) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + cc::callJSfunc(it->second.get(), "onBillingServiceDisconnected"); + billingClient->_listeners.erase(it); + } + } } void GoogleBillingHelper::onProductDetailsResponse(JNIEnv* env, jclass clazz, - jobject billingResultObj, - jobject productDetailsListObj, - jint startID) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - std::vector productDetailsList = cc::GoogleBillingHelper::toProductDetailList(env, productDetailsListObj, startID); - cc::callJSfunc("onProductDetailsResponse", billingResult, productDetailsList); + jint tag, + jint callbackId, + jobject billingResultObj, + jobject productDetailsListObj, + jint startID) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + std::vector productDetailsList = cc::JniBilling::toProductDetailList(env, productDetailsListObj, tag, startID); + cc::callJSfunc(it->second.get(), "onProductDetailsResponse", billingResult, productDetailsList); + billingClient->_listeners.erase(it); + } + } } void GoogleBillingHelper::onPurchasesUpdated(JNIEnv* env, jclass clazz, - jobject billingResultObj, - jobject purchasesListObj, - jint startID) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - if (purchasesListObj != nullptr) { - std::vector purchasesList = cc::GoogleBillingHelper::toPurchaseList(env, purchasesListObj, startID); - cc::callJSfunc("onPurchasesUpdated", billingResult, purchasesList); - } else { - cc::callJSfunc("onPurchasesUpdated", billingResult, std::vector()); + jint tag, + jobject billingResultObj, + jobject purchasesListObj, + jint startID) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient && billingClient->_purchasesUpdatedListener) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + std::vector purchasesList; + if (purchasesListObj != nullptr) { + purchasesList = cc::JniBilling::toPurchaseList(env, purchasesListObj, tag, startID); + } + cc::callJSfunc(billingClient->_purchasesUpdatedListener.get(), "onPurchasesUpdated", billingResult, purchasesList); } } -void GoogleBillingHelper::onConsumeResponse(JNIEnv* env, jclass clazz, jobject billingResultObj, jstring purchaseToken) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast(purchaseToken))); -} - -void GoogleBillingHelper::onQueryPurchasesResponse(JNIEnv* env, jclass clazz, jobject billingResultObj, jobject purchasesListObj, jint startID) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - std::vector purchasesList = cc::GoogleBillingHelper::toPurchaseList(env, purchasesListObj, startID); - cc::callJSfunc("onQueryPurchasesResponse", billingResult, purchasesList); -} - -void GoogleBillingHelper::onAcknowledgePurchaseResponse(JNIEnv* env, jclass clazz, jobject billingResultObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onAcknowledgePurchaseResponse", billingResult); -} - -void GoogleBillingHelper::onBillingConfigResponse(JNIEnv* env, jclass clazz, jobject billingResultObj, jobject billingConfigObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::BillingConfig* billingConfig = nullptr; - if (billingConfigObj) { - billingConfig = cc::GoogleBillingHelper::toBillingConfig(env, billingConfigObj); +void GoogleBillingHelper::userSelectedAlternativeBilling(JNIEnv* env, jclass clazz, jint tag, jobject userChoiceDetailsObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient && billingClient->_userChoiceBillingListener) { + auto* userChoiceDetails = cc::JniBilling::toUserChoiceDetails(env, userChoiceDetailsObj); + cc::callJSfunc(billingClient->_userChoiceBillingListener.get(), "userSelectedAlternativeBilling", userChoiceDetails); } - cc::callJSfunc("onBillingConfigResponse", billingResult, billingConfig); -} -void GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(JNIEnv* env, jclass clazz, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::AlternativeBillingOnlyReportingDetails* toAlternativeBillingOnlyReporting = nullptr; - if (alternativeBillingOnlyReportingDetailsObj) { - toAlternativeBillingOnlyReporting = cc::GoogleBillingHelper::toAlternativeBillingOnlyReportingDetails(env, alternativeBillingOnlyReportingDetailsObj); - } - cc::callJSfunc("onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting); } -void GoogleBillingHelper::onExternalOfferReportingDetailsResponse(JNIEnv* env, jclass clazz, jobject billingResultObj, jobject externalOfferReportingDetailsObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::ExternalOfferReportingDetails* externalOfferReportingDetails = nullptr; - if (externalOfferReportingDetailsObj) { - externalOfferReportingDetails = cc::GoogleBillingHelper::toExternalOfferReportingDetails(env, externalOfferReportingDetailsObj); - } - cc::callJSfunc("onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails); -} - -void GoogleBillingHelper::onAlternativeBillingOnlyAvailabilityResponse(JNIEnv* env, jclass clazz, jobject billingResultObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onAlternativeBillingOnlyAvailabilityResponse", billingResult); -} - -void GoogleBillingHelper::onExternalOfferAvailabilityResponse(JNIEnv* env, jclass clazz, jobject billingResultObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onExternalOfferAvailabilityResponse", billingResult); -} - -void GoogleBillingHelper::onAlternativeBillingOnlyInformationDialogResponse(JNIEnv* env, jclass clazz, jobject billingResultObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onAlternativeBillingOnlyInformationDialogResponse", billingResult); -} - -void GoogleBillingHelper::onExternalOfferInformationDialogResponse(JNIEnv* env, jclass clazz, jobject billingResultObj) { - auto* billingResult = cc::GoogleBillingHelper::toBillingResult(env, billingResultObj); - cc::callJSfunc("onExternalOfferInformationDialogResponse", billingResult); -} - -void GoogleBillingHelper::onInAppMessageResponse(JNIEnv* env, jclass clazz, jobject inAppMessageResultObj) { - auto* inAppMessageResult = cc::GoogleBillingHelper::toInAppMessageResult(env, inAppMessageResultObj); - cc::callJSfunc("onInAppMessageResponse", inAppMessageResult); -} - -cc::BillingResult* GoogleBillingHelper::toBillingResult(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* billingResult = ccnew cc::BillingResult; - billingResult->debugMessage = callStringMethod(env, clazz, obj, "getDebugMessage"); - billingResult->responseCode = callIntMethod(env, clazz, obj, "getResponseCode"); - billingResult->toString = callStringMethod(env, clazz, obj, "toString"); - return billingResult; -} - -cc::OneTimePurchaseOfferDetails* GoogleBillingHelper::toOneTimePurchaseOfferDetails(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto oneTimePurchaseOfferDetails = new cc::OneTimePurchaseOfferDetails; - oneTimePurchaseOfferDetails->formattedPrice = callStringMethod(env, clazz, obj, "getFormattedPrice"); - oneTimePurchaseOfferDetails->priceAmountMicros = callLongMethod(env, clazz, obj, "getPriceAmountMicros"); - oneTimePurchaseOfferDetails->priceCurrencyCode = callStringMethod(env, clazz, obj, "getPriceCurrencyCode"); - return oneTimePurchaseOfferDetails; -} - -cc::InstallmentPlanDetails* GoogleBillingHelper::toInstallmentPlanDetails(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* installmentPlanDetails = new cc::InstallmentPlanDetails; - installmentPlanDetails->installmentPlanCommitmentPaymentsCount = callIntMethod(env, clazz, obj, "getInstallmentPlanCommitmentPaymentsCount"); - installmentPlanDetails->subsequentInstallmentPlanCommitmentPaymentsCount = callIntMethod(env, clazz, obj, "subsequentInstallmentPlanCommitmentPaymentsCount"); - return installmentPlanDetails; -} - -cc::PricingPhase* GoogleBillingHelper::toPricingPhase(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - - auto* pricingPhase = new cc::PricingPhase; - pricingPhase->billingCycleCount = callIntMethod(env, clazz, obj, "getBillingCycleCount"); - pricingPhase->billingPeriod = callStringMethod(env, clazz, obj, "getBillingPeriod"); - pricingPhase->formattedPrice = callStringMethod(env, clazz, obj, "getFormattedPrice"); - pricingPhase->priceAmountMicros = callLongMethod(env, clazz, obj, "getPriceAmountMicros"); - pricingPhase->priceCurrencyCode = callStringMethod(env, clazz, obj, "getPriceCurrencyCode"); - pricingPhase->recurrenceMode = callIntMethod(env, clazz, obj, "getRecurrenceMode"); - return pricingPhase; -} - -cc::PricingPhases* GoogleBillingHelper::toPricingPhases(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - - auto* pricingPhases = new cc::PricingPhases; - jmethodID methodId = env->GetMethodID(clazz, "getPricingPhaseList", "()Ljava/util/List;"); - jobject listObj = env->CallObjectMethod(obj, methodId); - jclass listClazz = env->GetObjectClass(listObj); - jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, listClazz, listObj, "size"); - for (int i = 0; i < size; ++i) { - jobject pricingPhaseObj = env->CallObjectMethod(listObj, listGetMethod, i); - cc::PricingPhase* pricingPhase = toPricingPhase(env, pricingPhaseObj); - pricingPhases->pricingPhaseList.push_back(pricingPhase); - } - return pricingPhases; -} - -cc::SubscriptionOfferDetails* GoogleBillingHelper::toSubscriptionOfferDetails(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* details = ccnew cc::SubscriptionOfferDetails; - details->basePlanId = callStringMethod(env, clazz, obj, - "getBasePlanId"); - - jobject installmentPlanDetailsObj = callObjectMethod(env, clazz, obj, "getInstallmentPlanDetails", "com/android/billingclient/api/ProductDetails$InstallmentPlanDetails;"); - if (installmentPlanDetailsObj != nullptr) { - details->installmentPlanDetails.reset(toInstallmentPlanDetails(env, installmentPlanDetailsObj)); - } - details->offerId = callStringMethod(env, clazz, obj, "getOfferId"); - - jmethodID methodId = env->GetMethodID(clazz, "getOfferTags", "()Ljava/util/List;"); - jobject listObj = env->CallObjectMethod(obj, methodId); - jclass listClazz = env->GetObjectClass(listObj); - jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, listClazz, listObj, "size"); - for (int i = 0; i < size; ++i) { - jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); - details->offerTags.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); - } - details->offerToken = callStringMethod(env, clazz, obj, "getOfferToken"); - jobject pricingPhasesObj = callObjectMethod(env, clazz, obj, "getPricingPhases", "com/android/billingclient/api/ProductDetails$PricingPhases;"); - details->pricingPhases.reset(toPricingPhases(env, pricingPhasesObj)); - - return details; -} - -std::vector GoogleBillingHelper::toProductDetailList(JNIEnv* env, jobject productListObj, jint startID) { - jclass clazz = env->GetObjectClass(productListObj); - jmethodID listGetMethod = env->GetMethodID(clazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, clazz, productListObj, "size"); - std::vector productDetailsList; - for (int i = 0; i < size; ++i) { - jobject productDetailObj = env->CallObjectMethod(productListObj, listGetMethod, i); - cc::ProductDetails* productDetails = cc::GoogleBillingHelper::toProductDetail(env, productDetailObj); - productDetails->_id = startID++; - productDetailsList.push_back(productDetails); - } - return std::move(productDetailsList); -} - -cc::ProductDetails* GoogleBillingHelper::toProductDetail(JNIEnv* env, jobject productObj) { - jclass clazz = env->GetObjectClass(productObj); - auto* productDetails = new cc::ProductDetails; - - productDetails->hashCode = callIntMethod(env, clazz, productObj, "hashCode"); - productDetails->description = callStringMethod(env, clazz, productObj, "getDescription"); - productDetails->name = callStringMethod(env, clazz, productObj, "getName"); - productDetails->productId = callStringMethod(env, clazz, productObj, "getProductId"); - productDetails->productType = callStringMethod(env, clazz, productObj, "getProductType"); - productDetails->title = callStringMethod(env, clazz, productObj, "getTitle"); - productDetails->toString = callStringMethod(env, clazz, productObj, "toString"); - - jmethodID methodId = env->GetMethodID(clazz, "getOneTimePurchaseOfferDetails", "()Lcom/android/billingclient/api/ProductDetails$OneTimePurchaseOfferDetails;"); - jobject oneTimePurchaseOfferDetailsObj = env->CallObjectMethod(productObj, methodId); - if (oneTimePurchaseOfferDetailsObj != nullptr) { - productDetails->oneTimePurchaseOfferDetails.reset(toOneTimePurchaseOfferDetails(env, oneTimePurchaseOfferDetailsObj)); - } - - jmethodID getSubscriptionOfferDetails = env->GetMethodID(clazz, "getSubscriptionOfferDetails", "()Ljava/util/List;"); - jobject listObj = env->CallObjectMethod(productObj, getSubscriptionOfferDetails); - if (listObj != nullptr) { - jclass listClazz = env->GetObjectClass(listObj); - jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, listClazz, listObj, "size"); - std::vector details; - for (int i = 0; i < size; ++i) { - jobject subscriptionOfferDetailsObj = env->CallObjectMethod(listObj, listGetMethod, i); - cc::SubscriptionOfferDetails* detail = toSubscriptionOfferDetails(env, subscriptionOfferDetailsObj); - productDetails->subscriptionOfferDetails.push_back(detail); +void GoogleBillingHelper::onConsumeResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jstring purchaseToken) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + cc::callJSfunc(it->second.get(), "onConsumeResponse", billingResult, cc::StringUtils::getStringUTFCharsJNI(env, static_cast(purchaseToken))); + billingClient->_listeners.erase(it); } } - - return productDetails; } -cc::AccountIdentifiers* GoogleBillingHelper::toAccountIdentifiers(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* accountIdentifiers = new cc::AccountIdentifiers; - accountIdentifiers->obfuscatedAccountId = callStringMethod(env, clazz, obj, "getObfuscatedAccountId"); - accountIdentifiers->obfuscatedProfileId = callStringMethod(env, clazz, obj, "getObfuscatedProfileId"); - return accountIdentifiers; +void GoogleBillingHelper::onAcknowledgePurchaseResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onAcknowledgePurchaseResponse", env, clazz, tag, callbackId, billingResultObj); } -cc::PendingPurchaseUpdate* GoogleBillingHelper::toPendingPurchaseUpdate(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* pendingPurchaseUpdate = new cc::PendingPurchaseUpdate; - jmethodID methodId = env->GetMethodID(clazz, "getProducts", "()Ljava/util/ArrayList;"); - jobject listObj = env->CallObjectMethod(obj, methodId); - jclass listClazz = env->GetObjectClass(listObj); - jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/String;"); - int size = callIntMethod(env, listClazz, listObj, "size"); - for (int i = 0; i < size; ++i) { - jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); - pendingPurchaseUpdate->products.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); +void GoogleBillingHelper::onQueryPurchasesResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject purchasesListObj, jint startID) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + std::vector purchasesList = cc::JniBilling::toPurchaseList(env, purchasesListObj, tag, startID); + cc::callJSfunc(it->second.get(), "onQueryPurchasesResponse", billingResult, purchasesList); + billingClient->_listeners.erase(it); + } } - pendingPurchaseUpdate->purchaseToken = callStringMethod(env, clazz, obj, "getPurchaseToken"); - return pendingPurchaseUpdate; } -std::vector GoogleBillingHelper::toPurchaseList(JNIEnv* env, jobject productsListObj, jint startID) { - jclass clazz = env->GetObjectClass(productsListObj); - jmethodID listGetMethod = env->GetMethodID(clazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, clazz, productsListObj, "size"); - std::vector purchases; - for (int i = 0; i < size; ++i) { - jobject purchaseObj = env->CallObjectMethod(productsListObj, listGetMethod, i); - cc::Purchase* purchase = cc::GoogleBillingHelper::toPurchase(env, purchaseObj); - purchase->_id = startID++; - purchases.push_back(purchase); +void GoogleBillingHelper::onBillingConfigResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject billingConfigObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + cc::BillingConfig* billingConfig = nullptr; + if (billingConfigObj) { + billingConfig = cc::JniBilling::toBillingConfig(env, billingConfigObj); + } + cc::callJSfunc(it->second.get(), "onBillingConfigResponse", billingResult, billingConfig); + billingClient->_listeners.erase(it); + } } - return std::move(purchases); } -cc::Purchase* GoogleBillingHelper::toPurchase(JNIEnv* env, jobject purchaseObj) { - jclass clazz = env->GetObjectClass(purchaseObj); - auto* purchase = new cc::Purchase; - - jmethodID getAccountIdentifiers = env->GetMethodID(clazz, "getAccountIdentifiers", "()Lcom/android/billingclient/api/AccountIdentifiers;"); - jobject accountIdentifiersObj = env->CallObjectMethod(purchaseObj, getAccountIdentifiers); - if (accountIdentifiersObj) { - purchase->accountIdentifiers.reset(toAccountIdentifiers(env, accountIdentifiersObj)); +void GoogleBillingHelper::onAlternativeBillingOnlyTokenResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + cc::AlternativeBillingOnlyReportingDetails* toAlternativeBillingOnlyReporting = nullptr; + if (alternativeBillingOnlyReportingDetailsObj) { + toAlternativeBillingOnlyReporting = cc::JniBilling::toAlternativeBillingOnlyReportingDetails(env, alternativeBillingOnlyReportingDetailsObj); + } + cc::callJSfunc(it->second.get(), "onAlternativeBillingOnlyTokenResponse", billingResult, toAlternativeBillingOnlyReporting); + billingClient->_listeners.erase(it); + } } +} - purchase->developerPayload = callStringMethod(env, clazz, purchaseObj, "getDeveloperPayload"); - purchase->orderId = callStringMethod(env, clazz, purchaseObj, "getOrderId"); - purchase->originalJson = callStringMethod(env, clazz, purchaseObj, "getOriginalJson"); - purchase->packageName = callStringMethod(env, clazz, purchaseObj, "getPackageName"); - - jmethodID getPendingPurchaseUpdate = env->GetMethodID(clazz, "getPendingPurchaseUpdate", "()Lcom/android/billingclient/api/Purchase$PendingPurchaseUpdate;"); - jobject pendingPurchaseUpdateObj = env->CallObjectMethod(purchaseObj, getPendingPurchaseUpdate); - if (pendingPurchaseUpdateObj) { - purchase->pendingPurchaseUpdate.reset(toPendingPurchaseUpdate(env, pendingPurchaseUpdateObj)); +void GoogleBillingHelper::onExternalOfferReportingDetailsResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject externalOfferReportingDetailsObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + cc::ExternalOfferReportingDetails* externalOfferReportingDetails = nullptr; + if (externalOfferReportingDetailsObj) { + externalOfferReportingDetails = cc::JniBilling::toExternalOfferReportingDetails(env, externalOfferReportingDetailsObj); + } + cc::callJSfunc(it->second.get(), "onExternalOfferReportingDetailsResponse", billingResult, externalOfferReportingDetails); + billingClient->_listeners.erase(it); + } } +} - jmethodID methodId = env->GetMethodID(clazz, "getProducts", "()Ljava/util/List;"); - jobject listObj = env->CallObjectMethod(purchaseObj, methodId); - jclass listClazz = env->GetObjectClass(listObj); - jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); - int size = callIntMethod(env, listClazz, listObj, "size"); - auto& products = purchase->products; - for (int i = 0; i < size; ++i) { - jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); - products.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); +void GoogleBillingHelper::onAlternativeBillingOnlyAvailabilityResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onAlternativeBillingOnlyAvailabilityResponse", env, clazz, tag, callbackId, billingResultObj); +} + +void GoogleBillingHelper::onExternalOfferAvailabilityResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onExternalOfferAvailabilityResponse", env, clazz, tag, callbackId, billingResultObj); +} + +void GoogleBillingHelper::onAlternativeBillingOnlyInformationDialogResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onAlternativeBillingOnlyInformationDialogResponse", env, clazz, tag, callbackId, billingResultObj); +} + +void GoogleBillingHelper::onExternalOfferInformationDialogResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + responseOnlyWithBillingResult("onExternalOfferInformationDialogResponse", env, clazz, tag, callbackId, billingResultObj); +} + +void GoogleBillingHelper::onInAppMessageResponse(JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject inAppMessageResultObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* inAppMessageResult = cc::JniBilling::toInAppMessageResult(env, inAppMessageResultObj); + cc::callJSfunc(it->second.get(), "onInAppMessageResponse", inAppMessageResult); + billingClient->_listeners.erase(it); + } } - purchase->purchaseState = callIntMethod(env, clazz, purchaseObj, "getPurchaseState"); - purchase->purchaseTime = callLongMethod(env, clazz, purchaseObj, "getPurchaseTime"); - purchase->purchaseToken = callStringMethod(env, clazz, purchaseObj, "getPurchaseToken"); - purchase->quantity = callIntMethod(env, clazz, purchaseObj, "getQuantity"); - purchase->signature = callStringMethod(env, clazz, purchaseObj, "getSignature"); - purchase->hashCode = callIntMethod(env, clazz, purchaseObj, "hashCode"); - purchase->isAcknowledged = callBooleanMethod(env, clazz, purchaseObj, "isAcknowledged"); - purchase->isAutoRenewing = callBooleanMethod(env, clazz, purchaseObj, "isAutoRenewing"); - purchase->toString = callStringMethod(env, clazz, purchaseObj, "toString"); - return purchase; } -cc::BillingConfig* GoogleBillingHelper::toBillingConfig(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* billingConfig = new cc::BillingConfig; - billingConfig->countryCode = callStringMethod(env, clazz, obj, "getCountryCode"); - return billingConfig; -} - -cc::AlternativeBillingOnlyReportingDetails* GoogleBillingHelper::toAlternativeBillingOnlyReportingDetails(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* alternativeBillingOnlyReportingDetails = new cc::AlternativeBillingOnlyReportingDetails; - alternativeBillingOnlyReportingDetails->externalTransactionToken = callStringMethod(env, clazz, obj, "getExternalTransactionToken"); - return alternativeBillingOnlyReportingDetails; -} - -cc::ExternalOfferReportingDetails* GoogleBillingHelper::toExternalOfferReportingDetails(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* externalOfferReportingDetails = new cc::ExternalOfferReportingDetails; - externalOfferReportingDetails->externalTransactionToken = callStringMethod(env, clazz, obj, "getExternalTransactionToken"); - return externalOfferReportingDetails; -} - -cc::InAppMessageResult* GoogleBillingHelper::toInAppMessageResult(JNIEnv* env, jobject obj) { - jclass clazz = env->GetObjectClass(obj); - auto* inAppMessageResult = new cc::InAppMessageResult; - inAppMessageResult->responseCode = callIntMethod(env, clazz, obj, "getResponseCode"); - inAppMessageResult->purchaseToken = callStringMethod(env, clazz, obj, "getPurchaseToken"); - return inAppMessageResult; +void GoogleBillingHelper::responseOnlyWithBillingResult(const std::string& functionName, JNIEnv* env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj) { + auto* billingClient = GoogleBillingManager::getInstance()->getBillingClient(tag); + if (billingClient) { + auto it = billingClient->_listeners.find(callbackId); + if (it != billingClient->_listeners.end()) { + auto* billingResult = cc::JniBilling::toBillingResult(env, billingResultObj); + cc::callJSfunc(it->second.get(), functionName.c_str(), billingResult); + billingClient->_listeners.erase(it); + } + } } } // namespace cc diff --git a/native/vendor/google/billing/GoogleBillingHelper.h b/native/vendor/google/billing/GoogleBillingHelper.h index bd73a35a9b..d8a736b988 100644 --- a/native/vendor/google/billing/GoogleBillingHelper.h +++ b/native/vendor/google/billing/GoogleBillingHelper.h @@ -29,7 +29,7 @@ #include #include "base/Macros.h" - +#include "vendor/google/billing/GoogleBilling.h" namespace cc { class BillingResult; class ProductDetails; @@ -45,73 +45,66 @@ class BillingConfig; class AlternativeBillingOnlyReportingDetails; class ExternalOfferReportingDetails; class InAppMessageResult; +class BillingFlowParams; +class ConsumeParams; +class AcknowledgePurchaseParams; class CC_DLL GoogleBillingHelper { public: - static void removeProductDetails(int productDetailsID); - static void removePurchase(int purchaseID); - static void startConnection(); - static void endConnection(); - static int getConnectionState(); - static bool isReady(); - static void queryProductDetailsParams(const std::vector &productIds, const std::string &type); + static int createGoogleBilling(BillingClient::Builder *builder); + static void removeGoogleBilling(int tag); + static void removeProductDetails(int tag, int productDetailsID); + static void removePurchase(int tag, int purchaseID); + static void startConnection(int tag, int callbackID); + static void endConnection(int tag); + static int getConnectionState(int tag); + static bool isReady(int tag); + static void queryProductDetailsAsync(int tag, int callbackID, const std::vector &productIds, const std::vector &productTypes); - static void launchBillingFlow(const std::vector &productDetailsList, const std::string &selectedOfferToken); - static void consumePurchases(const std::vector &purchases); - static void acknowledgePurchase(const std::vector &purchases); - static void queryPurchasesAsync(const std::string &productType); - static void getBillingConfigAsync(); + static void launchBillingFlow(int tag, BillingFlowParams *params); + static void consumeAsync(int tag, int callbackId, ConsumeParams *purchase); + static void acknowledgePurchase(int tag, int callbackId, AcknowledgePurchaseParams *purchase); + static void queryPurchasesAsync(int tag, int callbackId, const std::string &productType); + static void getBillingConfigAsync(int tag, int callbackId); - static void createAlternativeBillingOnlyReportingDetailsAsync(); - static void isAlternativeBillingOnlyAvailableAsync(); - static void createExternalOfferReportingDetailsAsync(); - static void isExternalOfferAvailableAsync(); - static BillingResult *isFeatureSupported(const std::string &feature); + static void createAlternativeBillingOnlyReportingDetailsAsync(int tag, int callbackId); + static void isAlternativeBillingOnlyAvailableAsync(int tag, int callbackId); + static void createExternalOfferReportingDetailsAsync(int tag, int callbackId); + static void isExternalOfferAvailableAsync(int tag, int callbackId); + static BillingResult *isFeatureSupported(int tag, const std::string &feature); - static BillingResult *showAlternativeBillingOnlyInformationDialog(); - static BillingResult *showExternalOfferInformationDialog(); - static BillingResult *showInAppMessages(); + static void showAlternativeBillingOnlyInformationDialog(int tag, int callbackId); + static void showExternalOfferInformationDialog(int tag, int callbackId); + static void showInAppMessages(int tag, int callbackId, const std::vector &inAppMessageCategoryId); - static void onBillingSetupFinished(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onBillingServiceDisconnected(JNIEnv *env, jclass clazz); - static void onProductDetailsResponse(JNIEnv *env, jclass clazz, + static void onBillingSetupFinished(JNIEnv *env, jclass clazz, jint tag, jint callbackID, jobject billingResultObj); + static void onBillingServiceDisconnected(JNIEnv *env, jclass clazz, jint tag, jint callbackID); + static void onProductDetailsResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackID, jobject billingResultObj, jobject productDetailsListObj, jint startID); static void onPurchasesUpdated(JNIEnv *env, jclass clazz, + jint tag, jobject billingResultObj, jobject purchaseListObj, jint startID); - static void onConsumeResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jstring purchaseToken); - static void onQueryPurchasesResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject purchaseListObj, jint startID); - static void onAcknowledgePurchaseResponse(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onBillingConfigResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject billingConfigObj); - static void onAlternativeBillingOnlyTokenResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj); - static void onExternalOfferReportingDetailsResponse(JNIEnv *env, jclass clazz, jobject billingResultObj, jobject externalOfferReportingDetailsObj); - static void onAlternativeBillingOnlyAvailabilityResponse(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onExternalOfferAvailabilityResponse(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onAlternativeBillingOnlyInformationDialogResponse(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onExternalOfferInformationDialogResponse(JNIEnv *env, jclass clazz, jobject billingResultObj); - static void onInAppMessageResponse(JNIEnv *env, jclass clazz, jobject inAppMessageResultObj); + static void onConsumeResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jstring purchaseToken); + static void onQueryPurchasesResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject purchaseListObj, jint startID); + static void onAcknowledgePurchaseResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); + static void onBillingConfigResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject billingConfigObj); + static void onAlternativeBillingOnlyTokenResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject alternativeBillingOnlyReportingDetailsObj); + static void onExternalOfferReportingDetailsResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj, jobject externalOfferReportingDetailsObj); + static void onAlternativeBillingOnlyAvailabilityResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); + static void onExternalOfferAvailabilityResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); + static void onAlternativeBillingOnlyInformationDialogResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); + static void onExternalOfferInformationDialogResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); + static void onInAppMessageResponse(JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject inAppMessageResultObj); + static void userSelectedAlternativeBilling(JNIEnv *env, jclass clazz, jint tag, jobject userChoiceDetailsObj); + +private: + static void responseOnlyWithBillingResult(const std::string &functionName, JNIEnv *env, jclass clazz, jint tag, jint callbackId, jobject billingResultObj); private: - static BillingResult *toBillingResult(JNIEnv *env, jobject obj); - static std::vector toProductDetailList(JNIEnv *env, jobject productsObj, jint startID); - static std::vector toPurchaseList(JNIEnv *env, jobject productsObj, jint startID); - static BillingConfig *toBillingConfig(JNIEnv *env, jobject billingConfigObj); - static AlternativeBillingOnlyReportingDetails *toAlternativeBillingOnlyReportingDetails(JNIEnv *env, jobject alternativeBillingOnlyReportingDetailsObj); - static ExternalOfferReportingDetails *toExternalOfferReportingDetails(JNIEnv *env, jobject externalOfferReportingDetailsObj); - static InAppMessageResult *toInAppMessageResult(JNIEnv *env, jobject inAppMessageResultObj); - static ProductDetails *toProductDetail(JNIEnv *env, jobject productObj); - static Purchase *toPurchase(JNIEnv *env, jobject purchaseObj); - static OneTimePurchaseOfferDetails *toOneTimePurchaseOfferDetails(JNIEnv *env, jobject obj); - static InstallmentPlanDetails *toInstallmentPlanDetails(JNIEnv *env, jobject obj); - static SubscriptionOfferDetails *toSubscriptionOfferDetails(JNIEnv *env, jobject obj); - static AccountIdentifiers *toAccountIdentifiers(JNIEnv *env, jobject obj); - static PendingPurchaseUpdate *toPendingPurchaseUpdate(JNIEnv *env, jobject obj); - static PricingPhase *toPricingPhase(JNIEnv *env, jobject obj); - static PricingPhases *toPricingPhases(JNIEnv* env, jobject obj); - static BillingResult *callFunctionAndReturnBillingResult(const std::string &functionName); }; } // namespace cc diff --git a/native/vendor/google/billing/GoogleBillingManager.h b/native/vendor/google/billing/GoogleBillingManager.h new file mode 100644 index 0000000000..a502e93b45 --- /dev/null +++ b/native/vendor/google/billing/GoogleBillingManager.h @@ -0,0 +1,64 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { +class BillingClient; +class CC_DLL GoogleBillingManager { +public: + static GoogleBillingManager* getInstance() { + static GoogleBillingManager mgr; + return &mgr; + } + void pushBillingClient(int tag, BillingClient* client) { + _billingClients.insert(std::make_pair(tag, client)); + } + + void removeGoogleBilling(int tag) { + auto it = _billingClients.find(tag); + if (it != _billingClients.end()) { + _billingClients.erase(it); + } + } + + BillingClient* getBillingClient(int tag) { + auto it = _billingClients.find(tag); + if (it != _billingClients.end()) { + return it->second; + } + return nullptr; + } + +private: + std::unordered_map _billingClients; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/JniBilling.cpp b/native/vendor/google/billing/JniBilling.cpp new file mode 100644 index 0000000000..f902bcdcf3 --- /dev/null +++ b/native/vendor/google/billing/JniBilling.cpp @@ -0,0 +1,529 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ +#include "vendor/google/billing/JniBilling.h" + +#include "platform/java/jni/JniHelper.h" + +#include +#include "base/UTF8.h" +#include "base/memory/Memory.h" + +#include "cocos/bindings/jswrapper/SeApi.h" +#include "cocos/bindings/jswrapper/Value.h" +#include "cocos/bindings/manual/jsb_conversions.h" +#include "cocos/bindings/manual/jsb_global_init.h" +#include "vendor/google/billing/GoogleBilling.h" +#include "vendor/google/billing/build-params/PendingPurchasesParams.h" + +namespace { + +#ifndef JCLS_BILLING + #define JCLS_BILLING "google/billing/GoogleBillingHelper" +#endif +}; // namespace + +namespace cc { +namespace { +std::string callStringMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { + jmethodID methodId = env->GetMethodID(clazz, methodName, "()Ljava/lang/String;"); + jobject jStringObj = env->CallObjectMethod(obj, methodId); + if (jStringObj != nullptr) { + return cc::StringUtils::getStringUTFCharsJNI(env, static_cast(jStringObj)); + } + return ""; +} +jobject callObjectMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName, const char* returnType) { + std::string returnSign = cc::StringUtils::format("()L%s", returnType); + jmethodID methodId = env->GetMethodID(clazz, methodName, returnSign.c_str()); + return env->CallObjectMethod(obj, methodId); +} + +int callIntMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { + jmethodID methodId = env->GetMethodID(clazz, methodName, "()I"); + return env->CallIntMethod(obj, methodId); +} + +bool callBooleanMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { + jmethodID methodId = env->GetMethodID(clazz, methodName, "()Z"); + return env->CallBooleanMethod(obj, methodId); +} + +long callLongMethod(JNIEnv* env, jclass clazz, jobject obj, const char* methodName) { + jmethodID methodId = env->GetMethodID(clazz, methodName, "()J"); + return env->CallLongMethod(obj, methodId); +} + +} // namespace + +cc::BillingResult* JniBilling::toBillingResult(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* billingResult = ccnew cc::BillingResult; + billingResult->_debugMessage = callStringMethod(env, clazz, obj, "getDebugMessage"); + billingResult->_responseCode = callIntMethod(env, clazz, obj, "getResponseCode"); + billingResult->_toString = callStringMethod(env, clazz, obj, "toString"); + return billingResult; +} + +cc::ProductDetails::OneTimePurchaseOfferDetails* JniBilling::toOneTimePurchaseOfferDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto oneTimePurchaseOfferDetails = new cc::ProductDetails::OneTimePurchaseOfferDetails; + oneTimePurchaseOfferDetails->_formattedPrice = callStringMethod(env, clazz, obj, "getFormattedPrice"); + oneTimePurchaseOfferDetails->_priceAmountMicros = callLongMethod(env, clazz, obj, "getPriceAmountMicros"); + oneTimePurchaseOfferDetails->_priceCurrencyCode = callStringMethod(env, clazz, obj, "getPriceCurrencyCode"); + return oneTimePurchaseOfferDetails; +} + +cc::ProductDetails::InstallmentPlanDetails* JniBilling::toInstallmentPlanDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* installmentPlanDetails = new cc::ProductDetails::InstallmentPlanDetails; + installmentPlanDetails->_commitmentPaymentsCount = callIntMethod(env, clazz, obj, "getInstallmentPlanCommitmentPaymentsCount"); + installmentPlanDetails->_subsequentCommitmentPaymentsCount = callIntMethod(env, clazz, obj, "subsequentInstallmentPlanCommitmentPaymentsCount"); + return installmentPlanDetails; +} + +cc::ProductDetails::PricingPhase* JniBilling::toPricingPhase(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + + auto* pricingPhase = new cc::ProductDetails::PricingPhase; + pricingPhase->_billingCycleCount = callIntMethod(env, clazz, obj, "getBillingCycleCount"); + pricingPhase->_billingPeriod = callStringMethod(env, clazz, obj, "getBillingPeriod"); + pricingPhase->_formattedPrice = callStringMethod(env, clazz, obj, "getFormattedPrice"); + pricingPhase->_priceAmountMicros = callLongMethod(env, clazz, obj, "getPriceAmountMicros"); + pricingPhase->_priceCurrencyCode = callStringMethod(env, clazz, obj, "getPriceCurrencyCode"); + pricingPhase->_recurrenceMode = callIntMethod(env, clazz, obj, "getRecurrenceMode"); + return pricingPhase; +} + +cc::ProductDetails::PricingPhases* JniBilling::toPricingPhases(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + + auto* pricingPhases = new cc::ProductDetails::PricingPhases; + jmethodID methodId = env->GetMethodID(clazz, "getPricingPhaseList", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(obj, methodId); + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + for (int i = 0; i < size; ++i) { + jobject pricingPhaseObj = env->CallObjectMethod(listObj, listGetMethod, i); + cc::ProductDetails::PricingPhase* pricingPhase = toPricingPhase(env, pricingPhaseObj); + pricingPhases->_pricingPhaseList.push_back(pricingPhase); + } + return pricingPhases; +} + +cc::ProductDetails::SubscriptionOfferDetails* JniBilling::toSubscriptionOfferDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* details = ccnew cc::ProductDetails::SubscriptionOfferDetails; + details->_basePlanId = callStringMethod(env, clazz, obj, + "getBasePlanId"); + + jobject installmentPlanDetailsObj = callObjectMethod(env, clazz, obj, "getInstallmentPlanDetails", "com/android/billingclient/api/ProductDetails$InstallmentPlanDetails;"); + if (installmentPlanDetailsObj != nullptr) { + details->_installmentPlanDetails = toInstallmentPlanDetails(env, installmentPlanDetailsObj); + } + details->_offerId = callStringMethod(env, clazz, obj, "getOfferId"); + + jmethodID methodId = env->GetMethodID(clazz, "getOfferTags", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(obj, methodId); + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + for (int i = 0; i < size; ++i) { + jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); + details->_offerTags.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); + } + details->_offerToken = callStringMethod(env, clazz, obj, "getOfferToken"); + jobject pricingPhasesObj = callObjectMethod(env, clazz, obj, "getPricingPhases", "com/android/billingclient/api/ProductDetails$PricingPhases;"); + details->_pricingPhases = toPricingPhases(env, pricingPhasesObj); + + return details; +} + +std::vector JniBilling::toProductDetailList(JNIEnv* env, jobject productListObj, jint tag, jint startID) { + jclass clazz = env->GetObjectClass(productListObj); + jmethodID listGetMethod = env->GetMethodID(clazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, clazz, productListObj, "size"); + std::vector productDetailsList; + for (int i = 0; i < size; ++i) { + jobject productDetailObj = env->CallObjectMethod(productListObj, listGetMethod, i); + cc::ProductDetails* productDetails = cc::JniBilling::toProductDetail(env, productDetailObj); + productDetails->_id = startID++; + productDetails->_tag = tag; + productDetailsList.push_back(productDetails); + } + return std::move(productDetailsList); +} + +cc::ProductDetails* JniBilling::toProductDetail(JNIEnv* env, jobject productObj) { + jclass clazz = env->GetObjectClass(productObj); + auto* productDetails = new cc::ProductDetails; + + productDetails->_hashCode = callIntMethod(env, clazz, productObj, "hashCode"); + productDetails->_description = callStringMethod(env, clazz, productObj, "getDescription"); + productDetails->_name = callStringMethod(env, clazz, productObj, "getName"); + productDetails->_productId = callStringMethod(env, clazz, productObj, "getProductId"); + productDetails->_productType = callStringMethod(env, clazz, productObj, "getProductType"); + productDetails->_title = callStringMethod(env, clazz, productObj, "getTitle"); + productDetails->_toString = callStringMethod(env, clazz, productObj, "toString"); + + jmethodID methodId = env->GetMethodID(clazz, "getOneTimePurchaseOfferDetails", "()Lcom/android/billingclient/api/ProductDetails$OneTimePurchaseOfferDetails;"); + jobject oneTimePurchaseOfferDetailsObj = env->CallObjectMethod(productObj, methodId); + if (oneTimePurchaseOfferDetailsObj != nullptr) { + productDetails->_oneTimePurchaseOfferDetails = toOneTimePurchaseOfferDetails(env, oneTimePurchaseOfferDetailsObj); + } + + jmethodID getSubscriptionOfferDetails = env->GetMethodID(clazz, "getSubscriptionOfferDetails", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(productObj, getSubscriptionOfferDetails); + if (listObj != nullptr) { + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + for (int i = 0; i < size; ++i) { + jobject subscriptionOfferDetailsObj = env->CallObjectMethod(listObj, listGetMethod, i); + cc::ProductDetails::SubscriptionOfferDetails* detail = toSubscriptionOfferDetails(env, subscriptionOfferDetailsObj); + productDetails->_subscriptionOfferDetails.push_back(detail); + } + } + + return productDetails; +} + +cc::AccountIdentifiers* JniBilling::toAccountIdentifiers(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* accountIdentifiers = new cc::AccountIdentifiers; + accountIdentifiers->_obfuscatedAccountId = callStringMethod(env, clazz, obj, "getObfuscatedAccountId"); + accountIdentifiers->_obfuscatedProfileId = callStringMethod(env, clazz, obj, "getObfuscatedProfileId"); + return accountIdentifiers; +} + +cc::Purchase::PendingPurchaseUpdate* JniBilling::toPendingPurchaseUpdate(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* pendingPurchaseUpdate = new cc::Purchase::PendingPurchaseUpdate; + jmethodID methodId = env->GetMethodID(clazz, "getProducts", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(obj, methodId); + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/String;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + for (int i = 0; i < size; ++i) { + jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); + pendingPurchaseUpdate->_products.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); + } + pendingPurchaseUpdate->_purchaseToken = callStringMethod(env, clazz, obj, "getPurchaseToken"); + return pendingPurchaseUpdate; +} + +std::vector JniBilling::toPurchaseList(JNIEnv* env, jobject productsListObj, jint tag, jint startID) { + jclass clazz = env->GetObjectClass(productsListObj); + jmethodID listGetMethod = env->GetMethodID(clazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, clazz, productsListObj, "size"); + std::vector purchases; + for (int i = 0; i < size; ++i) { + jobject purchaseObj = env->CallObjectMethod(productsListObj, listGetMethod, i); + cc::Purchase* purchase = cc::JniBilling::toPurchase(env, purchaseObj); + purchase->_id = startID++; + purchase->_tag = tag; + purchases.push_back(purchase); + } + return std::move(purchases); +} + +cc::Purchase* JniBilling::toPurchase(JNIEnv* env, jobject purchaseObj) { + jclass clazz = env->GetObjectClass(purchaseObj); + auto* purchase = new cc::Purchase; + + jmethodID getAccountIdentifiers = env->GetMethodID(clazz, "getAccountIdentifiers", "()Lcom/android/billingclient/api/AccountIdentifiers;"); + jobject accountIdentifiersObj = env->CallObjectMethod(purchaseObj, getAccountIdentifiers); + if (accountIdentifiersObj) { + purchase->_accountIdentifiers = toAccountIdentifiers(env, accountIdentifiersObj); + } + + purchase->_developerPayload = callStringMethod(env, clazz, purchaseObj, "getDeveloperPayload"); + purchase->_orderId = callStringMethod(env, clazz, purchaseObj, "getOrderId"); + purchase->_originalJson = callStringMethod(env, clazz, purchaseObj, "getOriginalJson"); + purchase->_packageName = callStringMethod(env, clazz, purchaseObj, "getPackageName"); + + jmethodID getPendingPurchaseUpdate = env->GetMethodID(clazz, "getPendingPurchaseUpdate", "()Lcom/android/billingclient/api/Purchase$PendingPurchaseUpdate;"); + jobject pendingPurchaseUpdateObj = env->CallObjectMethod(purchaseObj, getPendingPurchaseUpdate); + if (pendingPurchaseUpdateObj) { + purchase->_pendingPurchaseUpdate = toPendingPurchaseUpdate(env, pendingPurchaseUpdateObj); + } + + jmethodID methodId = env->GetMethodID(clazz, "getProducts", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(purchaseObj, methodId); + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + auto& products = purchase->_products; + for (int i = 0; i < size; ++i) { + jobject strObj = env->CallObjectMethod(listObj, listGetMethod, i); + products.push_back(cc::StringUtils::getStringUTFCharsJNI(env, static_cast(strObj))); + } + purchase->_purchaseState = callIntMethod(env, clazz, purchaseObj, "getPurchaseState"); + purchase->_purchaseTime = callLongMethod(env, clazz, purchaseObj, "getPurchaseTime"); + purchase->_purchaseToken = callStringMethod(env, clazz, purchaseObj, "getPurchaseToken"); + purchase->_quantity = callIntMethod(env, clazz, purchaseObj, "getQuantity"); + purchase->_signature = callStringMethod(env, clazz, purchaseObj, "getSignature"); + purchase->_hashCode = callIntMethod(env, clazz, purchaseObj, "hashCode"); + purchase->_isAcknowledged = callBooleanMethod(env, clazz, purchaseObj, "isAcknowledged"); + purchase->_isAutoRenewing = callBooleanMethod(env, clazz, purchaseObj, "isAutoRenewing"); + purchase->_toString = callStringMethod(env, clazz, purchaseObj, "toString"); + return purchase; +} + +cc::BillingConfig* JniBilling::toBillingConfig(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* billingConfig = new cc::BillingConfig(""); + billingConfig->_countryCode = callStringMethod(env, clazz, obj, "getCountryCode"); + return billingConfig; +} + +cc::AlternativeBillingOnlyReportingDetails* JniBilling::toAlternativeBillingOnlyReportingDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* alternativeBillingOnlyReportingDetails = new cc::AlternativeBillingOnlyReportingDetails; + alternativeBillingOnlyReportingDetails->_externalTransactionToken = callStringMethod(env, clazz, obj, "getExternalTransactionToken"); + return alternativeBillingOnlyReportingDetails; +} + +cc::ExternalOfferReportingDetails* JniBilling::toExternalOfferReportingDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* externalOfferReportingDetails = new cc::ExternalOfferReportingDetails; + externalOfferReportingDetails->_externalTransactionToken = callStringMethod(env, clazz, obj, "getExternalTransactionToken"); + return externalOfferReportingDetails; +} + +cc::InAppMessageResult* JniBilling::toInAppMessageResult(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* inAppMessageResult = new cc::InAppMessageResult(0, ""); + inAppMessageResult->_responseCode = callIntMethod(env, clazz, obj, "getResponseCode"); + inAppMessageResult->_purchaseToken = callStringMethod(env, clazz, obj, "getPurchaseToken"); + return inAppMessageResult; +} + +cc::UserChoiceDetails::Product* JniBilling::toUserChoiceDetailsProduct(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* product = new cc::UserChoiceDetails::Product(); + product->_hashCode = callIntMethod(env, clazz, obj, "hashCode"); + product->_id = callStringMethod(env, clazz, obj, "getId"); + product->_offerToken = callStringMethod(env, clazz, obj, "getOfferToken"); + product->_type = callStringMethod(env, clazz, obj, "getType"); + product->_toString = callStringMethod(env, clazz, obj, "toString"); + return product; +} + +cc::UserChoiceDetails* JniBilling::toUserChoiceDetails(JNIEnv* env, jobject obj) { + jclass clazz = env->GetObjectClass(obj); + auto* userChoiceDetails = new cc::UserChoiceDetails(); + userChoiceDetails->_externalTransactionToken = callStringMethod(env, clazz, obj, "getExternalTransactionToken"); + userChoiceDetails->_originalExternalTransactionId = callStringMethod(env, clazz, obj, "getOriginalExternalTransactionId"); + + jmethodID methodId = env->GetMethodID(clazz, "getProducts", "()Ljava/util/List;"); + jobject listObj = env->CallObjectMethod(obj, methodId); + jclass listClazz = env->GetObjectClass(listObj); + jmethodID listGetMethod = env->GetMethodID(listClazz, "get", "(I)Ljava/lang/Object;"); + int size = callIntMethod(env, listClazz, listObj, "size"); + auto& products = userChoiceDetails->_products; + for (int i = 0; i < size; ++i) { + jobject productObj = env->CallObjectMethod(listObj, listGetMethod, i); + products.push_back(toUserChoiceDetailsProduct(env, productObj)); + } + return userChoiceDetails; +} + +BillingResult* JniBilling::callFunctionAndReturnBillingResult(const std::string& functionName, int tag, int callbackId) { + auto* env = JniHelper::getEnv(); + cc::JniMethodInfo t; + if (cc::JniHelper::getStaticMethodInfo(t, JCLS_BILLING, functionName.c_str(), "(II)Lcom/android/billingclient/api/BillingResult;")) { + jobject obj = t.env->CallStaticObjectMethod(t.classID, t.methodID, tag, callbackId); + return cc::JniBilling::toBillingResult(env, obj); + } + return nullptr; +} + +jobject JniBilling::newSubscriptionUpdateParamsObject(const BillingFlowParams::SubscriptionUpdateParams* params) { + if (!params) { + return nullptr; + } + auto* env = JniHelper::getEnv(); + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, "com/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams", "newBuilder", "()Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams$Builder;"); + jobject builder = t.env->CallStaticObjectMethod(t.classID, t.methodID); + jclass builderClass = env->GetObjectClass(builder); + + jmethodID setOldPurchaseTokenMethodId = env->GetMethodID(builderClass, "setOldPurchaseToken", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams$Builder;"); + env->CallObjectMethod(builder, setOldPurchaseTokenMethodId, cc::StringUtils::newStringUTFJNI(env, params->_purchaseToken)); + + jmethodID setOriginalExternalTransactionIdMethodId = env->GetMethodID(builderClass, "setOriginalExternalTransactionId", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams$Builder;"); + env->CallObjectMethod(builder, setOriginalExternalTransactionIdMethodId, cc::StringUtils::newStringUTFJNI(env, params->_externalTransactionId)); + + jmethodID setObfuscatedProfileIdMethodId = env->GetMethodID(builderClass, "setSubscriptionReplacementMode", "(I)Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams$Builder;"); + env->CallObjectMethod(builder, setObfuscatedProfileIdMethodId, params->_subscriptionReplacementMode); + + jmethodID buildMethodIdMethodId = env->GetMethodID(builderClass, "build", "()Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams;"); + return env->CallObjectMethod(builder, buildMethodIdMethodId); +} + +jobject JniBilling::newProductDetailsParamsObject(int tag, const BillingFlowParams::ProductDetailsParams* params) { + auto* env = JniHelper::getEnv(); + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, "com/android/billingclient/api/BillingFlowParams$ProductDetailsParams", "newBuilder", "()Lcom/android/billingclient/api/BillingFlowParams$ProductDetailsParams$Builder;"); + jobject builder = t.env->CallStaticObjectMethod(t.classID, t.methodID); + jclass builderClass = env->GetObjectClass(builder); + + if (!params->_offerToken.empty()) { + jmethodID setOldPurchaseTokenMethodId = env->GetMethodID(builderClass, "setOfferToken", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingFlowParams$ProductDetailsParams$Builder;"); + env->CallObjectMethod(builder, setOldPurchaseTokenMethodId, cc::StringUtils::newStringUTFJNI(env, params->_offerToken)); + } + + cc::JniMethodInfo t2; + cc::JniHelper::getStaticMethodInfo(t2, JCLS_BILLING, "getProductDetailsObject", "(II)Lcom/android/billingclient/api/ProductDetails;"); + if (params->_productDetails) { + jobject productDetailsObject = t2.env->CallStaticObjectMethod(t2.classID, t2.methodID, tag, params->_productDetails->_id); + jmethodID setProductDetailsMethodId = env->GetMethodID(builderClass, "setProductDetails", "(Lcom/android/billingclient/api/ProductDetails;)Lcom/android/billingclient/api/BillingFlowParams$ProductDetailsParams$Builder;"); + env->CallObjectMethod(builder, setProductDetailsMethodId, productDetailsObject); + } + + jmethodID buildMethodId = env->GetMethodID(builderClass, "build", "()Lcom/android/billingclient/api/BillingFlowParams$ProductDetailsParams;"); + return env->CallObjectMethod(builder, buildMethodId); +} + +jobject JniBilling::newProductDetailsParamsListObject(int tag, const std::vector& listParams) { + JNIEnv* env = cc::JniHelper::getEnv(); + jclass listClass = env->FindClass("java/util/ArrayList"); + jmethodID methodInit = env->GetMethodID(listClass, "", "()V"); /* 无参构造 */ + jobject list = env->NewObjectA(listClass, methodInit, 0); + jmethodID methodAdd = env->GetMethodID(listClass, "add", "(Ljava/lang/Object;)Z"); + for (auto param : listParams) { + env->CallBooleanMethod(list, methodAdd, newProductDetailsParamsObject(tag, param)); + } + return list; +} + +jobject JniBilling::newBillingFlowParamsObject(int tag, const BillingFlowParams* params) { + JNIEnv* env = cc::JniHelper::getEnv(); + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, "com/android/billingclient/api/BillingFlowParams", "newBuilder", "()Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + jobject builder = t.env->CallStaticObjectMethod(t.classID, t.methodID); + jclass builderClass = env->GetObjectClass(builder); + + jmethodID setIsOfferPersonalizedMethodId = env->GetMethodID(builderClass, "setIsOfferPersonalized", "(Z)Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + env->CallObjectMethod(builder, setIsOfferPersonalizedMethodId, params->_isOfferPersonalized); + + jmethodID setObfuscatedAccountIdMethodId = env->GetMethodID(builderClass, "setObfuscatedAccountId", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + env->CallObjectMethod(builder, setObfuscatedAccountIdMethodId, cc::StringUtils::newStringUTFJNI(env, params->_obfuscatedAccountid)); + + jmethodID setObfuscatedProfileIdMethodId = env->GetMethodID(builderClass, "setObfuscatedProfileId", "(Ljava/lang/String;)Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + env->CallObjectMethod(builder, setObfuscatedProfileIdMethodId, cc::StringUtils::newStringUTFJNI(env, params->_obfuscatedProfileId)); + + jobject listObjs = JniBilling::newProductDetailsParamsListObject(tag, params->_productDetailsParamsList); + jmethodID setProductDetailsParamsListMethodId = env->GetMethodID(builderClass, "setProductDetailsParamsList", "(Ljava/util/List;)Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + env->CallObjectMethod(builder, setProductDetailsParamsListMethodId, listObjs); + + if (params->_subscriptionUpdateParams) { + jobject subscriptionOfferDetailsObj = JniBilling::newSubscriptionUpdateParamsObject(params->_subscriptionUpdateParams); + jmethodID setSubscriptionUpdateParamsMethodId = env->GetMethodID(builderClass, "setSubscriptionUpdateParams", "(Lcom/android/billingclient/api/BillingFlowParams$SubscriptionUpdateParams;)Lcom/android/billingclient/api/BillingFlowParams$Builder;"); + env->CallObjectMethod(builder, setSubscriptionUpdateParamsMethodId, subscriptionOfferDetailsObj); + } + + jmethodID buildMethodId = env->GetMethodID(builderClass, "build", "()Lcom/android/billingclient/api/BillingFlowParams;"); + return env->CallObjectMethod(builder, buildMethodId); +} + +jobject JniBilling::newPendingPurchasesParamsObject(const PendingPurchasesParams* params) { + auto* env = JniHelper::getEnv(); + cc::JniMethodInfo t; + cc::JniHelper::getStaticMethodInfo(t, "com/android/billingclient/api/PendingPurchasesParams", "newBuilder", "()Lcom/android/billingclient/api/PendingPurchasesParams$Builder;"); + jobject builder = t.env->CallStaticObjectMethod(t.classID, t.methodID); + jclass builderClass = env->GetObjectClass(builder); + + if (params->_enableOneTimeProducts) { + jmethodID methodId = env->GetMethodID(builderClass, "enableOneTimeProducts", "()Lcom/android/billingclient/api/PendingPurchasesParams$Builder;"); + env->CallObjectMethod(builder, methodId); + } + if (params->_enablePrepaidPlans) { + jmethodID methodId = env->GetMethodID(builderClass, "enablePrepaidPlans", "()Lcom/android/billingclient/api/PendingPurchasesParams$Builder;"); + env->CallObjectMethod(builder, methodId); + } + + jmethodID buildMethodId = env->GetMethodID(builderClass, "build", "()Lcom/android/billingclient/api/PendingPurchasesParams;"); + return env->CallObjectMethod(builder, buildMethodId); +} + +jobject JniBilling::newCustomListenerObject(int tag, const std::string& functionName) { + auto* env = JniHelper::getEnv(); + std::string listener = std::string(JCLS_BILLING) + "$" + functionName; + + cc::JniMethodInfo t; + cc::JniHelper::getMethodInfo(t, listener.c_str(), "", "(I)V"); + + return t.env->NewObject(t.classID, t.methodID, tag); +} + +jobject JniBilling::newPurchaseUpdateListenerObject(int tag) { + return newCustomListenerObject(tag, "BillingClientPurchasesUpdatedListener"); +} + +jobject JniBilling::newUserChoiceBillingListenerObj(int tag) { + return newCustomListenerObject(tag, "BillingClientUserChoiceBillingListener"); +} + +jobject JniBilling::newBillingClientBuilderObject(int tag, const BillingClient::Builder* params) { + auto* env = JniHelper::getEnv(); + cc::JniMethodInfo t; + auto* javaGameActivity = cc::JniHelper::getActivity(); + cc::JniHelper::getStaticMethodInfo(t, "com/android/billingclient/api/BillingClient", "newBuilder", "(Landroid/content/Context;)Lcom/android/billingclient/api/BillingClient$Builder;"); + jobject builder = t.env->CallStaticObjectMethod(t.classID, t.methodID, javaGameActivity); + jclass builderClass = env->GetObjectClass(builder); + + if (params->_enableAlternativeBillingOnly) { + jmethodID methodId = env->GetMethodID(builderClass, "enableAlternativeBillingOnly", "()Lcom/android/billingclient/api/BillingClient$Builder;"); + env->CallObjectMethod(builder, methodId); + } + + if (params->_enableExternalOffer) { + jmethodID methodId = env->GetMethodID(builderClass, "enableExternalOffer", "()Lcom/android/billingclient/api/BillingClient$Builder;"); + env->CallObjectMethod(builder, methodId); + } + + if (params->_pendingPurchasesParams) { + jobject pendingPurchasesParamsObj = newPendingPurchasesParamsObject(params->_pendingPurchasesParams); + jmethodID methodId = env->GetMethodID(builderClass, "enablePendingPurchases", "(Lcom/android/billingclient/api/PendingPurchasesParams;)Lcom/android/billingclient/api/BillingClient$Builder;"); + env->CallObjectMethod(builder, methodId, pendingPurchasesParamsObj); + } + + if (params->_purchasesUpdatedListener) { + jobject listenerObj = newPurchaseUpdateListenerObject(tag); + jmethodID methodId = env->GetMethodID(builderClass, "setListener", "(Lcom/android/billingclient/api/PurchasesUpdatedListener;)Lcom/android/billingclient/api/BillingClient$Builder;"); + env->CallObjectMethod(builder, methodId, listenerObj); + } + + if (params->_userChoiceBillingListener) { + jobject userChoiceBillingListenerObj = newUserChoiceBillingListenerObj(tag); + jmethodID methodId = env->GetMethodID(builderClass, "enableUserChoiceBilling", "(Lcom/android/billingclient/api/UserChoiceBillingListener;)Lcom/android/billingclient/api/BillingClient$Builder;"); + env->CallObjectMethod(builder, methodId, userChoiceBillingListenerObj); + } + + return builder; +} + +} // namespace cc diff --git a/native/vendor/google/billing/JniBilling.h b/native/vendor/google/billing/JniBilling.h new file mode 100644 index 0000000000..6f7cae5f2c --- /dev/null +++ b/native/vendor/google/billing/JniBilling.h @@ -0,0 +1,83 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include +#include +#include + +#include "base/Macros.h" +#include "vendor/google/billing/GoogleBilling.h" +#include "vendor/google/billing/build-params/BillingFlowParams.h" +#include "vendor/google/billing/result-values/AccountIdentifiers.h" +#include "vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h" +#include "vendor/google/billing/result-values/BillingConfig.h" +#include "vendor/google/billing/result-values/BillingResult.h" +#include "vendor/google/billing/result-values/ExternalOfferReportingDetails.h" +#include "vendor/google/billing/result-values/InAppMessageResult.h" +#include "vendor/google/billing/result-values/ProductDetails.h" +#include "vendor/google/billing/result-values/Purchase.h" +#include "vendor/google/billing/result-values/UserChoiceDetails.h" + +namespace cc { + +class CC_DLL JniBilling { +public: + static BillingResult *toBillingResult(JNIEnv *env, jobject obj); + static std::vector toProductDetailList(JNIEnv *env, jobject productsObj, jint tag, jint startID); + static std::vector toPurchaseList(JNIEnv *env, jobject productsObj, jint tag, jint startID); + static BillingConfig *toBillingConfig(JNIEnv *env, jobject billingConfigObj); + static AlternativeBillingOnlyReportingDetails *toAlternativeBillingOnlyReportingDetails(JNIEnv *env, jobject alternativeBillingOnlyReportingDetailsObj); + static ExternalOfferReportingDetails *toExternalOfferReportingDetails(JNIEnv *env, jobject externalOfferReportingDetailsObj); + static InAppMessageResult *toInAppMessageResult(JNIEnv *env, jobject inAppMessageResultObj); + static ProductDetails *toProductDetail(JNIEnv *env, jobject productObj); + static Purchase *toPurchase(JNIEnv *env, jobject purchaseObj); + static ProductDetails::OneTimePurchaseOfferDetails *toOneTimePurchaseOfferDetails(JNIEnv *env, jobject obj); + static ProductDetails::InstallmentPlanDetails *toInstallmentPlanDetails(JNIEnv *env, jobject obj); + static ProductDetails::SubscriptionOfferDetails *toSubscriptionOfferDetails(JNIEnv *env, jobject obj); + static AccountIdentifiers *toAccountIdentifiers(JNIEnv *env, jobject obj); + static Purchase::PendingPurchaseUpdate *toPendingPurchaseUpdate(JNIEnv *env, jobject obj); + static ProductDetails::PricingPhase *toPricingPhase(JNIEnv *env, jobject obj); + static ProductDetails::PricingPhases *toPricingPhases(JNIEnv *env, jobject obj); + static BillingResult *callFunctionAndReturnBillingResult(const std::string &functionName, int tag, int callbackId); + + static UserChoiceDetails::Product *toUserChoiceDetailsProduct(JNIEnv *env, jobject obj); + static UserChoiceDetails *toUserChoiceDetails(JNIEnv *env, jobject obj); + + static jobject newBillingFlowParamsObject(int tag, const BillingFlowParams *params); + static jobject newBillingClientBuilderObject(int tag, const BillingClient::Builder *params); + +private: + static jobject newSubscriptionUpdateParamsObject(const BillingFlowParams::SubscriptionUpdateParams *params); + static jobject newProductDetailsParamsObject(int tag, const BillingFlowParams::ProductDetailsParams *params); + static jobject newProductDetailsParamsListObject(int tag, const std::vector &listParams); + + static jobject newPurchaseUpdateListenerObject(int tag); + static jobject newUserChoiceBillingListenerObj(int tag); + static jobject newPendingPurchasesParamsObject(const PendingPurchasesParams *params); + static jobject newCustomListenerObject(int tag, const std::string &functionName); +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/AcknowledgePurchaseParams.h b/native/vendor/google/billing/build-params/AcknowledgePurchaseParams.h new file mode 100644 index 0000000000..05f0749655 --- /dev/null +++ b/native/vendor/google/billing/build-params/AcknowledgePurchaseParams.h @@ -0,0 +1,65 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { +class AcknowledgePurchaseParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + public: + Builder& setPurchaseToken(const std::string& purchaseToken) { + _purchaseToken = purchaseToken; + return *this; + } + + AcknowledgePurchaseParams* build() { + return new AcknowledgePurchaseParams(std::move(_purchaseToken)); + } + + private: + std::string _purchaseToken; + }; + + std::string getPurchaseToken() const { + return _purchaseToken; + } + + static Builder* newBuilder() { + return new Builder(); + } + +private: + AcknowledgePurchaseParams(const std::string&& purchaseToken) : _purchaseToken(purchaseToken) { + } + + std::string _purchaseToken; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/BillingFlowParams.h b/native/vendor/google/billing/build-params/BillingFlowParams.h new file mode 100644 index 0000000000..7c50170b1e --- /dev/null +++ b/native/vendor/google/billing/build-params/BillingFlowParams.h @@ -0,0 +1,185 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" +#include "vendor/google/billing/result-values/ProductDetails.h" + +namespace cc { +class CC_DLL BillingFlowParams : public cc::RefCounted { +public: + class SubscriptionUpdateParams : public cc::RefCounted { + public: + class Builder : public cc::RefCounted { + public: + Builder& setOldPurcchaseToken(const std::string& purchaseToken) { + _purchaseToken = purchaseToken; + return *this; + } + Builder& setOriginalExternalTransactionId(const std::string& externalTransactionId) { + _externalTransactionId = externalTransactionId; + return *this; + } + Builder& setSubscriptionReplacementMode(int subscriptionReplacementMode) { + _subscriptionReplacementMode = subscriptionReplacementMode; + return *this; + } + SubscriptionUpdateParams* build() { + return new SubscriptionUpdateParams(_subscriptionReplacementMode, std::move(_purchaseToken), std::move(_externalTransactionId)); + } + + private: + int _subscriptionReplacementMode{0}; + std::string _purchaseToken; + std::string _externalTransactionId; + }; + static Builder* newBuilder() { + return new Builder(); + } + + private: + SubscriptionUpdateParams(int subscriptionReplacementMode, const std::string&& purchaseToken, const std::string&& externalTransactionId) + : _subscriptionReplacementMode(subscriptionReplacementMode), _purchaseToken(purchaseToken), _externalTransactionId(externalTransactionId) { + } + friend class JniBilling; + int _subscriptionReplacementMode{0}; + std::string _purchaseToken; + std::string _externalTransactionId; + }; + + class ProductDetailsParams : public cc::RefCounted { + public: + ~ProductDetailsParams() { + if (_productDetails) { + _productDetails->release(); + } + _productDetails = nullptr; + } + class Builder : public cc::RefCounted { + public: + ~Builder() { + if (_productDetails) { + _productDetails->release(); + } + _productDetails = nullptr; + } + Builder& setOfferToken(const std::string& offerToken) { + _offerToken = offerToken; + return *this; + } + Builder& setProductDetails(ProductDetails* productDetails) { + _productDetails = productDetails; + if (_productDetails) { + _productDetails->addRef(); + } + return *this; + } + ProductDetailsParams* build() { + return new ProductDetailsParams(std::move(_offerToken), _productDetails); + } + + private: + std::string _offerToken; + ProductDetails* _productDetails; + }; + static Builder* newBuilder() { + return new Builder(); + } + + private: + friend class JniBilling; + ProductDetailsParams(const std::string&& offerToken, ProductDetails* productDetails) : _offerToken(offerToken), _productDetails(productDetails) { + if (_productDetails) { + _productDetails->addRef(); + } + } + + std::string _offerToken; + ProductDetails* _productDetails{nullptr}; + }; + + class Builder : public cc::RefCounted { + public: + Builder& setIsOfferPersonalized(bool isOfferPersonalized) { + _isOfferPersonalized = isOfferPersonalized; + return *this; + } + Builder& setObfuscatedAccountId(const std::string& obfuscatedAccountid) { + _obfuscatedAccountid = obfuscatedAccountid; + return *this; + } + Builder& setObfuscatedProfileId(const std::string& obfuscatedProfileId) { + _obfuscatedProfileId = obfuscatedProfileId; + return *this; + } + Builder& setProductDetailsParamsList(const std::vector& productDetailsParamsList) { + _productDetailsParamsList = productDetailsParamsList; + return *this; + } + Builder& setSubscriptionUpdateParams(SubscriptionUpdateParams* subscriptionUpdateParams) { + _subscriptionUpdateParams = subscriptionUpdateParams; + return *this; + } + BillingFlowParams* build() { + return new BillingFlowParams(_isOfferPersonalized, + std::move(_obfuscatedAccountid), + std::move(_obfuscatedProfileId), + std::move(_productDetailsParamsList), + _subscriptionUpdateParams); + } + + private: + friend class JniBilling; + bool _isOfferPersonalized{false}; + std::string _obfuscatedAccountid; + std::string _obfuscatedProfileId; + std::vector _productDetailsParamsList; + SubscriptionUpdateParams* _subscriptionUpdateParams{nullptr}; + }; + static Builder* newBuilder() { + return new Builder(); + } + +private: + friend class GoogleBillingHelper; + friend class JniBilling; + BillingFlowParams(bool isOfferPersonalized, + const std::string&& obfuscatedAccountid, + const std::string&& obfuscatedProfileId, + const std::vector&& productDetailsParamsList, + SubscriptionUpdateParams* subscriptionUpdateParams) + : _isOfferPersonalized(isOfferPersonalized), _obfuscatedAccountid(obfuscatedAccountid), _obfuscatedProfileId(obfuscatedProfileId), _productDetailsParamsList(productDetailsParamsList), _subscriptionUpdateParams(subscriptionUpdateParams) { + } + bool _isOfferPersonalized{false}; + std::string _obfuscatedAccountid; + std::string _obfuscatedProfileId; + std::vector _productDetailsParamsList; + SubscriptionUpdateParams* _subscriptionUpdateParams{nullptr}; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/ConsumeParams.h b/native/vendor/google/billing/build-params/ConsumeParams.h new file mode 100644 index 0000000000..ba4b04d514 --- /dev/null +++ b/native/vendor/google/billing/build-params/ConsumeParams.h @@ -0,0 +1,66 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class ConsumeParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + public: + Builder& setPurchaseToken(const std::string& purchaseToken) { + _purchaseToken = purchaseToken; + return *this; + } + + ConsumeParams* build() { + return new ConsumeParams(std::move(_purchaseToken)); + } + + private: + std::string _purchaseToken; + }; + + std::string getPurchaseToken() const { + return _purchaseToken; + } + + static Builder* newBuilder() { + return new Builder(); + } + +private: + ConsumeParams(std::string&& purchaseToken) : _purchaseToken(purchaseToken) { + } + + std::string _purchaseToken; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/GetBillingConfigParams.h b/native/vendor/google/billing/build-params/GetBillingConfigParams.h new file mode 100644 index 0000000000..8ae2c22156 --- /dev/null +++ b/native/vendor/google/billing/build-params/GetBillingConfigParams.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class GetBillingConfigParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + public: + GetBillingConfigParams* build() { + return new GetBillingConfigParams(); + } + }; + + static Builder* newBuilder() { + return new Builder(); + } + +private: + GetBillingConfigParams() = default; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/InAppMessageParams.h b/native/vendor/google/billing/build-params/InAppMessageParams.h new file mode 100644 index 0000000000..b82518213c --- /dev/null +++ b/native/vendor/google/billing/build-params/InAppMessageParams.h @@ -0,0 +1,67 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class InAppMessageParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + public: + Builder& addAllInAppMessageCategoriesToShow() { + _inAppMessageCategoryIds.push_back(2); + return *this; + } + + Builder& addInAppMessageCategoryToShow(int inAppMessageCategoryId) { + _inAppMessageCategoryIds.push_back(inAppMessageCategoryId); + return *this; + } + + InAppMessageParams* build() { + return new InAppMessageParams(std::move(_inAppMessageCategoryIds)); + } + + private: + std::vector _inAppMessageCategoryIds; + }; + + static Builder* newBuilder() { + return new Builder(); + } + +private: + InAppMessageParams(std::vector&& inAppMessageCategoryIds) : _inAppMessageCategoryIds(inAppMessageCategoryIds) { + } + friend class BillingClient; + std::vector _inAppMessageCategoryIds; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/PendingPurchasesParams.h b/native/vendor/google/billing/build-params/PendingPurchasesParams.h new file mode 100644 index 0000000000..7b00b3319c --- /dev/null +++ b/native/vendor/google/billing/build-params/PendingPurchasesParams.h @@ -0,0 +1,74 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class PendingPurchasesParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + private: + bool _enableOneTimeProducts{false}; + bool _enablePrepaidPlans{false}; + + public: + Builder& enableOneTimeProducts() { + _enableOneTimeProducts = true; + return *this; + } + Builder& enablePrepaidPlans() { + _enablePrepaidPlans = true; + return *this; + } + PendingPurchasesParams* build() { + if (!_enableOneTimeProducts) { + return nullptr; + } + return new PendingPurchasesParams(_enableOneTimeProducts, _enablePrepaidPlans); + } + }; + + static Builder* newBuilder() { + return new Builder(); + } + +private: + PendingPurchasesParams(bool enableOneTimeProducts, bool enablePrepaidPlans) + : _enableOneTimeProducts(enableOneTimeProducts), _enablePrepaidPlans(enablePrepaidPlans) { + } + +private: + friend class JniBilling; + friend class BillingClient; + bool _enableOneTimeProducts{false}; + bool _enablePrepaidPlans{false}; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/QueryProductDetailsParams.h b/native/vendor/google/billing/build-params/QueryProductDetailsParams.h new file mode 100644 index 0000000000..04bea7d53e --- /dev/null +++ b/native/vendor/google/billing/build-params/QueryProductDetailsParams.h @@ -0,0 +1,97 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { +class QueryProductDetailsParams : public cc::RefCounted { +public: + class Product { + public: + class Builder : public cc::RefCounted { + private: + std::string _productId; + std::string _productType; + + public: + Builder& setProductId(const std::string& productId) { + _productId = productId; + return *this; + } + Builder& setProductType(const std::string& productType) { + _productType = productType; + return *this; + } + Product* build() { + return new Product(std::move(_productId), std::move(_productType)); + } + }; + + static Builder* newBuilder() { + return new Builder(); + } + + private: + Product(const std::string& productId, const std::string& productType) : _productId(productId), _productType(productType) { + } + + private: + friend class BillingClient; + std::string _productId; + std::string _productType; + }; + class Builder : public cc::RefCounted { + private: + std::vector _productList; + + public: + Builder& setProductList(const std::vector& productList) { + _productList = productList; + return *this; + } + + QueryProductDetailsParams* build() { + return new QueryProductDetailsParams(std::move(_productList)); + } + }; + + static Builder* newBuilder() { + return new Builder(); + } + +private: + QueryProductDetailsParams(std::vector&& productLists) : _productList(productLists) { + } + +private: + friend class BillingClient; + std::vector _productList; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/build-params/QueryPurchasesParams.h b/native/vendor/google/billing/build-params/QueryPurchasesParams.h new file mode 100644 index 0000000000..8130c1d00f --- /dev/null +++ b/native/vendor/google/billing/build-params/QueryPurchasesParams.h @@ -0,0 +1,62 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class QueryPurchasesParams : public cc::RefCounted { +public: + class Builder : public cc::RefCounted { + public: + Builder& setProductType(const std::string& productType) { + _productType = productType; + return *this; + } + + QueryPurchasesParams* build() { + return new QueryPurchasesParams(std::move(_productType)); + } + + private: + std::string _productType; + }; + + static Builder* newBuilder() { + return new Builder(); + } + +private: + QueryPurchasesParams(const std::string& productType) : _productType(productType) { + } + friend class BillingClient; + std::string _productType; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/AccountIdentifiers.h b/native/vendor/google/billing/result-values/AccountIdentifiers.h new file mode 100644 index 0000000000..2ee4fedec7 --- /dev/null +++ b/native/vendor/google/billing/result-values/AccountIdentifiers.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class CC_DLL AccountIdentifiers { +public: + std::string getObfuscatedAccountId() const { + return _obfuscatedAccountId; + } + + std::string getObfuscatedProfileId() const { + return _obfuscatedProfileId; + } + +private: + friend class JniBilling; + friend class Purchase; + std::string _obfuscatedAccountId; + std::string _obfuscatedProfileId; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h b/native/vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h new file mode 100644 index 0000000000..35f0a87654 --- /dev/null +++ b/native/vendor/google/billing/result-values/AlternativeBillingOnlyReportingDetails.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class AlternativeBillingOnlyReportingDetails : public cc::RefCounted { +public: + std::string getExternalTransactionToken() const { + return _externalTransactionToken; + } + +private: + friend class JniBilling; + std::string _externalTransactionToken; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/BillingConfig.h b/native/vendor/google/billing/result-values/BillingConfig.h new file mode 100644 index 0000000000..28a38b0663 --- /dev/null +++ b/native/vendor/google/billing/result-values/BillingConfig.h @@ -0,0 +1,51 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class CC_DLL BillingConfig : public cc::RefCounted { +public: + std::string getCountryCode() const { + return _countryCode; + } + static BillingConfig* forCountryCode(const std::string& countryCode) { + return new BillingConfig(countryCode); + } + +private: + friend class JniBilling; + BillingConfig(const std::string countryCode) { + _countryCode = countryCode; + } + std::string _countryCode; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/BillingResult.h b/native/vendor/google/billing/result-values/BillingResult.h new file mode 100644 index 0000000000..955b18bb0b --- /dev/null +++ b/native/vendor/google/billing/result-values/BillingResult.h @@ -0,0 +1,79 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { +class CC_DLL BillingResult : public cc::RefCounted { +public: + int getResponseCode() const { + return _responseCode; + } + + std::string getDebugMessage() const { + return _debugMessage; + } + + std::string toString() const { + return _toString; + } + class Builder : public cc::RefCounted { + private: + int _responseCode{0}; + std::string _debugMessage; + std::string _toStr; + + public: + Builder& setDebugMessage(const std::string& debugMsg) { + _debugMessage = debugMsg; + return *this; + } + Builder& setResponseCode(int responseCode) { + _responseCode = responseCode; + return *this; + } + BillingResult* build() { + auto* billingResult = new BillingResult(); + billingResult->_responseCode = _responseCode; + billingResult->_debugMessage = std::move(_debugMessage); + return billingResult; + } + }; + static Builder* newBuilder() { + return new Builder(); + } + +private: + friend class JniBilling; + int _responseCode{0}; + std::string _debugMessage; + std::string _toString; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/ExternalOfferReportingDetails.h b/native/vendor/google/billing/result-values/ExternalOfferReportingDetails.h new file mode 100644 index 0000000000..fef23c2b19 --- /dev/null +++ b/native/vendor/google/billing/result-values/ExternalOfferReportingDetails.h @@ -0,0 +1,45 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class ExternalOfferReportingDetails : public cc::RefCounted { +public: + std::string getExternalTransactionToken() const { + return _externalTransactionToken; + } + +private: + friend class JniBilling; + std::string _externalTransactionToken; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/InAppMessageResult.h b/native/vendor/google/billing/result-values/InAppMessageResult.h new file mode 100644 index 0000000000..5e3cf93e57 --- /dev/null +++ b/native/vendor/google/billing/result-values/InAppMessageResult.h @@ -0,0 +1,54 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class InAppMessageResult : public cc::RefCounted { +public: + int getResponseCode() const { + return _responseCode; + } + + std::string getPurchaseToken() const { + return _purchaseToken; + } + + InAppMessageResult(int responseCode, const std::string& purchaseToken) { + _responseCode = responseCode; + _purchaseToken = purchaseToken; + } + +private: + friend class JniBilling; + int _responseCode{0}; + std::string _purchaseToken; +}; +} // namespace cc diff --git a/native/vendor/google/billing/result-values/ProductDetails.cpp b/native/vendor/google/billing/result-values/ProductDetails.cpp new file mode 100644 index 0000000000..20463ca50c --- /dev/null +++ b/native/vendor/google/billing/result-values/ProductDetails.cpp @@ -0,0 +1,43 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include "vendor/google/billing/result-values/ProductDetails.h" +#include +#include "vendor/google/billing/GoogleBillingHelper.h" + +namespace cc { + +ProductDetails::~ProductDetails() { + if (_oneTimePurchaseOfferDetails) { + delete _oneTimePurchaseOfferDetails; + _oneTimePurchaseOfferDetails = nullptr; + } + for (auto* details : _subscriptionOfferDetails) { + delete details; + } + _subscriptionOfferDetails.clear(); + GoogleBillingHelper::removeProductDetails(_tag, _id); +} + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/ProductDetails.h b/native/vendor/google/billing/result-values/ProductDetails.h new file mode 100644 index 0000000000..9059f5e700 --- /dev/null +++ b/native/vendor/google/billing/result-values/ProductDetails.h @@ -0,0 +1,227 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { + +class CC_DLL ProductDetails : public cc::RefCounted { +public: + ~ProductDetails() override; + class OneTimePurchaseOfferDetails { + public: + long getPriceAmountMicros() const { + return _priceAmountMicros; + } + + std::string getFormattedPrice() const { + return _formattedPrice; + } + + std::string getPriceCurrencyCode() const { + return _priceCurrencyCode; + } + + private: + friend class JniBilling; + long _priceAmountMicros{0}; + std::string _formattedPrice; + std::string _priceCurrencyCode; + }; + + class InstallmentPlanDetails { + public: + int getInstallmentPlanCommitmentPaymentsCount() const { + return _commitmentPaymentsCount; + } + int getSubsequentInstallmentPlanCommitmentPaymentsCount() const { + return _subsequentCommitmentPaymentsCount; + } + + private: + friend class JniBilling; + int _commitmentPaymentsCount{0}; + int _subsequentCommitmentPaymentsCount{0}; + }; + + class PricingPhase { + public: + int getBillingCycleCount() const { + return _billingCycleCount; + } + + int getRecurrenceMode() const { + return _recurrenceMode; + } + + long getPriceAmountMicros() const { + return _priceAmountMicros; + } + + std::string getBillingPeriod() const { + return _billingPeriod; + } + std::string getFormattedPrice() const { + return _formattedPrice; + } + + std::string getPriceCurrencyCode() const { + return _priceCurrencyCode; + } + + private: + friend class JniBilling; + int _billingCycleCount{0}; + long _priceAmountMicros{0}; + int _recurrenceMode{0}; + std::string _billingPeriod; + std::string _formattedPrice; + std::string _priceCurrencyCode; + }; + + class PricingPhases { + public: + std::vector getPricingPhaseList() const { + return _pricingPhaseList; + } + ~PricingPhases() { + for (auto* pricingPhase : _pricingPhaseList) { + delete pricingPhase; + } + _pricingPhaseList.clear(); + } + + private: + friend class JniBilling; + std::vector _pricingPhaseList; + }; + + class SubscriptionOfferDetails { + public: + ~SubscriptionOfferDetails() { + if (_pricingPhases != nullptr) { + delete _pricingPhases; + _pricingPhases = nullptr; + } + + if (_installmentPlanDetails != nullptr) { + delete _installmentPlanDetails; + _installmentPlanDetails = nullptr; + } + } + InstallmentPlanDetails* getInstallmentPlanDetails() const { + return _installmentPlanDetails; + } + + PricingPhases* getPricingPhases() const { + return _pricingPhases; + } + + std::string getBasePlanId() const { + return _basePlanId; + } + + std::string getOfferId() const { + return _offerId; + } + + std::string getOfferToken() const { + return _offerToken; + } + + std::vector getOfferTags() const { + return _offerTags; + } + + private: + friend class JniBilling; + std::string _basePlanId; + std::string _offerId; + std::string _offerToken; + std::vector _offerTags; + PricingPhases* _pricingPhases{nullptr}; + InstallmentPlanDetails* _installmentPlanDetails{nullptr}; + }; + int hashCode() const { + return _hashCode; + } + + OneTimePurchaseOfferDetails* getOneTimePurchaseOfferDetails() const { + return _oneTimePurchaseOfferDetails; + } + + std::string getDescription() const { + return _description; + } + + std::string getName() const { + return _name; + } + + std::string getProductId() const { + return _productId; + } + + std::string getProductType() const { + return _productType; + } + + std::string getTitle() const { + return _title; + } + + std::string toString() const { + return _toString; + } + + bool equals(const ProductDetails& other) const { + return _hashCode == other._hashCode; + } + + std::vector getSubscriptionOfferDetails() const { + return _subscriptionOfferDetails; + } + +private: + friend class JniBilling; + friend class GoogleBillingHelper; + int _id{-1}; // This is an ID that is not visible to ts and is used to free the java object. + int _tag{-1}; // This is an ID that is not visible to ts and is used to specify which billingclient. + int _hashCode{0}; + std::string _description; + std::string _name; + std::string _productId; + std::string _productType; + std::string _title; + std::string _toString; + OneTimePurchaseOfferDetails* _oneTimePurchaseOfferDetails{nullptr}; + std::vector _subscriptionOfferDetails; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/Purchase.cpp b/native/vendor/google/billing/result-values/Purchase.cpp new file mode 100644 index 0000000000..20e5847a75 --- /dev/null +++ b/native/vendor/google/billing/result-values/Purchase.cpp @@ -0,0 +1,36 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#include + +#include "vendor/google/billing/GoogleBillingHelper.h" +#include "vendor/google/billing/result-values/Purchase.h" + +namespace cc { + +Purchase::~Purchase() { + GoogleBillingHelper::removePurchase(_tag, _id); +} + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/Purchase.h b/native/vendor/google/billing/result-values/Purchase.h new file mode 100644 index 0000000000..4a4d01c5ed --- /dev/null +++ b/native/vendor/google/billing/result-values/Purchase.h @@ -0,0 +1,141 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" +#include "vendor/google/billing/result-values/AccountIdentifiers.h" + +namespace cc { + +class CC_DLL Purchase : public cc::RefCounted { +public: + class CC_DLL PendingPurchaseUpdate { + public: + std::string getPurchaseToken() const { + return _purchaseToken; + } + + std::vector getProducts() const { + return _products; + } + + private: + friend class JniBilling; + std::string _purchaseToken; + std::vector _products; + }; + + int getPurchaseState() const { + return _purchaseState; + } + int getQuantity() const { + return _quantity; + } + + int hashCode() const { + return _hashCode; + } + + long getPurchaseTime() const { + return _purchaseTime; + } + + AccountIdentifiers* getAccountIdentifiers() const { + return _accountIdentifiers; + } + PendingPurchaseUpdate* getPendingPurchaseUpdate() const { + return _pendingPurchaseUpdate; + } + + std::string getDeveloperPayload() const { + return _developerPayload; + } + + std::string getOrderId() const { + return _orderId; + } + + std::string getOriginalJson() const { + return _originalJson; + } + + std::string getPackageName() const { + return _packageName; + } + + std::string getPurchaseToken() const { + return _purchaseToken; + } + + std::string getSignature() const { + return _signature; + } + + std::string toString() const { + return _toString; + } + + std::vector getProducts() const { + return _products; + } + bool isAcknowledged() const { + return _isAcknowledged; + } + + bool isAutoRenewing() const { + return _isAutoRenewing; + } + ~Purchase() override; + bool equals(const Purchase& other) const { + return _originalJson == other._originalJson && _signature == other._signature; + } + +private: + friend class JniBilling; + friend class GoogleBillingHelper; + int _id{-1}; // This is an ID that is not visible to ts and is used to free the java object. + int _tag{-1}; // This is an ID that is not visible to ts and is used to specify which billingclient. + bool _isAcknowledged{false}; + bool _isAutoRenewing{false}; + int _purchaseState{0}; + int _hashCode{0}; + int _quantity{0}; + long _purchaseTime{0}; + std::string _developerPayload; + std::string _orderId; + std::string _originalJson; + std::string _packageName; + std::string _purchaseToken; + std::string _signature; + std::string _toString; + AccountIdentifiers* _accountIdentifiers{nullptr}; + PendingPurchaseUpdate* _pendingPurchaseUpdate{nullptr}; + std::vector _products; +}; + +} // namespace cc diff --git a/native/vendor/google/billing/result-values/UserChoiceDetails.h b/native/vendor/google/billing/result-values/UserChoiceDetails.h new file mode 100644 index 0000000000..105f8d2b69 --- /dev/null +++ b/native/vendor/google/billing/result-values/UserChoiceDetails.h @@ -0,0 +1,92 @@ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +****************************************************************************/ + +#pragma once + +#include + +#include "base/Macros.h" +#include "base/RefCounted.h" + +namespace cc { +class UserChoiceDetails : public cc::RefCounted { +public: + class Product { + public: + int hashCode() const { + return _hashCode; + } + std::string getId() const { + return _id; + } + std::string getOfferToken() const { + return _type; + } + std::string getType() const { + return _offerToken; + } + std::string toString() const { + return _toString; + } + bool equals(const Product& p) { + if (&p == this) { + return true; + } + return p._id == _id && p._type == _type && p._offerToken == _offerToken; + } + + private: + friend class JniBilling; + int _hashCode{0}; + std::string _id; + std::string _type; + std::string _offerToken; + std::string _toString; + }; + + ~UserChoiceDetails() { + for (auto* product : _products) { + delete product; + } + _products.clear(); + } + std::string getExternalTransactionToken() const { + return _externalTransactionToken; + } + std::string getOriginalExternalTransactionId() const { + return _originalExternalTransactionId; + } + + std::vector getProducts() { + return this->_products; + } + +private: + friend class JniBilling; + std::string _externalTransactionToken; + std::string _originalExternalTransactionId; + std::vector _products; +}; + +} // namespace cc diff --git a/platforms/native/builtin/index.js b/platforms/native/builtin/index.js index 81f991398a..46130a11b3 100644 --- a/platforms/native/builtin/index.js +++ b/platforms/native/builtin/index.js @@ -217,12 +217,6 @@ for (const key in jsbWindow) { } } -// In the openharmony platform, XMLHttpRequest is not undefined, but there are problems to using it. -// So the native implementation is forced to be used. -if (window.oh && typeof globalThis.XMLHttpRequest !== 'undefined') { - globalThis.XMLHttpRequest = jsbWindow.XMLHttpRequest; -} - if (typeof globalThis.window === 'undefined') { globalThis.window = globalThis; } diff --git a/scripts/native-pack-tool/source/platforms/google-play.ts b/scripts/native-pack-tool/source/platforms/google-play.ts index dc02b01b25..74659e8012 100644 --- a/scripts/native-pack-tool/source/platforms/google-play.ts +++ b/scripts/native-pack-tool/source/platforms/google-play.ts @@ -175,7 +175,7 @@ export class GooglePlayPackTool extends NativePackTool { if (options.androidInstant) { buildMode = `bundle${outputMode}`; } else { - buildMode = `${this.params.projectName}:bundle${outputMode}`; + buildMode = `${this.projectNameASCII()}:bundle${outputMode}`; } await cchelper.runCmd(gradle, [buildMode], false, projDir); } @@ -504,7 +504,7 @@ export class GooglePlayPackTool extends NativePackTool { } if (options.appBundle) { - apkName = `${this.params.projectName}-${suffix}.aab`; + apkName = `${this.projectNameASCII()}-${suffix}.aab`; apkPath = ps.join(this.outputsDir(), `bundle/${suffix}/${apkName}`); if (!fs.existsSync(apkPath)) { throw new Error(`instant apk not found at ${apkPath}`); diff --git a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts index c9edd1e34b..7ce1005923 100644 --- a/scripts/native-pack-tool/source/platforms/harmonyos-next.ts +++ b/scripts/native-pack-tool/source/platforms/harmonyos-next.ts @@ -71,10 +71,10 @@ export class HarmonyOSNextPackTool extends NativePackTool { moduleJSON.module.abilities[0].orientation = 'auto_rotation'; } else if (cfg.landscapeRight && !cfg.landscapeLeft) { - moduleJSON.module.abilities[0].orientation = 'landscape'; + moduleJSON.module.abilities[0].orientation = 'landscape_inverted'; } else if (!cfg.landscapeRight && cfg.landscapeLeft) { - moduleJSON.module.abilities[0].orientation = 'landscape_inverted'; + moduleJSON.module.abilities[0].orientation = 'landscape'; } else if (cfg.landscapeRight && cfg.landscapeLeft) { moduleJSON.module.abilities[0].orientation = 'auto_rotation_landscape'; diff --git a/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/oh-package.json5 b/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/oh-package.json5 index 20aaf4fb86..7460650ce7 100644 --- a/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/oh-package.json5 +++ b/templates/harmonyos-next/entry/src/main/cpp/types/libcocos/oh-package.json5 @@ -1,6 +1,6 @@ { "name": "libcocos.so", "types": "./index.d.ts", - "version": "", + "version": "1.0.0", "description": "Please describe the basic information." } \ No newline at end of file diff --git a/templates/harmonyos-next/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js b/templates/harmonyos-next/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js deleted file mode 100644 index 641d0cd9a9..0000000000 --- a/templates/harmonyos-next/entry/src/main/ets/cocos/jsb-adapter/sys-ability-polyfill.js +++ /dev/null @@ -1,228 +0,0 @@ -/**************************************************************************** - Copyright (c) 2022-2023 Xiamen Yaji Software Co., Ltd. - - http://www.cocos.com - - Permission is hereby granted, free of charge, to any person obtaining a copy - of this software and associated engine source code (the "Software"), a limited, - worldwide, royalty-free, non-assignable, revocable and non-exclusive license - to use Cocos Creator solely to develop games on your target platforms. You shall - not use Cocos Creator software for developing other software or tools that's - used for developing games. You are not granted to publish, distribute, - sublicense, and/or sell copies of Cocos Creator. - - The software or tools in this License Agreement are licensed, not sold. - Xiamen Yaji Software Co., Ltd. reserves all rights not expressly granted to you. - - THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR - IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, - FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE - AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER - LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, - OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN - THE SOFTWARE. -****************************************************************************/ -import display from '@ohos.display'; -import I18n from '@ohos.i18n'; -import deviceInfo from '@ohos.deviceInfo'; -import batteryInfo from '@ohos.batteryInfo'; -import sensor from '@ohos.sensor'; -import connection from '@ohos.net.connection' -import vibrator from '@ohos.vibrator'; -import { ContextType } from "../common/Constants" -import cocos from "libcocos.so"; - -const systemUtils = cocos.getContext(ContextType.SYSTEM_UTILS); - -let cutout = { - left: 0, - top: 0, - width: 0, - height: 0 -}; - -export function systemReady () { - return new Promise(resolve => { - if (typeof XMLHttpRequest === 'undefined') { - window.XMLHttpRequest = function () {} - } - display.getDefaultDisplay((err, data) => { - window.oh.display = data; - // TODO: impl device in js. - //https://developer.harmonyos.com/cn/docs/documentation/doc-references/js-apis-display-0000001281001106 - }); - resolve(); - }) - -} - -window.getSystemLanguage = function () { - return I18n.System.getSystemLanguage(); -} - -window.getOSFullName = function () { - return deviceInfo.osFullName; -} - -window.getDeviceModel = function () { - return deviceInfo.productModel; -} - -window.getBatteryLevel = function () { - return batteryInfo.batterySOC; -} - -window.getDPI = function () { - var displayClass = display.getDefaultDisplaySync(); - return displayClass.densityDPI; -} - -window.getPixelRation = function () { - var displayClass = display.getDefaultDisplaySync(); - return displayClass.densityPixels; -} - -let onDisplayChange = (data) => { - // Monitor changes in screen orientation. - systemUtils.onDisplayChange(window.getDeviceOrientation()); - - // update screen cutout info - window.initScreenInfo(); -} - -try { - display.on("change", onDisplayChange); -} catch (exception) { - console.log('Failed to register callback. Code: ' + JSON.stringify(exception)); -} -window.getDeviceOrientation = function () { - var displayClass = display.getDefaultDisplaySync(); - return displayClass.rotation; -} - -function radiansToDegrees(radians) { - var pi = Math.PI; - return radians * (180/pi); -} - -let sDeviceMotionValues = []; -try { - sensor.on(sensor.SensorId.ACCELEROMETER, function (data) { - sDeviceMotionValues[0] = data.x; - sDeviceMotionValues[1] = data.y; - sDeviceMotionValues[2] = -data.z; - }, - { interval: 10000000000 } - ); -} catch (err) { - sDeviceMotionValues[0] = 0; - sDeviceMotionValues[1] = 0; - sDeviceMotionValues[2] = 0; -} - -try { - sensor.on(sensor.SensorId.LINEAR_ACCELEROMETER, function(data){ - sDeviceMotionValues[3] = data.x; - sDeviceMotionValues[4] = data.y; - sDeviceMotionValues[5] = data.z; - }, - {interval: 10000000000} - ); -} catch (err) { - sDeviceMotionValues[3] = 0; - sDeviceMotionValues[4] = 0; - sDeviceMotionValues[5] = 0; -} -try { - sensor.on(sensor.SensorId.GYROSCOPE, function(data){ - sDeviceMotionValues[6] = radiansToDegrees(data.x); - sDeviceMotionValues[7] = radiansToDegrees(data.y); - sDeviceMotionValues[8] = radiansToDegrees(data.z); - }, - {interval: 10000000000} - ); -} catch (err) { - sDeviceMotionValues[6] = 0; - sDeviceMotionValues[7] = 0; - sDeviceMotionValues[8] = 0; -} - -window.getDeviceMotionValue = function () { - return sDeviceMotionValues; -} - -window.getNetworkType = function () { - let netHandle = connection.getDefaultNetSync(); - if(netHandle && netHandle.netId != 0) { - let result = connection.getNetCapabilitiesSync(netHandle); - if (result && result.bearerTypes) { - return result.bearerTypes[0]; - } - } - return -1; -} - -window.vibrate = function (duration) { - console.log('begin to vibrate, duration is.' + duration); - try { - vibrator.startVibration({ - type: 'time', - duration: duration * 1000 - }, { - id: 0, - usage: 'alarm' - }, (error) => { - if (error) { - console.error('vibrate fail, error.code: ' + error.code + 'error.message: ', + error.message); - return error.code; - } - console.log('Vibration start sucessful.'); - return 0; - }); - } catch (err) { - console.error('errCode: ' + err.code + ' ,msg: ' + err.message); - } -} - -window.initScreenInfo = function () { - display.getDefaultDisplaySync().getCutoutInfo().then((data) => { - if (data.boundingRects.length == 0) { - return; - } - - cutout.left = data.boundingRects[0].left; - cutout.top = data.boundingRects[0].top; - cutout.width = data.boundingRects[0].width; - cutout.height = data.boundingRects[0].height; - }).catch((err) => { - console.log("get cutout info error!"); - }); -}; -window.initScreenInfo(); - -window.getCutoutWidth = function () { - if(!cutout.width) { - return 0; - } - - let disPlayWidth = display.getDefaultDisplaySync().width; - if(cutout.left + cutout.width > disPlayWidth - cutout.left) { - return disPlayWidth - cutout.left; - } - return cutout.left + cutout.width; -} - -window.getCutoutHeight = function () { - if(!cutout.height) { - return 0; - } - - let orientation = globalThis.getDeviceOrientation(); - if (orientation == display.Orientation.PORTRAIT) { - return cutout.top + cutout.height; - } else if(orientation == display.Orientation.PORTRAIT_INVERTED) { - let displayHeight = display.getDefaultDisplaySync().height; - return displayHeight - cutout.top; - } - return 0; -} \ No newline at end of file diff --git a/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js b/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js index 4d25256140..74b33024e4 100644 --- a/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js +++ b/templates/harmonyos-next/entry/src/main/ets/cocos/oh-adapter/sys-ability-polyfill.js @@ -182,11 +182,11 @@ globalThis.initScreenInfo = function () { if (data.boundingRects.length == 0) { return; } - const rc = data.boundingRects[0]; - cutout.left = rc.left; - cutout.top = rc.top; - cutout.width = rc.width; - cutout.height = rc.height; + + cutout.left = data.boundingRects[0].left; + cutout.top = data.boundingRects[0].top; + cutout.width = data.boundingRects[0].width; + cutout.height = data.boundingRects[0].height; }).catch((err) => { console.log("get cutout info error!"); }); diff --git a/templates/harmonyos-next/entry/src/main/ets/common/Constants.ts b/templates/harmonyos-next/entry/src/main/ets/common/Constants.ts index 6247ef4030..11889767ab 100644 --- a/templates/harmonyos-next/entry/src/main/ets/common/Constants.ts +++ b/templates/harmonyos-next/entry/src/main/ets/common/Constants.ts @@ -32,7 +32,6 @@ export enum ContextType { ENGINE_UTILS, EDITBOX_UTILS, WEBVIEW_UTILS, - SYSTEM_UTILS, DISPLAY_UTILS, UV_ASYNC_SEND, VIDEO_UTILS diff --git a/vendor/google/billing/billing-enum.ts b/vendor/google/billing/billing-enum.ts new file mode 100644 index 0000000000..aa9fd2a0a5 --- /dev/null +++ b/vendor/google/billing/billing-enum.ts @@ -0,0 +1,101 @@ +/* eslint-disable @typescript-eslint/no-namespace */ +/**************************************************************************** + Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. + + http://www.cocos.com + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights to + use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies + of the Software, and to permit persons to whom the Software is furnished to do so, + subject to the following conditions: + + The above copyright notice and this permission notice shall be included in + all copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN + THE SOFTWARE. +*****************************************************************************/ +import { JSB } from 'internal:constants'; + +declare const jsb: any; + +if (JSB) { + jsb.BillingClient.ConnectionState = { + DISCONNECTED: 0, + CONNECTING: 1, + CONNECTED: 2, + CLOSED: 3, + }; + jsb.BillingClient.BillingResponseCode = { + SERVICE_TIMEOUT: -3, + FEATURE_NOT_SUPPORTED: -2, + SERVICE_DISCONNECTED: -1, + OK: 0, + USER_CANCELED: 1, + SERVICE_UNAVAILABLE: 2, + BILLING_UNAVAILABLE: 3, + ITEM_UNAVAILABLE: 4, + DEVELOPER_ERROR: 5, + + ERROR: 6, + ITEM_ALREADY_OWNED: 7, + ITEM_NOT_OWNED: 8, + NETWORK_ERROR: 12, + }; + + jsb.BillingClient.FeatureType = { + SUBSCRIPTIONS: 'subscriptions', + SUBSCRIPTIONS_UPDATE: 'subscriptionsUpdate', + PRICE_CHANGE_CONFIRMATION: 'priceChangeConfirmation', + IN_APP_MESSAGING: 'bbb', + PRODUCT_DETAILS: 'fff', + BILLING_CONFIG: 'ggg', + ALTERNATIVE_BILLING_ONLY: 'jjj', + EXTERNAL_OFFER: 'kkk', + }; + + jsb.BillingClient.ProductType = { + INAPP: 'inapp', + SUBS: 'subs', + }; + + jsb.InAppMessageParams.InAppMessageCategoryId = { + UNKNOWN_IN_APP_MESSAGE_CATEGORY_ID: 0, + TRANSACTIONAL: 2, + }; + + jsb.InAppMessageResult.InAppMessageResponseCode = { + NO_ACTION_NEEDED: 0, + SUBSCRIPTION_STATUS_UPDATED: 1, + }; + + jsb.BillingFlowParams.SubscriptionUpdateParams.ReplacementMode = { + UNKNOWN_REPLACEMENT_MODE: 0, + WITH_TIME_PRORATION: 1, + CHARGE_PRORATED_PRICE: 2, + WITHOUT_PRORATION: 3, + CHARGE_FULL_PRICE: 5, + DEFERRED: 6, + }; + + jsb.ProductDetails.RecurrenceMode = { + INFINITE_RECURRING: 1, + FINITE_RECURRING: 2, + NON_RECURRING: 3, + }; + + jsb.Purchase.PurchaseState = { + PENDING: 2, + PURCHASED: 1, + UNSPECIFIED_STATE: 0, + }; +} + +export {}; diff --git a/vendor/google/billing/billing.ts b/vendor/google/billing/billing.ts index c31f64ad20..9cc50e9ada 100644 --- a/vendor/google/billing/billing.ts +++ b/vendor/google/billing/billing.ts @@ -1,3 +1,4 @@ +/* eslint-disable @typescript-eslint/no-namespace */ /**************************************************************************** Copyright (c) 2024 Xiamen Yaji Software Co., Ltd. @@ -21,809 +22,138 @@ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. *****************************************************************************/ + import { JSB } from 'internal:constants'; -import { EventTarget } from '../../../cocos/core/event'; - -interface BillingEventMap { - [google.BillingEventType.BILLING_SETUP_FINISHED]: (result: google.BillingResult) => void, - [google.BillingEventType.BILLING_SERVICE_DISCONNECTED]: () => void, - [google.BillingEventType.PRODUCT_DETAILS_RESPONSE]: - (result: google.BillingResult, productDetailsList: google.ProductDetails[]) => void, - [google.BillingEventType.PURCHASES_UPDATED]: (result: google.BillingResult, purchases: google.Purchase[]) => void, - [google.BillingEventType.CONSUME_RESPONSE]: (result: google.BillingResult, purchaseToken: string) => void, - [google.BillingEventType.ACKNOWLEDGE_PURCHASES_RESPONSE]: (result: google.BillingResult) => void - [google.BillingEventType.QUERY_PURCHASES_RESPONSE]: (result: google.BillingResult, purchases: google.Purchase[]) => void, - [google.BillingEventType.BILLING_CONFIG_RESPONSE]: (result: google.BillingResult, config: google.BillingConfig) => void - [google.BillingEventType.ALTERNATIVE_BILLING_ONLY_TOKEN_RESPONSE]: - (result: google.BillingResult, alternativeBillingOnlyReportingDetails: google.AlternativeBillingOnlyReportingDetails) => void - [google.BillingEventType.EXTERNAL_OFFER_REPORTING_DETAILS_RESPONSE]: - (result: google.BillingResult, externalOfferReportingDetails: google.ExternalOfferReportingDetails) => void - [google.BillingEventType.ALTERNATIVE_BILLING_ONLY_AVAILABILITY_RESPONSE]: (result: google.BillingResult) => void - [google.BillingEventType.EXTERNAL_OFFER_AVAILABILITY_RESPONSE]: (result: google.BillingResult) => void - [google.BillingEventType.ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG_RESPONSE]: (result: google.BillingResult) => void - [google.BillingEventType.EXTERNAL_OFFER_INFORMATION_DIALOG_RESPONSE]: (result: google.BillingResult) => void - [google.BillingEventType.IN_APP_MESSAGE_RESPONSE]: (result: google.InAppMessageResult) => void -} - -class Billing { - private _eventTarget: EventTarget = new EventTarget(); - constructor () { - if (!JSB || !jsb.googleBilling) { - return; - } - jsb.onBillingSetupFinished = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.BILLING_SETUP_FINISHED, result); - }; - - jsb.onBillingServiceDisconnected = (): void => { - this._eventTarget.emit(google.BillingEventType.BILLING_SERVICE_DISCONNECTED); - }; - - jsb.onProductDetailsResponse = ( - result: google.BillingResult, - productDetailsList: google.ProductDetails[], - ): void => { - this._eventTarget.emit(google.BillingEventType.PRODUCT_DETAILS_RESPONSE, result, productDetailsList); - }; - - jsb.onPurchasesUpdated = ( - result: google.BillingResult, - purchaseList: google.Purchase[], - ): void => { - this._eventTarget.emit(google.BillingEventType.PURCHASES_UPDATED, result, purchaseList); - }; - - jsb.onConsumeResponse = ( - result: google.BillingResult, - purchaseToken: string, - ): void => { - this._eventTarget.emit(google.BillingEventType.CONSUME_RESPONSE, result, purchaseToken); - }; - - jsb.onAcknowledgePurchaseResponse = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.ACKNOWLEDGE_PURCHASES_RESPONSE, result); - }; - - jsb.onQueryPurchasesResponse = ( - result: google.BillingResult, - purchaseList: google.Purchase[], - ): void => { - this._eventTarget.emit(google.BillingEventType.QUERY_PURCHASES_RESPONSE, result, purchaseList); - }; - - jsb.onBillingConfigResponse = (result: google.BillingResult, config: google.BillingConfig): void => { - this._eventTarget.emit(google.BillingEventType.BILLING_CONFIG_RESPONSE, result, config); - }; - - jsb.onAlternativeBillingOnlyTokenResponse = ( - result: google.BillingResult, - details: google.AlternativeBillingOnlyReportingDetails, - ): void => { - this._eventTarget.emit(google.BillingEventType.ALTERNATIVE_BILLING_ONLY_TOKEN_RESPONSE, result, details); - }; - - jsb.onExternalOfferReportingDetailsResponse = (result: google.BillingResult, details: google.ExternalOfferReportingDetails): void => { - this._eventTarget.emit(google.BillingEventType.EXTERNAL_OFFER_REPORTING_DETAILS_RESPONSE, result, details); - }; - - jsb.onAlternativeBillingOnlyAvailabilityResponse = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.ALTERNATIVE_BILLING_ONLY_AVAILABILITY_RESPONSE, result); - }; - - jsb.onExternalOfferAvailabilityResponse = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.EXTERNAL_OFFER_AVAILABILITY_RESPONSE, result); - }; - - jsb.onAlternativeBillingOnlyInformationDialogResponse = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG_RESPONSE, result); - }; - - jsb.onExternalOfferInformationDialogResponse = (result: google.BillingResult): void => { - this._eventTarget.emit(google.BillingEventType.EXTERNAL_OFFER_INFORMATION_DIALOG_RESPONSE, result); - }; - - jsb.onInAppMessageResponse = (result: google.InAppMessageResult): void => { - this._eventTarget.emit(google.BillingEventType.IN_APP_MESSAGE_RESPONSE, result); - }; - } - - /** - * @en Starts up BillingClient setup process asynchronously. - * @zh 异步启动 BillingClient 设置过程。 - */ - public startConnection (): void { - jsb.googleBilling?.startConnection(); - } - - /** - * @en Closes the connection and releases all held resources such as service connections. - * @zh 关闭连接并释放所有持有的资源,例如服务连接。 - */ - public endConnection (): void { - jsb.googleBilling?.endConnection(); - } - - /** - * @en Get the current billing client connection state. - * @zh 获取当前billing客户端连接状态。 - */ - public getConnectionState (): number { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.getConnectionState(); - } - return google.ConnectionState.DISCONNECTED; - } - - /** - * @en Checks if the client is currently connected to the service, so that requests to other methods will succeed. - Returns true if the client is currently connected to the service, false otherwise. - * @zh 检查客户端当前是否连接到服务,以便对其他方法的请求能够成功。 - 如果客户端当前已连接到服务,则返回 true,否则返回 false。 - */ - public isReady (): boolean { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.isReady(); - } - return false; - } - - /** - * @en Performs a network query the details of products available for sale in your app. - * @zh 执行网络查询您的应用中可供销售的产品的详细信息。 - * @param productId @zh 产品ID。 @en product id. - * @param productType @zh 产品类型。 @en product type. - * - */ - public queryProductDetailsParams (productId: string[], productType: google.ProductType): void { - jsb.googleBilling?.queryProductDetailsParams(productId, productType); - } - - /** - * @en Initiates the billing flow for an in-app purchase or subscription. - * @zh 启动应用内购买或订阅的计费流程。 - * @param productDetails @zh 产品详情。 @en product details. - * @param selectedOfferToken @zh 选择提供的token。 @en selected offer token. - */ - public launchBillingFlow (productDetails: google.ProductDetails[], selectedOfferToken: string | null): void { - jsb.googleBilling?.launchBillingFlow(productDetails, selectedOfferToken); - } - - /** - * @en Consumes a given in-app product. - * @zh 消费指定的应用内产品。 - * @param purchase @zh 已经购买的产品。 @en Purchased Products. - */ - public consumePurchases (purchase: google.Purchase[]): void { - jsb.googleBilling?.consumePurchases(purchase); - } - - /** - * @en Acknowledges in-app purchases. - * @zh 确认应用内购买。 - * @param purchase @zh 已经购买的产品。 @en Purchased Products. - */ - public acknowledgePurchase (purchase: google.Purchase[]): void { - jsb.googleBilling?.acknowledgePurchase(purchase); - } - - /** - * @en Returns purchases details for currently owned items bought within your app. - * @zh 返回您应用内当前拥有的购买商品的购买详情。 - * @param productType @zh 产品类型 @en Product type. - */ - public queryPurchasesAsync (productType: google.ProductType): void { - jsb.googleBilling?.queryPurchasesAsync(productType); - } - - /** - * @en Gets the billing config, which stores configuration used to perform billing operations. - * @zh 获取计费配置,其中存储用于执行计费操作的配置。 - */ - public getBillingConfigAsync (): void { - jsb.googleBilling?.getBillingConfigAsync(); - } - - /** - * @en Creates alternative billing only purchase details that can be used to report a transaction made - * via alternative billing without user choice to use Google Play billing. - * @zh 创建仅限替代结算的购买详情,可用于报告通过替代结算进行的交易,而无需用户选择使用 Google Play 结算。 - */ - public createAlternativeBillingOnlyReportingDetailsAsync (): void { - jsb.googleBilling?.createAlternativeBillingOnlyReportingDetailsAsync(); - } - - /** - * @en Checks the availability of offering alternative billing without user choice to use Google Play billing. - * @zh 检查是否可以提供替代结算方式,而无需用户选择使用 Google Play 结算方式。 - */ - public isAlternativeBillingOnlyAvailableAsync (): void { - jsb.googleBilling?.isAlternativeBillingOnlyAvailableAsync(); - } - - /** - * @en Creates purchase details that can be used to report a transaction made via external offer. - * @zh 创建可用于报告通过外部报价进行的交易的购买详情。 - */ - public createExternalOfferReportingDetailsAsync (): void { - jsb.googleBilling?.createExternalOfferReportingDetailsAsync(); - } - - /** - * @en Checks the availability of providing external offer. - * @zh 检查提供外部报价的可用性。 - */ - public isExternalOfferAvailableAsync (): void { - jsb.googleBilling?.isExternalOfferAvailableAsync(); - } - - /** - * @en Checks if the specified feature or capability is supported by the Play Store. - * @zh 检查 Play Store 是否支持指定的功能。 - * @param feature @zh 功能特性 @en feature. - */ - public isFeatureSupported (feature: string): google.BillingResult | null { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.isFeatureSupported(feature); - } - return null; - } - - /** - * @en Shows the alternative billing only information dialog on top of the calling app. - * @zh 在调用应用程序顶部显示仅显示备用计费信息对话框。 - */ - public showAlternativeBillingOnlyInformationDialog (): google.BillingResult | null { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.showAlternativeBillingOnlyInformationDialog(); - } - return null; - } - - /** - * @en Shows the external offer information dialog on top of the calling app. - * @zh 在调用应用程序顶部显示外部优惠信息对话框。 - */ - public showExternalOfferInformationDialog (): google.BillingResult | null { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.showExternalOfferInformationDialog(); - } - return null; - } - - /** - * @en Overlays billing related messages on top of the calling app. - * @zh 在调用应用程序上叠加与计费相关的消息。 - */ - public showInAppMessages (): google.BillingResult | null { - if (jsb.googleBilling) { - // eslint-disable-next-line @typescript-eslint/no-unsafe-return - return jsb.googleBilling.showInAppMessages(); - } - return null; - } - - public on (type: K, callback: BillingEventMap[K], target?: unknown): BillingEventMap[K] { - this._eventTarget.on(type, callback, target); - return callback; - } - public once (type: K, callback: BillingEventMap[K], target?: unknown): BillingEventMap[K] { - this._eventTarget.once(type, callback, target); - return callback; - } - public off (eventType: K, callback?: BillingEventMap[K], target?: any): void { - this._eventTarget.off(eventType, callback, target); - } -} - -const gpBilling = new Billing(); +import './billing-enum'; +const ns = JSB ? jsb : {} as unknown as typeof jsb; export namespace google { - /** - * @en Google Play Billing event type - * @zh Google Play Billing事件类型 - */ - export enum BillingEventType { - /** - * @en - * Called to notify that setup is complete. - * - * @zh - * 当安装已经完成时触发。 - */ - BILLING_SETUP_FINISHED = 'billing_setup_finished', - /** - * @en - * Called to notify that the connection to the billing service was lost. - * - * @zh - * 当Billing服务连接断开时触发。 - */ - BILLING_SERVICE_DISCONNECTED = 'billing_service_disconnected', - /** - * @en - * Listen to this event to get notifications of purchase updates. - * - * @zh - * 监听这个事件可以获取购买更新。 - */ - PURCHASES_UPDATED = 'purchases_updated', - /** - * @en - * Called to notify that query product details operation has finished. - * - * @zh - * 查询产品详细信息操作完成时触发。 - */ - PRODUCT_DETAILS_RESPONSE = 'product_details_response', - /** - * @en - * Called to notify that the query purchases operation has finished. - * - * @zh - * 查询购买操作完成时触发。 - */ - QUERY_PURCHASES_RESPONSE = 'query_purchases_response', - /** - * @en - * Called to notify that a consume operation has finished. - * - * @zh - * 消费操作完成时触发。 - */ - CONSUME_RESPONSE = 'consume_response', - /** - * @en - * Called to notify that an acknowledge purchase operation has finished. - * - * @zh - * 确认购买操作完成时触发。 - */ - ACKNOWLEDGE_PURCHASES_RESPONSE = 'acknowledge_purchases_response', - /** - * @en - * Called to notify when the get billing config flow has finished. - * - * @zh - * 获取Billing配置流程完成时触发。 - */ - BILLING_CONFIG_RESPONSE = 'billing_config_response', - /** - * @en - * Called to receive the results from createAlternativeBillingOnlyReportingDetailsAsync when it is finished. - * - * @zh - * 当调用createAlternativeBillingOnlyReportingDetailsAsync接口完成时触发,可以接收调用结果。 - */ - ALTERNATIVE_BILLING_ONLY_TOKEN_RESPONSE = 'alternative_billing_only_token_response', - /** - * @en - * Called to receive the results from createExternalOfferReportingDetailsAsync when it is finished. - * - * @zh - * 当调用createExternalOfferReportingDetailsAsync接口完成时触发,可以接收调用结果。 - */ - EXTERNAL_OFFER_REPORTING_DETAILS_RESPONSE = 'external_offer_reporting_details_response', - /** - * @en - * Called to receive the results from BillingClient#isAlternativeBillingOnlyAvailableAsync when it is finished. - * - * @zh - * 当调用BillingClient#isAlternativeBillingOnlyAvailableAsync接口完成时触发,可以接收调用结果。 - */ - ALTERNATIVE_BILLING_ONLY_AVAILABILITY_RESPONSE = 'alternative_billing_only_availability_response', - /** - * @en - * Called to receive the results from BillingClient#isExternalOfferAvailableAsync when it is finished. - * - * @zh - * 当调用BillingClient#isExternalOfferAvailableAsync接口完成时触发,可以接收调用结果。 - */ - EXTERNAL_OFFER_AVAILABILITY_RESPONSE = 'external_offer_availability_response', - /** - * @en - * Called to notify that the alternative billing only dialog flow is finished. - * - * @zh - * 当仅替代Billing对话流程已完成时触发。 - */ - ALTERNATIVE_BILLING_ONLY_INFORMATION_DIALOG_RESPONSE = 'alternative_billing_only_information_dialog_response', - /** - * @en - * Called to notify that the external offer information dialog flow is finished. - * - * @zh - * 当外部报价信息对话流程已完成时触发。 - */ - EXTERNAL_OFFER_INFORMATION_DIALOG_RESPONSE = 'external_offer_information_dialog_response', - /** - * @en - * Called to notify when the in-app messaging flow has finished. - * - * @zh - * 当应用内消息流程完成时触发。 - */ - IN_APP_MESSAGE_RESPONSE = 'in_app_message_response', - + export namespace billing { + export const BillingClient = ns.BillingClient; + export const BillingResult = ns.BillingResult; + export const InAppMessageResult = ns.InAppMessageResult; + export const ProductDetails = ns.ProductDetails; + export const Purchase = ns.Purchase; + export const PendingPurchasesParams = ns.PendingPurchasesParams; + export const QueryProductDetailsParams = ns.QueryProductDetailsParams; + export const BillingFlowParams = ns.BillingFlowParams; + export const ConsumeParams = ns.ConsumeParams; + export const AcknowledgePurchaseParams = ns.AcknowledgePurchaseParams; + export const QueryPurchasesParams = ns.QueryPurchasesParams; + export const GetBillingConfigParams = ns.GetBillingConfigParams; + export const InAppMessageParams = ns.InAppMessageParams; + } +} +export declare namespace google { + export namespace billing { + export type AcknowledgePurchaseResponseListener = jsb.AcknowledgePurchaseResponseListener; + export type AlternativeBillingOnlyAvailabilityListener = jsb.AlternativeBillingOnlyAvailabilityListener; + export type AlternativeBillingOnlyInformationDialogListener = jsb.AlternativeBillingOnlyInformationDialogListener; + export type AlternativeBillingOnlyReportingDetailsListener = jsb.AlternativeBillingOnlyReportingDetailsListener; + export type BillingConfigResponseListener = jsb.BillingConfigResponseListener; + export type ConsumeResponseListener = jsb.ConsumeResponseListener; + export type ExternalOfferAvailabilityListener = jsb.ExternalOfferAvailabilityListener; + export type ExternalOfferInformationDialogListener = jsb.ExternalOfferInformationDialogListener; + export type ExternalOfferReportingDetailsListener = jsb.ExternalOfferReportingDetailsListener; + export type InAppMessageResponseListener = jsb.InAppMessageResponseListener; + export type ProductDetailsResponseListener = jsb.ProductDetailsResponseListener; + export type PurchasesResponseListener = jsb.PurchasesResponseListener; + export type PurchasesUpdatedListener = jsb.PurchasesUpdatedListener; + export type UserChoiceBillingListener = jsb.UserChoiceBillingListener; + export type BillingClientStateListener = jsb.BillingClientStateListener; + + export type UserChoiceDetails = jsb.UserChoiceDetails; + export type AccountIdentifiers = jsb.AccountIdentifiers; + export type PendingPurchaseUpdate = jsb.PendingPurchaseUpdate; + export type BillingConfig = jsb.BillingConfig; + export type AlternativeBillingOnlyReportingDetails = jsb.AlternativeBillingOnlyReportingDetails; + export type ExternalOfferReportingDetails = jsb.ExternalOfferReportingDetails; + export namespace InAppMessageResult { + export type InAppMessageResponseCode = jsb.InAppMessageResponseCode; + } + export type InAppMessageResult = jsb.InAppMessageResult; + + export namespace PendingPurchasesParams { + export type Builder = jsb.PendingPurchasesParamsBuilder; + } + export type PendingPurchasesParams = jsb.PendingPurchasesParams; + + export namespace ProductDetails { + export type RecurrenceMode = jsb.RecurrenceMode; + export type OneTimePurchaseOfferDetails = jsb.OneTimePurchaseOfferDetails; + export type InstallmentPlanDetails = jsb.InstallmentPlanDetails; + export type PricingPhase = jsb.PricingPhase; + export type PricingPhases = jsb.PricingPhases; + export type SubscriptionOfferDetails = jsb.SubscriptionOfferDetails; + } + export type ProductDetails = jsb.ProductDetails; + + export namespace Purchase { + export type PurchaseState = jsb.PurchaseState; + } + export type Purchase = jsb.Purchase; + + export namespace BillingClient { + export type Builder = jsb.BillingClientBuilder; + export type ConnectionState = jsb.ConnectionState; + export type BillingResponseCode = jsb.BillingResponseCode; + export type FeatureType = jsb.FeatureType; + export type ProductType = jsb.ProductType; + } + export type BillingClient = jsb.BillingClient; + export namespace BillingFlowParams { + export type Builder = jsb.BillingFlowParamsBuilder; + export namespace SubscriptionUpdateParams { + export type Builder = jsb.SubscriptionUpdateParamsBuilder; + export type ReplacementMode = jsb.ReplacementMode; + } + export type SubscriptionUpdateParams = jsb.SubscriptionUpdateParams; + export namespace ProductDetailsParams { + export type Builder = jsb.ProductDetailsParamsBuilder; + } + export type ProductDetailsParams = jsb.ProductDetailsParams; + + } + export type BillingFlowParams = jsb.BillingFlowParams; + + export namespace QueryProductDetailsParams { + export type Builder = jsb.QueryProductDetailsParamsBuilder; + export namespace Product { + export type Builder = jsb.QueryProductDetailsParamsProductBuilder; + } + export type Product = jsb.QueryProductDetailsParamsProduct; + } + export type QueryProductDetailsParams = jsb.QueryProductDetailsParams; + + export namespace BillingResult { + export type Builder = jsb.BillingResultBuilder; + } + export type BillingResult = jsb.BillingResult; + + export namespace ConsumeParams { + export type Builder = jsb.ConsumeParamsBuilder; + } + export type ConsumeParams = jsb.ConsumeParams; + + export namespace AcknowledgePurchaseParams { + export type Builder = jsb.AcknowledgePurchaseParamsBuilder; + } + export type AcknowledgePurchaseParams = jsb.AcknowledgePurchaseParams; + + export namespace QueryPurchasesParams { + export type Builder = jsb.QueryPurchasesParamsBuilder; + } + export type QueryPurchasesParams = jsb.QueryPurchasesParams; + + namespace InAppMessageParams { + export type Builder = jsb.InAppMessageParamsBuilder; + export type InAppMessageCategoryId = jsb.InAppMessageCategoryId; + } + export type InAppMessageParams = jsb.InAppMessageParams; + namespace GetBillingConfigParams { + export type Builder = jsb.GetBillingConfigParams; + } + export type GetBillingConfigParams = jsb.GetBillingConfigParams; + } - - /** - * @en - * Supported Product types. - * - * @zh - * 支持的产品类型。 - */ - export enum ProductType { - /** - * @en - * A Product type for Android apps in-app products. - * - * @zh - * Android 应用内产品的产品类型。 - */ - INAPP = 'inapp', - /** - * @en - * A Product type for Android apps subscriptions. - * - * @zh - * Android 应用程序订阅的产品类型。 - */ - SUBS = 'subs' - } - - /** - * @en - * Possible response codes. - * - * @zh - * 可能的响应代码。 - */ - export enum BillingResponseCode { - /** - * @en - * This field is deprecated. - * See SERVICE_UNAVAILABLE which will be used instead of this code. - * - * @zh - * 这个字段已经废弃。 - * 看看SERVICE_UNAVAILABLE将使用哪一个来代替此代码。 - */ - SERVICE_TIMEOUT = -3, - /** - * @en - * The requested feature is not supported by the Play Store on the current device. - * - * @zh - * 当前设备上的 Play Store 不支持所请求的功能。 - */ - FEATURE_NOT_SUPPORTED = -2, - /** - * @en - * The app is not connected to the Play Store service via the Google Play Billing Library. - * - * @zh - * 该应用未通过 Google Play Billing库连接到 Play Store 服务。 - */ - SERVICE_DISCONNECTED = -1, - /** - * @en - * Success. - * - * @zh - * 成功。 - */ - OK = 0, - /** - * @en - * Transaction was canceled by the user. - * - * @zh - * 交易已被用户取消。 - */ - USER_CANCELED = 1, - /** - * @en - * The service is currently unavailable. - * - * @zh - * 当前设备上的 Play Store 不支持所请求的功能。 - */ - SERVICE_UNAVAILABLE = 2, - /** - * @en - * A user billing error occurred during processing. - * - * @zh - * 处理过程中出现用户billing错误。 - */ - BILLING_UNAVAILABLE = 3, - /** - * @en - * The requested product is not available for purchase. - * - * @zh - * 所请求的产品无法购买。 - */ - ITEM_UNAVAILABLE = 4, - /** - * @en - * Error resulting from incorrect usage of the API. - * - * @zh - * 由于错误使用 API 而导致的错误。 - */ - DEVELOPER_ERROR = 5, - /** - * @en - * Fatal error during the API action. - * - * @zh - * API 操作期间发生致命错误。 - */ - ERROR = 6, - /** - * @en - * The purchase failed because the item is already owned. - * - * @zh - * 购买失败,因为该物品已被拥有。 - */ - ITEM_ALREADY_OWNED = 7, - /** - * @en - * Requested action on the item failed since it is not owned by the user. - * - * @zh - * 由于该项目不属于用户,因此对该项目请求的操作失败。 - */ - ITEM_NOT_OWNED = 8, - /** - * @en - * A network error occurred during the operation. - * - * @zh - * 操作期间发生网络错误。 - */ - NETWORK_ERROR = 12, - } - - /** - * @en - * Recurrence mode of the pricing phase. - * - * @zh - * 定价阶段的复现模式。 - */ - export enum RecurrenceMode { - /** - * @en - * The billing plan payment recurs for infinite billing periods unless cancelled. - * - * @zh - * 除非取消,否则billing计划付款将无限期地重复。 - */ - INFINITE_RECURRING = 1, - /** - * @en - * The billing plan payment recurs for a fixed number of billing period set in billingCycleCount. - * - * @zh - * Billing计划付款将在 billingCycleCount 中设置的固定计费周期内重复发生。 - */ - FINITE_RECURRING = 2, - /** - * @en - * The billing plan payment is a one time charge that does not repeat. - * - * @zh - * Billing计划付款是一次性费用,不会重复。 - */ - NON_RECURRING = 3, - } - - /** - * @en - * Connection state of billing client. - * - * @zh - * Billing client的连接状态 - */ - export enum ConnectionState { - /** - * @en - * This client was not yet connected to billing service or was already closed. - * - * @zh - * 此客户端尚未连接到Billing服务或已关闭。 - */ - DISCONNECTED = 0, - /** - * @en - * This client is currently in process of connecting to billing service. - * - * @zh - * 此客户端目前正在连接到Billing服务。 - */ - CONNECTING = 1, - /** - * @en - * This client is currently connected to billing service. - * - * @zh - * 此客户端当前已连接到Billing服务。 - */ - CONNECTED = 2, - /** - * @en - * This client was already closed and shouldn't be used again. - * - * @zh - * 该客户端已关闭,不应再次使用。 - */ - CLOSED = 3, - } - - /** - * @en - * Features/capabilities supported by isFeatureSupported. - * - * @zh - * 支持的特性/能力isFeatureSupported。 - */ - export enum FeatureType { - /** - * @en - * Alternative billing only. - * - * @zh - * 仅限替代Billing。 - */ - ALTERNATIVE_BILLING_ONLY = 'jjj', - /** - * @en - * Get billing config. - * - * @zh - * 获取计费配置。 - */ - BILLING_CONFIG = 'ggg', - /** - * @en - * Play billing library support for external offer. - * - * @zh - * Play billing库支持外部报价。 - */ - EXTERNAL_OFFER = 'kkk', - /** - * @en - * Show in-app messages. - * - * @zh - * 显示应用内消息。 - */ - IN_APP_MESSAGING = 'bbb', - /** - * @en - * Launch a price change confirmation flow. - * - * @zh - * 启动价格变动确认流程。 - */ - PRICE_CHANGE_CONFIRMATION = 'priceChangeConfirmation', - /** - * @en - * Play billing library support for querying and purchasing. - * - * @zh - * Play Billing库支持查询、购买。 - */ - PRODUCT_DETAILS = 'fff', - /** - * @en - * Purchase/query for subscriptions. - * - * @zh - * 购买/查询订阅。 - */ - SUBSCRIPTIONS = 'subscriptions', - /** - * @en - * Subscriptions update/replace. - * - * @zh - * 订阅更新/替换。 - */ - UBSCRIPTIONS_UPDATE = 'subscriptionsUpdate', - } - - /** - * @en - * Possible purchase states. - * - * @zh - * 可能的购买状态。 - */ - export enum PurchaseState { - /** - * @en - * Purchase is pending and not yet completed to be processed by your app. - * - * @zh - * 购买处于待处理状态且尚未完成,无法由您的应用程序处理。 - */ - PENDING = 2, - /** - * @en - * Purchase is completed.. - * - * @zh - * 购买完成。 - */ - PURCHASED = 1, - /** - * @en - * Purchase with unknown state. - * - * @zh - * 未知状态 - */ - UNSPECIFIED_STATE = 0, - } - - /** - * @en - * Possible response codes. - * - * @zh - * InAppMessage可能的影响代码。 - */ - export enum InAppMessageResponseCode { - /** - * @en - * The flow has finished and there is no action needed from developers. - * - * @zh - * 流程已完成,开发人员无需采取任何行动。 - */ - NO_ACTION_NEEDED = 0, - /** - * @en - * The subscription status changed. - * - * @zh - * 订阅状态已改变。 - */ - SUBSCRIPTION_STATUS_UPDATED = 1, - } - - export type BillingResult = jsb.BillingResult; - export type OneTimePurchaseOfferDetails = jsb.OneTimePurchaseOfferDetails; - export type InstallmentPlanDetails = jsb.InstallmentPlanDetails; - export type PricingPhase = jsb.PricingPhase; - export type SubscriptionOfferDetails = jsb.SubscriptionOfferDetails; - export type ProductDetails = jsb.ProductDetails; - export type AccountIdentifiers = jsb.AccountIdentifiers; - export type PendingPurchaseUpdate = jsb.PendingPurchaseUpdate; - export type Purchase = jsb.Purchase; - export type BillingConfig = jsb.BillingConfig; - export type AlternativeBillingOnlyReportingDetails = jsb.AlternativeBillingOnlyReportingDetails; - export type ExternalOfferReportingDetails = jsb.ExternalOfferReportingDetails; - export type InAppMessageResult = jsb.InAppMessageResult; - - /** - * @en - * Interface for Google Play blling module. - * - * @zh - * Google Play blling模块的接口。 - * - */ - export const billing = gpBilling; }