Full documentation (text version for AI assistants & reference)
Plain-text export: llms-full.txt · llms.txt
Welcome to the Xsolla SDK 3
https://developers.xsolla.com/sdk/
*Xsolla SDK 3* is built for developers who want to monetize their game and go live across distribution channels — App Store, Google Play, Android APK, iOS, Xsolla Launcher and standalone PC. Powered by **Xsolla Pay Station**, with multi-platform support and direct distribution built in.1,000+payment methods200+countries130+currencies25+UI languages
## SDK Explorer
**Interactive Demo**: Walk through every step of the integration — authentication, catalog loading, purchasing, and finalization — in a live, interactive environment.
- ✓No account required
- ✓No code to write
- ✓Live API calls, not simulated
[Try SDK Explorer](https://developers.xsolla.com/sdk/demo/)[![SDK Explorer interface — try the Xsolla SDK payment flow step by step]](https://developers.xsolla.com/sdk/demo/)
## Buy Button: Instant Web Shop Access
The April 2025 contempt ruling in Epic v. Apple requires Apple to allow external payment links in US iOS apps; the December 2025 appellate modification permits Apple to charge a commission on such transactions, with the rate under court review. Beyond the U.S., Japan's Mobile Software Competition Act (effective December 18, 2025) and Apple's CADE antitrust settlement in Brazil (effective June 18, 2026) likewise require Apple to let developers offer external payments and web link-outs on iOS. In the EU, Apple's unified business terms (effective October 1, 2026) let an app offer Apple In-App Purchase alongside alternative payment options. The Epic v. Google injunction (effective October 29, 2025) requires Google Play to permit alternative billing options and external payment links for US users; in July 2026, Epic and Google withdrew only their motion to modify this injunction, not their separate settlement, so the original injunction remains the operative court order, with its end date disputed across sources. The Xsolla SDK is fully compliant with both Apple's revised App Store guidelines and Google Play's updated billing policies.
The [**Buy Button ↗**](https://xsolla.com/mobile-buy-button) [(xsolla.com)](https://xsolla.com/mobile-buy-button) feature enables direct access to your Web Shop payment UI: **One-Tap Purchase Flow**
Players access payment UI for specific items instantly — no extra navigation steps.**Seamless Integration**
Launch web payment UI directly from your game without breaking user flow.**Expanded Payment Options**
Full Web Shop payment range including Apple Pay and global alternatives.**Enhanced Conversion**
Streamlined purchase flow reduces friction and increases completion rates.**Advanced Analytics**
MMP attribution via [Adjust ↗](https://developers.xsolla.com/solutions/web-shop/analytics/adjust/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/adjust/), [AppsFlyer ↗](https://developers.xsolla.com/solutions/web-shop/analytics/appsflyer/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/appsflyer/), [Airbridge ↗](https://developers.xsolla.com/solutions/web-shop/analytics/airbridge/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/airbridge/), and [Singular ↗](https://developers.xsolla.com/solutions/web-shop/analytics/singular/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/singular/) — maintaining full visibility into your campaigns and revenue.
## Supporting Multiple Monetization Models
With the **Xsolla SDK**, we bring ease of integration to all developers as part of our **"Equal Access for Everyone"** initiative, greatly simplifying the initial phases of integration while allowing for further fine-tuning and customization. Setting and integrating your project with **Xsolla SDK** automatically provides access to a fully-fledged, highly customizable **Xsolla Web Shop** — establishing your direct-to-consumer connection outside of your application.
SDK overview — payment flows, distribution, and direct-to-consumer in one platform
**Out-of-store** payments allow developers to distribute their own application files — like APKs for Android or Notarized versions of apps for iOS (e.g., through Web Distribution) — outside the confines of traditional app stores. When developers opt for distributing games independently, in a direct-to-consumer way, they retain greater control over their profits. This approach is further supported by evolving regulations such as the **Digital Markets Act** (DMA), which expands developers' freedom to offer alternative payment methods. The answer to these complexities lies in **Xsolla Pay Station**, accessible through the **Xsolla SDK**.
## Solutions
**Xsolla Pay Station** is specifically designed to enable developers to monetize their applications efficiently, preserving a larger share of revenue. With over 1,000 payment options, Xsolla Pay Station opens up monetization opportunities in regions and through methods not typically supported by platform-native billing, letting developers tap into new markets and cater to a broader audience.
Additionally, pairing the **Xsolla SDK** with distribution solutions like those from *Digital Turbine* amplifies this advantage. *Digital Turbine* drives large-scale APK distribution through partnerships with major carriers and device manufacturers, putting games directly on millions of devices worldwide. Beyond pre-installs, its SingleTap technology delivers instant installs from ads, links, or messages from a CDN of your choice — bypassing "*scare screens*," app store friction and boosting conversions. This combination lets developers go direct-to-player at scale, keep UA workflows intact, and capture a greater share of their revenue.
Please reach out to your Account Manager and/or Business Development team for recipes for success to supercharge your out-of-store distribution strategy with up-to-date tips and tricks.
### Alternative Payment Options
If you're interested in implementing [Apple's Alternative Payment options ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) [(developer.apple.com)](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) on the App Store or [Google Play's Alternative Billing ↗](https://developer.android.com/google/play/billing/alternative) [(developer.android.com)](https://developer.android.com/google/play/billing/alternative), please contact your Account Manager and/or Business Development team for guidance and implementation support. [SDK**Mobile SDK**iOS · Android→](https://developers.xsolla.com/sdk/mobilesdk/)[SDK**Unity SDK**iOS · Android · Windows · macOS · Web→](https://developers.xsolla.com/sdk/unity/)[SDK**Windows Stores SDK**Windows · Epic Games→](https://developers.xsolla.com/sdk/windows/)
Reporting External Transactions to Google Play
https://developers.xsolla.com/sdk/compliance/android
When you sell through **Xsolla** on storefronts where Google permits external transactions, Google still requires you to report those transactions. This page explains what Google expects, and how to build that report from the data **Xsolla** already sends you.
## Who reports what
Reporting is part of your integration, not something **Xsolla** does on your behalf.
| | Handled by |
| --- | --- |
| Processing the payment, tax calculation, refunds | Xsolla |
| Notifying your backend of each order | Xsolla (webhooks) |
| Obtaining Google's external transaction token in your app | You |
| Filing the report with Google | You, from your own server |
Google Play's reporting API is authenticated with **your own** service-account credentials, tied to **your** app's listing in Play Console, so no payment provider can file on your behalf. What **Xsolla** provides is the transaction data the report is built from.
## When this applies
Google's programs differ by region, and the list has grown. Check which ones apply to where you ship before building anything.
| Program | Applies in | Reporting required |
| --- | --- | --- |
| External content links & alternative billing | United States | Not yet — starting October 1, 20261 |
| Billing choice | United Kingdom, European Economic Area | Yes |
| External offers | European Economic Area | Yes |
| External payments | Japan | Yes |
| User Choice Billing | 35+ countries, including the EEA, UK, Australia, Brazil, Indonesia, Japan, and South Africa | Yes |
note
Rates, deadlines and eligibility change often, and they differ per program and region. This page deliberately avoids repeating Google's numbers. Always check Google's own pages for current terms: [User Choice Billing ↗](https://support.google.com/googleplay/android-developer/answer/13821247), [Billing choice (UK/EEA) ↗](https://support.google.com/googleplay/android-developer/answer/17161464), [External offers (EEA) ↗](https://support.google.com/googleplay/android-developer/answer/14372887), [External content links & alternative billing (US) ↗](https://support.google.com/googleplay/android-developer/answer/16470497), and [External payments (Japan) ↗](https://support.google.com/googleplay/android-developer/answer/16787536). important
Each program is enrolled separately in Play Console and comes with its own updated Developer Distribution Agreement terms. Sort that out before you write code, since the Billing Library APIs below report the program as unavailable without it.
To enable external transactions only for the storefronts that permit them, see [How to detect Google Play storefront (Android)?](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detect-gpb-storefront-android/).
## The flow end to end
- Your app checks program availability and asks the Play Billing Library for an **external transaction token**.
- Your app sends that token to your backend, which stores it against the customer.
- The player buys through **Xsolla** as normal — in-app for User Choice Billing and alternative billing, or after a link-out for external offers, external content links, external payments, and billing choice.
- **Xsolla** sends your backend an [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_paid) webhook with the financial detail of that order.
- Your backend pairs the token with the order data and reports the transaction to Google — most programs expect this within a fixed window measured in hours, not days, far tighter than a monthly cadence, so build the job to run per webhook rather than batching. See Google's [reporting guide ↗](https://developer.android.com/google/play/billing/outside-gpb-backend) for the exact deadline per program.
- Refunds and chargebacks arrive as [`order_canceled`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_canceled) and are reported to Google as refunds against the original transaction.
## Getting the token
Tokens come from the Play Billing Library, not from the **Xsolla SDK**. Which surface you call depends on the program. The API differs per program
`enableUserChoiceBilling` is the surface for **User Choice Billing**. External offers, external content links, external payments, and billing choice use a newer, unified surface instead — `isBillingProgramAvailableAsync`, `createBillingProgramReportingDetailsAsync`, and `launchExternalLink`. Alternative-billing-only integrations (no choice screen shown) use a third method, `createAlternativeBillingOnlyReportingDetailsAsync`. Check [Google's alternative billing overview ↗](https://developer.android.com/google/play/billing/alternative) for which surface and Billing Library version your program needs.
Even within that unified surface the four programs aren't interchangeable. The link-out example below is written for **external offers** and works unchanged for **external content links**. **External payments** swaps `LaunchExternalLinkParams` for `DeveloperBillingOptionParams`, and **billing choice** additionally needs `setDeveloperBillingType` plus a check of `getBillingChoiceAvailabilityDetails()` on the availability response before it may link out.
```java
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.PurchasesUpdatedListener;
// Application context, and Google Play Billing's own purchase-update listener.
final Context context = // ...
final PurchasesUpdatedListener purchasesUpdatedListener = // ...
final BillingClient googlePlayBillingClient = BillingClient.newBuilder(context)
.setListener(purchasesUpdatedListener)
.enableUserChoiceBilling(userChoiceDetails -> {
// Called when the player picks your alternative over Google Play Billing.
final String token = userChoiceDetails.getExternalTransactionToken();
// Send the token to your own backend and store it before continuing.
sendTokenToYourServer(token);
// ...then start your Xsolla purchase, attaching the token as shown below.
})
.build();
```
```java
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.BillingProgram;
import com.android.billingclient.api.BillingClient.BillingResponseCode;
import com.android.billingclient.api.BillingProgramReportingDetailsParams;
import com.android.billingclient.api.LaunchExternalLinkParams;
// Application context, the activity to launch the external link from, and the
// Xsolla Pay Station or Web Shop URL to send the player to.
final Context context = // ...
final Activity activity = // ...
final String checkoutUrl = // ...
// Use EXTERNAL_CONTENT_LINK instead for external content links.
final int billingProgram = BillingProgram.EXTERNAL_OFFER;
final BillingClient googlePlayBillingClient = BillingClient.newBuilder(context)
.enableBillingProgram(billingProgram)
.build();
googlePlayBillingClient.isBillingProgramAvailableAsync(billingProgram, (billingResult, availability) -> {
if (billingResult.getResponseCode() != BillingResponseCode.OK) return;
final BillingProgramReportingDetailsParams params = BillingProgramReportingDetailsParams.newBuilder()
.setBillingProgram(billingProgram)
.build();
googlePlayBillingClient.createBillingProgramReportingDetailsAsync(params, (reportingResult, details) -> {
if (reportingResult.getResponseCode() != BillingResponseCode.OK) return;
final String token = details.getExternalTransactionToken();
// Send the token to your own backend and store it before continuing.
sendTokenToYourServer(token);
final LaunchExternalLinkParams linkParams = LaunchExternalLinkParams.newBuilder()
.setBillingProgram(billingProgram)
.setLinkUri(Uri.parse(checkoutUrl))
// A checkout page is a digital content offer. LINK_TO_APP_DOWNLOAD is
// billed per install instead of per transaction, and its reports require
// installedAppPackage and installedAppCategory.
.setLinkType(LaunchExternalLinkParams.LinkType.LINK_TO_DIGITAL_CONTENT_OFFER)
.setLaunchMode(LaunchExternalLinkParams.LaunchMode.LAUNCH_IN_EXTERNAL_BROWSER_OR_APP)
.build();
googlePlayBillingClient.launchExternalLink(activity, linkParams, launchResult -> {
// The player leaves the app here and finishes the purchase on your own
// site (Pay Station or Web Shop). See "Correlating the token" below.
});
});
});
```
The token returned by either surface is an opaque string — `externalTransactionToken` — that Google correlates against the report you file later. Which token types apply, when to request them, and how long they stay valid all vary by region and program. See Google's [reporting guide ↗](https://developer.android.com/google/play/billing/outside-gpb-backend) for the current rules. Generate a fresh token per transaction
Request a new token immediately before each purchase or link-out — don't cache and reuse one across transactions. Only the first payment of a recurring subscription carries a token; renewals are reported against `initialExternalTransactionId` instead. See Google's [reporting guide ↗](https://developer.android.com/google/play/billing/outside-gpb-backend) for the exact rules per program.
### Correlating the token with your Xsolla order
How you tie the token to the order depends on which path the purchase took.
**Purchases that run in-app** — User Choice Billing and alternative billing — go through the **Xsolla SDK**, so pass the token straight into `BillingFlowParams.Builder.setExternalTransactionToken` when you launch the flow, right alongside the product you're selling:
```java
import com.xsolla.android.mobile.BillingFlowParams;
import com.xsolla.android.mobile.ProductDetails;
// token is the one your app just got from the Play Billing Library above, and
// mBillingClient the com.xsolla.android.mobile.BillingClient you initialized earlier.
final ProductDetails productDetails = // ...
final String token = // ...
final Activity activity = // ...
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.setExternalTransactionToken(token)
.build()
);
```
See [Launch a billing flow](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#starting-purchasing-flow) for the rest of `BillingFlowParams.Builder`'s settings.
**Purchases that link out** — external offers, external content links, external payments, and billing choice — leave the app before the player pays, so there's no **Xsolla SDK** call to attach the token to. Correlate it yourself instead: key the stored token to the buyer's user ID, and pair it with the order when the webhook arrives. Google also suggests carrying the token in the link URI as a query parameter, which hands your checkout page the same correlation key — but a token arriving that way still doesn't reach the Xsolla order, so your backend stays the place where the two are joined.
Once the token is attached through `setExternalTransactionToken`, Xsolla builds a `ucb_report` object for the order — a ready-built Google `externalTransactions` request body (`originalPreTaxAmount`, `originalTaxAmount`, `transactionTime`, `userTaxAddress`, and the token itself under `oneTimeTransaction.externalTransactionToken`) — and attaches it to the order webhook. On the combined [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_paid) / `order_canceled` model, it nests under `billing.ucb_report`; on the legacy [`payment`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#payment) / [`refund`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#refund) webhooks, it's at the top level. Either way, report from `ucb_report` directly instead of reconstructing the fields yourself.
## Building the report from webhook data
Most of what a Google transaction report needs is already assembled for you in `ucb_report` — `billing.ucb_report` on `order_paid` / `order_canceled`, or top-level `ucb_report` on the legacy `payment` / `refund` model (see above). If you need to build it yourself, the same data lives in the `order_paid` payload under `billing.payment_details`. Here's where each field comes from either way.
| Google transaction field | Where it comes from |
| --- | --- |
| externalTransactionId | You generate it. Persist it, refunds and renewals reference it |
| externalTransactionToken | The token from the Play Billing Library, forwarded through your Xsolla order (see setExternalTransactionToken above) |
| transactionTime | billing.transaction.payment_date, converted to RFC 3339 |
| originalPreTaxAmount | billing.payment_details.payment.amount minus originalTaxAmount below, converted to micros |
| originalTaxAmount | billing.payment_details.vat.amount outside the US and Canada, sales_tax.amount in the US and Canada. See the note below |
| userTaxAddress.regionCode | user.country — already the two-letter code Google expects, no conversion needed |
| Transaction type (oneTimeTransaction / recurringTransaction / otherRecurringProduct) | Presence and type of billing.purchase.subscription |
| externalSubscription.subscriptionType | RECURRING or PREPAID, from billing.purchase.subscription |
Report what the player paid, not what you receive
`billing.payment_details.payout` is your share after **Xsolla**'s fees. Google's report expects the amount the player was charged, so `originalPreTaxAmount` and `originalTaxAmount` must derive from `billing.payment_details.payment`. Using `payout` under-reports your transactions.
`vat` isn't EU-only despite its name — it's the general non-US/Canada consumption-tax field, so it also carries JCT in Japan and GST elsewhere covered by these programs. India needs a state code
Google requires `userTaxAddress.administrativeArea` in addition to `regionCode` for transactions in India specifically — it's optional everywhere else, and the field only accepts Google's fixed list of Indian states and union territories. `user.country` doesn't carry that level of detail, so if you're assembling the report yourself from the fields above, source the player's state from your own data for Indian transactions. `ucb_report` (see above) already includes it correctly, since Xsolla holds the player's state internally for tax purposes even though `user.country` doesn't expose it.
### Amounts and rounding
Webhook amounts are decimal values, while Google expects integer **micros** — millionths of the currency unit, not the minor units (cents) Apple's report uses. Convert with a decimal type rather than a float, and derive `originalPreTaxAmount` by subtracting the tax you reported rather than recomputing it from a percentage, so the two figures add up. Free trials count
Google requires $0 transactions from free trials to be reported the same as paid ones. Don't filter these out of your reporting job because `billing.payment_details.payment.amount` is zero.
### Refunds
`order_canceled` covers both refunds and chargebacks. Report both with `refundexternaltransaction`, referencing the original `externalTransactionId` — for subscriptions, the `externalTransactionId` of the specific recurrence being refunded. Ignore an `order.id` you've already reported, since [webhooks are retried](https://developers.xsolla.com/sdk/publisher-account/webhooks/#retries) and a repeated delivery must not produce a second refund report.
Unlike Apple's report, you don't need to track a running net yourself: Google recomputes `currentPreTaxAmount` and `currentTaxAmount` automatically once a refund is reported against a transaction.
## What Xsolla can't tell you
Some of Google's requirements sit outside anything **Xsolla** observes. Your backend has to cover them:
- **Tokens that produced no purchase.** Google expects these reported too. There's no order and therefore no webhook, so your token store is the only record.
- **App installs completed through a link-out.** The US external content links program and the EEA external offers program also require reporting successful installs, not just purchases, using the `externalOfferDetails` block (`installedAppPackage`, `installedAppCategory`). Installs aren't purchases, so **Xsolla** has no visibility into them at all — your own attribution tracking has to supply this.
- **Transaction identity.** `externalTransactionId` values are yours to generate and persist. Without them, refunds and renewals can't reference the transaction they belong to.
## Testing
License testers reported through the Play Billing Library are marked with `testPurchase` on Google's side and aren't invoiced. **Xsolla** test orders are marked separately — `order.mode: "sandbox"` on `order_paid` / `order_canceled`, or `transaction.dry_run: 1` on the legacy `payment` / `refund` webhooks — keep these straight, since neither implies the other.
## Further reading
- [Google Play Developer API — externaltransactions ↗](https://developers.google.com/android-publisher/api-ref/rest/v3/externaltransactions) — the reporting endpoints and transaction schema
- [Reporting transactions from outside Google Play's billing system ↗](https://developer.android.com/google/play/billing/outside-gpb-backend)
- [Alternative billing overview ↗](https://developer.android.com/google/play/billing/alternative)
- [Xsolla webhooks](https://developers.xsolla.com/sdk/publisher-account/webhooks/) — payload reference and signature verification
- [How to detect Google Play storefront (Android)?](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detect-gpb-storefront-android/)
## Footnotes
- The one program date this page commits to, since it's the date Google has published for when it starts collecting fees and requiring reports on U.S. external transactions. Reconfirm on Google's [External Content Links Program page ↗](https://support.google.com/googleplay/android-developer/answer/16470497) before building a deadline around it — it's exactly the kind of detail this page otherwise avoids stating outright. [↩](https://developers.xsolla.com/sdk/compliance/android#user-content-fnref-1)
Reporting External Purchases to Apple
https://developers.xsolla.com/sdk/compliance/ios
When you sell through **Xsolla** on storefronts where Apple permits external purchases, Apple still requires you to report those transactions. This page explains what Apple expects, and how to build that report from the data **Xsolla** already sends you.
## Who reports what
Reporting is part of your integration, not something **Xsolla** does on your behalf.
| | Handled by |
| --- | --- |
| Processing the payment, tax calculation, refunds | Xsolla |
| Notifying your backend of each order | Xsolla (webhooks) |
| Obtaining Apple's external purchase token in your app | You |
| Filing the report with Apple | You, from your own server |
Apple's reporting API is authenticated with **your** App Store Connect key and is tied to **your** app record, so no payment provider can file on your behalf. What **Xsolla** provides is the transaction data the report is built from.
## When this applies
Apple's rules differ sharply by storefront, so check where you actually ship before building anything.
| Storefront | Entitlement | Apple commission | Reporting required |
| --- | --- | --- | --- |
| United States | Not required | Not currently charged | No |
| Japan | Required | Yes | Yes |
| Brazil | Required | Yes | Yes |
| European Union | Required | Yes | Yes |
note
Rates, deadlines and eligibility change often, and they differ per region and per developer program. This page deliberately avoids repeating Apple's numbers. Always check Apple's own pages for current terms: [Payment options in Japan ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-japan/), [Payment options in Brazil ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-brazil/), and [Payment options in the EU ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/).
Apple's EU terms change on **October 1, 2026**, including which payment options you may combine in one app. If you ship in the EU, re-read Apple's page before you settle on a design. important
The entitlement is requested from and granted by Apple, and comes with its own addendum to your developer agreement. Sort that out before you write code, since the StoreKit APIs below return nothing without it.
To enable external payments only for the storefronts that permit them, see [How to detect iOS Storefront?](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/).
## The flow end to end
- Your app checks eligibility and asks StoreKit for an **external purchase token**.
- Your app sends that token to your backend, which stores it against the customer.
- The player buys through **Xsolla** as normal.
- **Xsolla** sends your backend an [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_paid) webhook with the financial detail of that order.
- Your backend pairs the token with the order data and files the report with Apple.
- Refunds and chargebacks arrive as [`order_canceled`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_canceled) and are reported to Apple as refund line items.
## Getting the token
Tokens come from StoreKit, not from the **Xsolla SDK**. Apple's `ExternalPurchaseCustomLink` API is the current surface for custom links and in-app alternative payments. Apple requires these calls in a fixed order: `canMakePayments`, then `isEligible`, then the disclosure sheet. Swift only
`ExternalPurchaseCustomLink` is a Swift enumeration with `async` members, so it has no Objective-C counterpart. This differs from the `SKPaymentQueue`-style API that **Xsolla SDK** mirrors, which is available in both languages. If your app is written in Objective-C, add a small Swift file to your target and expose it with `@objc`, as shown in the Objective-C tab below.
```swift
// Whether this player is allowed to pay at all. Must come first.
guard AppStore.canMakePayments else { return }
// False when the app lacks the entitlement, or the storefront doesn't permit external purchases.
guard await ExternalPurchaseCustomLink.isEligible else { return }
// Token type depends on your region and flow. Apple defines several,
// including in-app alternative payment and link-out variants.
guard let token = try await ExternalPurchaseCustomLink.token(for: "LINK_OUT") else { return }
// Send token.value to your own backend and store it before continuing.
await sendTokenToYourServer(token.value)
// Required. Must follow a deliberate action such as a button tap.
// Use .browser when leaving the app, .withinApp for a web view or native flow inside it.
let notice = try await ExternalPurchaseCustomLink.showNotice(type: .browser)
guard case .continued = notice else { return }
// ...then start your Xsolla purchase or link-out.
```
Add this Swift file to your app target:
```swift
import StoreKit
@objc(XSExternalPurchaseBridge)
public final class ExternalPurchaseBridge: NSObject {
/// Returns the token string, or nil when the app isn't eligible or no active token exists.
@objc(requestTokenOfType:completion:)
public static func requestToken(ofType tokenType: String,
completion: @escaping (String?, Error?) -> Void) {
Task { @MainActor in
do {
guard SKPaymentQueue.canMakePayments(),
await ExternalPurchaseCustomLink.isEligible else {
completion(nil, nil)
return
}
let token = try await ExternalPurchaseCustomLink.token(for: tokenType)
completion(token?.value, nil)
} catch {
completion(nil, error)
}
}
}
/// Shows Apple's disclosure sheet. Continue only when `shouldContinue` is YES.
@objc(showNoticeForBrowserWithCompletion:)
public static func showNoticeForBrowser(completion: @escaping (Bool, Error?) -> Void) {
Task { @MainActor in
do {
let result = try await ExternalPurchaseCustomLink.showNotice(type: .browser)
switch result {
case .continued: completion(true, nil)
default: completion(false, nil)
}
} catch {
completion(false, error)
}
}
}
}
```
Then call it from Objective-C:
```objectivec
#import "YourApp-Swift.h"
[XSExternalPurchaseBridge requestTokenOfType:@"LINK_OUT"
completion:^(NSString *token, NSError *error) {
if (token == nil) { return; }
// Send the token to your own backend and store it before continuing.
[self sendTokenToYourServer:token];
[XSExternalPurchaseBridge showNoticeForBrowserWithCompletion:^(BOOL shouldContinue, NSError *e) {
if (!shouldContinue) { return; }
// ...then start your Xsolla purchase or link-out.
}];
}];
```
The token's `value` is a Base64URL-encoded JSON string. Decode it to read `externalPurchaseId`, which is the field Apple's report is keyed on. Send that to your backend and keep it.
Which token types apply, when to request them, and how long they stay valid all vary by region. See Apple's [Receiving and decoding external purchase tokens ↗](https://developer.apple.com/documentation/storekit/receiving-and-decoding-external-purchase-tokens) for the current rules. Disclosure sheet
In Japan, Brazil and the EU, Apple additionally requires an in-app disclosure sheet telling players they are transacting with you rather than with Apple, before you route them to an external purchase. It is system-provided, so `showNotice` is all you call.
Players can choose not to see it again, so branch on the result the call returns rather than on whether anything appeared. A silent call is not a failure.
Apple publishes the required wording and downloadable assets in the "In-app disclosure sheet" section of [Payment options in Japan ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-japan/), [Payment options in Brazil ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-brazil/) and [Payment options in the EU ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/).
## Building the report from webhook data
Apple's report covers one token and the transactions attached to it. Most of what a line item needs is already in the [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks/#order_paid) payload, under `billing.payment_details`.
The mapping below is for one-time purchases, which is what **Xsolla SDK** sells. Apple reports subscriptions as a separate line item type with its own fields, including renewals and zero-charge events such as free-trial starts. If you sell subscriptions through a Web Shop link-out, don't reuse this mapping for them — see Apple's [reporting guide ↗](https://developer.apple.com/documentation/externalpurchaseserverapi/reportwithtransactions) for the subscription line item.
| Apple line item field | Where it comes from |
| --- | --- |
| externalPurchaseId | Decoded from the Apple token you stored |
| lineItemId | You generate it. Persist it, refunds reference it |
| creationDate | billing.transaction.payment_date, converted to epoch milliseconds |
| eventType | order_paid is a purchase, order_canceled is a refund |
| productType | items[].type, or the presence of billing.purchase.subscription |
| productIdentifier | items[].sku |
| quantity | items[].quantity |
| amountTaxInclusive | billing.payment_details.payment.amount, converted to minor units |
| taxAmount | billing.payment_details.vat.amount |
| amountTaxExclusive | Tax-inclusive amount minus the tax amount |
| netAmountTaxExclusive | Running net for the line item across purchases and refunds |
| reportingCurrency | billing.payment_details.payment.currency |
| pricingCurrency | order.currency |
| taxCountry | user.country, converted to a three-letter code |
| referenceLineItemId | On refunds, the lineItemId of the original purchase |
Report what the player paid, not what you receive
`billing.payment_details.payout` is your share after **Xsolla**'s fees. Apple's report expects the amount the player was charged, which is `billing.payment_details.payment`. Using `payout` under-reports your transactions and produces an incorrect commission calculation. Tax fields
`billing.payment_details.vat` is the general consumption-tax field despite its name, not a EU-only one. It carries JCT in Japan and the local tax in Brazil just as it carries VAT in the EU, so it is the field to use for `taxAmount` in every market where Apple requires reporting.
`user.country` is the jurisdiction the tax was paid in, which is what Apple's `taxCountry` asks for. The only conversion needed is the format: `user.country` is a two-letter ISO 3166-1 alpha-2 code, while Apple expects the three-letter alpha-3 form, such as `ES` becoming `ESP`.
The fields above are the subset the Apple report needs. The payload carries considerably more — subscription and gift objects, promotions, coupons, fee breakdowns — and the same webhook drives your fulfillment. For the full structure, delivery guarantees and signature verification, see the [webhooks documentation](https://developers.xsolla.com/sdk/publisher-account/webhooks/).
### Amounts and rounding
Webhook amounts are decimal values, while Apple expects integer minor units. Convert with a decimal type rather than a float, and derive the tax-exclusive amount by subtracting the tax you reported rather than recomputing it from a percentage, so the three figures always add up.
### Refunds
`order_canceled` covers both refunds and chargebacks. Report both as refund line items, referencing the `lineItemId` of the original purchase. Ignore an `order.id` you've already reported, since [webhooks are retried](https://developers.xsolla.com/sdk/publisher-account/webhooks/#retries) and a repeated delivery must not produce a second refund line item.
## What Xsolla can't tell you
Some of Apple's requirements sit outside anything **Xsolla** observes. Your backend has to cover them:
- **Tokens that produced no purchase.** Apple expects these reported too. There's no order and therefore no webhook, so your token store is the only record.
- **Tokens Apple knows about that you don't.** Apple can notify you of a token your system has never seen, which has its own reporting status.
- **Line item identity.** `lineItemId` values are yours to generate and persist. Without them, refunds can't reference the purchase they reverse.
- **Running totals.** The net amount on a line item accumulates across purchases and refunds, so it can't be derived from a single webhook in isolation.
## Testing
The External Purchase APIs return environment-specific tokens. A token created in the sandbox has an `externalPurchaseId` beginning with `SANDBOX`, so your backend can route it away from production reporting. **Xsolla** test orders are marked separately, with `order.mode: "sandbox"` on the webhook.
## Further reading
- [External Purchase Server API ↗](https://developer.apple.com/documentation/externalpurchaseserverapi) — the reporting endpoints and line item schema
- [Receiving and decoding external purchase tokens ↗](https://developer.apple.com/documentation/storekit/receiving-and-decoding-external-purchase-tokens)
- [Reporting tokens and transactions ↗](https://developer.apple.com/help/app-store-connect/making-payments-to-apple/reporting-tokens-and-transactions)
- [Xsolla webhooks](https://developers.xsolla.com/sdk/publisher-account/webhooks/) — payload reference and signature verification
- [How to detect iOS Storefront?](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/)
News
https://developers.xsolla.com/sdk/documentation-changelog
Documentation updates and release notes for the Xsolla SDK.
This page contains information about any additions or updates to the **Xsolla SDK** documentation.
### [3.1.24] - 2026-11-19
- (Unity) Documented passing purchase arguments, such as the developer payload or the [**external transaction token**](https://developers.xsolla.com/sdk/unity/sdk/purchase/?integration-method=with#starting-purchasing-flow), through the Xsolla store extension when purchasing with Unity IAP.
### [3.1.23] - 2026-11-17
- Links to a heading inside a collapsed section, such as [**Advanced Settings**](https://developers.xsolla.com/sdk/unity/sdk/purchase/?integration-method=without#external-id), or inside an inactive tab now open the section or switch the tab and scroll to the heading.
### [3.1.22] - 2026-11-04
- (Unity) Documented the Android [**sign-in redirect URIs**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/#sign-in-redirect-uris): which redirect URI each sign-in method sends and must be registered on your OAuth 2.0 client in Publisher Account, or the server rejects the sign-in.
### [3.1.21] - 2026-11-02
- (iOS, Unity) Documented the install source for iOS ([**iOS**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#install-source)): it is detected only on iOS 17.4 and later unless you set `installSource` yourself, and the value is sent as is. The [**Unity**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#build-configuration-from-the-settings) `SetInstallSource` entry now lists the per-platform differences.
### [3.1.20] - 2026-11-02
- (Android, Unity) Documented the install source ([**Android**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#payments), [**Unity**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#build-configuration-from-the-settings)), which lets builds distributed outside an app store, such as an APK downloaded from your website, report their own distribution channel instead of the one detected from the OS installer. See also [**Android**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/#reporting-a-custom-install-source) and [**Unity**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore/#reporting-a-custom-install-source).
### [3.1.19] - 2026-10-05
- (Android, iOS, Unity) Documented the attribution user ID ([**Android**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#payments), [**iOS**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#attribution-user-id), [**Unity**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#build-configuration-from-the-settings)), which keys purchase events sent to attribution platforms such as AppsFlyer to the same user ID your attribution SDK reports.
### [3.1.18] - 2026-10-01
- (Android, iOS, Unity, Windows) Corrected the steps for [**enabling the Events API**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api) in Publisher Account, which is now under **Project settings** > **Integration settings**.
### [3.1.17] - 2026-09-17
- (iOS) Updated the [**restored purchases**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/#restored-purchases) docs for SDK 3.11.0: a restored purchase now points at the purchase it repeats, and carries the real quantity and payment date.
- Simplified the wording on several pages. The guidance is unchanged.
### [3.1.16] - 2026-09-14
- (iOS) Added a [**Restored purchases**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/#restored-purchases) section to the purchase docs, covering what a restored transaction carries, what the inventory doesn't restore, and when restoration is skipped.
- (iOS) Corrected the [**configuration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings) docs to name the iOS properties the *Events API* populates, and to state that inventory-backed restoration leaves them `nil`.
### [3.1.15] - 2026-09-09
- (Android) Added an [**Inventory API vs. Events API**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api/) addendum covering how the SDK selects a restoration backend, what a purchase carries in each mode, and what migrating a live project involves.
- (Android) Promoted purchase restoration to its own section in the [**purchase flow**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#restored-purchases) docs, with a field-by-field breakdown of a restored `Purchase` under each backend.
- (Android) Documented that bundles don't restore from the *Inventory API* — **including virtual currency packages**, which the catalog classifies as bundles rather than as currency — and that time-limited items are excluded as well.
- (Android) Corrected the configuration docs' claim that inventory-backed restoration has no order to reference: the SDK synthesizes order and invoice identifiers on-device, and they match nothing in *Publisher Account* or an order lookup.
- (Android) Added [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#purchase-restoration-settings) and [**Units per restored purchase**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#units-per-restored-purchase) to the configuration docs, covering backend selection and `withCollapseRestoredMultiUnitPurchases`.
- (Android) Added a **Default** column to every settings table in the [**configuration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#common) docs, along with five previously undocumented `Config.Common` settings, and clarified that a `null` retry override falls back to 12 attempts at 750 ms rather than disabling retries.
### [3.1.14] - 2026-09-07
- (Android, iOS, Unity, Windows) Documented that a restored purchase only carries the identifiers of the original Xsolla order when restoration runs through the [**Events API**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#using-xsolla-events-api-for-restoration).
### [3.1.13] - 2026-08-19
- (iOS, Android) Added a new **Platform Compliance** section documenting how to report external purchases to [**Apple**](https://developers.xsolla.com/sdk/compliance/ios/) and external transactions to [**Google Play**](https://developers.xsolla.com/sdk/compliance/android/) when selling through Xsolla on storefronts where they permit it.
- (iOS, Unity) Updated the iOS external-payment guidance for Apple's EU terms taking effect October 1, 2026: in the EU you may keep the payment flow in-app or route out to the web, and the choice affects Apple's commission.
- (Android) Added [**`setExternalTransactionToken`**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#starting-purchasing-flow) to the `BillingFlowParams` API reference, now that it's public.
- (Android) Corrected the **Epic v. Google** case timeline in the [Glossary](https://developers.xsolla.com/sdk/welcome/glossary/): fixed the Ninth Circuit affirmation date, clarified the July 2026 settlement withdrawal, and dropped an unverified injunction expiry date.
- (Unity) Added [**`externalTransactionToken`**](https://developers.xsolla.com/sdk/unity/sdk/purchase/#starting-purchasing-flow) to the `XsollaStoreClientPurchaseArgs.Builder` API reference, now that it's public — Android-only for now.
### [3.1.12] - 2026-07-23
- (Unity) Corrected the supported Unity Editor version to 2022.3+ and Unity 6+.
### [3.1.11] - 2026-07-16
- Renamed the **Integration Articles** category (formerly "Technical Articles").
- Refreshed the SDK 3 integration guides.
- Added a **Video Guides** section with integration walkthrough videos.
### [3.1.10] - 2026-07-07
- (iOS, Unity) Expanded iOS external-payment compliance guidance to cover **Brazil** alongside the United States across the iOS and Unity docs, and consolidated the iOS SDK's [**regional configuration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#regional-compliance-configuration) into a single, market-based section.
- (iOS) Clarified in the [**purchase validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/ios/) docs that the SDK's transaction callbacks still fire during server-side validation but are for UI only — the backend awards entitlements from the webhook.
### [3.1.9] - 2026-07-06
- (iOS) Added a [**Troubleshooting**](https://developers.xsolla.com/sdk/mobilesdk/sdk/troubleshooting/ios/) page covering empty catalogs, purchase restoration, URL scheme setup, login errors, main-thread warnings, and the hosts to allowlist for firewalls.
- (iOS) Clarified in [**configuration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings) and [**purchase**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/) docs that `restoreCompletedTransactions()` is a no-op and transactions must be finished to avoid re-delivery on the next launch.
- (iOS) Documented that [**`useSandbox`**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#testing-in-sandbox-mode) defaults to `true` and must be turned off before going live.
### [3.1.8] - 2026-06-02
- (Android, iOS, Unity, Windows) Clarified in the **initialization** docs that the SDK loads **Virtual Items** only.
### [3.1.7] - 2026-05-08
- Fixed the [**integration widget**](https://developers.xsolla.com/sdk/integration-widget/) layout to remove forced horizontal padding, preventing visual overflow when the browser window is narrow.
### [3.1.6] - 2026-04-02
- (Android) Added [**`withRedirectAppRelaunch`**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#payments) to the `Config.Payments` API reference.
- (Unity) Added Android-specific [**external browser app relaunch**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/#external-browser-app-relaunch) setting documentation.
### [3.1.5] - 2026-04-01
- Added a **Download SDK** button to the navigation bar.
- (Android) Expanded the [**consumption**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/) section with updated purchase flow diagrams.
- (Android) Updated the [**client-side validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/) diagram to include the consume request to Xsolla services.
- (Android) Added an [**event listeners**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#xsolla-events-api) API reference to configuration docs.
- Updated the [**integration widget**](https://developers.xsolla.com/sdk/integration-widget/) with a correct **How to Install** link for Android GitHub Maven.
### [3.1.4] - 2026-03-18
- Updated the SDK availability links.
- (Android) Added [**billing flow cancellation API**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/) and token-based params builder.
- (Android) Added [**GitHub repository installation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/android/) with tabbed GitHub/Maven Central layout.
- (Unity) Updated [**configuration**](https://developers.xsolla.com/sdk/unity/sdk/configuration/) with email consent, restore interval, locale settings, and full builder table.
- (Unity) Added Android-specific [**cancellation reason querying**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/#cancellation-reason-querying) and [**WebView splash screen**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/#webview-splash-screen) settings.
### [3.1.3] - 2026-03-05
- Added interactive [**SDK integration widget**](https://developers.xsolla.com/sdk/integration-widget/).
- (Android, Unity) Updated configuration API references and method names.
- (iOS) Added [**SPM installation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios/) instructions.
- Reworked landing and Publisher Account pages with new layouts.
- Reworked quick-start guides with timeline layouts.
- Standardized terminology and proper noun capitalization across documentation.
### [3.1.2] - 2025-12-22
- (Unity) Updated [**Configuration**](https://developers.xsolla.com/sdk/unity/sdk/configuration/) around mobile purchase settings, purchase restoration, and deep link overrides.
- (iOS, Unity) Added “purchase cancelled” handling examples to purchase flow docs.
- (iOS, Unity) Clarified iOS Storefront behavior for alternative distribution installs.
- (iOS) Added an advanced guide for **Universal Links** and linked it from deep link configuration docs.
### [3.1.1] - 2025-10-16
- (Unity) Fixed the product registration in the [**extended example**](https://developers.xsolla.com/sdk/unity/quick-start/extended-example/#configuration--initialization).
### [3.1.0] - 2025-10-07
ℹ️ANDROID
Following the Supreme Court's refusal to pause the ruling, **effective October 29, 2025**, Google must permit U.S. **Google Play** apps to guide users to **external payment methods via link-outs** and allow the use of **alternative billing solutions**. This change enables developers to avoid Google's fees and inform users about lower-cost options outside Google Play—fostering more competitive pricing and greater revenue control.
Read more on the Xsolla Blog: [**New platform rules for Android—what developers need to know ↗**](https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know) ([https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know](https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know))
Learn more about the Buy Button: [**Xsolla Buy Button ↗**](https://xsolla.com/mobile-buy-button) ([https://xsolla.com/mobile-buy-button](https://xsolla.com/mobile-buy-button))
- (Android) Added information on [**Buy Button**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#buy-button-solution).
- (Android) Added information on [**Web Shop link-outs**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/?purchase-method=linkout-webshop#starting-purchasing-flow).
### [3.0.4] - 2025-09-23
- (Android) Added information on [**advanced Events API settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#xsolla-events-api).
### [3.0.3] - 2025-09-02
- (Android) Added information on integration [**helpers**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/?platform=android).
- (Unity) Added information on integration [**helpers for Android**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore/?platform=android).
- (Android) Added information on additional [**purchasing flow launching methods**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#starting-purchasing-flow).
- (Android) Added a collapsible section under [**`Default`**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow) purchasing method tab describing advanced settings.
- (Unity) Added a collapsible section with advanced purchasing flow settings under the [**`Unity InAppPurchasing-less`**](https://developers.xsolla.com/sdk/unity/sdk/purchase/?integration-method=without) integration method's tab.
### [3.0.2] - 2025-08-21
- Clarified Web Shop link-out behavior in [iOS Configuration](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#web-shop-link-outs): SDK opens Web Shop and cancels SDK purchase callbacks; fulfillment should be handled via webhooks/server.
- Added a new [Unity Configuration: Web Shop Link-outs](https://developers.xsolla.com/sdk/unity/sdk/configuration/#web-shop-link-outs) section with setup code.
### [3.0.1] - 2025-08-18
- Documented default Pay Station payment method [configuration](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#default-payment-method) on iOS.
### [3.0.0] - 2025-08-12
- Major documentation rework around the new **Xsolla SDK**, which supersedes the legacy **Xsolla Mobile SDK**.
- **Unity** is now a dedicated top-level section with guides for all supported platforms (Mobile, PC, Web).
- **Mobile** documentation is split into platform-specific pages: separate Android and iOS guides across quick start, installation, initialization, configuration, purchase, testing, validation, and advanced topics.
- Added information on authentication using third-party social provider access tokens.
### [1.1.4] – 2025-08-06
- **Events API**: introduced full documentation for the Xsolla Events API in Publisher Account webhooks and in Android & Unity SDK configuration guides, including setup steps, code samples, and caution notes.
- **Trusted Web Activity**: added Android and Unity sections covering TWA configuration, splash-screen options, fallback behavior, and accompanying assets.
- **iOS configuration**: expanded with purchase restoration settings, automatic vs. manual deep-link handling (incl. URL-scheme setup), and orientation management examples.
- **Quick-start & overview pages**: updated top-level README and quick-start guides with concise notes on DMA compliance, global payment methods, and rapid onboarding.
### [1.1.3] - 2025-07-16
- Enhanced [iOS Configuration](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/) with improved organization and structure, deep link handling guidance, Web Shop link-outs and Buy Button Solution documentation, and Purchase Restoration Settings configuration.
### 2025-06-26
On 26th of June, [Apple has released](https://developer.apple.com/news/?id=awedznci) the following changes for apps distributed on the App Store in the EU. Developers can now **communicate and promote offers** for digital goods or services, including steering to external payment options through the **StoreKit External Purchase Link Entitlement**.
While you can use Xsolla Mobile SDK to serve external payments and comply with these new EU requirements through Apple's **Alternative Terms Addendum for Apps in the EU** or **StoreKit External Purchase Link Entitlement (EU) Addendum** (contact your account manager for access and implementation guidance), we recommend using **[Web Shops](https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop/) as a more viable and streamlined alternative** for maximum flexibility and reduced complexity in the current regulatory landscape.
[Read more about Apple's EU payment rules ↗](https://developer.apple.com/support/communication-and-promotion-of-offers-on-the-app-store-in-the-eu/)
### [1.1.2] - 2025-06-25
- Unity now has its own subsection (`Unity`)
- Aggregated mobile platforms (Android/iOS) under their own section (`Mobile`)
- Added diagrams and flow mapping comparison tables to `Purchase Validation` (Android)
- Added links to virtual items external documentation in **Publisher Account** -> **Virtual Items**
- Moved iOS US & EU compliance into a separate page (**Unity** -> **SDK** -> **Configuration** -> **iOS**)
### [1.1.1] - 2025-06-09
- Improved [Quick Start Guide](https://developers.xsolla.com/sdk/mobilesdk/quick-start/) with better organization and clearer structure
- Added [Storefront Detection](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/) documentation for Unity integration
- Enhanced [Installation Guide](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios/) with iOS version support details
- Updated [Webshop Integration](https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop/) documentation with Buy Button information
- Updated [Configuration](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/) with custom login token configuration example for iOS
- Added cross-platform compatibility information to [Unity Integration](https://developers.xsolla.com/sdk/unity/quick-start/extended-example/) examples
- Improved navigation and external links throughout the documentation
- Added information about Buy Button and alternative billing options to the landing page
### [1.1.0] - 2025-05-07
- Updated to ensure compliance with Apple's revised App Store guidelines.
- The Xsolla Mobile SDK is now stable and ready for production use.
- Added an [article](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/) on how to detect iOS Storefront.
- Improved an [article](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/) on how to detect store installation for iOS.
### [1.0.1] - 2024-07-26
- Added [Glossary](https://developers.xsolla.com/sdk/welcome/glossary/).
- Expanded [Core Concepts (iOS)](https://developers.xsolla.com/sdk/welcome/core-concepts-ios/).
- Updated [Core Concepts (Android)](https://developers.xsolla.com/sdk/welcome/core-concepts-android/).
### [1.0.0]
- Initial revision.
Integration
https://developers.xsolla.com/sdk/integration-widget
Loading Integration Widget…
Xsolla SDK for Mobile
https://developers.xsolla.com/sdk/mobilesdk
AvailableXsolla SDK for Mobile[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
The **Xsolla SDK for Mobile** empowers developers to seamlessly integrate in-game payments via **Xsolla Pay Station** across iOS and Android games, supporting monetization for both in-store builds (e.g., App Store iOS and Google Play builds in the USA) and out-of-store distributed game builds (e.g., Android APK, Notarized iOS). The SDK empowers developers to connect directly with players, maintain control over the checkout experience, and keep up to 95% of their revenue. Games automatically benefit from updates for new monetization tools, regulatory compliance, and global policy changes.
Trusted by the studios behind *Crossout*, *Modern Warship*, and *Fantasy Tales: Sword and Magic* to power direct-to-consumer commerce across iOS and Android at global scale.
## Platform Support
### iOS
In the **United States** (*Epic v. Apple*), **Japan** (Mobile Software Competition Act), and **Brazil** (Apple's CADE settlement), Apple now lets developers direct players to external web payments. The **Xsolla SDK for Mobile** aligns with Apple's revised App Store guidelines, supporting both in-app Pay Station flows and link-out payments via Web Shop.
### Android
Following the **October 29, 2025** Epic v. Google injunction, U.S. Google Play apps may use alternative billing solutions, external payment links, and are no longer subject to anti-steering restrictions. The SDK supports out-of-store APK distribution, Google Play Billing, and browser-based checkout — all in one integration.
## Key Benefits for Mobile Developers
**iOS & Android Integration**
Purpose-built SDKs for iOS (Swift/Obj-C) and Android, each designed for its platform's distribution model and compliance requirements. The same Xsolla infrastructure powers both.**DMA & Court-Order Compliant**
Full compliance with Apple's revised App Store guidelines and Google Play's updated billing policies — including link-out payments, alternative billing, and out-of-store distribution, out-of-the-box.**Up to 95% Revenue Retention**
Distribute directly via APK, Notarized iOS, or link-out flows. Bypass platform fees, maintain pricing control, and build a direct-to-consumer revenue channel that grows with your player base.**1,000+ Payment Methods**
Global payment infrastructure covering 200+ regions, 130+ currencies, and 25+ UI languages — with localized checkout flows and advanced anti-fraud included at no extra cost.**Compliance Updates Automatically**
Apple and Google policy changes propagate to the SDK automatically. No emergency releases, no compliance debt — stay current without interrupting your development cycle.
## Getting Started
Ready to integrate the Xsolla SDK into your iOS or Android project? Follow the Quick Start guide to process your first test payment in minutes, or contact your Account Manager for personalized implementation guidance. **Xsolla Buy Button**Fast Path
One-tap Web Shop purchase flows with 1,000+ payment methods — no SDK installation required. Launch browser-based checkout directly from your iOS or Android game, fully compliant with Apple and Google billing policies.[Learn more →](https://developers.xsolla.com/sdk/mobilesdk/buy-button/) [QUICK START**Integration Guide**Process your first test payment on iOS or Android→](https://developers.xsolla.com/sdk/mobilesdk/quick-start/)[FAST PATH**Buy Button**One-tap external payments — no full SDK required→](https://developers.xsolla.com/sdk/mobilesdk/buy-button/)[REFERENCE**Full SDK Docs**Installation, configuration, and advanced features→](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/)
Google Play User Choice Billing
https://developers.xsolla.com/sdk/mobilesdk/addendum/android/google-play-user-choice-billing
## Overview
- **Program**: Google Play lets approved apps in select countries present a user choice screen so players can select either Google Play Billing (GPB) or a third-party payment service provider (PSP).
- **Xsolla path**: Keep GPB available, and launch **Xsolla Pay Station** when players choose the alternative option. No separate Android branch is required.
## What Xsolla provides
- 1000+ localized payment methods to complement GPB and boost conversion in markets where native billing underperforms.
- SKU parity by mirroring GPB product IDs as [Virtual Items](https://developers.xsolla.com/sdk/publisher-account/virtual-items/) (IAPs) in your Xsolla Catalog.
- Authentication via [Xsolla Login](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#authentication) or your own token service.
- Webhooks and reporting that align with standard Pay Station deployments — though reporting the resulting transactions to Google is still on your integration, see [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/).
## Further guidance
Please route any questions about Google Play User Choice Billing through your Xsolla account manager.
Inventory API vs. Events API
https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api
Under the hood, the Android SDK sources purchase data from one of two Xsolla backends: Inventory API or Events API.
The inventory records every purchase. Events are recorded only once Events API is enabled for the project in *Publisher Account* — and from that point they are recorded regardless of which mode the SDK itself runs in. That difference is what makes switching a live project hard: see [**Migrating a live project**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api#migration).
## Selecting a mode
Two independent settings decide it, both off by default: the project-level toggle in *Publisher Account*, and an `Events` config passed to the SDK (`Config.Integration.Xsolla.Events`, supplied via `.withEvents(...)`).
They govern different things. The *Publisher Account* toggle decides whether events are **recorded** at all. The SDK config decides which backend the client **restores from** — on its own, without consulting the project's toggle.
| Events API in Publisher Account | Events API in SDK config | Inventory populated | Events populated | SDK restores from |
| --- | --- | --- | --- | --- |
| ✘ | ✘ | ✔ | ✘ | Inventory API |
| ✘ | ✔ | ✔ | ✘ | Events API — but nothing is ever recorded, so restoration comes back empty |
| ✔ | ✘ | ✔ | ✔ | Inventory API — meanwhile events accumulate unread |
| ✔ | ✔ | ✔ | ✔ | Events API |
The inventory is populated either way. Events only exist once the project toggle is on — and once it is, they are recorded whether the client reads them or not. Row three is where that matters: the project accumulates a full event history the client has never seen, which is what [**Migrating a live project**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api#migration) has to deal with.
## What each mode gives you
Neither mode requires you to run a server of your own. What differs is what a queried purchase carries:
| | Inventory API | Events API |
| --- | --- | --- |
| Order and invoice IDs | Not stored — the SDK synthesizes both locally | Stored permanently, and returned in full |
| Purchase timestamp | None — getPurchaseTime() is always 0 | Real timestamp of the original payment |
| What one record covers | A SKU and how many the player owns — not individual payments | One payment |
| Bundle purchases, including virtual currency packages | Can't be restored — only what the bundle granted | Come back as the bundle's content items |
Field-by-field behavior of a restored `Purchase` in each mode is documented in [**Purchase flow → Restored purchases**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#restored-purchases).
Enabling Events API for a project **disables that project's webhooks** — the two cannot run at the same time. If your server handles payments, or splits that work with the client, that arrangement ends when the project switches over.
### Why inventory-backed purchases can't be matched against anything
An inventory query returns holdings, not transactions. Five separate one-unit purchases of `sku_0` come back as a single entry with a quantity of `5`:
| To match a purchase you'd need | Inventory API returns |
| --- | --- |
| Order ID | A value synthesized locally by the SDK |
| Invoice ID | The same synthesized value |
| Timestamp | Nothing (0) |
| One record per payment | Nothing — only an aggregate quantity per SKU |
By default the SDK does split that aggregate into five separate `Purchase` objects, one per unit, and `withCollapseRestoredMultiUnitPurchases` turns that off in favor of a single `Purchase` carrying the quantity (see [**Units per restored purchase**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#units-per-restored-purchase)). Either shape is a presentation choice — splitting adds no identifying information, so it doesn't make matching possible.
## Migrating a live project
New projects should start on Events API and will never hit any of this. What follows applies only to live projects with existing purchase history.
Two problems collide on the first launch after the client switches to Events API:
- Events API **hands you the whole history.** It has been recording purchases for as long as the *Publisher Account* toggle has been on — including the entire period the client ran inventory-backed and never read them. All of it arrives at once.
- Inventory API **may still owe the player goods.** Purchases can sit unconsumed because the payment completed but the app crashed, was updated, or was killed mid-flow. Those still need to be awarded.
The clean fix would be to match the two sets and silently settle — consume without awarding — everything already handled on the inventory side. That isn't possible: the event records are complete, and the inventory records carry nothing to anchor them to (see above).
### Approach A — client-side migration build
Drain the inventory before reading a single event:
- Ship a build that initializes the SDK in Inventory API mode on launch.
- Query outstanding purchases, consume them, and award them.
- Write a persistent marker recording that the inventory has been drained and must never be read again.
- Re-initialize the SDK with the Events API configuration.
- Discard — consume without awarding — every event dated before the drain in step 2.
| Pros | Cons |
| --- | --- |
| Runs entirely on the device, needing no coordination on the Xsolla side, and settles what the inventory actually owes before any event is read. | Only reaches players who install the migration build. The marker is lost on reinstall or cleared app data, so the drain can run twice. Step 5 cuts on a timestamp rather than an identity match, so purchases close to the cutoff can be double-awarded or dropped. |
### Approach B — sorted out on the Xsolla side
Xsolla settles the overlap for you, without involving the client. Whether it fits your project depends on its history and scale — raise it with your integration manager.
| Pros | Cons |
| --- | --- |
| Reaches players who never install a migration build, which Approach A cannot. | Has to be arranged per project, so it can't be scheduled from your side. A single pass also covers nothing that happens after it runs. |
### Planning around the residual
Approach A is the part you control, and it's worth shipping regardless. However the migration runs, expect a residue of players who miss a purchase or receive one twice, and have a support and compensation path ready before the switch.
Buy Button ⚡
https://developers.xsolla.com/sdk/mobilesdk/buy-button
ℹ️External payment link-outs — iOS & Android
**iOS:** In the U.S., Japan, and Brazil, Apple now lets developers direct players to external web payments. The **Xsolla SDK** aligns with Apple’s updated guidelines.
**Android — Effective Oct 29, 2025:** Following the **Epic v. Google** injunction, U.S. **Google Play** apps may guide users to **external payment methods via link-outs**, use **alternative billing solutions**, and are no longer subject to **anti-steering restrictions**.
## Fastest non-SDK approach (Recommended)
For both platforms, the fastest *recommended* non-SDK approach is the **Buy Button via link-outs to Web Shop**
Buy Button integration via Web Shop link is a quick, low-code way to enable item-specific purchases from your game using a browser-based checkout. It offers:
- A seamless flow — tapping Buy Button opens the Web Shop checkout for a specific item, allowing users to automatically return to the game after a successful payment.
- Support for a wide range of payment methods, including one-click payments via Apple Pay, for fast and familiar mobile checkout.
- Fast setup — if your Web Shop is already set up, you only need to add a link with parameters to the game.
- Instant onboarding — if you don’t have Web Shop yet, you can get started quickly by instantly creating Web Shop, adding payment links to your game, and going live.
tip
For additional information, please visit: [**Buy Button via link-outs to Web Shop** ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)
([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)).
## SDK approach
Use Web Shop link-outs when you want minimal code changes by redirecting the user to your existing Xsolla Web Shop to complete the purchase. caution
In Web Shop link-out mode, the SDK does not execute its native in-app payment flow. It only opens the Web Shop and cancels any SDK purchase callbacks. Handle fulfillment and post-payment updates via your Web Shop processes (for example, webhooks or server-side logic), not via SDK purchase callbacks.
Select your platform to get started with the integration:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/buy-button/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/buy-button/ios/)
Buy Button - Android
https://developers.xsolla.com/sdk/mobilesdk/buy-button/android
Two simple ways to add external payments to your Android app: redirect users to your Web Shop, or launch Pay Station's native in-app UI. Both are production-ready — pick the one that fits your workflow. Recommended
#### Web Shop Link-outs
Redirect users to your existing Xsolla Web Shop in the browser.
- Already have an Xsolla Web Shop
- Want minimal code changes
- Need web and mobile payment consistency
- Doing a phased migration from web
#### Buy Button Solution
Full payment UI handled natively inside your app — no browser redirect.
- Want a fully native integration
- Need 1,000+ payment methods out of the box
- Prefer Xsolla to manage the payment UI
- Want automatic regional compliance
important
To enable **U.S.-only** link-outs **effective October 29, 2025**, first detect the **Google Play** storefront country code — see the [**guide**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detect-gpb-storefront-android/). Several of these programs carry a Google commission and must be reported back to Google, see [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/).
```java
final Context context = // Your activity context
final String webshopUrl = "https://yourwebshop.xsolla.site";
final String sku = "money.100"; // Virtual item SKU from your Xsolla Catalog
final String userId = "user_12345"; // Current user's ID
final String redirectUrl = "yourgame://"; // Deep link back to your app
WebShop.launchBillingFlow(context, webshopUrl, sku, userId, redirectUrl,
new WebShop.ILaunchBillingFlowCallback() {
@Override
public void onLaunchBillingFlow(@NonNull final Either<Error, Void> result) {
result.voidFold(
err -> Log.e(TAG, "Link-out error: " + err.getMessage()),
__ -> Log.d(TAG, "Web Shop opened successfully")
);
}
}
);
```
This opens your Web Shop in the device browser. Fulfillment happens via your server-side webhooks — see [webhook setup](https://developers.xsolla.com/sdk/publisher-account/webhooks/).
```java
final Config.Payments paymentsConfig = Config.Payments.getDefault()
.withBuyButtonSolutionEnabled(true);
```
Enable this once in your SDK configuration — Buy Button activates automatically for all [default purchase flows](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow). See [configuration docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/) for themes, logos, and custom domains. Still not sure?
**Web Shop** is great if you have an existing store or want to start with minimal changes. **Pay Station** is the fastest path to a fully native integration. Both support the same payment methods and regions worldwide.
Buy Button - iOS
https://developers.xsolla.com/sdk/mobilesdk/buy-button/ios
### Buy Button Solution (Recommended)
ℹ️iOS — external payment link-outs (US, Japan, Brazil, EU)
**iOS:** In the U.S., Japan, Brazil, and the EU, Apple now lets developers direct players to external web payments. The **Xsolla SDK** aligns with Apple’s updated guidelines. In Japan, Brazil and the EU these transactions carry an Apple commission and must be reported back to Apple, see [Reporting External Purchases to Apple](https://developers.xsolla.com/sdk/compliance/ios/).
The *Buy Button Solution* provides a complete, native payment experience with minimal integration effort. This approach handles the entire payment flow within your app using Xsolla's optimized UI components.
**When to use Buy Button Solution:**
- You want a quick, native payment integration
- You prefer Xsolla to handle payment UI and optimization
- You need support for multiple payment methods out of the box
- You want automatic compliance with regional payment regulations
```objectivec
// Enable Buy Button solution
settings.useBuyButtonSolution = YES;
```
```swift
// Enable Buy Button solution
settings.useBuyButtonSolution = true
```
### Web Shop Link-outs
The Web Shop approach redirects users to your existing Xsolla Web Shop in a browser, then returns them to your app after purchase completion. This method is ideal for gradual migration or when you want to maintain consistency with existing web-based payment flows.
**When to use Web Shop link-outs:**
- You already have an established Xsolla Web Shop
- You want to test Xsolla integration with minimal code changes
- You need to maintain payment consistency across multiple platforms
- You're implementing a phased migration from web to mobile payments
caution
In Web Shop link-out mode, the SDK does not execute its native in-app payment flow. It only opens the Web Shop and immediately cancels any SDK purchase callbacks. This mode is intended for minimal code changes: handle fulfillment and post-payment updates via your Web Shop processes (for example, webhooks or server-side logic), not via SDK purchase callbacks.
#### Configuring Web Shop Integration
Use the helper method to configure the Web Shop redirect flow:
```objectivec
[settings setupBuyButtonWebShopWithUrl:[NSURL URLWithString:@"https://yourwebshop.xsolla.site"]
userId:@"<USER_ID>"
returnUrl:@"yourgame://"
openExternally:YES];
```
```swift
settings.setupBuyButtonWebShop(url: URL(string: "https://yourwebshop.xsolla.site")!,
userId: "<USER_ID>",
returnUrl: "yourgame://",
openExternally: true)
```
**Parameter explanation:**
- `url`: The URL of your Xsolla Web Shop where users complete purchases
- `userId`: A unique identifier for the user in your system, used for purchase attribution and user tracking
- `returnUrl`: The deep link URL scheme that brings users back to your app after purchase completion
- `openExternally`: Whether to open the Web Shop in an external browser (recommended for compliance and better user experience)
#### Initiating Web Shop Purchases
After configuration, initiate purchases by calling the purchase method with your product SKU:
```objectivec
// Attempt to purchase an item via Web Shop
BOOL handledExternally = [[SKPaymentQueue defaultQueue] purchaseWithSKU:@"money.100"];
if (handledExternally) {
// Web Shop opened successfully, update UI to reflect the redirect
NSLog(@"Purchase redirected to Web Shop");
// Optionally show a loading indicator or message to the user
}
```
```swift
// Attempt to purchase an item via Web Shop
let handledExternally: Bool = SKPaymentQueue.default().purchase(withSKU: "money.100")
if handledExternally {
// Web Shop opened successfully, update UI to reflect the redirect
print("Purchase redirected to Web Shop")
// Optionally show a loading indicator or message to the user
}
```
Quick Start — Mobile SDK
https://developers.xsolla.com/sdk/mobilesdk/quick-start
This quick start guide will walk you through integrating *Xsolla Mobile SDK* to accept payments in your game. Using a pre-configured test project ID, we'll cover the essentials: setting up basic user authentication, importing SKUs, and processing a test payment. By the end, you'll have a functional payment system integrated into your game, demonstrating how Xsolla can streamline your monetization process. Let's get started and have your game accepting payments in just a few simple steps!
⚡ **DMA-ready & revenue-boosting**: leverage direct APK/IPA distribution alongside in-app compliance with DMA—unlocking access to 1,000+ global payment methods and bypassing app-store fees to maximize your margins.
## Choose Your Platform
Select your platform to get started with the integration:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/quick-start/ios/)
Each platform-specific guide will walk you through:
- Installing the SDK
- Configuring the SDK
- Initializing the SDK
- Making a purchase
- Collecting payments
Quick Start - Android
https://developers.xsolla.com/sdk/mobilesdk/quick-start/android
Get the **Xsolla Mobile SDK** integrated and process your first test payment. We'll use pre-configured test credentials so you can start in minutes.
## Getting Started
Ensure your project targets **Android 7.0+** (`minSdk 24`), then add Maven Central and the **Xsolla Mobile SDK** dependency:
```kotlin
// settings.gradle
repositories {
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
```
```kotlin
// build.gradle
dependencies {
def version_mobilesdk = '<version>'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
See [installation details](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/android/#prerequisites) for more configuration options.
## Authenticate
Add this to your Activity's `onCreate()`:
```java
import com.xsolla.android.mobile.*;
@Nullable
private BillingClient mBillingClient;
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(), // Test project
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow() // Test login ID
)
);
final Config config = new Config(
configCommon,
configIntegration,
Config.Payments.getDefault(),
Config.Analytics.getDefault()
);
// Inside onCreate(), after creating Config:
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener((billingResult, purchases) -> {
// Handle purchase completion — see Finalize Purchase
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected from Xsolla services.");
}
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (!billingResult.isSuccess()) {
Log.e(TAG, "Connection failed: " + billingResult.getResponseCode());
return;
}
}
});
```
This creates your `Config` with `AutoJWT` authentication, sandbox mode, and debug logging, then initializes the `BillingClient` and connects to Xsolla services. For production, replace the test project ID and login ID with your own from [**Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/). See [configuration docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/) for advanced options.important
If you are using your own **Project/Login IDs**, make sure to enable **Device ID login** in your Project. Learn how to enable it here: [https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
## Load Catalog
Query your product catalog once connected:
```java
mBillingClient.queryProductDetailsAsync(
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // Test product SKU
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build(),
(result, productDetailsList) -> {
// Launch purchase — see Purchase Product
}
);
```
This loads product `key_1` from your catalog. See [initialization docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/android/) for reconnection handling and advanced options.
## Purchase Product
Use the product details from your catalog query to launch a purchase:
```java
// Inside productDetails callback (from Load Catalog):
if (billingResult.isSuccess() &&
productDetailsList != null && !productDetailsList.isEmpty()) {
mBillingClient.launchBillingFlow(
activity, // Your Activity reference
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetailsList.get(0))
.build()
))
.build()
);
} else {
Log.e(TAG, "No products available: " + billingResult.getResponseCode());
}
```
This opens **Xsolla Pay Station** where users complete payment. For testing, use a [test card ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards):
![Choose payment method]
![Processing payment]
![Payment confirmed]
## Finalize Purchase
Once the purchase completes, consume it and award the product to the user:
```java
// Inside onPurchasesUpdated callback:
if (billingResult.isSuccess() && purchases != null) {
for (Purchase purchase : purchases) {
mBillingClient.consumeAsync(
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build(),
(result, purchaseToken) -> {
if (result.isSuccess()) {
Log.d(TAG, "Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
} else {
Log.e(TAG, "Consumption failed: " + result.getResponseCode());
}
}
);
}
} else {
Log.e(TAG, "Purchase failed or cancelled: " + billingResult.getResponseCode());
}
```
This consumes the purchase and lets you award the product (virtual item). See [purchase flow docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/) for error scenarios and advanced options.
## What's next?
You've built a complete payment integration: authentication, catalog loading, purchase flow, and fulfillment. Your app now has access to 1,000+ payment methods across 200+ countries.
- **[Set up your project](https://developers.xsolla.com/sdk/publisher-account/)** — create your Publisher Account and replace the sandbox test credentials with production ones
- **[Buy Button](https://developers.xsolla.com/sdk/mobilesdk/buy-button/android/)** — fastest path to external payments
- **[Extended example](https://developers.xsolla.com/sdk/mobilesdk/quick-start/extended-examples/android-example/)** — complete working implementation
- **[Full SDK docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/android/)** — advanced features, retry policies, custom UI
Android Extended Example
https://developers.xsolla.com/sdk/mobilesdk/quick-start/extended-examples/android-example
**Xsolla Mobile SDK** requires very few steps to get a working integration, which normally consists of these steps:
- Configuring and initializing the SDK
- Launching a payment collection flow
- Awarding the purchased content to the user (i.e. consumption)
Here is a *fully-fledged* example implementation that achieves the aforementioned functionality in just under **150 lines of code**:
```java
package com.example.yoursdkintegration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.xsolla.android.mobile.*;
import com.xsolla.android.mobile.common.LogLevel;
import java.util.Arrays;
import java.util.List;
public class YourSDKIntegrationActivity extends Activity {
private static final String TAG = "YourSDKIntegration";
@Nullable
private BillingClient mBillingClient = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(),
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow()
)
);
final Config.Analytics configAnalytics = Config.Analytics.getDefault();
final Config.Payments configPayments = Config.Payments.getDefault();
final Config config = new Config(
configCommon,
configIntegration,
configPayments,
configAnalytics
);
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener(new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
for (int i = 0; i < purchases.size(); ++i) {
final ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchases.get(i).getPurchaseToken())
.build();
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(
@NonNull BillingResult billingResult, String purchaseToken
) {
Log.d(TAG,
"Purchase consumption response: " +
billingResult.getResponseCode()
);
}
});
}
} else {
Log.e(TAG,
"Purchase consumption response: " +
billingResult.getResponseCode()
);
}
}
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected.");
}
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.isSuccess()) {
final QueryProductDetailsParams queryProductDetailsParams =
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100")
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build();
mBillingClient.queryProductDetailsAsync(
queryProductDetailsParams, new ProductDetailsResponseListener() {
@Override
public void onProductDetailsResponse(
@NonNull BillingResult billingResult,
@Nullable List<ProductDetails> productDetailsList
) {
if (billingResult.isSuccess() && productDetailsList != null &&
!productDetailsList.isEmpty()) {
// We'll just use the very first element on the list, but you'd normally
// want to handle the rest of the product details as well.
final ProductDetails productDetails = productDetailsList.get(0);
// Create parameters for the purchasing flow..
final BillingFlowParams billingFlowParams =
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetails)
.build()
))
.build();
// Initiate a purchasing flow.
mBillingClient.launchBillingFlow(
YourSDKIntegrationActivity.this, billingFlowParams
);
} else {
Log.e(TAG,
"Received an invalid product details response: " +
billingResult.getResponseCode()
);
}
}
}
);
} else {
Log.e(TAG, "Failed to connect.");
}
}
});
}
}
```
important
If you are using your own **Project/Login IDs**, make sure to enable **Device ID login** in your Project. Learn how to enable it here: [https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
Quick Start - iOS
https://developers.xsolla.com/sdk/mobilesdk/quick-start/ios
Get the **Xsolla Mobile SDK** integrated and process your first test payment. We'll use pre-configured test credentials so you can start in minutes.
⚡ **DMA-ready & revenue-boosting**: leverage direct IPA distribution alongside in-app compliance with DMA — unlocking access to 1,000+ global payment methods and bypassing app-store fees to maximize your margins.
## Getting Started
ℹ️iOS — external payment link-outs (US, Japan, Brazil)
**iOS:** In the U.S., Japan, and Brazil, Apple now lets developers direct players to external web payments. The **Xsolla SDK** aligns with Apple's updated guidelines.
Add the **Xsolla Mobile SDK** to your project using Swift Package Manager:
- In Xcode, go to **File → Add Package Dependencies…**
- Enter the repository URL: `https://github.com/xsolla/xsolla-sdk-ios`
- Set the dependency rule to **Up to Next Major Version** and click **Add Package**.
- Select **XsollaMobileSDK** and add it to your target.
Then set up a URL scheme for your target:
- Select your target and open the *Info* tab.
- Click ➕ in the *URL Types* section.
- Set the URL Scheme to `$(PRODUCT_BUNDLE_IDENTIFIER)`.
![URL Scheme]
See [installation details](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios/) for more configuration options.
## Authenticate
Configure the SDK with test credentials, start the payment queue, and register a transaction observer:
```swift
import XsollaMobileSDK
let settings = SKPaymentSettings(projectId: 301871,
loginProjectId: "dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a",
platform: .standalone)
settings.useSandbox = true
settings.openExternalBrowser = true // External web payment (US, Japan, Brazil); either is allowed in the EU
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self) // Handle purchase completion — see Finalize Purchase
```
```objectivec
#import <XsollaMobileSDK/StoreKitWrapper.h>
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: 301871
loginProjectId:@"dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a"
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
settings.useSandbox = YES;
settings.openExternalBrowser = YES; // External web payment (US, Japan, Brazil); either is allowed in the EU
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
[queue addTransactionObserver: self]; // Handle purchase completion — see Finalize Purchase
```
This creates your settings with sandbox mode and test credentials, then starts the `SKPaymentQueue` and registers a transaction observer. For production, replace the test project ID and login ID with your own from [**Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/). See [configuration docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/) for advanced options including [storefront detection](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/).important
If you are using your own **Project/Login IDs**, make sure to enable **Device ID login** in your Project. Learn how to enable it here: [https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
## Load Catalog
Query your product catalog once connected:
```swift
let skus: Set<String> = ["money.100", "ticket.10"]
let req = SKProductsRequest(productIdentifiers: skus)
req.delegate = self
req.start()
// Conform your class to SKProductsRequestDelegate
extension YourClass: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
self.products = response.products
// Launch purchase — see Purchase Product
}
}
```
```objectivec
NSSet *skus = [NSSet setWithArray:@[@"money.100", @"ticket.10"]];
SKProductsRequest* req = [[SKProductsRequest alloc] initWithProductIdentifiers:skus];
req.delegate = self;
[req start];
// Conform your class to SKProductsRequestDelegate
@interface YourClass (SKProductsRequestDelegate) <SKProductsRequestDelegate>
@end
@implementation YourClass (SKProductsRequestDelegate)
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
self.products = response.products;
// Launch purchase — see Purchase Product
}
@end
```
This loads your products by SKU. See [initialization docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/ios/) for reconnection handling and advanced options.
## Purchase Product
Use the product details from your catalog query to launch a purchase:
```swift
let product = products.first! // Previously fetched product
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
```
```objectivec
SKProduct *product = ...; // Previously fetched product
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
This opens **Xsolla Pay Station** where users complete payment. For testing, use a [test card ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards):
![Choose payment method]
![Processing payment]
![Payment confirmed]
## Finalize Purchase
Handle completed transactions in your `SKPaymentTransactionObserver` and finish each one:
```swift
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .purchased:
// Award the product (virtual item) to the user here
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// Handle error
SKPaymentQueue.default().finishTransaction(transaction)
default:
break
}
}
}
}
```
```objectivec
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
// Award the product (virtual item) to the user here
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
// Handle error
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
default: break;
}
}
}
```
This processes purchase results and finishes transactions. Always call `finishTransaction` to acknowledge each transaction. See [purchase flow docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/) for error scenarios and advanced options.
## What's next?
You've built a complete payment integration: authentication, catalog loading, purchase flow, and fulfillment. Your app now has access to 1,000+ payment methods across 200+ countries.
- **[Set up your project](https://developers.xsolla.com/sdk/publisher-account/)** — create your Publisher Account and replace the sandbox test credentials with production ones
- **[Buy Button](https://developers.xsolla.com/sdk/mobilesdk/buy-button/ios/)** — fastest path to external payments
- **[Full SDK docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios/)** — advanced features, configuration, custom UI
Web Shop and Xsolla SDK: A Symbiotic Relationship
https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop
**Xsolla Web Shop** and **Xsolla SDK** are designed to work well together, creating a powerful ecosystem for game monetization both inside and outside your game. This synergy not only enhances your monetization strategy but also simplifies the integration process for both solutions.
📈 **Boost revenue across channels**: combine Web Shop and Xsolla SDK to reach players worldwide with over 1,000 payment methods, a ready-made Buy Button, and a unified backend—driving higher conversions with minimal added effort.
### From Web Shop to Xsolla SDK: A Natural Progression
If your game already uses Xsolla's Web Shop, you're well-positioned to integrate the Xsolla SDK with minimal effort:
- Existing Infrastructure: Your Web Shop integration means you already have server hooks and backend integrations in place for user authentication, inventory management, and purchase processing.
- Product Mirroring: To enable in-app purchases via the Xsolla SDK, you primarily need to mirror your existing Web Shop products as in-app products. This process is straightforward, as the groundwork is already laid.
- Unified Backend: With Web Shop in place, your backend is primed to handle requests from the Xsolla SDK, requiring only minor adjustments to support in-app transactions.
### From Xsolla SDK to Web Shop: Opening New Channels Effortlessly
Conversely, if you've integrated Xsolla SDK, launching a Web Shop becomes a breeze:
- Ready-to-Go Infrastructure: The Xsolla SDK integration means your game already communicates with Xsolla's backend services for user authentication and purchase processing.
- Xsolla Catalog in Place: Your in-app products (Virtual Items with SKUs) are already defined in Xsolla's system, making it simple to extend these offerings to a web-based storefront.
- Minimal Additional Setup: With the core integration complete via the Xsolla SDK, setting up a Web Shop requires just a few additional tweaks to go live, such as customizing the web interface and defining web-specific offers.
### The Power of Integration
By using both Xsolla SDK and Web Shop, you create a comprehensive monetization ecosystem that offers:
- The same buying experience for players on every platform
- Unified product catalog (Xsolla Catalog with Virtual Items) for easier management
- Flexibility to offer platform-specific deals and promotions
- Optional data collection for better player insights
- Increased touchpoints for player engagement and monetization
### Buy Button: Web Shop Integration
The Buy Button feature enhances the integration between your game and Web Shop by enabling direct link-outs to specific items:
- **Streamlined Purchase Flow**: Players can tap the Buy Button in your game to instantly access the Web Shop payment UI for a specific item, eliminating extra navigation steps
- **Familiar Payment Experience**: Use the full range of Web Shop payment methods, including Apple Pay, giving players a familiar, trusted checkout
- **Simplified Integration**: Implement the Buy Button with minimal effort, as it builds upon your existing Web Shop infrastructure
- **Enhanced Conversion**: Reduce purchase friction by enabling one-tap access to the payment flow, increasing conversion rates
- **Advanced Analytics**: Track purchases and measure lifetime value (LTV) with MMP (Mobile Measurement Partners) like AppsFlyer, maintaining full visibility into your campaigns and revenue
note
For detailed implementation instructions, including Android/iOS storefront detection, URL parameters, and analytics integration, see our [Buy Button documentation ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/) ([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/)).
Whether you start with Web Shop or Xsolla SDK, adding the other component becomes a straightforward process, allowing you to quickly expand your monetization channels and provide more options for your players to engage with and support your game. important
For more information, please follow the link:
[Xsolla Mobile Web Shop ↗](https://xsolla.com/mobile-web-shop) ([https://xsolla.com/mobile-web-shop](https://xsolla.com/mobile-web-shop))
How to detect Google Play storefront (Android)?
https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detect-gpb-storefront-android
When distributing your app through **Google Play**, you may need to detect the current storefront to implement region-specific functionality. The storefront represents the Google Play region associated with the user’s account, identified by a two-letter country code in **ISO-3166-1 alpha-2** format (e.g., `"US"` for United States). important
This detection is particularly important in light of the **Epic v. Google injunction effective October 29, 2025**, which permits U.S. Google Play apps to guide users to external payment methods via link-outs and prohibits anti-steering restrictions.
You can use storefront detection to:
- Enable alternative billing options specifically for U.S. users
- Implement region-specific payment flows
- Control feature availability based on local billing regulations
- Ensure compliance with U.S. court-mandated requirements
note
Google's programs and requirements differ per storefront, and several carry a commission you must report back to Google. See [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/) before enabling external transactions in a new market.
You can use the following snippet to retrieve the country code of the Google Play storefront:
```java
final Context context = ...
IntegrationUtils.queryGooglePlayCountryCodeAsync(context, result -> {
result.voidFold(
error -> {
// Handle the error here.
},
countryCode -> {
if (countryCode.equalsIgnoreCase("us")) {
// Handle the US storefront.
} else {
// Handle all other storefront variants.
}
}
);
});
```
important
This snippet is most useful, when **distributing** and **installing** your app **through Google Play store**. To check whether the app has been installed from Google Play store or side-loaded (third-party stores or APK distribution) you can use the `IntegrationUtils.isInstalledFromGooglePlayStore()` utility function. tip
Prior to retrieving the Google Play storefront country code, it's advised (but not mandatory) to verify whether Google Play Store is installed on the device as the query function will result in error if the store is not available. For this purpose you can rely on `IntegrationUtils.isGooglePlayStoreInstalled()` utility function.
How to detect store installation?
https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore
When distributing your app through alternative channels outside of official app stores (like Google Play Store or Apple's App Store), you may need to detect where your app was installed from. This is particularly important for:
- Implementing different payment flows for alternative distribution channels
- Adjusting app behavior based on the installation source
- Ensuring compliance with platform-specific requirements
- Managing features that should only be available in certain distribution channels
To determine where the game was installed from, use the snippets below.
### How to check if Google Play Store is installed?
Can be useful in scenarios where certain functionality should not run outside the Google Play ecosystem. This snippet lets you check whether the device has the **Google Play Store** installed:
```java
final Context context = ...
if (IntegrationUtils.IsGooglePlayStoreInstalled(context)) {
// The store is installed on the device..
} else {
// The store is NOT installed on the device..
}
```
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean installed = IntegrationUtils.isGooglePlayStoreInstalled(context);
if (installed) {
// Google Play Store is installed.
} else {
// Google Play Store couldn't be found on the device.
}
```
### Checking if the App is Installed from Google Play Store
This snippet helps to determine whether the app was installed directly from the **Google Play Store** or side-loaded (installed from a third-party store or an APK):
```java
final Context context = ...
if (IntegrationUtils.IsInstalledFromGooglePlayStore(context)) {
// The app was installed from Google Play Store..
} else {
// The app was NOT installed (side-loaded) from Google Play Store..
}
```
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean installed = IntegrationUtils.isInstalledFromGooglePlayStore(context);
if (installed) {
// The app was installed from Google Play Store.
} else {
// The app wasn't installed from Google Play Store.
}
```
### Querying the country code of Google Play Store
Use this snippet to query the country code for the Google Play's storefront.important
The country code format is based on ISO-3166-1 alpha2 (UN country codes).
[https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html](https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html)
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
import com.xsolla.android.mobile.Either;
import com.xsolla.android.mobile.Error;
```
```java
final Context context = ...;
IntegrationUtils.queryGooglePlayCountryCodeAsync(
context, new IntegrationUtils.IQueryGooglePlayCountryCodeCallback() {
@Override
public void onQueryGooglePlayCountryCode(@NonNull final Either<Error, String> result) {
result.voidFold(
err -> {
// Handle the error here.
},
countryCode -> {
if (countryCode.equalsIgnoreCase("us")) {
// Handle the US storefront.
} else {
// Handle all other storefront variants.
}
}
);
}
}
);
```
### Querying the installer's package name
If you need to know the exact package name of your app's installer, use the following code below.
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
import com.xsolla.android.mobile.Either;
import com.xsolla.android.mobile.Error;
```
```java
final Context context = ...;
final Either<Error, String> result = IntegrationUtils.getInstallerPackageName(context);
result.voidFold(
err -> {
// Handle the error.
},
packageName -> {
if (packageName.equalsIgnoreCase("com.xxx.yyy.zzz")) {
// Handle the expected package name.
} else {
// Handle the unknown package name.
}
}
);
```
Or if you prefer a simplified approach that omits error handling, use this code:
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean matched = IntegrationUtils.isInstallerPackageName(
context, "con.xxx.yyy.zzz"
);
if (matched) {
// The package name matched.
} else {
// The package name didn't match.
}
```
### Reporting a custom install source
Every order carries the channel your app was installed from (`user.mobile_app.install_source`). The SDK detects it from the installer package name: `google_play`, `aptoide`, `epic_games_store`, or the package name itself for any other installer.
For a build distributed outside an app store, such as an APK downloaded from your website, the OS reports the browser, the system package installer or no installer at all. Set the channel yourself and it is sent instead of the detected one:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withInstallSource("website");
```
To determine alternative app distribution status, use the following code snippets:
```objectivec
[SKPaymentQueue checkIfRunningInAlternativeDistributionWithCompletion:^(BOOL isRunningInAlternativeDistribution) {
settings.enablePayments = isRunningInAlternativeDistribution;
[[SKPaymentQueue defaultQueue] startWithSettings:settings];
}];
```
```swift
SKPaymentQueue.checkIfRunningInAlternativeDistribution { isInAlternativeStore in
settings.enablePayments = isInAlternativeStore
SKPaymentQueue.default().start(settings)
}
```
You can also implement the official method described in [Apple's Documentation ↗](https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms) ([https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms](https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms)) to detect alternative app distribution. The following implementation is written in Swift but includes Objective-C compatibility. Call `getMarketplaceOrWeb()` and the callback will return `true` if the app is distributed through an alternative marketplace or web distribution.
```swift
getMarketplaceOrWeb { isAlternative in
settings.enablePayments = isAlternative
SKPaymentQueue.default().start(settings)
}
@objc
@MainActor
public static func getMarketplaceOrWeb(_ callback: @escaping ((Bool) -> Void)) {
Task(priority: .high) {
let flag = await isMarketplaceOrWeb()
callback(flag)
}
}
static func isMarketplaceOrWeb() async -> Bool {
if #available(iOS 17.4, *) {
#if canImport(MarketplaceKit)
do {
let currentDistributor = try await AppDistributor.current
switch currentDistributor {
case .appStore:
return false
case .testFlight:
return false
case .marketplace(let bundleId): // Alternative App Marketplace; the argument String identifies the marketplace app bundle ID
return true
case .web: // Alternative Web distribution
return true
case .other:
return false
@unknown default:
return false
}
} catch { return false }
#endif
}
return false
}
```
How to detect iOS Storefront?
https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront
When distributing your app through Apple's App Store, you may need to detect the current storefront to implement region-specific functionality. The storefront represents the App Store region that the user is currently using, identified by a three-letter country code (e.g., "USA" for United States).
This detection is particularly important because several storefronts now permit developers to direct players to external payment pages — the **United States** (*Epic v. Apple*), **Japan** (Mobile Software Competition Act), **Brazil** (CADE settlement), and the **European Union** (Digital Markets Act). You can use the storefront detection to:
- Enable external payment links for the storefronts that permit them
- Implement region-specific payment flows
- Control feature availability based on regional requirements
- Ensure compliance with local regulations
note
Apple's requirements differ per storefront. Japan, Brazil and the EU need an Apple entitlement and require you to report the resulting transactions back to Apple, while the United States storefront currently needs neither. The EU storefronts are left out of the snippet below; add the ones you ship to. See [Reporting External Purchases to Apple](https://developers.xsolla.com/sdk/compliance/ios/) before enabling external payments in a new market. note
If the app is installed via **alternative distribution** (for example, an alternative marketplace/web distribution under the DMA), the Storefront country code may be unavailable and returned as an **empty string**. In that case, use the [**alternative store installation detection**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/) guide to determine whether the app is running in an alternative distribution environment.
To determine the current iOS storefront and control SDK functionality based on the region, use the following code snippets:
```objectivec
[SKPaymentQueue loadCurrentStorefrontCountryCodeWithCompletion:^(NSString* _Nullable countryCode) {
// Storefronts where Apple permits external payments. Add EU codes if you ship there.
NSSet<NSString*>* externalPaymentStorefronts = [NSSet setWithObjects:@"USA", @"JPN", @"BRA", nil];
settings.enablePayments = countryCode && [externalPaymentStorefronts containsObject:countryCode];
[[SKPaymentQueue defaultQueue] startWithSettings:settings];
}];
```
```swift
SKPaymentQueue.loadCurrentStorefrontCountryCode { countryCode in
// Storefronts where Apple permits external payments. Add EU codes if you ship there.
let externalPaymentStorefronts: Set = ["USA", "JPN", "BRA"]
settings.enablePayments = countryCode.map(externalPaymentStorefronts.contains) ?? false
SKPaymentQueue.default().start(settings)
}
```
The `loadCurrentStorefrontCountryCode` method asynchronously retrieves the three-letter country code for the current Storefront. You can use this information to enable or disable SDK functionality for specific regions.
Alternatively, you can use Apple's [Storefront ↗](https://developer.apple.com/documentation/storekit/storefront) ([https://developer.apple.com/documentation/storekit/storefront](https://developer.apple.com/documentation/storekit/storefront)) class directly, as demonstrated below: note
We recommend against using the Objective-C `SKStorefront` implementation as it performs synchronous loading that blocks the main thread. This can lead to UI freezes and poor user experience, as noted in Apple's [official documentation ↗](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront).
```swift
let storefront = await Storefront.current
let countryCode = storefront?.countryCode
settings.enablePayments = countryCode == "USA"
SKPaymentQueue.default().start(settings)
```
For more information, see the implementation in Apple's [official documentation ↗](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront) ([https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront)).
iOS Universal Links
https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-universal-links
When using **External Browser** flows, returning from Pay Station to your app via a **custom URL scheme** can trigger an iOS confirmation dialog (for example, “Open this page in *App Name*?”). Using **Universal Links** (HTTPS) avoids this prompt and provides a smoother redirect back to the game.
The SDK supports Universal Links for redirecting back to your app.
## Requirements
To use Universal Links, you must configure your iOS project and your domain:
- **Associated Domains**: enable and configure in Xcode. See Apple docs: [Supporting Associated Domains](https://developer.apple.com/documentation/xcode/supporting-associated-domains).
- **Universal Links** support. See Apple docs: [Supporting universal links in your app](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app).
## SDK handling (automatic vs manual)
If the SDK's automatic URL handling (swizzling) is enabled, Universal Links are handled automatically.
If you disabled automatic URL handling, you must forward the Universal Link to the SDK so it can process the callback (same idea as manual deep link handling, but the URL comes from `NSUserActivity.webpageURL`).
### AppDelegate
```objectivec
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
// Cold start (optional): app was launched by a Universal Link
NSDictionary *userActivityDict = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey];
NSUserActivity *activity = userActivityDict[UIApplicationLaunchOptionsUserActivityKey];
NSURL *url = activity.webpageURL;
if (url) {
[[SKPaymentQueue defaultQueue] openWithUrl:url];
}
return YES;
}
// Warm start: app receives a Universal Link while running/suspended
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
NSURL *url = userActivity.webpageURL;
if (!url) { return NO; }
// Forward to SDK
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
return handledBySDK;
}
```
```swift
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Cold start (optional): app was launched by a Universal Link
if let userActivityDict = launchOptions?[.userActivityDictionary] as? [AnyHashable: Any],
let activity = userActivityDict["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity,
let url = activity.webpageURL {
_ = SKPaymentQueue.default().open(url: url)
}
return true
}
// Warm start: app receives a Universal Link while running/suspended
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard let url = userActivity.webpageURL else { return false }
// Forward to SDK
let handledBySDK = SKPaymentQueue.default().open(url: url)
return handledBySDK
}
```
### SceneDelegate
```objectivec
// Cold start: app was launched by a Universal Link
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
for (NSUserActivity *activity in connectionOptions.userActivities) {
NSURL *url = activity.webpageURL;
if (!url) { continue; }
// Forward to SDK
[[SKPaymentQueue defaultQueue] openWithUrl:url];
break;
}
}
// Warm start: app receives a Universal Link while running/suspended
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
NSURL *url = userActivity.webpageURL;
if (!url) { return; }
// Forward to SDK
[[SKPaymentQueue defaultQueue] openWithUrl:url];
}
```
```swift
// Cold start: app was launched by a Universal Link
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
if let userActivity = connectionOptions.userActivities.first,
let url = userActivity.webpageURL {
_ = SKPaymentQueue.default().open(url: url)
}
}
// Warm start: app receives a Universal Link while running/suspended
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let url = userActivity.webpageURL else { return }
// Forward to SDK
_ = SKPaymentQueue.default().open(url: url)
}
```
Trusted Web Activity (Android)
https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/trusted-web-activity
A [**Trusted Web Activity (TWA) ↗**](https://developer.chrome.com/docs/android/trusted-web-activity) ([https://developer.chrome.com/docs/android/trusted-web-activity](https://developer.chrome.com/docs/android/trusted-web-activity)) enables Android apps to display web content in full-screen mode using Chrome, without any browser UI elements. Unlike WebView, *TWAs* run in the user's browser context, allowing better performance, access to browser features (like push notifications and background sync), and shared cookies, permissions, and storage between the app and the browser. important
To enable *Trusted Web Activity*, contact your integration manager with the app’s package name and certificate hash. DID YOU KNOW?
*Trusted Web Activity* support is project-independent and applies at the app level — based on the package name and signing certificate only.
### Configuring for Trusted Web Activity in the SDK
When configuring the SDK, supply an activity setting to the config like this:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forTrustedWebActivity());
```
This ensures that the *Trusted Web Activity* will be used by the payment flow. warning
*Trusted Web Activity* availability depends on the device's system configuration, i.e. a compatible browser needs to be installed. If *TWA* support is not available, then the SDK falls back to one of the default activity types for payments (e.g. *Custom Tabs* or *WebView*, depending on the environment).
An example of the *TWA* in action: [](https://developers.xsolla.com/sdk/assets/images/twa-1-737175ed3a44e80fb60131748dda4361.jpg)
### (Optional) Orientation locking
*Trusted Web Activity* natively supports orientation locking when it's shown on the screen. This can be set up during the configuration step with these lines:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivityOrientationLock(
// orientation setting
);
```
Orientation setting is one of the following values:
- `Config.Payments.ACTIVITY_ORIENTATION_LOCK_PORTRAIT` - forces the *TWA* to be displayed in *portrait* mode.
- `Config.Payments.ACTIVITY_ORIENTATION_LOCK_LANDSCAPE` - forces the *TWA* to be displayed in *landscape* mode.
- `null` - disables the orientation locking.
### (Optional) Adding a customizable splash screen
*Trusted Web Activity* also supports a customizable splash screen that's shown right before the *TWA* itself. To enable it, modify the configuration setting we added [earlier](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/trusted-web-activity#configuring-for-trusted-web-activity-in-the-sdk):
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage(
// image settings go here
));
```
An example of the *TWA* splash screen: [](https://developers.xsolla.com/sdk/assets/images/twa-2-fd93e4a14c1a92ff7574a04d1a7abf15.jpg)
#### Setting an image for the splash screen
Image can be supplied via two methods: a *drawable ID* and a filepath to the image:
- A *drawable ID*: important The drawable needs to be added to the Android resource manually beforehand. ```java final Config.Payments configPayments = Config.Payments.getDefault() .withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage( Config.Payments.Activity.TrustedWebActivity.Image.forDrawableId( <your_drawable_id> ) )); ``` tip SVG format is also supported, but needs to be wrapped into a valid drawable XML.
- A filepath: important The image file needs to be discoverable. Supports all major raster image formats. ```java final Config.Payments configPayments = Config.Payments.getDefault() .withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage( Config.Payments.Activity.TrustedWebActivity.Image.forFilepath( <filepath_to_your_splash_screen_image> ) )); ```
note
If you're working with **Unity**, consider visiting this page for more details: [**Trusted Web Activity - Unity (Android)**](https://developers.xsolla.com/sdk/unity/sdk/advanced/trusted-web-activity/).
Configuration
https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/)
Configuration - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android
The **Xsolla Mobile SDK** for Android splits its configuration into four major settings subcategories, each represented by its own specific class:
- [**Common**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#common) - settings that define SDK's generic properties.
- [**Integration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#integration) - settings that define how the SDK integrates with **Xsolla** services. - [**Authentication**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#authentication) - settings that define how the SDK authenticates with **Xsolla** services. - [**Events**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#xsolla-events-api) - settings that define how the SDK works with the **Xsolla Events API**.
- [**Payments**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#payments) - settings that define **Xsolla Pay Station** behavior (appearance, redirects, etc).
- [**Analytics**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#analytics) - settings that define the SDK's analytics related meta-data.
To create a `Config` for SDK from all of the subcategories, use the following snippet:
```java
final Config config = new Config(
configCommon,
configIntegration,
configPayments,
configAnalytics
);
```
## Common
Call `Config.Common.getDefault()` for default configuration. Here's an example best suited for testing:
```java
final Config.Common configCommon = Config.Common.getDefault()
.withSandboxEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withDebugEnabled(true);
```
Below is a list of all settings supported by `Config.Common`:
| Setting | Value | Default | Description |
| --- | --- | --- | --- |
| withSandboxEnabled | boolean | false | Are test payments enabled? If enabled, no real transactions. The project should not be in LIVE mode for the sandbox to work. |
| withLogLevel | enum LogLevel (VERBOSE, DEBUG, INFO, WARN, ERROR) | ERROR | Controls the verbosity of the logging (use DEBUG if encountered any difficulties and would like to get more information on what's going under the hood). |
| withSkipNonExistentProductsOnQuery | boolean | true | Does queryProductDetailsAsync() safely ignore any missing requested products on query or fail right away? |
| withDeferredAuthenticationEnabled | boolean | true | Controls whether the authentication is postponed until after it really becomes needed for the SDK functionality, potentially speeding up the initialization flow. |
| withDebugEnabled | boolean | false | Enables the debug mode (more logging, profiling, etc). |
| withLocaleOverride | LocaleInfo | null | A specific locale to use for pricing and formatting for returned products and Pay Station (automatic if null). |
| withFallbackToDeviceLocale | boolean | false | Shall device's current locale be used if no override has been explicitly specified (otherwise it will be deduced automatically by Pay Station)? |
| withFetchPersonalizedProductsOnly | boolean | true | Return personalized products only; set to false for generic catalogs. |
| withUseGeoLocaleOnProductQuery | boolean | false | Force use of geo locale when querying products. |
| withRetryPolicies | RetryPolicies | null | Override retry behavior globally or per operation (authentication, create order, query products, etc.). |
| withCollapseRestoredMultiUnitPurchases | boolean | false | Should multiple owned units of the same SKU be returned as a single Purchase on restoration? See Purchase Restoration Settings below. |
| withProductCacheTtlMillis | Long | 3600000 | How long a cached product stays fresh for queryProductDetailsAsync(), in milliseconds (1 hour by default), measured from when it was cached. null or a non-positive value never expires within the process — restarting the app is then the only thing that bounds staleness. |
| withMaxItemsPerProductRequest | Integer | null | How many SKUs queryProductDetailsAsync() requests per call when fetching products it hasn't cached yet. null uses the backend page cap of 50; values are clamped to 1–50, since the cap is a backend limit rather than a tunable. |
| withMaxParallelProductRequests | Integer | 4 | How many product-fetch requests may be in flight at once for a single queryProductDetailsAsync(), to stay clear of the backend's rate limit. Set 1 to fetch sequentially; null or a non-positive value dispatches every chunk at once. |
| withAllowBundlesAsInApp | boolean | false | Accept a SKU that resolves to a bundle when it was requested as INAPP, instead of reporting it as unavailable for the requested type. Lets a caller that doesn't distinguish the two fetch both in one query. |
| withAllowVirtualCurrencyAsInApp | boolean | false | The same relaxation for a SKU that resolves to virtual currency on an INAPP request. |
Both relaxations are narrow and one-directional: only that one type is accepted for an `INAPP` request, and `SUBS` or any other mismatch still fails. The product you get back also reports its **real** type — `getProductType()` returns `bundle` or `virtual_currency`, never `inapp` — so anything downstream that branches on product type has to tolerate that.
### Retry policies and profiles
Retry policy overrides (per operation):
| Setting | Value | Default | Description |
| --- | --- | --- | --- |
| withDefaultRetryProfileOverride | RetryProfile | null | Fallback profile applied if an operation-specific profile is not provided. |
| withAuthenticateRetryProfileOverride | RetryProfile | null | Overrides retries for authentication. |
| withCreateOrderRetryProfileOverride | RetryProfile | null | Overrides retries for order creation. |
| withPendingOrderStatusQueryRetryProfileOverride | RetryProfile | null | Overrides retries when polling pending order status. |
| withQueryProductsRetryProfileOverride | RetryProfile | null | Overrides retries for product list queries. |
| withQueryPurchasesRetryProfileOverride | RetryProfile | null | Overrides retries for purchase list queries. |
| withConsumePurchasesRetryProfileOverride | RetryProfile | null | Overrides retries for purchase consumption. |
`null` here doesn't mean "no retries" — it means no override, and the operation falls back to the built-in profile: a **uniform 750 ms delay, up to 12 attempts**. Set an override only to depart from that.
Use `RetryProfile` variants to build overrides for specific operations or a global default:
Fixed delay between attempts.
```java
final RetryProfile retryProfile = RetryProfile.uniform(
PositiveInteger.create(6).getRightOrThrow(),
PositiveInteger.create(1000).getRightOrThrow()
);
```
| Argument | Description |
| --- | --- |
| maxNumAttempts | Positive integer; total number of attempts allowed (initial try + retries). |
| intervalMillis | Fixed delay in milliseconds between attempts. |
Delay grows exponentially from the base interval, with optional caps and jitter.
```java
final RetryProfile retryProfile = RetryProfile.exponentialBackout(
PositiveInteger.create(5).getRightOrThrow(),
PositiveInteger.create(500).getRightOrThrow(),
PositiveInteger.create(4000).getRightOrThrow(),
null // optional jitter cap
);
```
| Argument | Description |
| --- | --- |
| maxNumAttempts | Positive integer; total number of attempts allowed (initial try + retries). |
| baseIntervalMillis | Initial delay in milliseconds; subsequent attempts grow exponentially from this base. |
| maxIntervalMillis (optional) | Cap for the backoff delay in milliseconds; if omitted, delay can grow until attempts are exhausted. |
| maxRandomExtraDelayMillis (optional) | Adds up to this many milliseconds of jitter to each backoff delay; null to disable jitter. |
```java
final RetryPolicies retryPolicies = RetryPolicies.getDefault()
.withDefaultRetryProfileOverride(retryProfile) // pick from a tab above
.withAuthenticateRetryProfileOverride(retryProfile);
final Config.Common configCommon = Config.Common.getDefault()
.withRetryPolicies(retryPolicies);
```
## Integration
### Authentication
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
LoginUuid.parse(<your_login_id>).getRightOrThrow()
)
);
```
Authenticates using a custom login **JWT** (must be valid). Useful for situations when JWT is generated or acquired externally (e.g. using the app's backend or services like Xsolla Login, etc) and fed into the SDK.
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
JWT.parse(<jwt>).getRightOrThrow()
)
);
```
**With manual JWT token updating:**
If your JWT tokens expire and need to be refreshed after the billing client is connected, use the `JWTRefresher` parameter:
```java
final JWTRefresher jwtRefresher = new JWTRefresher();
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
JWT.parse(<jwt>).getRightOrThrow(),
jwtRefresher
)
);
// Later, when you need to update the token:
jwtRefresher.update(JWT.parse(<new_jwt>).getRightOrThrow());
```
Authenticates using OAuth2.
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forOAuth2(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
LoginUuid.parse(<your_login_id>).getRightOrThrow(),
OAuth2ClientId.parse(<oauth2_client_id>).getRightOrThrow()
)
);
```
Authenticates using a social access token received from a 3rd-party provider.
First of all, for this approach to work you'll need to figure out which social provider you're going to work with and whether it's supported by Xsolla authentication services:All supported social providers names
- google
- facebook
- twitter
- linkedin
- naver
- baidu
- amazon
- apple
- battlenet
- discord
- github
- kakao
- mailru
- microsoft
- msn
- ok
- paypal
- psn
- qq
- reddit
- steam
- twitch
- vimeo
- vk
- wechat
- weibo
- yahoo
- yandex
- youtube
- xbox
- babka
- epicgames
`LoginUtils.SocialProvider` holds a set of predefined social provider values for convenience. To get a matching instance from a string, use `LoginUtils.SocialProvider.parse("<social-provider-name>")`.
```java
final LoginUtils.SocialProvider socialProvider = LoginUtils.SocialProvider.EPICGAMES;
final String socialAccessToken = "<social-access-token>";
```
Overall, there are two paths for this approach:
- **With OAuth2 (recommended)** ```java final Config.Integration configIntegration = Config.Integration.forXsolla( Config.Integration.Xsolla.Authentication.forSocial( ProjectId.parse(<your_project_id>).getRightOrThrow(), LoginUuid.parse(<your_login_id>).getRightOrThrow(), OAuth2ClientId.parse(<oauth2_client_id>).getRightOrThrow(), socialProvider, socialAccessToken ) ); ```
- **Without OAuth2** ```java final Config.Integration configIntegration = Config.Integration.forXsolla( Config.Integration.Xsolla.Authentication.forSocial( ProjectId.parse(<your_project_id>).getRightOrThrow(), LoginUuid.parse(<your_login_id>).getRightOrThrow(), socialProvider, socialAccessToken ) ); ```
Information on how to obtain **Product ID** and **Login ID** can be found [**here**](https://developers.xsolla.com/sdk/publisher-account/getids/).
You can also supply a [**Xsolla Login ↗**](https://xsolla.com/login) ([https://xsolla.com/login](https://xsolla.com/login)) token via the [**Custom Login Token**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/?auth-method=xsolla-jwt-custom#authentication) approach.
### Purchase Restoration Settings
Restoration recovers purchases a player already made — after a reinstall, a new device, or simply because the client never confirmed the original transaction — so they aren't charged twice for the same item.
Which backend the SDK restores from is decided by two settings — one in *Publisher Account*, one in the SDK config below. A project restores from Inventory API until both are switched over to Events API. For the exact combinations, what each backend records, and what switching a live project involves, see [**Selecting a mode**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api/#selecting-a-mode). warning
**Restoring from Inventory API does not give you real order or invoice identifiers.**
The inventory holds what a player currently owns, with no transaction behind it, so the SDK makes those identifiers up on the device — they don't correspond to anything in Publisher Account or an order lookup. If your backend, support tools, or fraud checks need to match a restored purchase to a real Xsolla order, that requires Events API. See [**Purchase flow — Restored purchases**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/#restored-purchases) for the field-by-field breakdown.
#### Units per restored purchase
An inventory row reports a SKU and a quantity, and by default the SDK splits that row into one single-unit `Purchase` per owned unit. That breaks down when a catalog models in-game currency as a per-unit virtual item: a single SKU can then report hundreds of thousands of owned units in one restore, and allocating a separate `Purchase` for each of them can put real pressure on memory.
`withCollapseRestoredMultiUnitPurchases` (on `Config.Common`, see [**Common**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#common) above) returns the row as a single `Purchase` carrying the full quantity instead. It defaults to `false`:
```java
final Config.Common configCommon = Config.Common.getDefault()
.withCollapseRestoredMultiUnitPurchases(true);
```
| Configuration | Holding | Result |
| --- | --- | --- |
| false | Under 100 units | One Purchase per unit, each with a quantity of 1 |
| false | 100 units or more | A single Purchase carrying the full quantity |
| true | Any size | Always a single Purchase carrying the full quantity |
That `100`-unit threshold is a hard ceiling guarding against the same case. It isn't configurable, and it applies even with the flag off — so a holding that grows past it changes shape on its own. Handle both shapes if a SKU's holdings can realistically get that large.
Consuming a collapsed `Purchase` drains all of its units in a single `consumeAsync()` call. Splitting is otherwise a presentation convenience only: the inventory reports an aggregate quantity per SKU, so the resulting objects carry no per-payment identity — see [**Inventory API vs. Events API**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api/#no-anchor-data).
### Xsolla Events API
The **Xsolla Events API** serves as an alternative to webhook-based integrations, where the integrator’s backend usually handles most of the logic (purchase validation, awarding, etc.). Instead of sending webhooks directly, the API intercepts them and stores their payloads in a remote queue managed by Xsolla. This approach enables serverless integrations for projects that lack backend capacity or don’t require one, yet still prefer handling the entire transaction flow directly from the app.
Supplying an `Events` config also switches restoration over to Events API, so restored purchases carry the real order and invoice IDs from the original Xsolla order — see [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android#purchase-restoration-settings) above.
To enable it, open your project in *Publisher Account*, go to **Project settings** > **Integration settings**, select **Use API** and click **Save**. See [**Events API in Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api) for details.
Opting for the ***Xsolla Events API*** **disables** your project’s **webhooks** — you **cannot use both simultaneously**.
Below is the minimal events configuration required to enable the functionality in SDK:
```java
final Config.Integration.Xsolla.Events configEvents =
Config.Integration.Events
.newBuilder()
.build()
```
If you would like to listen to incoming events, assign an optional custom event listener using `Events.Builder.withEventListener` method:
```java
final Config.Integration.Xsolla.Events configEvents =
Config.Integration.Events
.newBuilder()
.withEventListener(event -> {
// Don't consume the event (mark as processed on the queue).
return false;
})
.build()
```
Now, assign the events config to the integration config:
```java
final Config.Integration configIntegration =
Config.Integration
.forXsolla(
// ...your authentication configuration
)
.withEvents(configEvents);
```
Below is the list of advanced *Events API* related settings:
| Setting | Value | Default | Description |
| --- | --- | --- | --- |
| withDefaultQueryPeriodMillis | Long | 5000 | Amount of time between the consecutive event queries in milliseconds (-1 if disabled, null to use the default). |
| withQueryProfileIfExpectingPurchases | EventQueryProfile | null | A specific query profile to apply when expecting a purchase (e.g. just completed a purchasing flow and waiting for a confirmation and want to do an accelerated querying for a limited amount of time). |
| withExternalFreePurchaseHandlingEnabled | boolean | false | Should external purchase events that originated by claiming a free item be handled? |
## Payments
Call `Config.Payments.getDefault()` for default configuration. Here's an example that forces the close button to appear in **Xsolla Pay Station**:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withCloseButton(Config.Payments.CloseButton.show());
```
Below is a list of all settings supported by `Config.Payments`:
| Setting | Value | Default | Description |
| --- | --- | --- | --- |
| withRedirectUrl | URL | null | URL to redirect to when returning from Xsolla Pay Station. |
| withRedirectTimeoutSecs | Integer | null | Amount of time before Xsolla Pay Station automatically closes (if null, then uses the default value). |
| withRedirectButtonText | String | null | Text on the 'return' link in Xsolla Pay Station. |
| withRedirectCondition | Integer | null | Determines under what conditions automatic closure takes place (REDIRECT_CONDITION_DISABLED, REDIRECT_CONDITION_SUCCESS, REDIRECT_CONDITION_SUCCESS_OR_CANCELED, REDIRECT_CONDITION_ANY). |
| withTheme | Config.Payments.Theme | null | Defines the visual aspect of Xsolla Pay Station (Theme.Light, Theme.Dark, Theme.Custom) — with no theme set, Pay Station picks size and style automatically. |
| withCloseButton | Config.Payments.CloseButton | null | Defines the state of the close button in Xsolla Pay Station (not to be confused with the 'return' link; CloseButton.Hide, CloseButton.Show). |
| withActivity | Config.Payments.Activity | null | Determines which approach is used for displaying Xsolla Pay Station (Activity.System, Activity.WebView, Activity.CustomTabs, Activity.TrustedWebActivity - for TWA see more information here). |
| withActivityOrientationLock | Integer | null | Specifies a desired screen orientation to lock to, when displaying Xsolla Pay Station (availability depends on the chosen Config.Payments.Activity; ACTIVITY_ORIENTATION_LOCK_PORTRAIT, ACTIVITY_ORIENTATION_LOCK_LANDSCAPE). |
| withBuyButtonSolutionEnabled | boolean | false | Enables/disables the Buy Button Solution's state (see here for more information) |
| withEmailCollectionConsentOptInEnabled | boolean | false | Enable opt-in for collecting the user's email as part of the payment flow (for example, newsletter consent). |
| withInvokePurchasesUpdatedForMissingOrderId | boolean | false | Invoke purchase callback even if order ID is missing (for order-id-less flows). |
| withShowLogoEnabled | Boolean | null | Controls visibility of the Xsolla logo in Pay Station. Pass true to show, false to hide, or null for default behavior. |
| withEventListeners | EventListeners | null | Register listeners for Pay Station navigation events (page opened, loaded, closed). Use EventListeners builder to configure callbacks. |
| withDomainOverrideConfig | DomainOverrideConfig | null | Override default Pay Station domains for production and sandbox environments. Use DomainOverrideConfig builder to specify custom domains. |
| withCustomUserId | String | null | A custom user identifier to associate with the payment session in Pay Station (null to omit). Sent as custom_parameters.custom_user_id and returned in purchase webhooks; not used for attribution — see withAttributionUserId. |
| withAttributionUserId | String | null | The ID that purchase events reported to attribution platforms (AppsFlyer, Adjust, etc.) are keyed on, sent to Pay Station as custom_parameters.custom_id. It must equal the customer user ID your attribution SDK reports, or purchases won't match up with that user. With null, events are matched on the user ID in the payment token, which by default is the player's Xsolla Login user ID.1 |
| withInstallSource | String | null | The channel your app was distributed through, sent with the order as user.mobile_app.install_source in place of the one detected from the OS installer. Use it for builds distributed outside an app store, such as an APK downloaded from your website, where the OS reports the browser, the system package installer or no installer. The value is trimmed and otherwise sent as is; a blank value counts as unset. With null, the detected value is sent: google_play, aptoide, epic_games_store, or the installer's package name — see here. |
| withQueryCancellationReasonEnabled | boolean | false | Whether to query for the reason a payment was cancelled when the purchase flow ends without completion. |
| withRedirectAppRelaunch | boolean | false | When the app is killed during a payment flow in an external browser, enables the return-to-app button in Pay Station to relaunch the app instead of silently failing. |
1 If your project authenticates players through server-side custom ID login or PlayFab, or maps the user ID to a custom JWT claim, the payment token carries that value instead of the Login user ID. Call `withAttributionUserId`, or purchase events won't match your attribution platform.
### Custom Tabs / Trusted Web Activity provider controls
For Custom Tabs and Trusted Web Activity flows, control which browser providers are allowed and their priority:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forCustomTabs())
.withEmailCollectionConsentOptInEnabled(true)
.withActivity(
Config.Payments.Activity.forCustomTabs()
.withBlacklistedProviders(Set.of("com.android.chrome"))
.withInternalProviderBlacklistEnabled(true)
.withBlacklistedTWAProviders(Set.of("com.vendor.browser"))
.withInternalTWAProviderBlacklistEnabled(true)
.withProviderWeights(Map.of("com.google.android.apps.chrome", 2.0f))
.withFallbackToFirstAvailableTWAProvider(true)
);
```
### Buy Button Solution
The *Buy Button Solution* provides a complete, native payment experience with minimal integration effort. This approach handles the entire payment flow within your app using Xsolla's optimized UI components.
**When to use Buy Button Solution:**
- You want a fully native integration
- You need 1,000+ payment methods out of the box
- You prefer Xsolla to manage the payment UI
- You want automatic regional compliance
To enable the *Buy Button Solution* for your payments (works with [**default flows**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow) only), use the snippet below:
```java
final Config.Payments configPayments =
Config.Payments.getDefault()
.withBuyButtonSolutionEnabled(true);
```
### Event Listeners
`EventListeners` is an optional, immutable callback container that lets you hook into **Pay Station** UI lifecycle events without subclassing or modifying the billing flow. Attach it to your payments config via `.withEventListeners(...)`.
All callbacks are dispatched on the **main thread** — safe to update UI directly.
| Interface | Method | Fires when |
| --- | --- | --- |
| IOpenedListener | onOpened() | Pay Station activity has been started. |
| ILoadedListener | onLoaded() | WebView loading finishes (fired for successful load, failed load, and aborted load alike — the SDK does not distinguish between these outcomes at the EventListeners level). |
| ICompletedListener | onCompleted() | Payment succeeded and onPurchasesUpdated was called with OK and a non-empty purchases list. |
| ICancelledListener | onCancelled() | Flow ended with a USER_CANCELED response code (fires in addition to onPurchasesUpdated(USER_CANCELED, null) — does not replace it). |
info
For the SKU-based flow, `onCompleted` only fires if the purchases list is non-empty. Orders with no valid order ID on Xsolla's side are silently skipped.
Build an `EventListeners` instance using the copy-on-write builder — each `with*` call returns a new instance. All listeners are optional; unset listeners are simply not called. Passing `null` to `.withEventListeners(...)` disables all listeners.
```java
final EventListeners listeners = EventListeners.getDefault()
.withOpenedListener(() -> { /* Pay Station opened */ })
.withLoadedListener(() -> { /* Pay Station loaded */ })
.withCompletedListener(() -> { /* payment completed */ })
.withCancelledListener(() -> { /* payment cancelled */ });
final Config.Payments configPayments = Config.Payments.getDefault()
.withEventListeners(listeners);
```
## Analytics
Analytics configuration allows you to pass metadata to the SDK that Xsolla can use for internal analytics and reporting. While not strictly required, it can help improve visibility into app performance, user behavior, and transaction flows — and may assist in diagnosing or resolving issues more efficiently.
```java
final Config.Analytics configAnalytics =
Config.Analytics.getDefault()
.withGameEngine("<game-engine-identifier>")
.withGameEngineVersion("<game-engine-version>">);
```
Below is a list of all settings supported by `Config.Analytics`:
| Setting | Value | Default | Description |
| --- | --- | --- | --- |
| withGameEngine | String | null | A custom game engine identifier or null for defaults. |
| withGameEngineVersion | String | null | A custom game engine version or null for defaults. |
Before configuring analytics in the SDK, contact your **integration manager** to confirm whether it's viable for your integration.
## Testing purchase flow in sandbox mode
See [**here**](https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/android/) for more details on how to enable the sandbox mode and avoid spending real money while testing the integration.
Configuration - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios
This guide covers how to configure the **Xsolla Mobile SDK** for iOS to enable payment processing in your mobile application. The SDK provides multiple integration approaches, from full native implementations to web-based solutions, allowing you to choose the method that best fits your app's requirements and development timeline.
## Basic SDK Configuration
The *Xsolla Mobile SDK* requires configuration with your project credentials from the [**Xsolla Publisher Account ↗**](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/](https://publisher.xsolla.com/)). These settings control how the SDK connects to Xsolla's services and handles payment flows.
### Required Configuration Parameters
- **Project ID**: Your Xsolla project identifier (numeric value)
- **Login Project ID**: Your Xsolla Login project identifier (UUID string)
- **Platform**: Specifies the target platform (typically `.standalone` for mobile apps)
For initial development and testing, you can use the example credentials shown below:
```objectivec
#import <XsollaMobileSDK/StoreKitWrapper.h>
// Initialize SDK settings with your project credentials
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: 301871
loginProjectId:@"dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a"
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
// Enable sandbox mode for testing (disable for production)
settings.useSandbox = YES;
// Enable the SDK functionality (set to NO to completely disable payments)
settings.enablePayments = YES;
// Configure external browser behavior (see compliance section below)
settings.openExternalBrowser = YES; // Set based on your compliance requirements
// Initialize the payment queue with your settings
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
[queue addTransactionObserver: self];
```
```swift
import XsollaMobileSDK
// Initialize SDK settings with your project credentials
let settings = SKPaymentSettings(projectId: 301871,
loginProjectId: "dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a",
platform: .standalone)
// Enable sandbox mode for testing (disable for production)
settings.useSandbox = true
// Enable the SDK functionality (set to false to completely disable payments)
settings.enablePayments = true
// Configure external browser behavior (see compliance section below)
settings.openExternalBrowser = true // Set based on your compliance requirements
// Initialize the payment queue with your settings
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
```
### Regional Compliance Configuration
The `openExternalBrowser` setting controls whether a purchase completes on an **external web payment page** (`true`) or **inside the app** (`false`). Set it to match your target market — a growing number of jurisdictions now require Apple to let developers direct players to external payments:
- **United States** — external purchase links are permitted (*Epic v. Apple*) → `openExternalBrowser = true`
- **Japan** — the **Mobile Software Competition Act (MSCA)** permits external payments and web link-outs → `openExternalBrowser = true`
- **Brazil** — Apple's **CADE** antitrust settlement permits external payments and link-outs → `openExternalBrowser = true`
- **European Union** — under the **Digital Markets Act (DMA)** either works: keep the flow in-app → `openExternalBrowser = false`, or send the player to the web → `openExternalBrowser = true`. Apple charges a different commission for each, and from **October 1, 2026** you have to keep whichever you pick for 12 months, so agree it with your business team first
```objectivec
settings.openExternalBrowser = YES; // External web payment — US, Japan, Brazil
settings.openExternalBrowser = NO; // In-app payment — EU
```
```swift
settings.openExternalBrowser = true // External web payment — US, Japan, Brazil
settings.openExternalBrowser = false // In-app payment — EU
```
note
Platform rules and commissions differ by market and continue to change. Confirm Apple's current requirements for every region you ship to before going live.
For more advanced compliance scenarios, you can programmatically detect the user's region and distribution channel to automatically configure the appropriate settings. Learn how to [**detect iOS storefront**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/) to enable external payments for the regions that permit them, or [**detect alternative app distribution status**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detectstore/) for enabling EU-specific compliance flows based on the app's installation source.
### Essential Configuration Notes
- **Enable Payments**: The SDK must be explicitly enabled by setting `enablePayments` to `true`. This allows you to completely disable payment functionality if needed without removing the SDK integration.
- **Sandbox Mode**: `useSandbox` is `true` by default, so the SDK runs against the sandbox environment unless you change it. Keep it `true` during development and testing to avoid processing real transactions, and be sure to set `useSandbox = false` before going live.
- **Transaction Observer**: Don't forget to add your class as a transaction observer to receive payment completion callbacks.
### Default Payment Method
You can set a default payment method for Xsolla Pay Station. Configure it globally in `settings` (applies to all purchases) or per purchase. The value is the Pay Station payment method identifier (for example, `3175` is Apple Pay).
```objectivec
// Global default (set before starting the SDK)
settings.paymentMethodId = [NSNumber numberWithInt:3175]; // 3175 = Apple Pay
// Per purchase override
SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
payment.paymentMethodId = [NSNumber numberWithInt:3175]; // 3175 = Apple Pay
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
```swift
// Global default (set before starting the SDK)
settings.paymentMethod = 3175 // 3175 = Apple Pay
// Per purchase override
let payment = SKPayment(product: product)
payment.paymentMethod = 3175 // 3175 = Apple Pay
SKPaymentQueue.default().add(payment)
```
note
If both are set, the per-purchase value overrides the global default for that transaction.
### Purchase Restoration Settings
By default, the SDK automatically handles local purchase restoration to ensure users can recover their purchases when reinstalling your app or when the app crashes or goes out of memory during payment processing. However, this behavior should be adjusted based on your backend integration architecture.
Restoration reads the player's Xsolla Inventory unless you turn on the Events API below. For what you get back in each case, and what you don't, see [**Restored purchases**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/#restored-purchases). note
**Coming from Apple StoreKit?** There is no manual "Restore Purchases" call to wire up — `restoreCompletedTransactions()` is a no-op in this SDK. Restoration happens automatically, as described above, through local restoration and, optionally, the Xsolla Events API. Consumable balances are recovered through your own backend or the Xsolla Inventory, so persist them there when the purchase is awarded.
Alternatively, if you prefer a serverless approach without maintaining webhooks, you can enable the **Xsolla Events API** for purchase restoration (see the subsection below) while keeping local purchase restoration enabled.
For webhook-based integrations where your backend receives and processes purchase notifications directly from Xsolla, disable local restoration to prevent conflicts with server-side transaction management:
```objectivec
// Disable local purchase restoration for webhook-based integrations
settings.useLocalPurchaseRestoration = NO;
```
```swift
// Disable local purchase restoration for webhook-based integrations
settings.useLocalPurchaseRestoration = false
```
warning
**When to disable local purchase restoration:**
- Your backend uses webhooks to receive purchase notifications from Xsolla
- You handle transaction lifecycle management on your server
- You want to avoid duplicate purchase processing between local and server-side systems
**Important limitations:**
- Restored purchases cannot be validated through the standard validation flow
- Restored purchases don't carry the identifiers of the original Xsolla order unless restoration runs through the Events API
- Transaction finishing must be handled by your backend when webhooks are used
- If local purchase restoration is disabled, the SDK will not perform restoration via either local restoration or the Events API
- [**Web Shop link-out**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios#web-shop-link-outs) mode skips restoration entirely, whatever these settings say
This setting directly impacts the `finishTransaction(_ transaction: SKPaymentTransaction)` method behavior described in the [**Purchase Flow guide**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/). When local restoration is disabled, your backend becomes responsible for managing the complete transaction lifecycle through webhook notifications. Note that with local restoration disabled, unfinished transactions will not reappear on app relaunch, making proper backend handling essential.
#### Using Xsolla Events API for Restoration
The Xsolla Events API serves as an alternative to webhook-based integrations, where the integrator’s backend usually handles most of the logic (purchase validation, awarding, etc.). Instead of sending webhooks directly, the API intercepts them and stores their payloads in a remote queue managed by Xsolla. This approach enables serverless integrations for projects that lack backend capacity or don't require one, yet still prefer handling the entire transaction flow directly from the app.
Restoring through the Events API also fills in `transactionIdentifier` with the order ID and `invoiceIdentifier` with the invoice ID from the player's original order, so you can match a restored purchase to your own records. Restoring from the inventory leaves both `nil`, because the inventory only lists what the player owns — there's no order behind it.
Opting for the ***Xsolla Events API*** **disables** your project's **webhooks** — you **cannot use both simultaneously**.
To enable it, open your project in *Publisher Account*, go to **Project settings** > **Integration settings**, select **Use API** and click **Save**. See [**Events API in Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api) for details.
##### Enabling Events in the iOS SDK
Enable Events-based purchase restoration in the SDK configuration:
```objectivec
// Enable Events API for purchase restoration
settings.useEventsApiForPurchaseRestoration = YES;
```
```swift
// Enable Events API for purchase restoration
settings.useEventsApiForPurchaseRestoration = true
```
info
For additional information, see the [**webhooks page**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api). note
Events-based restoration requires `settings.useLocalPurchaseRestoration = true`. If you disable local purchase restoration, the SDK will not query or use the Events API for restoration.
### Attribution User ID
If you use an attribution platform (AppsFlyer, Adjust, etc.), set `attributionUserId` so that purchases made through **Pay Station** are reported to it under the same user as the rest of your app's events. The SDK sends this value to **Pay Station** as `custom_parameters.custom_id`, and purchase events forwarded to the attribution platform are keyed on it.
The value must equal the customer user ID your attribution SDK reports; otherwise the purchase events will not match up with that user. If you leave it unset, purchase events are matched on the user ID in the payment token. By default that is the player's **Xsolla Login** user ID.[1](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios#attribution-user-id-fallback)
1 If your project authenticates players through server-side custom ID login or PlayFab, or maps the user ID to a custom JWT claim, the payment token carries that value instead of the Login user ID. Set `attributionUserId` explicitly, or purchase events won't match your attribution platform.
This is separate from `customUserId`, which is sent as `custom_parameters.custom_user_id` and returned to you in purchase webhooks, but is not used for attribution.
```objectivec
// Must match the customer user ID reported by your attribution SDK
settings.attributionUserId = @"your-attribution-user-id";
```
```swift
// Must match the customer user ID reported by your attribution SDK
settings.attributionUserId = "your-attribution-user-id"
```
### Install Source
Set `installSource` to report the channel your app was distributed through, such as your own website or launcher. The SDK sends it with the order as `user.mobile_app.install_source`, and it is sent as is, without trimming.
If you leave it unset, the SDK detects the channel itself, but only on iOS 17.4 and later, where it can tell the App Store, web distribution and an alternative marketplace apart. On earlier iOS versions no install source is sent.
```objectivec
settings.installSource = @"website";
```
```swift
settings.installSource = "website"
```
## Authentication with Xsolla Login
If your app uses Xsolla Login for user authentication, you can provide the login token to the SDK so it works with Xsolla's payment services.
### Setting the Login Token
Configure the login token after initializing your settings but before starting the payment queue:
```objectivec
// After initializing settings, set the Xsolla Login token
settings.customLoginToken = @"your_xsolla_login_token";
// Then start the SDK
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
// After initializing settings, set the Xsolla Login token
settings.customLoginToken = "your_xsolla_login_token"
// Then start the SDK
SKPaymentQueue.default().start(settings)
```
note
The Xsolla Login token should be obtained from your [**Xsolla Login ↗**](https://xsolla.com/login) ([https://xsolla.com/login](https://xsolla.com/login)) integration. Ensure the token is valid and set before starting the payment queue to enable authenticated payment flows.
## Testing in Sandbox Mode
During development, always enable sandbox mode to test your payment integration without processing real transactions or charges. The sandbox environment simulates the complete payment flow while using test data.
### Enabling Sandbox Mode
```objectivec
settings.useSandbox = YES; // Objective-C
settings.useSandbox = true // Swift
```
note
`useSandbox` defaults to `true`, so payments run against the sandbox environment out of the box. Set `useSandbox = false` before going live to process real transactions. tip
For full testing guidance, including test card numbers and payment scenarios, see our [**iOS Testing Guide**](https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/ios/). This covers avoiding real charges, testing different payment methods, and validating your integration.
## Payment Integration Options
The Xsolla Mobile SDK offers multiple payment integration approaches to suit different development needs and timelines.
### Buy Button Solution (Recommended)
The Buy Button Solution provides a complete, native payment experience with minimal integration effort. This approach handles the entire payment flow within your app using Xsolla's optimized UI components.
For more details (including Web Shop link-outs vs Pay Station and platform notes), see [**Buy Button - iOS**](https://developers.xsolla.com/sdk/mobilesdk/buy-button/ios/).
**When to use Buy Button Solution:**
- You want a quick, native payment integration
- You prefer Xsolla to handle payment UI and optimization
- You need support for multiple payment methods out of the box
- You want automatic compliance with regional payment regulations
```objectivec
// Enable Buy Button solution
settings.useBuyButtonSolution = YES;
```
```swift
// Enable Buy Button solution
settings.useBuyButtonSolution = true
```
### Web Shop Link-outs
The Web Shop approach redirects users to your existing Xsolla Web Shop in a browser, then returns them to your app after purchase completion. This method is ideal for gradual migration or when you want to maintain consistency with existing web-based payment flows.
**When to use Web Shop link-outs:**
- You already have an established Xsolla Web Shop
- You want to test Xsolla integration with minimal code changes
- You need to maintain payment consistency across multiple platforms
- You're implementing a phased migration from web to mobile payments
caution
In Web Shop link-out mode, the SDK does not execute its native in-app payment flow. It only opens the Web Shop and immediately cancels any SDK purchase callbacks. This mode is intended for minimal code changes: handle fulfillment and post-payment updates via your Web Shop processes (for example, webhooks or server-side logic), not via SDK purchase callbacks.
#### Configuring Web Shop Integration
Use the helper method to configure the Web Shop redirect flow:
```objectivec
[settings setupBuyButtonWebShopWithUrl:[NSURL URLWithString:@"https://yourwebshop.xsolla.site"]
userId:@"<USER_ID>"
returnUrl:@"yourgame://"
openExternally:YES];
```
```swift
settings.setupBuyButtonWebShop(url: URL(string: "https://yourwebshop.xsolla.site")!,
userId: "<USER_ID>",
returnUrl: "yourgame://",
openExternally: true)
```
**Parameter explanation:**
- `url`: The URL of your Xsolla Web Shop where users complete purchases
- `userId`: A unique identifier for the user in your system, used for purchase attribution and user tracking
- `returnUrl`: The deep link URL scheme that brings users back to your app after purchase completion
- `openExternally`: Whether to open the Web Shop in an external browser (recommended for compliance and better user experience)
#### Initiating Web Shop Purchases
After configuration, initiate purchases by calling the purchase method with your product SKU:
```objectivec
// Attempt to purchase an item via Web Shop
BOOL handledExternally = [[SKPaymentQueue defaultQueue] purchaseWithSKU:@"money.100"];
if (handledExternally) {
// Web Shop opened successfully, update UI to reflect the redirect
NSLog(@"Purchase redirected to Web Shop");
// Optionally show a loading indicator or message to the user
}
```
```swift
// Attempt to purchase an item via Web Shop
let handledExternally: Bool = SKPaymentQueue.default().purchase(withSKU: "money.100")
if handledExternally {
// Web Shop opened successfully, update UI to reflect the redirect
print("Purchase redirected to Web Shop")
// Optionally show a loading indicator or message to the user
}
```
**Backend Integration**
With the Web Shop approach, you don't need to fetch product catalogs through the mobile SDK (though you can for display purposes). Purchase fulfillment should be handled on your backend using the same webhooks and processes you use for standard Web Shop transactions, ensuring consistency across your payment infrastructure.
## Deep Links Configuration
Deep links are essential for completing payment flows when users are redirected to external payment pages and need to return to your app. The SDK provides both automatic and manual deep link handling options. tip
The SDK also supports **Universal Links** (HTTPS), which can be used instead of custom URL schemes (and avoid the “Open in *App Name*?” prompt when returning from an external browser). See [**iOS Universal Links**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-universal-links/).
### Setting Up URL Scheme
Before configuring deep link handling, you must set up a custom URL scheme for your app. This URL scheme enables external sources (like payment pages) to redirect users back to your application.
**To configure your URL scheme:**
- Select your project in the Xcode project navigator
- Select your app target
- Open the **Info** tab
- Scroll down to **URL Types** and click the ➕ button
- Set the **URL Schemes** field to `$(PRODUCT_BUNDLE_IDENTIFIER)`
![URL Scheme Configuration] tip
Using `$(PRODUCT_BUNDLE_IDENTIFIER)` ensures your URL scheme matches your app's bundle identifier, which guarantees uniqueness and prevents conflicts with other apps.
### Automatic Deep Link Handling (Default)
By default, the Xsolla Mobile SDK automatically handles deep links using method swizzling—a technique that intercepts and modifies iOS method calls at runtime. This means the SDK automatically captures incoming URLs and processes them without requiring additional code from you.
**Benefits of automatic handling:**
- Zero additional code required
- Works with most app architectures
- Handles all Xsolla-related URLs automatically
- Maintains compatibility with your existing URL handling
The automatic handling works out of the box once you've configured your URL scheme as described above.
### Manual Deep Link Handling
In some scenarios, you may need to disable automatic handling and implement manual deep link processing. This is typically necessary when:
- Your app has existing custom URL handling logic that conflicts with method swizzling
- You're using a framework (like React Native or Unity) that doesn't work well with method swizzling
- You need more control over how deep links are processed
- You're experiencing issues with automatic handling in your specific setup
- Your app architecture requires explicit URL routing
#### Implementing Manual Handling
**Step 1: Disable Automatic Handling**
Before starting the SDK, disable automatic URL handling:
```objectivec
// Disable automatic deep link handling before starting SDK
settings.swizzleUrlHandling = NO;
// Then start the SDK as usual
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
// Disable automatic deep link handling before starting SDK
settings.swizzleUrlHandling = false
// Then start the SDK as usual
SKPaymentQueue.default().start(settings)
```
**Step 2: Implement Manual URL Handling**
Add URL handling to your `AppDelegate` or `SceneDelegate`. The SDK's `openWithUrl:` method returns a boolean indicating whether it recognized and handled the URL:
```objectivec
// In your AppDelegate.m
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
// First, try to handle the URL with Xsolla SDK
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
if (handledBySDK) {
// URL was recognized and handled by Xsolla SDK
return YES;
}
// Handle other URLs specific to your app
// Add your custom URL handling logic here
return [self handleCustomURL:url];
}
// Alternative: In your SceneDelegate.m (for iOS 13+)
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
for (UIOpenURLContext *context in URLContexts) {
NSURL *url = context.URL;
// Try to handle with Xsolla SDK first
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
if (!handledBySDK) {
// Handle other URLs specific to your app
[self handleCustomURL:url];
}
}
}
```
```swift
// In your AppDelegate.swift
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// First, try to handle the URL with Xsolla SDK
let handledBySDK = SKPaymentQueue.default().open(url: url)
if handledBySDK {
// URL was recognized and handled by Xsolla SDK
return true
}
// Handle other URLs specific to your app
return handleCustomURL(url)
}
// Alternative: In your SceneDelegate.swift (for iOS 13+)
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
let url = urlContext.url
// Try to handle with Xsolla SDK first
let handledBySDK = SKPaymentQueue.default().open(url: url)
if !handledBySDK {
// Handle other URLs specific to your app
handleCustomURL(url)
}
}
}
```
**Return Value Usage**
The `openWithUrl:` method returns `true`/`YES` if the URL was recognized as a Xsolla payment callback and processed by the SDK. This allows you to implement fallback logic for URLs that aren't related to Xsolla payments, ensuring your app can handle all types of deep links appropriately.
**Step 3: Handle Pay Station Screen Orientation (Optional)**
If your app supports a different orientation than you want for the Pay Station screen, you need to implement additional orientation handling. For example, if your game supports only landscape orientation but you want the Pay Station to appear in portrait mode, add the following method to your `AppDelegate`:
```objectivec
// In your AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
// Since the app may not support portrait, we must ensure that for the UIWindow
// that SDK creates it returns correct value for portrait support
UIInterfaceOrientationMask mask = [[SKPaymentQueue defaultQueue] supportedInterfaceOrientationsForWindow:window];
if (mask != 0) {
return mask;
}
// Fall back to default app orientation support
return [application supportedInterfaceOrientationsForWindow:window];
}
```
```swift
// In your AppDelegate.swift
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
// Since the app may not support portrait, we must ensure that for the UIWindow
// that SDK creates it returns correct value for portrait support
let mask = SKPaymentQueue.default().supportedInterfaceOrientationsFor(window: window)
if !mask.isEmpty {
return mask
}
// Fall back to default app orientation support
return application.supportedInterfaceOrientations(for: window)
}
```
This method allows the SDK to specify orientation requirements for its own windows (like the Pay Station screen) while maintaining your app's normal orientation restrictions for other windows. Note that this is automatically handled if automatic deep link handling is enabled. **Choosing the Right Approach**
If you're unsure whether you need manual deep link handling, start with the default automatic handling. It works for most applications and requires no additional code. You can always switch to manual handling later if you encounter specific issues or have requirements that necessitate more control over the URL handling process.
## Next Steps
After configuring the SDK, you're ready to initialize it and start processing payments. Continue to the [**iOS Initialization Guide**](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/ios/) to learn how to set up payment observers and handle transaction events in your application.
Initialization
https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/ios/)
Initialization - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/android
After [configuring](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/), the **Xsolla Mobile SDK** needs to be initialized and connected to Xsolla services. Initialization is a 3-step process:
## Create a billing client
Create a `BillingClient` with your `Config` and a `PurchasesUpdatedListener`, guarding against double initialization:
```java
if (billingClient == null) {
billingClient = BillingClient.newBuilder(this)
.setConfig(config) // Config built in the previous step
.setListener((billingResult, purchases) -> {
// Invoked for every purchase flow outcome — success, cancel, or error.
// Handle consumption or entitlement grant here.
})
.build();
}
```
## Start a connection
Call `startConnection()` — `onBillingSetupFinished()` fires when the SDK is authenticated and ready:
```java
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (billingResult.isSuccess()) {
// Connected — safe to query products and launch purchases.
}
}
@Override
public void onBillingServiceDisconnected() {
// Connection dropped — release the client so it's recreated on next use.
billingClient.endConnection();
billingClient = null;
}
});
```
## Query product details
Inside `onBillingSetupFinished()`, fetch `ProductDetails` for each SKU — required by the [purchasing flow](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/):
```java
// Build the list of SKUs to fetch — add one Product entry per item in your catalog.
final QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // SKU from your Xsolla Catalog
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build();
billingClient.queryProductDetailsAsync(params, (billingResult, productDetailsList) -> {
// Store productDetailsList — it's passed directly to the purchasing flow.
});
```
The SDK loads only Virtual Items from your Xsolla Catalog — Virtual Currency, Bundles, and other catalog types are not returned.
Initialization - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/ios
After [configuring](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/), the **Xsolla Mobile SDK** needs to be initialized and connected to **Xsolla** services.
Initialization is done using settings created in previous step. Put this logic somewhere in your initialization code, perhaps, in AppDelegate's [didFinishLaunchingWithOptions ↗](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) ([https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions):)).
```objectivec
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings]; // settings from the previous step
// conform your class to SKPaymentTransactionObserver and implement its method
@interface YourClass (SKPaymentTransactionObserver) <SKPaymentTransactionObserver>
@end
@implementation YourClass (SKPaymentTransactionObserver)
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStateFailed:
// purchase failed, present an error
break;
case SKPaymentTransactionStatePurchased:
// award the player with the purchased item (SKU: transaction.payment.productIdentifier)
break;
default: break;
}
}
}
@end
```
```swift
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
// conform your class to SKPaymentTransactionObserver and implement its method
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .failed:
// purchase failed, present an error
case .purchased:
// award the player with the purchased item (SKU: transaction.payment.productIdentifier)
default:
break
}
}
}
}
```
After `SKPaymentQueue` is started and observer is added, application can request SKU information:
```objectivec
NSSet *skus = [NSSet setWithArray:@[@"money.100", @"ticket.10"]];
SKProductsRequest* req = [[SKProductsRequest alloc] initWithProductIdentifiers:skus];
req.delegate = self;
[req start];
// conform your class to SKProductsRequestDelegate and implement its method
@interface YourClass (SKProductsRequestDelegate) <SKProductsRequestDelegate>
@end
@implementation YourClass (SKProductsRequestDelegate)
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
// save loaded products somewhere
self.products = response.products
}
@end
```
```swift
let skus: Set<String> = ["money.100", "ticket.10"]
let req = SKProductsRequest(productIdentifiers: skus)
req.delegate = self
req.start()
// conform your class to SKProductsRequestDelegate and implement its method
extension YourClass: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
// save loaded products somewhere
self.products = response.products
}
}
```
The SDK loads only Virtual Items from your Xsolla Catalog — Virtual Currency, Bundles, and other catalog types are not returned.
For more information, see the implementation in Apple's [official documentation ↗](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue) ([https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue)).
Installation
https://developers.xsolla.com/sdk/mobilesdk/sdk/installation
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios/)
Installation - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/android
### Prerequisites
warning
- Android SDK >= **24**
- Java >= **11**
### Installation Steps
- Add the repository to your project's Gradle script (usually `settings.gradle`):
```kotlin
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
}
```
*Coming soon.*
- Add a new dependency for *Xsolla Mobile SDK* to your module's `build.gradle`:
```kotlin
dependencies {
def version_mobilesdk = '<version_code>' // e.g. '3.0.37'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
Installation - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/installation/ios
## iOS Version Requirements
The *Xsolla Mobile SDK* supports iOS 12.0 and later as the minimum deployment target. However, please note that some features that rely on Apple's APIs for External Purchases or Alternative App Distributions may require iOS 17.5 or later.
## Installation via Swift Package Manager
### Using Xcode
- In Xcode, go to **File → Add Package Dependencies…**
- Enter the repository URL: ```text https://github.com/xsolla/xsolla-sdk-ios ```
- Set the dependency rule to **Up to Next Major Version** and specify the version (e.g., `3.8.0`).
- Click **Add Package**.
- In the package products dialog, select **XsollaMobileSDK** and add it to your target.
### Using Package.swift
Add the dependency to your `Package.swift` file:
```swift
dependencies: [
.package(url: "https://github.com/xsolla/xsolla-sdk-ios", from: "3.8.0")
]
```
Then add `XsollaMobileSDK` to your target's dependencies:
```swift
.target(
name: "YourTarget",
dependencies: [
.product(name: "XsollaMobileSDK", package: "xsolla-sdk-ios"),
]
)
```
Purchasing flow
https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/)
Purchase flow - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android
Purchasing flow is a multistage process, which involves [**payment collection**](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android/#purchase-product), purchase [**validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/) and [**consumption**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android#consuming-purchased-goods). Purchases a player already made are recovered separately, through [**restoration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android#restored-purchases).
## Launch a billing flow
You have multiple options on how to start a purchasing flow depending on your needs and goals.
To start a purchasing flow, pass one of the `ProductDetails` [acquired earlier](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/android/) with a `BillingFlowParams` into `launchBillingFlow` method:
```java
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.build()
);
```
**Advanced Settings**
`BillingFlowParams.Builder` supports multiple other properties that can be specified prior to launching a billing flow using `BillingClient.launchBillingFlow()`:
| Setting | Value | Description |
| --- | --- | --- |
| setObfuscatedAccountId | string | Sets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook). |
| setObfuscatedProfileId | string | Sets an obfuscated account ID that can be used upon purchasing flow completion (callback or webhook). |
| setDeveloperPayload | string | Allows passing developer's arbitrary meta-data with the purchasing flow, which can be used upon purchasing flow completion (callback or webhook). |
| setExternalTransactionId | string | Allows setting a custom unique transaction ID that should be associated with the launched purchasing flow (make sure to enable external transaction IDs in your Publisher Account as well or the purchasing flow will fail). |
| setExternalTransactionToken | string | Attaches a Google Play external transaction token (from enableUserChoiceBilling, createBillingProgramReportingDetailsAsync, or createAlternativeBillingOnlyReportingDetailsAsync) to the launched purchasing flow, so it carries through to your order. See Reporting External Transactions to Google Play. |
| setTrackingId | string | A tracking ID intended for Xsolla's internal analytics (consult with your integration manager beforehand). |
| setForcePaymentMethodId | int | Forces a specific payment method to be selected for the launched purchasing flow (IDs can be found in your Publisher Account). |
| setCanceller | BillingFlowCanceller | Attaches a canceller that lets you programmatically cancel the billing flow after it has been launched. |
**Cancelling a billing flow**
Create a `BillingFlowCanceller`, pass it to the params builder, and call `cancel()` when needed (for example, on a timeout or user action). The SDK will stop any in-progress retries and return a `USER_CANCELED` result.
```java
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
```
This approach allows to initiate the billing flow using an externally generated Xsolla Pay Station payment token.
```java
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
final String paymentToken = "<your-externally-generated-payment-token>";
final String developerPayload = null;
mBillingClient.launchBillingFlow(
activity, paymentToken, developerPayload
);
```
**Advanced Settings**
For more control over the token-based billing flow, use the `BillingFlowTokenParams` builder instead:
```java
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowTokenParams
.newBuilder()
.setPaymentToken("<your-externally-generated-payment-token>")
.setDeveloperPayload(null)
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
```
| Setting | Value | Description |
| --- | --- | --- |
| setPaymentToken | string | The externally generated Xsolla Pay Station payment token. |
| setDeveloperPayload | string | Allows passing developer's arbitrary meta-data with the purchasing flow, which can be used upon purchasing flow completion (callback or webhook). |
| setCanceller | BillingFlowCanceller | Attaches a canceller that lets you programmatically cancel the billing flow after it has been launched. |
Two ways to integrate **Buy Button**: redirect users to your [**Web Shop**](https://developers.xsolla.com/sdk/mobilesdk/buy-button/android/?purchase-method=webshop-linkouts), or use the native in-app [**Buy Button Solution**](https://developers.xsolla.com/sdk/mobilesdk/buy-button/android/?purchase-method=buy-button).important
Following the **Epic v. Google** ruling effective **October 29, 2025**, U.S. **Google Play** apps can use the Xsolla SDK purchasing flow directly, but must first detect the **storefront country code** using the guide provided [**here**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/detect-gpb-storefront-android/).
## Validate the purchase (recommended)
For instructions on how to validate your purchases, see [**Purchase validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/).warning
Although validation is **NOT** a mandatory step, it's highly recommended to minimize the chance of fraud and any other malevolent intents.
## Consume purchased goods
The final step in the purchasing flow is to award the purchased goods to the user and mark them as processed. This is known as **purchase consumption**. Once consumed, the item is no longer listed as a pending purchase and — depending on your product configuration — the user may purchase it again.
How consumption is handled depends on whether your integration processes purchases **on the client** or **on your backend via webhooks**.
### Client-based (no webhooks)
In a client-based integration, the game client is responsible for awarding goods to the user and notifying Xsolla that the purchase has been processed. This is done inside the `PurchasesUpdatedListener.onPurchasesUpdated()` callback after a successful purchase (and, ideally, after [**validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/)):
```java
final Purchase purchase = // ...
final ConsumeParams consumeParams = ConsumeParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
// Notify Xsolla that the purchase has been processed and mark it as consumed.
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(
@NonNull final BillingResult billingResult, final String purchaseToken
) {
if (billingResult.isSuccess()) {
// Consumption succeeded — award the purchased goods to the user here.
} else {
// Consumption failed — do not grant entitlement.
}
}
});
```
important
It's highly recommended to perform at least some form of [**validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/) before consuming the purchased goods.
### Server-based (webhooks)
In a server-based integration, your backend handles the full purchase lifecycle — validation, awarding, and consumption — triggered by a webhook from Xsolla. The `PurchasesUpdatedListener.onPurchasesUpdated()` callback is still invoked on the client when a purchase completes, but it carries no authority in this flow and should not be used to drive any purchase logic.
**The simplest approach** is to ignore the callback entirely and let your backend confirm the outcome.
**A more complete approach** is to use it purely for UI purposes — for example, showing a pending state for the purchased product and clearing it once your server confirms the result:
```java
final PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull final BillingResult billingResult, @Nullable final List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
// The purchase was initiated successfully.
// Your backend will handle validation, consumption, and entitlement via webhook.
// Optionally, show a pending/processing state in the UI here and
// update it once your server relays the confirmed result back to the client.
} else {
// The purchase did not complete (e.g. user cancelled or a connection error occurred).
// No action required — your backend will not receive a webhook for this purchase.
}
}
};
```
info
For details on how the webhook-based flow works end-to-end, including consumption handled on the backend, see [**Purchase validation — Server-side**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/#server-side-validation).
## Restore existing purchases
Restoration hands you purchases a player already made — after a reinstall, on a new device, or when the client never confirmed the original transaction. `BillingClient.queryPurchases()` is a manual call; the SDK never invokes it for you.
Restored purchases come from one of two backends — Inventory API, the default, or Events API. See [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#purchase-restoration-settings) for how a project selects one, and [**Inventory API vs. Events API**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api/) for what each does under the hood.
Restoration is most useful for confirming ownership of **non-consumable** products whose SKUs the app knows upfront. Where your own server is the authority on purchase state, it is generally not needed for consumables.
### What a restored purchase contains
| Accessor | Inventory API | Events API |
| --- | --- | --- |
| getOrigin() | INVENTORY_RESTORE | EVENTS_RESTORE |
| isRestored() | true | true |
| getPurchaseTime() | Always 0 | Time of the original payment |
| getOrderId() — the invoice ID | Synthesized locally, stable across queries | Real invoice ID from the original order |
| getOriginalOrderId() — the order (cart) ID | The same synthesized value as getOrderId() | Real order ID from the original order |
| getQuantity() | 1 by default — a holding is split into one Purchase per unit; the full quantity when collapsed | Quantity from the original order |
| isFree() | Always false — the inventory doesn't distinguish paid items from free ones | true if the order carried no invoice |
Despite the names, `getOrderId()` returns the Xsolla **invoice** ID and `getOriginalOrderId()` returns the Xsolla **order** (cart) ID — the `Purchase` class mirrors Google Play Billing Library's naming, where `getOrderId()` is the post-payment identifier. If you're matching a purchase against your own order records, that's `getOriginalOrderId()`.
`getPurchaseState()` always reports `PURCHASED` and `isAcknowledged()` is always `false` — acknowledgement isn't supported by either backend, so there's no acknowledge step to implement. Neither field indicates a restore; use `getOrigin()` or `isRestored()` for that.warning
**Under Inventory API, `getOrderId()` and `getOriginalOrderId()` are not real order identifiers — never send them to your backend as one.**
They're derived locally from the SKU and the unit's position in the holding, and the same made-up value is written into both fields, which is why they're equal in this mode. No Xsolla system — Publisher Account, order lookup, webhook payload, anything — will recognize them. Treating one as a real order reference — to match an order, check for fraud, look up a refund, or help a player through support — will silently match nothing.
The values are stable across repeated `queryPurchasesAsync()` calls for the same held units, and consuming part of a holding leaves the remaining units' values unchanged — as of [**Android SDK 3.0.55 ↗**](https://github.com/xsolla/xsolla-sdk-android/releases/tag/3.0.55). Before that release, they were drawn at random on every query.
This is the mode a project restores from by default — see [**Selecting a mode**](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/inventory-vs-events-api/#selecting-a-mode).
**iOS behaves differently here** — the equivalent identifiers are left empty rather than synthesized, since the iOS SDK models StoreKit (where the identifier is optional) while Android models Play Billing Library (where it's populated once a purchase reaches `PURCHASED`). Neither platform is going to converge on the other's behavior.
### What restores, by product type
Inventory API restoration reads the player's item inventory, which only ever reports virtual goods and virtual currency. A product type with no inventory representation comes back empty:
| ProductType | Restored under Inventory API |
| --- | --- |
| INAPP | ✔ Virtual goods the player holds — except time-limited items, which are filtered out |
| VIRTUAL_CURRENCY | ✔ One Purchase per currency, from a balance endpoint |
| BUNDLE | ✘ Nothing — including virtual currency packages, which the catalog classifies as bundles |
| SUBS, PLAY_PASS_SUBS | ✘ Nothing — unsupported product types |
warning
**A `BUNDLE` query restores nothing under Inventory API, and virtual currency packages are bundles** — the catalog classifies them as such, not as currency.
The currency a package granted is still recoverable: it lands in the player's balance, so a `VIRTUAL_CURRENCY` query returns it. What can't be recovered is the **package purchase itself**. Under Events API it can be — but it arrives as the bundle's **content items**, never as the bundle SKU, so match against the contents rather than the SKU the player paid for.
A `VIRTUAL_CURRENCY` query returns `getQuantity()` set to the player's cumulative balance rather than a list of transactions. Because a balance is a single figure, it always collapses into one `Purchase` per currency regardless of [`withCollapseRestoredMultiUnitPurchases`](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#units-per-restored-purchase). Zero and negative balances are omitted, and a balance above `Integer.MAX_VALUE` is clamped to it.
Product type is an Inventory API filter only. Under Events API a restore query returns **every unconsumed event** whatever type you pass, so expect virtual currency and bundle contents alongside in-app products.
### Consuming a restored purchase
A restored purchase is consumed exactly like a fresh one — take its `getPurchaseToken()` and pass it to `consumeAsync()`, as in [**Consume purchased goods**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android#consuming-purchased-goods). The token identifies the purchase in both modes; there's nothing mode-specific to handle.
A bundle's content items are consumed individually. The SDK tracks partial consumption locally and settles the underlying order once every item has been consumed.
### Practices worth adopting
How many of these you need depends on how much of the purchase lifecycle you own:
| Practice | If ignored | When you need it |
| --- | --- | --- |
| Check your own records before you grant. Restoration hands you purchases the player may already have been given, so a purchase you've handled must not be granted again. | Critical — players awarded the same purchase twice | Always, including client-only integrations |
| Treat getPurchaseTime() == 0 as unknown, not as an instant. Every Inventory API restore reports 0, so sorting a mixed list by time buckets them all at the epoch. | Low — purchase history sorts wrongly | If you sort or display purchase history |
| Check getOrigin() rather than guessing from a field's value. isRestored() tells you the purchase is an old one coming back; getOrigin() also tells you which backend it came from, and the two give you different things. | Medium — old purchases trigger first-purchase UI and rewards | If restored purchases take a different path from fresh ones, such as suppressing a "purchase complete" popup |
| Only match purchases by order ID where the ID means something. Events API IDs are real and stable, so they work anywhere. Inventory API IDs are stable but local to the device, so they match nothing on your server or on another device. | High — the check on your server silently stops working | If your server checks for purchases it has already handled, or you check across devices |
| Compare against your own record of what you've granted before switching backends. Once Events API is enabled for the project, events are recorded whether or not the SDK reads them — so switching to it hands you a history the client has never seen. | Critical — that backlog arrives at once, granting purchases twice or dropping them | Only when migrating a live project — see Migrating a live project |
Purchase flow - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios
Purchasing flow is a multistage process, which involves [payment collection](https://developers.xsolla.com/sdk/mobilesdk/quick-start/ios/#purchase-product), purchase [validation](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios#validating-purchases-recommended) and [consumption](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios#consuming-purchased-goods). Purchases the player already made are recovered separately, through [restoration](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios#restored-purchases).
### Starting purchasing flow
We can use previously acquired `SKProduct` info to create payment and initiate purchase:
```objectivec
SKProduct *product = ...; // previously fetched product
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
```swift
let product = ... // previously fetched product
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
```
### Validating purchases (recommended)
warning
Although validation is **NOT** a mandatory step, yet it's highly recommended to minimize the chance of fraud and any other malevolent intents.
For instructions on how to validate your purchases, see [**Purchase validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/ios/).
### Consuming purchased goods
The very final step in the chain of purchasing flow stages is to award the purchased goods to the user and mark these goods as "awarded". The process also known as **purchase consumption**.
Use the code below to do just that:
Purchase result will become known in `paymentQueue:updatedTransactions:` method:
```objectivec
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStateFailed:
// Check if the user cancelled the purchase (don't treat as an error)
if (transaction.error.code == SKErrorPaymentCancelled) {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
}
// Always acknowledge transaction and finish it
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStatePurchased:
// here you can save the purchase and award it to the user
// Always acknowledge transaction and finish it after it was saved
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
default: break;
}
}
}
```
Purchase result will become known in `paymentQueue(_:updatedTransactions:)` method:
```swift
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .failed:
// Check if the user cancelled the purchase (don't treat as an error)
if (transaction.error as? SKXError)?.errorCode == .paymentCancelled {
SKPaymentQueue.default().finishTransaction(transaction)
break
}
// Always acknowledge transaction and finish it
SKPaymentQueue.default().finishTransaction(transaction)
case .purchased:
// here you can save the purchase and award it to the user
// Always acknowledge transaction and finish it after it was saved
SKPaymentQueue.default().finishTransaction(transaction)
default:
break
}
}
}
```
important
It's highly recommended to perform at least some form of [**validation**](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios#validating-purchases-recommended) before consuming the purchased goods. note
Always call `finishTransaction(_:)` after you've awarded the purchased goods. If local purchase restoration is enabled (the default), an unfinished transaction is re-delivered to `paymentQueue(_:updatedTransactions:)` on the next launch until it is finished — see [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings).
### Restored purchases
Restoration hands you purchases the player already made, after a reinstall, on a new device, or when the app was closed before the purchase finished. It runs on its own, and there's no call to make. Where it reads them from is set in [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings) — the player's Xsolla Inventory by default, or the Xsolla Events API.
In a [**webhook-based integration**](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/ios/#server-side-validation) neither is used: Xsolla sends the purchase to your backend, and your backend decides what a returning player gets. Turn restoration off in the app with `settings.useLocalPurchaseRestoration = false` and use the transaction callbacks only to update your UI, as you would during server-side validation.
Restored purchases arrive in `paymentQueue(_:updatedTransactions:)` as `.purchased`, not `.restored`, and you finish them the same way as a new purchase. To tell the two apart, check `original`: it's set on a restored purchase and `nil` on one the player just made.
What a restored transaction carries depends on the backend:
| Property | Xsolla Inventory (default) | Events API |
| --- | --- | --- |
| transactionIdentifier | nil | Xsolla order ID |
| invoiceIdentifier | nil | Xsolla invoice ID |
| transactionDate | When restoration delivered it | When restoration delivered it |
| original.transactionDate | nil | When the player paid |
| payment.quantity | Units the player holds | Quantity from the original order |
As in StoreKit, `transactionDate` on a restored purchase is when the SDK handed it to you, and `original.transactionDate` is when the player paid. The Xsolla Inventory keeps no record of past purchases, so a restore from it gives you no date and no order IDs — only the fact that the player owns the item.
A player who reinstalls gets back everything they still own, so check your own records before you award a restored purchase. Otherwise a player can be given the same item twice.
Restoring from the Xsolla Inventory returns **consumable Virtual Items only**. Non-consumable items, virtual currency balances and bundles don't come back this way — get those from your own records or from the Xsolla Inventory.
Restoration is skipped while any purchase is still unfinished, and it doesn't tell you it was skipped. Finish every transaction you receive, or later restores quietly do nothing.
Testing & Sandbox
https://developers.xsolla.com/sdk/mobilesdk/sdk/testing
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/ios/)
Testing & Sandbox - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/android
This section provides various snippets and examples of how to configure the sandbox environment to be able to make test payments, make logging more verbose, and so on.
### Enabling sandbox mode
```java
final var configCommon = Config.Common.getDefault()
// ...other settings
.withSandboxEnabled(true);
```
### Enabling additional logging
```java
final var configCommon = Config.Common.getDefault()
// ...other settings
.withLogLevel(LogLevel.DEBUG)
// Forces even more internal data to be logged (e.g. profiling stats, etc).
.withDebugEnabled(true);
```
Before going live, turn **sandbox mode** and **debug logging** OFF.
### Test cards
For a list of cards to simulate payments in sandbox mode, see [here ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)). important
The test cards won't work outside the **sandbox mode**.
Testing & Sandbox - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/testing/ios
This section provides various snippets and examples of how to configure the sandbox environment to be able to make test payments, make logging more verbose, and so on.
### Enabling sandbox mode
```objectivec
SKPaymentSettings* settings = ...;
settings.useSandbox = YES;
```
```swift
let settings = SKPaymentSettings(...)
settings.useSandbox = true
```
note
`useSandbox` is `true` by default, so the SDK runs in sandbox mode until you set it otherwise. warning
Remember to turn the **sandbox** mode **OFF** (`useSandbox = false`) before going **LIVE**.
### Enabling additional logging
```objectivec
SKPaymentSettings* settings = ...;
settings.logLevel = SKLogLevelDebug;
```
```swift
let settings = SKPaymentSettings(...)
settings.logLevel = .debug
```
warning
Make sure the debug **logging** is **OFF** before going **LIVE**.
### Test cards
For a list of cards to simulate payments in sandbox mode, see [here ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)). important
The test cards won't work outside the **sandbox mode**.
Troubleshooting
https://developers.xsolla.com/sdk/mobilesdk/sdk/troubleshooting
Choose your platform:
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/troubleshooting/ios/)
Troubleshooting - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/troubleshooting/ios
Common integration issues, their causes, and how to resolve them. If you're coming from Apple StoreKit, a few behaviors differ — those are called out below.
### Products don't appear or the catalog is empty
`SKProductsRequest` returns no products (or fewer than expected), usually without an error. This is almost always a configuration mismatch on the Xsolla side rather than a code issue. Check, in order:
- **Wrong `projectId`.** An incorrect `projectId` still connects successfully and simply returns an empty catalog — no error is thrown. Verify it against your Publisher Account.
- **Items not published.** Every item must be **published / active** in Publisher Account. Draft items are not returned.
- **SKU mismatch.** The SKUs you request must match the Publisher Account SKUs **exactly**, including case and separators (for example, dots vs. underscores).
### Purchases don't restore, or there's no "Restore" button to wire up
Restoration in this SDK is **automatic**, and there is no manual restore call to invoke — `restoreCompletedTransactions()` is a no-op. See [**Purchase Restoration Settings**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings) for how local restoration and the Xsolla Events API work. Consumable balances are recovered through your own backend or the Xsolla Inventory.
### "Application doesn't support login scheme" / "...payments redirect scheme"
The SDK routes login and Pay Station redirects back to your app through a URL scheme, and logs one of these errors if the scheme isn't registered. The SDK cannot modify your `Info.plist` — register the scheme once:
- Add a URL scheme equal to your bundle identifier (`$(PRODUCT_BUNDLE_IDENTIFIER)`). See [**URL scheme setup**](https://developers.xsolla.com/sdk/mobilesdk/quick-start/ios/). The single bundle-id scheme covers **both** login and payments.
- The redirect URLs (`redirectUrl`, `paymentsRedirectUrl`) already default to bundle-id-based values, so you don't normally need to set them.
note
**Device ID login needs no return URL.** Device-ID (anonymous) login is a client-side identifier exchange — there is no browser redirect and nothing to register in Publisher Account for it. Just enable **Device ID login** for your project. A redirect URL only becomes relevant for browser-based login flows.
### "User is not logged in" when starting a purchase
The SDK requires an authenticated session before it can create an order, and a purchase attempted before authentication fails with `User is not logged in`. Make sure authentication completes at startup, before the first purchase:
- If your game authenticates with device-ID login, confirm **Device ID login** is enabled for your project.
- If your game supplies its own Xsolla Login token, confirm `settings.customLoginToken` is set to a valid, non-expired token **before** you start the payment queue — see [**Setting the Login Token**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#setting-the-login-token).
### Main Thread Checker warning when starting a purchase
`SKPaymentQueue.default().add(_:)` drives UIKit presentation and should be called on the main thread. If you start a purchase from an async `Task` or a background queue, the Main Thread Checker may flag it. Dispatch to the main thread:
```objectivec
dispatch_async(dispatch_get_main_queue(), ^{
[[SKPaymentQueue defaultQueue] addPayment:payment];
});
```
```swift
await MainActor.run {
SKPaymentQueue.default().add(payment)
}
```
### Hosts the SDK connects to (firewall / allowlisting)
If your network tooling or firewall restricts outbound traffic, allowlist the Xsolla hosts the SDK uses:
| Purpose | Host |
| --- | --- |
| Store API (catalog, orders, inventory) | store.xsolla.com |
| Pay Station (checkout) | secure.xsolla.com — or sandbox-secure.xsolla.com when useSandbox = true |
| Login | login.xsolla.com |
### Harmless console warnings
Console output such as `Couldn't read values in CFPrefsPlistSource... kCFPreferencesAnyUser...` is harmless and can be safely ignored — it does not affect payments or SDK behavior.
Purchase validation
https://developers.xsolla.com/sdk/mobilesdk/sdk/validation
Choose your platform:
- [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android/)
- [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/ios/)
Purchase validation - Android
https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/android
Each purchase should be validated before awarding it to the end-user. This assists in preventing unauthorized purchases and ensures the integrity of your in-app economy. Validating purchases is a critical security measure to prevent fraud, protect your revenue, and ensure fair user experiences.
Essentially, that are two distinct validation approaches readily available.
### Server-side Validation
The most secure and reliable way to validate purchases is by using **server-to-server** (**S2S**) communication, with the client completely removed from the validation process. This minimizes security risks and ensures that entitlements are only granted based on verified data received directly from Xsolla.
With Xsolla, server-side validation is implemented through a **webhook-based model**:
- Once a user completes a purchase through your app, Xsolla services automatically trigger a [**webhook event**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#user_validation) to your backend.
- This webhook contains all the necessary purchase data, including the *Xsolla* `order ID`, enabling your server to validate and process the purchase asynchronously.
- Your backend can then use this data to update the user’s entitlements, balance, inventory, etc., without requiring any additional input from the client.
This flow ensures that the client has no role in deciding the outcome of a purchase — all validation logic lives on the server, using trusted data that originates from Xsolla itself. tip
For more information about how webhooks work, see our [**Webhooks**](https://developers.xsolla.com/sdk/publisher-account/webhooks/) guide. How does this compare to Google Play Billing?
This table provides a quick-glance comparison between **Xsolla’s webhook-based server-side validation** approach and **Google Play Billing’s API-driven validation**. While both are designed to assure the legitimacy of purchases, they operate through fundamentally different infrastructures and workflows. Notably, **Xsolla does not use or abstract Google Play Developer APIs**; instead, it provides an independent validation mechanism through webhooks.
| Feature/Aspect | Xsolla Mobile SDK | Google Play Billing |
| --- | --- | --- |
| Validation Flow | Webhook-driven: Xsolla services send a notification to your backend when a purchase completes. Your backend then validates and processes the order. | API-driven: Your backend polls or queries the Google Play Developer API using a purchaseToken received from the client to verify purchase authenticity. |
| Primary Identifier | Xsolla order ID | Google Play purchaseToken |
| Verification Authority | Xsolla's backend infrastructure and your own server logic | Google Play Developer API (purchases.products:get, purchases.subscriptionsv2:get, etc.) |
| Backend Integration Pattern | Reactive: Webhook-based model automatically pushes purchase data to your backend. | Polling or request-based: Your server must pull data from Google's APIs after receiving a purchaseToken from the client. |
| Asynchronous Handling | ✅ Yes. Webhooks trigger upon purchase completion, enabling early or background processing. | ⚠️ Possible, but typically requires polling or client-to-server relay before querying Google. |
| Security Handling | Simplified. Xsolla ensures validation before triggering webhook to your backend. You validate order ID and fulfill the order accordingly. | Complex. Your backend must securely handle API tokens, verify signatures, and respond to purchase states appropriately. |
| Integration Complexity | Lower — No need to manage credential scopes or external billing endpoints. Xsolla manages purchase flow and signals your backend. | Higher — Requires OAuth, service account setup, token lifecycle management, and detailed error handling. |
### Client-side Validation
Provides means of validating a purchase on the user's device without a need for a backend (server). While it's better than nothing, it has inherent drawbacks: anything that runs on the client can potentially be exploited. This approach offers a rudimentary level of validation but is generally **not recommended for critical applications** due to its inherent security vulnerabilities.
When [initializing](https://developers.xsolla.com/sdk/mobilesdk/sdk/initialization/android/) a `BillingClient`, extend the `onPurchasesUpdated` callback of `PurchasesUpdatedListener` with the code below to enable a rudimentary (non-secure) purchase validation on the client:
```java
final PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull final BillingResult billingResult, @Nullable final List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
// Validate and consume purchases one by one.
for (int i = 0; i < purchases.size(); ++i) {
final ValidateParams validateParams = ValidateParams.newBuilder()
.setPurchaseToken(purchases.get(i).getPurchaseToken())
.build();
// This `validateAsync` method is part of the Xsolla Mobile SDK.
// It performs a client-side network call to Xsolla's services for validation.
// For developers coming from GPB, this serves a similar *purpose* to how you
// might send a `purchaseToken` from the client to your *own* backend for validation,
// but here, Xsolla's services act as that immediate validation point.
mBillingClient.validateAsync(validateParams, new ValidateResponseListener() {
@Override
public void onValidateResponse(
@NonNull final BillingResult billingResult, @Nullable final String purchaseToken
) {
// Make sure validation of the purchase was a success..
if (billingResult.isSuccess() && !TextUtils.isEmpty(purchaseToken)) {
// Prepare consumption parameters based on the purchase
// token received with the validation response.
final ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchaseToken)
.build();
// Notify Xsolla that the purchase has been processed and mark it as consumed.
mBillingClient.consumeAsync(consumeParams,
// TODO: Handle consumption success/failure.
// After successful consumption, grant entitlement to the user.
);
} else {
// Purchase validation has failed on the client-side.
// Handle error, do not grant entitlement.
}
}
});
}
} else {
// An error occurred, while trying to update the purchases.
// This could be due to BillingClient connection issues or a user cancellation.
// Handle error appropriately, do not grant entitlement.
}
}
}
```
How does this compare to Google Play Billing?
The Xsolla Mobile SDK follows a structure similar to Google Play Billing, which helps streamline development and simplifies adoption for those familiar with GPB. The table below outlines how common validation and fulfillment flows compare between the two:
| Feature | Xsolla Mobile SDK | Google Play Billing |
| --- | --- | --- |
| Validation | validateAsync(...) – sends purchaseToken to Xsolla services for basic validation | No built-in validation; purchaseToken must be sent manually to your backend |
| Consumption & Entitlement | consumeAsync(...) – called after validation to mark the purchase and unlock content | consumeAsync(...) – called after custom backend validation to complete the flow |
## Conclusion and Recommendations
The Xsolla Mobile SDK supports both **client-side** and **server-side** purchase validation flows to accommodate a wide range of application needs and developer workflows. Each approach comes with trade-offs in terms of security, complexity, and integration effort.
For production environments, especially where real monetary value or access to premium content is involved, **server-side validation is the strongly recommended method**. It ensures that all entitlements are granted based on verified purchase data received directly through **Xsolla's secure webhook system**, with no reliance on data provided by the client. This significantly reduces the risk of fraud or tampering.
Client-side validation, while faster to implement and sufficient for low-risk use cases, should be treated as a lightweight solution. It involves making validation requests from the device directly to Xsolla's services and can be bypassed if used in isolation. This method may be appropriate for prototypes or apps offering non-critical, low-value items. info
The *Xsolla Mobile SDK* provides flexible validation options to help developers start quickly and scale securely. For best results, adopt the **server-side webhook-based validation** as your primary mechanism for managing purchase authenticity and entitlement fulfillment.
Purchase validation - iOS
https://developers.xsolla.com/sdk/mobilesdk/sdk/validation/ios
Each purchase should be validated before awarding it to the end-user. This assists in preventing unauthorized purchases and ensures the integrity of your in-app economy. Validating purchases is a critical security measure to prevent fraud, protect your revenue, and ensure fair user experiences.
Essentially, that are two distinct validation approaches readily available.
### Server-side Validation
The most secure and reliable way to validate purchases is by using **server-to-server** (**S2S**) communication, with the client completely removed from the validation process. This minimizes security risks and ensures that entitlements are only granted based on verified data received directly from Xsolla.
With Xsolla, server-side validation is implemented through a **webhook-based model**:
- Once a user completes a purchase through your app, Xsolla services automatically trigger a [**webhook event**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#user_validation) to your backend.
- This webhook contains all the necessary purchase data, including the **Xsolla** `order ID`, enabling your server to validate and process the purchase asynchronously.
- Your backend can then use this data to update the user's entitlements, balance, inventory, etc., without requiring any additional input from the client.
This flow ensures that the client has no role in deciding the outcome of a purchase — all validation logic lives on the server, using trusted data that originates from Xsolla itself. tip
For more information about how webhooks work, see our [**Webhooks**](https://developers.xsolla.com/sdk/publisher-account/webhooks/) guide. Transaction callbacks are UI-only in this flow
Even with server-side validation, the SDK still delivers its usual client callbacks — `paymentQueue(_:updatedTransactions:)`, and the `validateTransaction(_:)` result if you call it. In a server-side (webhook) flow these are for **UI/UX only**: show a spinner, a confirmation screen, or refresh the storefront. They do **not** grant the reward and must not be used to do so — the entitlement is already awarded by your backend from the trusted webhook, independently of the device. Treat the client callback as a display signal, not the source of truth.
### Client-side Validation
Provides means of validating a purchase on the user's device without a need for a backend (server). It's better than nothing, but has its own drawbacks, i.e. anything that runs on the client can potentially be exploited.
Before finishing transaction, it can be validated on client side. Unfinished transactions restored after app was closed can't be validated.
```objectivec
SKPaymentTransaction* transaction = ...;
[[SKPaymentQueue defaultQueue] validateTransaction:transaction completion:^(BOOL isValid, NSError * _Nullable error) {
// isValid will be YES for valid transactions
}];
```
```swift
let transaction: SKPaymentTransaction = ...
SKPaymentQueue.default().validateTransaction(transaction) { isValid, error in
// isValid will be true for valid transactions
}
```
## Comparison with Native StoreKit Validation
While Xsolla provides streamlined validation approaches, it's helpful to understand how they compare to Apple's native StoreKit validation [methods ↗](https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique) ([https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique](https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique)).
### Server-side Validation Differences
| Aspect | Xsolla Webhook-based | Apple's verifyReceipt API |
| --- | --- | --- |
| Implementation | Webhook automatically triggered by Xsolla | Manual server-to-server calls to Apple's endpoint |
| Security | High - No client involvement | High - Direct validation with Apple |
| Setup Complexity | Low - Configure webhook endpoint | Medium - Implement receipt parsing and API calls |
| Data Format | JSON webhook payload | Base64-encoded receipt → JSON response |
| Timing | Asynchronous, real-time notifications | Synchronous, on-demand validation |
| Transaction History | Individual purchase events | Complete receipt with all transactions |
| Network Requirements | Webhook endpoint accessible to Xsolla | Secure HTTPS to Apple's servers |
With **Xsolla's webhook-based approach**, purchase validation happens automatically when Xsolla pushes verified purchase data to your backend endpoint, eliminating the need to handle receipt extraction, parsing, or validation requests.
With **Apple's native approach**, your app must extract receipt data from the app bundle and your server must make validation requests to Apple's endpoints (`https://buy.itunes.apple.com/verifyReceipt` for production or `https://sandbox.itunes.apple.com/verifyReceipt` for sandbox), then parse the JSON response.
### Client-side Validation Differences
| Aspect | Xsolla Mobile SDK | Apple's Native Local Validation |
| --- | --- | --- |
| Implementation | Simple SDK method call | Complex PKCS #7 container decoding |
| Code Complexity | Low - Single function call | High - ASN.1 parsing, cryptographic validation |
| Validation Steps | Handled internally by SDK | Manual verification of certificate chain, bundle ID, version, device hash |
| Dependencies | Xsolla Mobile SDK | Security frameworks |
| Maintenance | Managed by Xsolla | Developer maintains cryptographic code |
| Security Level | Medium - Client-side limitations apply | Medium - Client-side limitations apply |
**Xsolla's client-side validation** provides a simplified interface:
```swift
SKPaymentQueue.default().validateTransaction(transaction) { isValid, error in
// Simple validation result
}
```
**Apple's native local validation** requires extensive implementation including decoding receipts as PKCS #7 containers using ASN.1 notation, verifying certificate chains and signature validity, computing SHA-1 hashes for device identification, and validating multiple receipt fields (bundle ID, version, device hash).
Offerwall SDK
https://developers.xsolla.com/sdk/offerwall
Coming SoonSDK binaries · API reference · Integration guides
The **Xsolla Offerwall SDK** will let you surface an offerwall directly inside your game — presenting advertiser tasks, granting virtual rewards, and tracking completions natively, without leaving the app.7xhigher retention by Day 3010–14xmore likely to convert to paying120%LTV increase among daily users90%revenue share for developers
**Interested?** SDK binaries, API reference, and integration guides are in development — reach out to your Account Manager for details.
## Monetize Your Entire Player Base
Most games monetize only 2–5% of their player base through in-app purchases. **Xsolla Offerwall** is an interactive advertising platform that turns the remaining 95% into a revenue source — without asking them to spend money. Players earn virtual rewards (in-game currencies, items, and other content) by completing tasks from advertisers, creating a value exchange where everyone benefits.
Offerwall users show 7x higher retention by Day 30 and are 10–14x more likely to convert into paying users. Games that integrate offerwalls see up to 120% LTV increase among daily offerwall users — making it both a monetization tool and a retention driver. **Industry-Leading Revenue Share**
Xsolla offers developers up to 90% revenue share — far exceeding the typical industry average of 30–60%.**Fraud Prevention**
SMS-based user verification improves traffic quality and prevents fraudulent completions, protecting your revenue.**Xsolla Points**
A cross-game rewards currency that gives players lasting value beyond a single title, encouraging long-term engagement.**Global Reach**
Quests and rewards designed for a global audience, with advertiser demand spanning multiple regions and verticals.
## Rewarded Engagement Models
The **Xsolla Offerwall** supports multiple task types to maximize engagement and fill rates: **Cost Per Install (CPI)**
Players earn rewards by installing and opening a promoted app — high-value actions that drive installs for advertisers.**Cost Per Engagement (CPE)**
Rewards for completing in-app milestones such as reaching a game level, finishing a tutorial, or achieving a goal.**Cost Per Acquisition (CPA)**
Players complete sign-ups, subscriptions, or purchases — the highest-value conversion events for advertisers.**Cost Per Click (CPC)**
Lightweight tasks where players engage with content, watch videos, or interact with promotional material.
**Xsolla Offerwall** is also available as a no-code addition to your [**Xsolla Web Shop** ↗](https://xsolla.com/mobile-web-shop) [(xsolla.com)](https://xsolla.com/mobile-web-shop) — activate it from **Publisher Account** and it appears as a native section in your storefront. For more information, visit [**Offerwall** ↗](https://xsolla.com/offerwall) [(xsolla.com)](https://xsolla.com/offerwall).
Publisher Account
https://developers.xsolla.com/sdk/publisher-account
**Publisher Account** is the central control panel for your Xsolla integration — where you create your project, set up authentication, manage your product catalog, and configure webhooks.
## Create Your Project
[Recommended
I already have an app on the App Store or Google Play
Import your app's store listing automatically. Xsolla pre-populates your Web Shop with game data — imagery, title, and branding — and you get a Project ID in minutes.Set up from existing store page →](https://developers.xsolla.com/sdk/publisher-account/new-project/setup-fasttrack/)[I'm starting fresh
Create a new project, configure Xsolla Login, and get your Project ID and Login ID for SDK integration.Set up manually →](https://developers.xsolla.com/sdk/publisher-account/new-project/setup-manual/) **Authentication**
Configure Xsolla Login with Device ID for seamless auth, or server-side login for full backend control.**Product Catalog**
Create and manage Virtual Items (SKUs) with multi-currency pricing, or import directly from Google Play or App Store.**Webhooks & Events**
Configure payment webhooks for backend transaction handling, or use the Xsolla Events API for serverless purchase validation.**Go Live**
Sign the licensing agreement and switch out of sandbox mode to enable real payments.
Finding Your Project IDs
https://developers.xsolla.com/sdk/publisher-account/getids
Locate your **Project ID** and **Login ID** in the **Publisher Account** — you'll need both to initialize the SDK.
## Project ID
Your **Project ID** is displayed in the **Publisher Account** next to your project name. ![Project ID location in Publisher Account]
## Login ID
To find your **Login ID**, navigate to **Login** > **Dashboard** in the **Publisher Account** and copy the ID displayed next to your Login project name. ![Login ID location in Publisher Account]
## Using the IDs with SDK
Use these IDs when initializing the SDK in your project.
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(<Project ID>)
.SetLoginId(<Login ID>)
...
```
tip
For more information on how to configure the SDK, visit [Configure SDK](https://developers.xsolla.com/sdk/unity/sdk/configuration/).
```java
final Config billingClientConfig = new Config(
Config.Common.getDefault(),
Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(<Project ID>).getRight(),
LoginUUID.parse(<Login ID>).getRight()
)
),
Config.Payments.getDefault()
);
```
tip
For more information on how to configure the SDK, visit [Configure SDK](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/).
```objectivec
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: <Project ID>
loginProjectId: <Login ID>
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
let settings = SKPaymentSettings(projectId: <Project ID>,
loginProjectId: <Login ID>,
platform: .standalone)
SKPaymentQueue.default().start(settings)
```
tip
For more information on how to configure the SDK, visit [Configure SDK](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/).
Going Live
https://developers.xsolla.com/sdk/publisher-account/gotolive
Sign the licensing agreement and switch from sandbox to production — the final steps before accepting real payments.
## Sign the Licensing Agreement
important
You must sign an agreement for every new project in your **Publisher Account**.
To sign the licensing agreement and enable real payments:
- Open your **Publisher Account**.
- In the side menu, go to **Agreements and taxes** > **Agreements** section.
- On the **Licensing Agreement** tab, click **Fill out application form**.
- Provide your information in the corresponding fields.
Your application will be reviewed within **3 business days**. If questions arise, Xsolla will contact the person listed in the application. Once approved, the agreement status changes to **Signed**.
Before you sign the licensing agreement, you can open the payment UI only in **sandbox mode**.
## Switch to Production Environment
- Make sure you signed the licensing agreement with Xsolla.
- Set **sandbox** to **false** from the SDK configuration code.
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSandbox(false)
.SetLogLevel(XsollaLogLevel.None)
// ...other settings
.Build();
```
```java
final Config billingClientConfig = new Config(
Config.Common.getDefault()
.withSandboxEnabled(false)
.withLogLevel(LogLevel.ERROR)
.withDebugEnabled(false),
// ...other settings
);
```
```objectivec
SKPaymentSettings* settings = ...;
settings.useSandbox = NO;
settings.logLevel = SKLogLevelError;
```
```swift
let settings = SKPaymentSettings(...)
settings.useSandbox = false
settings.logLevel = .error
```
## Test Cards and Sandbox Mode
warning
After the first **real payment** is made, a **strict sandbox** payment policy takes effect.
Payments made in sandbox mode are available only to users specified in the **Publisher Account** under **Company settings** > **Users**.
Setting Up Authentication
https://developers.xsolla.com/sdk/publisher-account/login
Configure an authentication method for your **Xsolla Login** project — choose the approach that fits your app's complexity.
## Login with Device ID
important
This is **required** if you are using **Xsolla SDK** and you don't have existing Xsolla Login integration.
Best suited for casual apps that don't need advanced features (e.g. server validation, explicit authentication with Xsolla, etc).
### Enable Device ID Login in Publisher Account
- In the **Login methods** block, choose any option and click **Configure**.
[![select login method]](https://cdn.xsolla.net/developers/current/images/sdk/general/use-xsolla-servers/select-method.svg)
- In the top settings block, click **Login API integration**.
- Set the **Login with device ID** toggle to **ON**.
- Click **Save changes**.
![device ID login settings]
For more information, see [Device ID authentication ↗](https://developers.xsolla.com/doc/login/authentication-options/device-id) ([https://developers.xsolla.com/doc/login/authentication-options/device-id](https://developers.xsolla.com/doc/login/authentication-options/device-id)).
## Login on Game Server
The most advanced method — relies on your project's backend to authenticate and validate users. Makes extensive use of webhooks for communication between the backend and Xsolla services. For more information, see the [**Auth by custom ID ↗**](https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id) ([https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id](https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id)) API reference.
Create Project from Store Page
https://developers.xsolla.com/sdk/publisher-account/new-project/setup-fasttrack
Link your **Google Play** or **App Store** listing — Xsolla automatically pulls your game's imagery, title, developer information, and color scheme to pre-populate your **Publisher Account** project and **Web Shop**.
- Sign up or log in to your **Publisher Account**. To sign up, visit [publisher.xsolla.com ↗](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/](https://publisher.xsolla.com/)).
- Create a project in the **Publisher Account** (if you haven't already).
- Navigate to **Storefronts** > **Websites** section within your project.
- Click the **Create site** button and select the **Web Shop** template.
- Add a URL to an external platform where your game is available (Google Play Store or Apple App Store). [![create site]](https://developers.xsolla.com/sdk/assets/images/web-shop-create-site-1-55c3c75c111949355a8045234f0fc380.png)
- Click **Create Web Shop**.
Xsolla automatically fetches your app's information from the store and populates your project and **Web Shop** with the game data.
The **Web Shop** template is styled to match your game and pairs directly with your **Xsolla SDK** integration.
## Set Up Authentication
Enable **Device ID** login for your project — sign-in with no player credentials required. Continue to [Setting up authentication](https://developers.xsolla.com/sdk/publisher-account/login/).
Create Project Manually
https://developers.xsolla.com/sdk/publisher-account/new-project/setup-manual
Create a **Publisher Account** project from scratch and configure **Xsolla Login** — get your Project ID and Login ID for SDK integration.
## Sign up for a Publisher Account
The Publisher Account is the primary tool for configuring Xsolla features, as well as working with analytics and transactions.
To sign up, visit [Publisher Account ↗](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/](https://publisher.xsolla.com/)).
## Create a New Project
Configure your project details:
- Select project type: **Game**, **Game platform**, or **Other**.
- Enter your project name in English.
- Choose the release platforms.
- Select monetization approaches.
- Indicate development stage.
- For games: specify genre and game engine.
- Add product/game link *(optional)*.
[![project info]](https://cdn.xsolla.net/developers/current/images/general/create-project/project-info.png)
- Click **Finish** to complete project creation.
Your project will appear in the side menu.
![created project]
You'll need your **Project ID** to configure and integrate the SDK. Find it in your **Publisher Account** next to the project name — see [**Finding your Project ID**](https://developers.xsolla.com/sdk/publisher-account/getids/#project-id) for reference.
## Set up Xsolla Login
To set up Xsolla Login, follow these steps:
- Navigate to **Players** > **Login** from the menu.
- Click **Create Login project**.
[![create login project]](https://cdn.xsolla.net/developers/current/images/sdk/general/use-xsolla-servers/create-login-project.svg)
- Select **Standard Login project**, then click **Create and set up**.
You'll need your project's **Login ID** for SDK integration. Find it on your Login project page next to the project name — see [**Finding your Login ID**](https://developers.xsolla.com/sdk/publisher-account/getids/#login-id) for reference.
## Set Up Authentication
Configure an authentication method for your **Xsolla Login** project. Continue to [Setting up authentication](https://developers.xsolla.com/sdk/publisher-account/login/).
Configuring Xsolla Catalog
https://developers.xsolla.com/sdk/publisher-account/virtual-items
Set up your **Virtual Items** (IAPs) — the purchasable products in your **Xsolla Catalog**, equivalent to in-app purchases from Google Play Billing or StoreKit. important
Your Xsolla Catalog consists of [**Virtual Items ↗**](https://developers.xsolla.com/doc/shop-builder/features/virtual-items) ([https://developers.xsolla.com/doc/shop-builder/features/virtual-items](https://developers.xsolla.com/doc/shop-builder/features/virtual-items)). Each Virtual Item has a name, description, SKU (product identifier), and a price.
Import in-app purchases (IAPs) from App Store Connect and synchronize them as Virtual Items in your Xsolla Catalog by following [**this guide ↗**](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog) ([https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog)).warning
Make sure to perform this action after every App Store in-app purchase catalog update.
Import in-app products (IAPs) from Google Play and synchronize them as Virtual Items in your Xsolla Catalog by following [**this guide ↗**](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog) ([https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog)).warning
Make sure to perform this action after every Google Play product catalog update.
Use this method to manually manage your Xsolla Catalog (IAPs) through the Publisher Account interface.
### Add a Virtual Item with Basic Settings to the Catalog
- Open your project in Publisher Account and go to **Items catalog** > **All items** section.
- Click **Add** and select **Virtual item** from the drop-down list.
![virtual items create]
- Configure the basic settings. Specify the following: - image (optional) - SKU - one or multiple groups - item name - item description (optional) Leave the item type set to the default one — **Consumable** (recommended).
- Set up virtual item pricing: - To create a free virtual item, in the **Paid or free** field, select **Free item**. - To create a paid virtual item, in the **Paid or free** field, select **Paid item**, and specify the price in one or more currencies. note To ensure that the API calls for getting the catalog work correctly, make sure that the default currency and the list of currencies in which prices are specified match for all items.
- Change the item status to **Available**.
![virtual items status]
- Click **Create item**.
For advanced catalog features (virtual currency, bundles, item groups, and more), see the [**catalog creation guide ↗**](https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa) ([https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa](https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa)).warning
There is a file size limit of **7MB** (~**1000** records).
No public documentation is available at this moment. Please contact your Account Manager for more details and manual import/sync.
You can use Rest API to manage Virtual Items (IAPs) in the **Publisher Account**. This will allow you to set up inventory sync between your game server product catalog and Xsolla Catalog.
- #### Get Items ```text GET /v2/project/{project_id}/admin/items/virtual_items ``` Documentation can be found [here ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/](https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/))
- #### Create Item ```text POST /v2/project/{project_id}/admin/items/virtual_items ``` Documentation can be found [here ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/))
- #### Update Item ```text PUT /v2/project/{project_id}/admin/items/virtual_items/sku/{item_sku} ``` Documentation can be found [here ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/))
- #### Delete Item ```text DELETE /v2/project/{project_id}/admin/items/virtual_items/sku/{item_sku} ``` Documentation can be found [here ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/))
Webhooks
https://developers.xsolla.com/sdk/publisher-account/webhooks
When a payment or user validation occurs, Xsolla sends an HTTP request with the event data to your backend.
## How webhook validation works
Server-side validation means Xsolla notifies your backend about each purchase, refund, and chargeback, and your backend grants or revokes the entitlement accordingly. The game client never decides fulfillment.
- Player completes a purchase through the SDK.
- Xsolla sends a webhook (HTTP POST) to your backend.
- Your backend [verifies the signature](https://developers.xsolla.com/sdk/publisher-account/webhooks#verifying-the-signature), then processes the event.
- Your backend grants the entitlement and [returns a success code](https://developers.xsolla.com/sdk/publisher-account/webhooks#responding-to-webhooks) (**`200`**/**`201`**/**`204`**) to Xsolla.
- Your backend notifies the game through your own channel — the SDK is not involved in this step.
For the client side of this flow — launching the purchase and treating the SDK's purchase-completed callback as UI feedback — see the purchase guide for your platform: [Android](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/), [iOS](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/), [Unity](https://developers.xsolla.com/sdk/unity/sdk/purchase/), [Windows](https://developers.xsolla.com/sdk/windowstores/sdk/purchase/). Don't grant items on the client when webhooks are enabled
The SDK has no knowledge of your Publisher Account webhook settings, so its purchase-completed callback still fires on the client after a purchase. When you handle fulfillment through webhooks, treat that callback as **UI feedback only** — granting the item there as well would award the purchase twice. Client-side handling (purchase callback → validate → consume) is the alternative model, used only when you have no backend.
The purchase-completed callback differs by SDK. Whichever one your client uses, leave it as UI feedback when webhooks own fulfillment:
| Platform | Purchase-completed callback | Client-side validate → consume (alternative model) |
| --- | --- | --- |
| Android | onPurchasesUpdated() | validateAsync() → consumeAsync() — Client-side validation |
| iOS | paymentQueue(_:updatedTransactions:) (.purchased) | validateTransaction(_:completion:) → finishTransaction(_:) — Client-side validation |
| Unity (with / without IAP) | ProcessPurchase(...) / PurchaseProduct(...) | ValidatePurchase(...) → ConsumeProduct(...) — Client-side validation |
| Windows | PurchaseProduct(...) | ValidatePurchase(...) → ConsumeProduct(...) — Client-side validation |
## Setting up webhooks in Publisher Account
![webhooks settings in Publisher Account]
### Enabling webhooks
- Open your project in the Publisher Account.
- In the side menu, go to **Settings** and select **Webhooks**.
- In the **Webhook server** field, specify the URL of your server where you want webhooks to be sent (e.g. `https://www.my-backend.com/webhooks`).
- A secret key for signing webhooks is generated by default. To add or rotate keys: - In the **Secret key** section, click **Add key**. - Enter a name and click **Create key**. - Copy the generated value (shown once). - When rotating: click **Set as active** on the new key. Up to 5 keys can exist per project; remove the old key after confirming signatures pass.
- Click **Enable webhooks**.
### Disabling webhooks
- Open your project in the Publisher Account.
- In the side menu, go to **Settings** and select **Webhooks**.
- Click **Disable webhooks**.
## Which webhooks will you receive?
The webhook types your project receives depend on when the project was registered. Newer projects use a combined order model, while legacy projects use separate payment and refund notifications.
| Project registered | You receive | Notes |
| --- | --- | --- |
| After Jan 22, 2025 | order_paid, order_canceled (combined) | Do not process payment / refund. |
| Before Jan 22, 2025 | payment, refund (separate) + order_paid / order_canceled with item data | Legacy separate model. |
How to check which model you're on
In Publisher Account → **Project Settings** → **Webhooks**, if the test section only shows `order_paid` examples, you're on the new (combined) model.
## Verifying the signature
Every webhook carries an `Authorization: Signature <value>` header. Verify it before processing any event.
- Read the signature from the `Authorization` header (format: `Signature <value>`).
- Take the **raw request body** exactly as received. Do not parse or re-serialize the JSON — re-encoding changes the bytes and the signature will not match.
- Concatenate: `raw_body + secret_key`.
- Apply **SHA-1**; take the lowercase hex digest.
- Compare to the header value using **constant-time** comparison to prevent timing attacks.
Use the raw request body
Signature verification must run on the **exact bytes** Xsolla sent. Capture the raw body before any JSON middleware parses it — parsing and re-serializing changes the bytes and the signature will never match. Each framework below shows how to get the raw body.
```js
const crypto = require('crypto');
// Capture the RAW body, not parsed JSON:
// app.use('/webhooks', express.raw({ type: 'application/json' }));
function verifyXsollaSignature(rawBody, authHeader, secretKey) {
const provided = String(authHeader || '').replace(/^Signature\s+/i, '').trim();
const expected = crypto
.createHash('sha1')
.update(rawBody.toString('utf8') + secretKey)
.digest('hex');
const a = Buffer.from(provided);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```
```php
function verifyXsollaSignature(string $rawBody, string $authHeader, string $secretKey): bool {
$provided = trim(preg_replace('/^Signature\s+/i', '', $authHeader));
$expected = sha1($rawBody . $secretKey);
return hash_equals($expected, $provided); // constant-time
}
```
```csharp
using System.Security.Cryptography;
using System.Text;
static bool VerifyXsollaSignature(string rawBody, string authHeader, string secretKey)
{
var provided = (authHeader ?? "").Replace("Signature ", "").Trim();
var hash = SHA1.HashData(Encoding.UTF8.GetBytes(rawBody + secretKey)); // .NET 5+
var expected = Convert.ToHexString(hash).ToLowerInvariant(); // .NET 5+
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(provided),
Encoding.UTF8.GetBytes(expected));
}
```
For .NET Framework / pre-.NET 5, replace `SHA1.HashData(...)` with `using var sha1 = SHA1.Create(); var hash = sha1.ComputeHash(...);` and `Convert.ToHexString(hash)` with `BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant()`.
```python
import hashlib
import hmac
def verify_xsolla_signature(raw_body: bytes, auth_header: str, secret_key: str) -> bool:
provided = auth_header.replace('Signature ', '').strip()
expected = hashlib.sha1((raw_body.decode('utf-8') + secret_key).encode('utf-8')).hexdigest()
return hmac.compare_digest(provided, expected)
```
```go
import (
"crypto/sha1"
"crypto/subtle"
"encoding/hex"
"strings"
)
func verifyXsollaSignature(rawBody []byte, authHeader, secretKey string) bool {
provided := strings.TrimSpace(strings.TrimPrefix(authHeader, "Signature "))
h := sha1.New()
h.Write(rawBody)
h.Write([]byte(secretKey))
expected := hex.EncodeToString(h.Sum(nil))
return subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
}
```
```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
static boolean verifyXsollaSignature(final byte[] rawBody, final String authHeader, final String secretKey)
throws NoSuchAlgorithmException {
final String provided = authHeader.replaceFirst("(?i)^Signature\\s+", "").trim();
final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
sha1.update(rawBody);
sha1.update(secretKey.getBytes(StandardCharsets.UTF_8));
final byte[] hash = sha1.digest();
final StringBuilder hex = new StringBuilder(hash.length * 2);
for (final byte b : hash) {
hex.append(String.format("%02x", b));
}
// MessageDigest.isEqual is constant-time on modern JDKs.
return MessageDigest.isEqual(
provided.getBytes(StandardCharsets.UTF_8),
hex.toString().getBytes(StandardCharsets.UTF_8)
);
}
```
## Responding to webhooks
Your handler must reply with the right HTTP code.
| Response | Meaning |
| --- | --- |
| 200 / 201 / 204 | Success — webhook accepted. |
| 400 (any 4xx) + error code | Problem with the request. Include an error body with code and message. Common codes: INVALID_SIGNATURE, INVALID_USER, INVALID_PARAMETER. |
| 5xx | Temporary problem on your side — Xsolla will retry. |
When you reject with a `4xx`, include an error body alongside the status code. It follows this shape — set `code` and `message` to whatever fits the rejection:
```json
{
"error": {
"code": "INVALID_SIGNATURE",
"message": "Signature mismatch"
}
}
```
Refunds on 4xx
If automatic refunds are enabled for your project, a `4xx` response to `order_paid` triggers an automatic refund to the player. Reject with `4xx` only when you genuinely want to decline the purchase — for transient problems on your side, return `5xx` so Xsolla retries instead.
### Retries
- `order_paid` / `order_canceled`: if your endpoint doesn't return success, Xsolla retries on an increasing schedule (2 attempts every 5 minutes, 7 every 15 minutes, then 10 every 60 minutes), for up to 20 delivery attempts (the initial one plus retries) within 12 hours.
- `payment` / `refund` (legacy model): also retried on an increasing schedule within 12 hours. See the [webhooks reference ↗](https://developers.xsolla.com/webhooks/overview) for the exact counts.
- `user_validation` is a gate, not a retry: if you return `400`/`5xx` or don't respond, the webhook is **not** resent, the player sees an error, and the subsequent `payment`/`order_paid` webhooks are **not** sent. Return success only for users you actually accept.
## Working with webhooks
Each webhook tells you to do something specific. Verify the signature on every request first (see [Verifying the signature](https://developers.xsolla.com/sdk/publisher-account/webhooks#verifying-the-signature)), then act on the `notification_type`.
### User Validation (user_validation)
A gate sent **before** payment to confirm the user may purchase. Return `204` to allow the purchase to proceed, or `400` with `INVALID_USER` to block it. This webhook is [not retried](https://developers.xsolla.com/sdk/publisher-account/webhooks#retries), and no payment webhook follows a rejected validation — so return success only for users that exist in your system.
The player's id is in `user.id` here and in the legacy [`payment`](https://developers.xsolla.com/sdk/publisher-account/webhooks#payment) webhook. The combined [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_paid) webhook identifies the player by `user.external_id` instead — key your logic off the right field per webhook type. Example
```json
{
"notification_type": "user_validation",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"user": {
"ip": "127.0.0.1",
"phone": "18777976552",
"email": "[email protected]",
"id": "1234567",
"name": "John Smith",
"country": "US"
}
}
```
For the full field list, see the [user_validation reference ↗](https://developers.xsolla.com/webhooks/operation/user-validation/).
### Order Paid (order_paid)
This is your fulfillment trigger and the primary webhook for projects registered after Jan 22, 2025. In the combined model it carries both the items to grant and the payment data. Read `items[]` (each has a `sku`, `type`, and `quantity`), grant them to `user.external_id`, and return `204`. Skip an `order.id` you've already handled, so retries never grant twice. Test orders arrive with `order.mode: "sandbox"` — skip real state changes for those.
Orders carrying a Google external transaction token additionally get a `billing.ucb_report` object — a pre-built Google `externalTransactions` report payload. See [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/#correlating-the-token-with-your-xsolla-order). Example
```json
{
"notification_type": "order_paid",
"items": [
{
"sku": "money.100",
"type": "virtual_good",
"quantity": 1,
"amount": "9.99",
"promotions": [
{
"amount_without_discount": "19.99",
"amount_with_discount": "9.99",
"sequence": 1
}
],
"is_pre_order": false,
"custom_attributes": {}
}
],
"order": {
"id": 123456789,
"mode": "default",
"currency_type": "real",
"currency": "USD",
"amount": "9.99",
"status": "paid",
"platform": "xsolla",
"invoice_id": "inv_12345",
"promotions": [],
"coupons": [],
"promocodes": []
},
"user": {
"external_id": "user_12345",
"email": "[email protected]",
"country": "US"
},
"billing": {
"notification_type": "payment",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"total": {
"currency": "USD",
"amount": 9.99
}
},
"transaction": {
"id": 555666777,
"external_id": "ext_trans_001",
"payment_date": "2025-01-15T14:22:10+00:00"
},
"payment_details": {
"payment": {
"currency": "USD",
"amount": 9.99
},
"vat": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"sales_tax": {
"currency": "USD",
"amount": 0.87,
"percent": 9.5
},
"payout": {
"currency": "USD",
"amount": 8.5
}
}
}
}
```
Subscription and gift purchases include additional `billing.purchase.subscription` / `billing.purchase.gift` objects. For the exhaustive field list, see the [order_paid reference ↗](https://developers.xsolla.com/webhooks/operation/successful-order-payment/).
### Order Canceled (order_canceled)
The reversal trigger for projects registered after Jan 22, 2025, sent on a refund or chargeback. It mirrors the [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_paid) structure: look up the original grant by `order.id`, revoke or claw back the entitlement, and return `204`. It is [retried](https://developers.xsolla.com/sdk/publisher-account/webhooks#retries) on the same schedule as `order_paid`, so dedupe on `order.id` to avoid double-revoking. Test reversals arrive with `order.mode: "sandbox"`.
Like [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_paid), this carries a `billing.ucb_report` object when the order has a Google external transaction token — see [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/#correlating-the-token-with-your-xsolla-order). Example
```json
{
"notification_type": "order_canceled",
"items": [
{
"sku": "money.100",
"type": "virtual_good",
"quantity": 1,
"amount": "9.99",
"is_pre_order": false,
"custom_attributes": {}
}
],
"order": {
"id": 123456789,
"mode": "default",
"currency_type": "real",
"currency": "USD",
"amount": "9.99",
"status": "canceled",
"platform": "xsolla",
"invoice_id": "inv_12345"
},
"user": {
"external_id": "user_12345",
"email": "[email protected]",
"country": "US"
},
"billing": {
"notification_type": "refund",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"transaction": {
"id": 555666777,
"external_id": "ext_trans_001"
}
}
}
```
For the full payload, see the [order_canceled reference ↗](https://developers.xsolla.com/webhooks/operation/order-cancellation).
### Payment (payment)
This webhook carries the financial record (with a line-item summary) in the legacy (separate) model — projects registered before Jan 22, 2025. A separate [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_paid) carries the authoritative item-grant data. Newer projects don't receive `payment` at all. Skip a `transaction.id` you've already handled; test transactions arrive with `transaction.dry_run: 1`. The legacy reversal counterpart is the [`refund`](https://developers.xsolla.com/sdk/publisher-account/webhooks#refund) webhook.
Orders carrying a Google external transaction token additionally get a `ucb_report` object — a pre-built Google `externalTransactions` report payload. See [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/#correlating-the-token-with-your-xsolla-order). Example
```json
{
"notification_type": "payment",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"subscription": {
"plan_id": "b5dac9c8",
"subscription_id": "10",
"product_id": "Demo Product",
"date_create": "2014-09-22T19:25:25+04:00",
"date_next_charge": "2014-10-22T19:25:25+04:00",
"currency": "USD",
"amount": 9.99
},
"checkout": {
"currency": "USD",
"amount": 50
},
"total": {
"currency": "USD",
"amount": 200
},
"promotions": [
{
"technical_name": "Demo Promotion",
"id": 853
}
],
"coupon": {
"coupon_code": "ICvj45S4FUOyy",
"campaign_code": "1507"
},
"order": {
"id": 1234,
"lineitems": [
{
"sku": "ticket.10",
"quantity": 1,
"price": {
"currency": "EUR",
"amount": 6.5
}
}
]
}
},
"user": {
"ip": "127.0.0.1",
"phone": "18777976552",
"email": "[email protected]",
"id": "1234567",
"name": "John Smith",
"country": "US"
},
"transaction": {
"id": 1,
"external_id": 1,
"payment_date": "2014-09-24T20:38:16+04:00",
"payment_method": 1,
"payment_method_name": "PayPal",
"payment_method_order_id": 1234567890123456789,
"dry_run": 1,
"agreement": 1
},
"payment_details": {
"payment": {
"currency": "USD",
"amount": 230
},
"vat": {
"currency": "USD",
"amount": 0,
"percent": 20
},
"sales_tax": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"direct_wht": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"payout_currency_rate": "1",
"payout": {
"currency": "USD",
"amount": 200
},
"xsolla_fee": {
"currency": "USD",
"amount": 10
},
"payment_method_fee": {
"currency": "USD",
"amount": 20
},
"repatriation_commission": {
"currency": "USD",
"amount": 10
}
},
"custom_parameters": {
"parameter1": "value1",
"parameter2": "value2"
}
}
```
For the full field list, see the [payment reference ↗](https://developers.xsolla.com/webhooks/operation/payment).
### Refund (refund)
The reversal trigger in the legacy (separate) model, and the counterpart to [`payment`](https://developers.xsolla.com/sdk/publisher-account/webhooks#payment), sent on a refund or chargeback. Look up the original grant by `transaction.id`, revoke or claw back the entitlement, and return `204`. Skip a `transaction.id` you've already handled, so retries never revoke twice. Test refunds arrive with `transaction.dry_run: 1`. Newer projects receive [`order_canceled`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_canceled) instead and don't get `refund` at all.
Like [`payment`](https://developers.xsolla.com/sdk/publisher-account/webhooks#payment), this carries a `ucb_report` object when the order has a Google external transaction token — see [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/#correlating-the-token-with-your-xsolla-order). Example
```json
{
"notification_type": "refund",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"total": {
"currency": "USD",
"amount": 9.99
},
"order": {
"id": 1234,
"lineitems": [
{
"sku": "ticket.10",
"quantity": 1,
"price": {
"currency": "USD",
"amount": 9.99
}
}
]
}
},
"user": {
"id": "1234567",
"email": "[email protected]",
"country": "US"
},
"transaction": {
"id": 1,
"external_id": "ext_trans_001",
"payment_date": "2014-09-24T20:38:16+04:00",
"dry_run": 1
},
"refund_details": {
"code": 1,
"reason": "Test refund"
}
}
```
For the exhaustive field list, see the [refund reference ↗](https://developers.xsolla.com/webhooks/operation/refund).
## Putting it together
Below is a minimal handler that verifies the signature, routes on `notification_type`, and responds with the right codes. Each language tab reuses the `verifyXsollaSignature()` function from [Verifying the signature](https://developers.xsolla.com/sdk/publisher-account/webhooks#verifying-the-signature): Two things the samples can't show inline
- **Key off the right field.** `user_validation` identifies the player by `user.id`; `order_paid` / `order_canceled` use `user.external_id`. Using the wrong one is the most common integration bug.
- **Don't return `4xx` for transient failures.** If automatic refunds are enabled, a `4xx` to `order_paid` can trigger a refund. Return `5xx` for problems on your side so Xsolla retries.
```js
const express = require('express');
const app = express();
// Raw body is required for signature verification.
app.use('/webhooks', express.raw({ type: 'application/json' }));
app.post('/webhooks', (req, res) => {
const secretKey = process.env.XSOLLA_WEBHOOK_SECRET;
if (!verifyXsollaSignature(req.body, req.get('authorization'), secretKey)) {
return res.status(400).json({
error: { code: 'INVALID_SIGNATURE', message: 'Signature mismatch' },
});
}
const event = JSON.parse(req.body.toString('utf8'));
switch (event.notification_type) {
case 'user_validation':
return userExists(event.user.id)
? res.sendStatus(204)
: res.status(400).json({
error: { code: 'INVALID_USER', message: 'User not found' },
});
case 'order_paid':
if (event.order.mode !== 'sandbox') {
enqueueFulfillment(event); // grant items async; dedupe on event.order.id
}
return res.sendStatus(204);
case 'order_canceled':
if (event.order.mode !== 'sandbox') {
enqueueRevocation(event); // revoke entitlement async; dedupe on event.order.id
}
return res.sendStatus(204);
default:
// Acknowledge unhandled types so Xsolla doesn't retry them.
return res.sendStatus(204);
}
});
```
```php
<?php
// Raw body is required for signature verification.
$rawBody = file_get_contents('php://input');
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$secretKey = getenv('XSOLLA_WEBHOOK_SECRET');
header('Content-Type: application/json');
if (!verifyXsollaSignature($rawBody, $authHeader, $secretKey)) {
http_response_code(400);
echo json_encode(['error' => ['code' => 'INVALID_SIGNATURE', 'message' => 'Signature mismatch']]);
exit;
}
$event = json_decode($rawBody, true);
switch ($event['notification_type']) {
case 'user_validation':
if (userExists($event['user']['id'])) {
http_response_code(204);
} else {
http_response_code(400);
echo json_encode(['error' => ['code' => 'INVALID_USER', 'message' => 'User not found']]);
}
break;
case 'order_paid':
if ($event['order']['mode'] !== 'sandbox') {
enqueueFulfillment($event); // grant items async; dedupe on order.id
}
http_response_code(204);
break;
case 'order_canceled':
if ($event['order']['mode'] !== 'sandbox') {
enqueueRevocation($event); // revoke entitlement async; dedupe on order.id
}
http_response_code(204);
break;
default:
http_response_code(204); // acknowledge unhandled types so Xsolla doesn't retry
break;
}
```
```csharp
app.MapPost("/webhooks", async (HttpRequest request) =>
{
var secretKey = Environment.GetEnvironmentVariable("XSOLLA_WEBHOOK_SECRET");
using var reader = new StreamReader(request.Body);
var rawBody = await reader.ReadToEndAsync();
var authHeader = request.Headers.Authorization.ToString();
if (!VerifyXsollaSignature(rawBody, authHeader, secretKey))
{
return Results.BadRequest(new { error = new { code = "INVALID_SIGNATURE", message = "Signature mismatch" } });
}
var evt = JsonSerializer.Deserialize<JsonElement>(rawBody);
switch (evt.GetProperty("notification_type").GetString())
{
case "user_validation":
return UserExists(evt.GetProperty("user").GetProperty("id").GetString())
? Results.StatusCode(204)
: Results.BadRequest(new { error = new { code = "INVALID_USER", message = "User not found" } });
case "order_paid":
if (evt.GetProperty("order").GetProperty("mode").GetString() != "sandbox")
EnqueueFulfillment(evt); // grant items async; dedupe on order.id
return Results.StatusCode(204);
case "order_canceled":
if (evt.GetProperty("order").GetProperty("mode").GetString() != "sandbox")
EnqueueRevocation(evt); // revoke entitlement async; dedupe on order.id
return Results.StatusCode(204);
default:
return Results.StatusCode(204); // acknowledge unhandled types
}
});
```
```python
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.post('/webhooks')
def webhooks():
secret_key = os.environ['XSOLLA_WEBHOOK_SECRET']
raw_body = request.get_data() # raw bytes, not parsed
auth_header = request.headers.get('Authorization', '')
if not verify_xsolla_signature(raw_body, auth_header, secret_key):
return jsonify(error={'code': 'INVALID_SIGNATURE', 'message': 'Signature mismatch'}), 400
event = request.get_json()
notification_type = event['notification_type']
if notification_type == 'user_validation':
if user_exists(event['user']['id']):
return '', 204
return jsonify(error={'code': 'INVALID_USER', 'message': 'User not found'}), 400
elif notification_type == 'order_paid':
if event['order']['mode'] != 'sandbox':
enqueue_fulfillment(event) # grant items async; dedupe on order.id
return '', 204
elif notification_type == 'order_canceled':
if event['order']['mode'] != 'sandbox':
enqueue_revocation(event) # revoke entitlement async; dedupe on order.id
return '', 204
else:
return '', 204 # acknowledge unhandled types so Xsolla doesn't retry
```
```go
func webhookHandler(w http.ResponseWriter, r *http.Request) {
secretKey := os.Getenv("XSOLLA_WEBHOOK_SECRET")
rawBody, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
if !verifyXsollaSignature(rawBody, r.Header.Get("Authorization"), secretKey) {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{"code": "INVALID_SIGNATURE", "message": "Signature mismatch"},
})
return
}
var event struct {
NotificationType string `json:"notification_type"`
User struct{ ID string `json:"id"` } `json:"user"`
Order struct{ Mode string `json:"mode"` } `json:"order"`
}
json.Unmarshal(rawBody, &event)
switch event.NotificationType {
case "user_validation":
if userExists(event.User.ID) {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{"code": "INVALID_USER", "message": "User not found"},
})
}
case "order_paid":
if event.Order.Mode != "sandbox" {
enqueueFulfillment(rawBody) // grant items async; dedupe on order.id
}
w.WriteHeader(http.StatusNoContent)
case "order_canceled":
if event.Order.Mode != "sandbox" {
enqueueRevocation(rawBody) // revoke entitlement async; dedupe on order.id
}
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusNoContent) // acknowledge unhandled types
}
}
```
```java
@RestController
public class WebhookController {
@PostMapping("/webhooks")
public ResponseEntity<?> handle(
@RequestBody final byte[] rawBody,
@RequestHeader(value = "Authorization", required = false) final String authHeader)
throws Exception {
final String secretKey = System.getenv("XSOLLA_WEBHOOK_SECRET");
if (!verifyXsollaSignature(rawBody, authHeader, secretKey)) {
return ResponseEntity.badRequest().body(
Map.of("error", Map.of("code", "INVALID_SIGNATURE", "message", "Signature mismatch"))
);
}
final JsonNode event = new ObjectMapper().readTree(rawBody);
switch (event.get("notification_type").asText()) {
case "user_validation":
return userExists(event.get("user").get("id").asText())
? ResponseEntity.noContent().build()
: ResponseEntity.badRequest().body(
Map.of("error", Map.of("code", "INVALID_USER", "message", "User not found")));
case "order_paid":
if (!"sandbox".equals(event.get("order").get("mode").asText())) {
enqueueFulfillment(event); // grant items async; dedupe on order.id
}
return ResponseEntity.noContent().build();
case "order_canceled":
if (!"sandbox".equals(event.get("order").get("mode").asText())) {
enqueueRevocation(event); // revoke entitlement async; dedupe on order.id
}
return ResponseEntity.noContent().build();
default:
return ResponseEntity.noContent().build(); // acknowledge unhandled types
}
}
}
```
## Best practices & testing
- **[Verify the signature](https://developers.xsolla.com/sdk/publisher-account/webhooks#verifying-the-signature) before doing anything else.** Reject mismatches with **`400`** `INVALID_SIGNATURE`.
- **Respond fast, process async.** Return `204` immediately after verification, then do business logic (granting items, DB writes) in a background queue. Xsolla recommends handlers respond within 1–3 s; on failure they [retry](https://developers.xsolla.com/sdk/publisher-account/webhooks#retries) up to 20 times over 12 hours.
- **Expect the same webhook twice.** Xsolla may deliver it more than once, for example after a timeout. Keep track of the `transaction.id` or `order.id` you've handled and ignore repeats, so a player is never granted an item twice.
- **Handle test transactions.** Publisher Account can send real webhooks for testing — [`payment`](https://developers.xsolla.com/sdk/publisher-account/webhooks#payment) marks them with `transaction.dry_run: 1`, and [`order_paid`](https://developers.xsolla.com/sdk/publisher-account/webhooks#order_paid) marks them with `order.mode: "sandbox"`. The signature is real, but no money moves. Skip state changes (item grants, DB writes) for these, or route them to a sandbox path.
- **Restrict by source IP** as defense in depth alongside signature checks. Xsolla sends webhooks from `185.30.20.0/24`–`185.30.23.0/24` plus a set of Google Cloud IPs; see the [official list ↗](https://developers.xsolla.com/webhooks/overview) for the authoritative, current set before relying on it.
- **Testing gotcha:** if you use `webhook.site` or a similar request inspector, it returns `200` to everything — it can't produce the `400` Xsolla expects for a bad signature. Use a real handler to test signature rejection.
## Alternative: serverless via Events API
The **Xsolla Events API** is an alternative to webhooks for projects without a backend. Instead of Xsolla POSTing events to your server, Xsolla stores the event payloads on its side and the SDK retrieves them directly from the app — so the entire transaction flow can run client-side. Events API and webhooks are mutually exclusive
Opting for the **Xsolla Events API** **disables** your project's **webhooks** — you cannot use both simultaneously. ![Events API settings in Publisher Account]
To enable the Events API for your project:
- Open your project in the Publisher Account.
- In the side menu, select **Project settings**.
- Open the **Integration settings** tab.
- Select **Use API** and click **Save**.
To initialize the SDK in Events API mode, see the platform-specific guides:
- [**Android**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#xsolla-events-api)
- [**iOS**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/#using-xsolla-events-api-for-restoration)
- [**Unity**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#using-xsolla-events-api-for-restoration)
- [**Windows**](https://developers.xsolla.com/sdk/windowstores/sdk/configuration/#events)
For the complete list of supported webhook types, see the [Xsolla webhooks reference ↗](https://developers.xsolla.com/webhooks/overview).
Hey Developers, this is Xsolla's SDK 3.
https://developers.xsolla.com/sdk/technical-articles/intro-to-sdk3-integrations
![Xsolla SDK 3 banner]
Hello Developers! We are Xsolla's Developer Relations Team and in this blog we want to tell you about Xsolla's SDK 3, the latest rev of our software toolkit that enables you to add monetization to your mobile and PC games all with one simple integration that takes less than 15 minutes to implement.
Previous versions of Xsolla's SDK duplicated the same logic across every integration target. SDK 3 moves that logic into a single native core and reduces each integration to a thin wrapper over it — one implementation, many bindings. Checkout follows the same principle: instead of shipping our own embedded browser, SDK 3 renders through the surfaces the operating system already provides, and treats link-out as a first-class flow rather than a fallback.
With SDK 3, you can add monetization to your games and start selling powerups, skins, equipment and whatever else suits your game design with four simple steps: **Authenticate**, **Load Catalog**, **Initiate Purchase**, and **Finalize Transaction**.
## Integration Guides
To get you started, we have created a selection of materials covering several different platforms and engines that will walk you through the integration.
Watch the videos here…
- [SDK 3 for Unity Mobile](https://youtu.be/wbfAUmP_v-s?si=DrNdxBc283VfMqwc)
- [SDK 3 for Unity PC](https://youtu.be/hnOibNa6XOI?si=U2QEBzG7SqqR1Agq)
- [SDK 3 for Native iOS](https://youtu.be/L2C1zoAAjFY?si=zB23GdkzTubiGmzO)
- [SDK 3 for Native Android](https://youtu.be/-G0ly2yck-8?si=cFZndIE76iLsS-GK)
- [SDK 3 for Unreal Engine (PC)](https://youtu.be/zbnJbwVVi9s)
…or if you prefer a written format, the articles below mirror the content in the videos above:
- [SDK 3 for Unity Mobile](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-mobile/)
- [SDK 3 for Unity PC](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-unity-pc/)
- [SDK 3 for Unity Web](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-web/)
- [SDK 3 for Native iOS](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-ios/)
- [SDK 3 for Native Android](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-android/)
- [SDK 3 for Unreal Engine (PC)](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unreal-pc/)
## Platform Compliance
**iOS:** Following the April 30, 2025 U.S. court decision, developers may include external payment links in iOS apps. The Xsolla SDK for Mobile is fully compliant with Apple's revised App Store guidelines, supporting both in-app Pay Station flows and link-out payments via Web Shop.
**Android:** Following the October 29, 2025 Epic v. Google injunction, U.S. Google Play apps may use alternative billing solutions, external payment links, and are no longer subject to anti-steering restrictions. The SDK supports out-of-store APK distribution, Google Play Billing, and browser-based checkout - all in one integration.
## SDK Explorer
Perhaps you want to see SDK 3 in action, within the context of a fully playable game? Try SDK Explorer and see how SDK 3 works in realtime. Choose your platform, language, and/or engine and as you play our Pizza Shop simulator, witness the actual calls happening under the hood.
- [SDK Explorer Demo](https://developers.xsolla.com/sdk/demo/)
## Get Started
When you're ready to get started, begin by creating a Publisher Account. (Yes, Publisher Account is for developers too. We're all publishers now!) It only takes a few seconds.
- [Create a Publisher Account](https://publisher.xsolla.com/)
## Let Us Do the Heavy Lifting
Xsolla covers over 130 currencies and over 1000 payment methods across over 200 regions spanning the globe. As your Merchant of Record, we handle tax, regional legal compliance, fraud protection, and more. Xsolla takes care of the business of monetization for you, freeing you up to do what you do best: make great games.
## Coming Soon
Thanks for making it this far. Keep an eye out for more SDK 3 content from Xsolla's DevRel Team covering more engines and more platforms, as well as other products and solutions that will help you build games and grow your gamedev business.
Native Android — Xsolla SDK 3 Integration Guide
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-android
![a65e3689-3367-4c52-9fc7-5ecadeb0880c.png]
## Integrating Xsolla SDK 3 into Your Native Android Game
Integrating a seamless, secure checkout experience shouldn't mean derailing your game's development schedule. In this guide, we're breaking down exactly how to integrate the Xsolla SDK into your native Android game to get your in-game monetization up and running.
By the end of this walkthrough, you'll have a fully working Xsolla payment flow running smoothly on Android. We will cover:
- **The Essential Resources:** Exactly where to find the right documentation to kickstart your integration without the guesswork.
- **A High-Level Walkthrough:** A step-by-step implementation guide to embedding the SDK into your native codebase.
- **Going Production-Ready:** The critical next steps required to configure your Xsolla Publisher Account and transition your game from testing to live production.
Whether you're looking to implement impulse-buy mechanics like health refills at a game-over screen or to set up a robust virtual storefront, this step-by-step guide will give you the foundational tools to start processing global payments natively.
## Prerequisites
Before diving into the code, make sure your development environment matches the baseline requirements. Having these elements sorted beforehand ensures a smooth implementation process.
### Development Requirements
- **Android SDK:** Minimum API level 24 (Android 7.0, Nougat) or higher.
- **Java Development Kit (JDK):** Version 11 or higher.
- **Android Studio:** It provides not only robust IDE capabilities, but also the full Gradle and SDK toolchain.
- **Existing Game Architecture:** We assume you already have a functional native Android project and a specific UI element (like a store menu, a game-over popup, or a checkout button) ready to trigger the payment flow. This article focuses strictly on SDK implementation, not building game UI elements from scratch.
### Xsolla Infrastructure
- **Xsolla Publisher Account:** An active account is essential, especially when you are ready to transition your project to live production. If you haven't created one yet, head over to the Xsolla Publisher Account signup page.
**Sandbox Environment:** Setting up a full merchant profile won't hold you back today. To keep things streamlined, this walkthrough utilizes the **Xsolla Sandbox environment**, allowing you to test the complete purchasing process from end to end without needing to configure a live, production-ready account first. If you need a step-by-step guide on full publisher account management, please refer to the official Xsolla configuration documentation.
## What We're Building
To demonstrate the Xsolla SDK 3 integration in a real-world scenario, this guide uses a straightforward demo project: a classic Android clicker game built entirely in native Java. Keeping the core gameplay mechanics simple allows us to focus 100% on the underlying monetization code without getting lost in complex game loops.
![c089ee5f-45c8-401d-a064-6e2416f7e61b.png]
*Simple Clicker game*
### The Demo Game Mechanics
The loop of our sample application centers on a few basic interactions:
- **The Core Action:** Players tap a large coin icon in the center of the screen to manually generate and accumulate virtual currency.
- **Progressive Upgrades:** Players can spend their accumulated coins on two distinct in-game items designed to accelerate their progress: - **Click Multiplier:** Increases the value of each tap, making manual collection more efficient. - **Auto-Collector:** Automatically accumulates coins over time, driving passive progression.
### The SDK Integration Point
The monetization magic happens right at the premium store button. When a player taps the purchase button to acquire a premium item or bundle, the application initializes the Xsolla payment flow.
Instead of routing players to an external web browser, the app invokes the Xsolla SDK directly. Within a second, a secure checkout UI overlays the game, allowing the player to complete a full transaction using the Xsolla Sandbox environment.
In the upcoming sections, we'll open up the codebase and examine exactly which files and classes we need to modify to bring this native checkout experience to life.
## Your Reference Resources
Before writing any code, you will want to open a few key documentation tabs. Having these reference points side-by-side with your IDE will save you a massive amount of time, as Xsolla provides pre-built code snippets specifically tailored for native Android environments.
### 1. The Central Hub: Xsolla SDK Site
Your primary starting point is [developers.xsolla.com/sdk](https://developers.xsolla.com/sdk). This portal provides a comprehensive overview of the SDK's core capabilities, cross-platform architecture, and essential integration use cases.
### 2. The SDK Explorer & Integration Widget
The most powerful tool at your disposal is the [**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) and its Integration Widget. The [Integration Widget](https://developers.xsolla.com/sdk/integration-widget) is a page on the Xsolla SDK site and a tab within the SDK Explorer that gives you the full, ready-to-use code for each integration step. Throughout this guide, we will frequently refer back to this widget to grab clean, production-ready blocks of Java code that you can copy and paste directly into your project files.
### 3. The Android Quick Start Guide
To find the exact code implementations used in this walkthrough, navigate through the sidebar following this path:
[Mobile → Quick Start → Android](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android)
This sub-section houses the foundational native code blocks. We will break down exactly how to pull from these resources to achieve two primary milestones:
- Locally loading and rendering your virtual item catalog.
- Triggering a secure, native sandbox checkout flow for your player.
**Looking Ahead:** Keep an eye on the **Publisher Account** documentation section as well. While our immediate focus is getting the local Android code running via the sandbox, that section will be your step-by-step roadmap later on for initializing projects, setting up items, and mapping out credentials within the Publisher Account dashboard to take your game live.
## Step 0: Set Up the Xsolla SDK Package
Before we can implement any payment features, we need to pull the Xsolla SDK into our Android project. While cross-platform tools like Unity use a Package Manager UI, native Android relies on Gradle to handle dependencies.
We will make two quick configuration changes to your project's Gradle files and then add a critical import to your main activity.
![de35ba8c-73fe-46c8-ae7b-44b342424f58.png]
*Setting Up Your Development Workspace*
### 1. Update settings.gradle
First, we need to ensure your project knows where to find the Xsolla package repository. Open your `settings.gradle` file and verify that `mavenCentral()` is included in your repositories block:
```java
// settings.gradle
repositories {
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
```
### 2. Configure build.gradle (Module: app)
Next, open your module-level `build.gradle` file. Scroll down to the `dependencies` block. Here, we will define the specific SDK version we want to use and declare the implementation line.
At the time of this guide, we are using version **3.0.37**. Add the following lines to your dependencies:
```java
// build.gradle
dependencies {
def version_mobilesdk = '<version>' // '3.0.37'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
Defining the version as a variable (`def version_mobilesdk`) keeps your file clean and makes it easy to update the SDK in the future.
### 3. Import the Package in Your Main Activity
Once you have modified your Gradle files, sync your project. To officially bridge the SDK with your game code, open your main Java activity file (e.g., `MainActivity.java`) and add the core Xsolla package import at the top of the file:
```java
//MainActivity.java
import com.xsolla.android.mobile.*;
```
With this line in place, your native project is fully connected to the Xsolla SDK, and you're ready to begin writing the initialization logic.
## Step 1: Authenticate
With the SDK package installed, our first official integration milestone is authentication. The Xsolla SDK requires a valid configuration initialized right as your application starts up. This process establishes a secure connection to Xsolla services, tells the system whether you are testing or running live transactions, and prepares the billing client for user interaction.
### Setting Up the Code Context
In a native Android environment, this initialization logic lives directly inside your main activity's lifecycle. Open your main game activity file and navigate to the `onCreate()` method.
Head over to the Xsolla [**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget), select the **Authentication** tab, and grab the ready-to-use configuration snippet. You will paste this directly into your `onCreate()` method:
```java
import com.xsolla.android.mobile.*;
@Nullable
private BillingClient mBillingClient;
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(), // Test project
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow() // Test login ID
)
);
final Config config = new Config(
configCommon,
configIntegration,
Config.Payments.getDefault(),
Config.Analytics.getDefault()
);
// Inside onCreate(), after creating Config:
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener((billingResult, purchases) -> {
// Handle purchase completion - see Finalize Purchase
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected from Xsolla services.");
}
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (!billingResult.isSuccessful()) {
Log.e(TAG, "Connection failed: " + billingResult.getResponseCode());
return;
}
}
});
```
**Transitioning to Production:** For our walkthrough using the clicker game, the default demo IDs will get us up and running immediately. However, once you are ready to take your game live, you must log into your Xsolla Publisher Account, locate your unique **Project ID** and **Login ID**, and swap them into this configuration block. For more advanced options like custom identity provider routing, check the official Xsolla configuration documentation.
## Step 2: Load Catalog
Once your game successfully establishes a connection to Xsolla services, the next step is pulling your virtual store data. The Xsolla SDK manages your catalog dynamically from the cloud, meaning any updates to item names, images, or regional pricing on your Publisher Account dashboard will update in your game automatically without requiring a new app update.
### Implementing the Catalog Query
To fetch your inventory details, you need to build a query targeting the specific product IDs you want to display.
```java
mBillingClient.queryProductDetailsAsync(
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // Test product SKU
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build(),
(billingResult, productDetailsList) -> {
// Launch purchase - see Purchase Product
}
);
```
## Step 3: Purchase Product
With the local catalog successfully loaded, we can now use that data to trigger a real transaction. When a player taps an item in your store UI, the Xsolla SDK intercepts the action and handles the heavy lifting, launching a secure overlay known as the **Xsolla Pay Station**. This overlay gives your users access to over 1,000 localized payment options natively inside your app.
### Launching the Checkout Flow
To start the billing process, you pass the `ProductDetails` object retrieved from your Step 2 catalog query into the SDK's billing flow method.
Grab the initialization snippet from the **Purchase Product** tab of the Integration Widget and map it to your store button's click listener:
```java
// Inside productDetails callback (from Load Catalog):
if (billingResult.isSuccessful() &&
productDetailsList != null && !productDetailsList.isEmpty()) {
mBillingClient.launchBillingFlow(
activity, // Your Activity reference
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetailsList.get(0))
.build()
))
.build()
);
} else {
Log.e(TAG, "No products available: " + billingResult.getResponseCode());
}
```
### Simulating a Completed Transaction
Because we enabled sandbox mode back in **Step 1**, you can test this complete payment cycle immediately without worrying about hidden credit card charges. When the Pay Station UI slides onto the screen, choose the **Credit/Debit Card** option and utilize one of Xsolla's official mock testing profiles:
| Card Brand | Test Card Number | Expiration | Security Code (CVV) |
| --- | --- | --- | --- |
| Visa | 4111 1111 1111 1111 | Any future date | Any 3 digits |
| Mastercard | 5555 5555 5555 4444 | Any future date | Any 3 digits |
Inputting these credentials simulates a successful, fully cleared authorization loop, prompting the SDK to pass a success token back to your application state.
## Step 4: Finalize Purchase
The final link in our monetization loop is listening for the transaction results and securely awarding the virtual item to the player. Launching the checkout UI is only half the battle; your game must listen for the callback from Xsolla servers when the player finishes entering their billing information.
Once the purchase is successfully completed, consume the transaction token to award the product to the user.
```java
// Inside onPurchasesUpdated callback:
if (billingResult.isSuccessful() && purchases != null) {
for (Purchase purchase : purchases) {
mBillingClient.consumeAsync(
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build(),
(billingResult, purchaseToken) -> {
if (billingResult.isSuccessful()) {
Log.d(TAG, "Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
} else {
Log.e(TAG, "Consumption failed: " + billingResult.getResponseCode());
}
}
);
}
} else {
Log.e(TAG, "Purchase failed or cancelled: " + billingResult.getResponseCode());
}
```
![a9148935-8a90-4a4e-a5da-17c6a187ed22.png]
*Xsolla Pay Station*
### Validate and Consume
This process consumes the transaction, allowing you to securely grant the virtual item to the player. For troubleshooting error scenarios or exploring advanced implementation options, refer to the official [purchase flow documentation](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android).
## Where to Go Next
Congratulations! You now have a working blueprint for a native Android Xsolla SDK integration. While our clicker game demonstrates the fundamental loop, transitioning a game from a local sandbox clone into a global commercial success requires a few strategic upgrades.
Here is your roadmap for taking your implementation to the next level:
### 1. Hands-On Experimentation: The Extended Example
If you want to poke around a complete, standalone implementation, head back to the [Android Quick Start Guide](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android) and scroll to the bottom to find the [**Extended Example**](https://developers.xsolla.com/sdk/mobilesdk/quick-start/extended-examples/android-example).
- **The Key Difference:** The Pay Station overlay launches immediately upon application boot. It serves as an excellent, isolated sandbox to copy, paste, and test your environment variables without external code interference.
### 2. Secure Your Economy with Server-Side Webhooks
While local client-side confirmation works for initial prototyping, a production title should never rely entirely on the device to validate payments.
- **The Upgrade:** To reduce the risk of fraud, transition your backend architecture to utilize the [**Xsolla Events API**](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api) or webhook-based server validation. This ensures transactions are securely verified server-to-server before items are handed out.
- *Note: To get the webhooks or Events API properly configured for your specific ecosystem, you can easily set it up via your Publisher Account dashboard or reach out directly to your account team at [[email protected]](mailto:[email protected]).*
### 3. The SDK Explorer
To get the most out of this guide, open the [Xsolla SDK Explorer](https://developers.xsolla.com/sdk/demo/) and its [Integration Widget](https://developers.xsolla.com/sdk/integration-widget) side-by-side with your IDE. The widget acts as your codebase foundation, supplying the exact Java snippets needed for each milestone. While we copy-paste that code directly into our game files, we'll use the wider SDK Explorer to configure credentials and check event behavior along the way.
![db34d3d6-4715-424d-b60d-f0303c8a9095.png]
*SDK Explorer - Integration Widget View (Large)*
### 4. Register as a Publisher
The most critical next step is stepping away from the code editor and claiming your home on the web. Head over to the Publisher Account page and register your official [**Publisher Account**](https://publisher.xsolla.com/).
Inside your Publisher Account dashboard, you will follow a simple setup wizard to:
- Generate your permanent, live **Project ID** and **Login ID**.
- Build out your authentic virtual store catalog, replacing generic testing keys with your actual premium items, artwork, and descriptions.
- Theme your **Pay Station** UI wrapper to match your game's unique brand visual identity.
The official documentation contains step-by-step guides for every single toggle inside the Publisher Account dashboard. Take your time exploring the tools, lean on the vibrant developer community if you hit a snag, and good luck launching your game on the global marketplace!
Native iOS — Xsolla SDK 3 Integration Guide
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-ios
**Integrating Xsolla SDK 3 into Your Native iOS Game**
*A step-by-step guide for Swift developers: authentication, catalog loading, purchasing, and validation.*
## Introduction
Xsolla SDK 3 gives native iOS games a direct path to Xsolla's payment infrastructure-without abandoning StoreKit. If you already have a StoreKit project, the SDK slots in as a thin wrapper around the familiar [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) API, adding authentication, Pay Station, and purchase validation on top of what you already know.
This guide walks through the full integration in four discrete steps: authentication, catalog loading, purchasing, and finalizing transactions. Every section pairs the what with the why, so you walk away with an integration you understand-not one you've copy-pasted. **[SDK Explorer](http://developers.xsolla.com/sdk/demo)**
Xsolla provides a live browser-based demo that mirrors the iOS integration exactly.
To configure it for this guide, click the settings at the top center of the screen and choose the following settings:
**Platform** - iOS **Country** - USA
- **Platform** - iOS
- **Country** - USA
- **Store** - App Store
- **Engine** - None
- Disable **Use Server Login**
- **Webhook Mode** - Off
- **Buy Button** - Off
- **Browser Mode** - External
then hit **Apply Changes**.
![6520bb66-2475-436b-8372-4b5e9fe9ceb9.png]
![0b3bd016-af0e-4c61-bc0d-b3905b4666be.png]
## Prerequisites
Before starting, make sure you have the following in place:
- **Xcode -** a current stable release. The Xsolla Mobile SDK supports iOS 12.0+, though some Apple External Purchase features require iOS 17.5+.
- **A Swift or SwiftUI iOS project -** targeting iPhone and iPad, with a working StoreKit setup and your product identifiers registered in [App Store Connect](https://appstoreconnect.apple.com/).
- **An Xsolla Publisher Account -** you'll need it to create your item catalog and retrieve your Project ID and Login Project ID. Sign up at [publisher.xsolla.com](https://publisher.xsolla.com/).
- **Your IDs ready -** Project ID (numeric) and Login Project ID (UUID). Find them in [Publisher Account](https://developers.xsolla.com/sdk/publisher-account/getids): Project ID is next to your project name; Login Project ID is under Players → Login → Dashboard.
**ID Precision Matters:** An incorrect Project ID or Login Project ID will still result in a successful connection-but the SDK will return zero results. Double-check both before debugging anything else.
## Installation
Add the [Xsolla Mobile SDK](https://github.com/xsolla/xsolla-sdk-ios) via [Swift Package Manager](https://www.swift.org/documentation/package-manager/):
##### 1. In Xcode, go to File → Add Package Dependencies…
![caeb2128-feed-4a29-8c6f-72456b46f2e3.png]
##### 2. Search for the repository URL:
`https://github.com/xsolla/xsolla-sdk-ios`
![e4fd1a85-ca1a-43c3-9b51-f340e340f870.png]
##### 3. Set the dependency rule to Up to Next Major Version (e.g., 3.8.0) and click Add Package.
##### 4. In the package products dialog, select XsollaMobileSDK and add it to your target.
![2ef2a327-67ce-4bee-8c65-c69a11e32b05.png]
If you manage dependencies via Package.swift instead:
```swift
// Package.swift
dependencies: [
.package(url: "https://github.com/xsolla/xsolla-sdk-ios", from: "3.9.2")
],
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "XsollaMobileSDK", package: "xsolla-sdk-ios")
]
)
]
```
## Step 1: Authentication
Authentication in SDK 3 is handled through a settings object passed to [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue). It bridges Xsolla's authentication layer and StoreKit in a single initialization call-you're not replacing [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue); you're extending it.
### Creating the SKPaymentSettings Object
Import XsollaMobileSDK and construct your [SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) object with your Project ID, Login Project ID, and platform target. Place this in your app's initialization path-[AppDelegate.application(_:didFinishLaunchingWithOptions:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) is the natural home.
```swift
import XsollaMobileSDK
let settings = SKPaymentSettings(
projectId: YOUR_PROJECT_ID, // Numeric, from Publisher Account
loginProjectId: "YOUR-LOGIN-UUID", // UUID string, from Login → Dashboard
platform: .standalone // Use .standalone for mobile
)
// Required: enable payments (false = silent no-op on purchase attempts)
settings.enablePayments = true
// Required for U.S. storefronts: opens Pay Station in external Safari
settings.openExternalBrowser = true
// Enable during development and testing only
settings.useSandbox = true
// Pass into SKPaymentQueue on start and connect SKPaymentTransactionObserver
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
```
**`.enablePayments = false` is a silent fail condition:** If enablePayments is false, purchase calls will appear to succeed but nothing will happen. No error, no callback, no log. Always set this to true explicitly, as it defaults to false. **💡 Best Practice: Configuration Dependent Settings**
Instead of an explicit `false` or `true`, take advantage of environment properties for your Development and Release build configurations.
```text
useSandbox = ProcessInfo.processInfo.environment["XSOLLA_SANDBOX"] == "1"
```
**External Browser and U.S. compliance:** As of April 30, 2025, Apple requires apps distributed in the U.S. App Store to open external payment links in Safari (not in-app web views). Set `.openExternalBrowser = true` to comply. In the EU both are allowed: set this to `false` to keep Pay Station within your app, or `true` to route out to the web. Apple charges a different commission for each, see [Payment options on the App Store in the EU](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/). See [storefront detection docs](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront) for region-aware configuration.
### Client-Side Anonymous Authentication
For games that don't require an account system, SDK 3 supports device-based anonymous authentication using a custom user ID. This can be any stable, unique string-a device identifier, a UUID you generate on first launch, or a player handle.
The key requirement is persistence: the ID must survive app restarts so Xsolla can associate purchases with the same user across sessions. [UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) is the right tool for this:
```swift
// Generate Player ID once and persist to UserDefaults
func resolvedPlayerID() -> String {
let key = "xsolla_player_id"
if let existing = UserDefaults.standard.string(forKey: key) {
return existing
}
let newID = UUID().uuidString
UserDefaults.standard.set(newID, forKey: key)
return newID
}
settings.customUserId = resolvedPlayerID()
```
If your game already has an account system backed by Xsolla Login, you can provide the login JWT directly instead:
```swift
// When using Xsolla Login for account management
settings.customLoginToken = yourXsollaLoginJWT
```
**💡 Best Practice: Wrapping Settings in a Provider Class**
Rather than scattering SDK initialization across your codebase, it's good practice to encapsulate it in a dedicated store manager class. This makes the integration easy to test, mock, and extend-especially useful when you want to support both sandbox and production modes via a build flag:
```swift
class XsollaStoreProvider {
init(projectId: Int, loginProjectId: String, sandbox: Bool) {
// Create SKPaymentSettings object
let settings = SKPaymentSettings(
projectId: projectId,
loginProjectId: loginProjectId,
platform: .standalone
)
// Configure settings
settings.enablePayments = true
settings.openExternalBrowser = true
settings.useSandbox = sandbox
settings.customUserId = resolvedPlayerID()
// Start SKPaymentQueue and connect observer
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(transactionObserver)
}
}
```
### Configuring URL Schemes and Redirect Handling
Pay Station and Xsolla Login use deep links to return the user to your app after payment and authentication flows complete. You must register a URL scheme and wire it through your settings.
In Xcode, select your target → Info tab → URL Types section. Add a new entry and set its URL Scheme to your bundle identifier (e.g., com.yourcompany.yourgame). You can use the variable $(PRODUCT_BUNDLE_IDENTIFIER) so it automatically tracks your target's ID.
![ea960ecd-33e1-4c32-b6ee-ce71ecb42537.png]
Then wire those redirects into your settings object:
```swift
let bundleID = Bundle.main.bundleIdentifier ?? "com.yourcompany.yourgame"
// Pay Station returns here after a completed purchase
settings.payments.redirectUrl = "\(bundleID)://xsolla_confirm/payment"
// Xsolla Login returns here after authentication callbacks
settings.redirectUrl = "\(bundleID)://auth/callback"
```
Finally, forward incoming URLs to the payment queue in your [app delegate](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) or scene delegate:
```swift
// For AppDelegate
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
SKPaymentQueue.default().open(url)
return true
}
// For SwiftUI scene lifecycle
// Add .onOpenURL { url in SKPaymentQueue.default().open(url) }
// to your root view
```
**💡 Best Practice: Pre-Warming Pay Station Connections**
Cold-launching Pay Station on first purchase can take several seconds. DNS resolution, TLS handshakes, and spinning up [SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) all compound. On slower connections this delay is noticeable enough to cause players to question whether their tap registered.
Pre-warming eliminates most of this lag. The strategy is to start warming the network stack and the Xsolla authentication handshake at app launch-before the player ever opens the store. [SFSafariViewController.prewarmConnections(to:)](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller/prewarmconnections(to:)) has been available since iOS 15:
```swift
import SafariServices
class XsollaStoreProvider {
private var prewarmSessions: [URLSessionDataTask] = []
func prewarm() {
// 1. Pre-warm Safari's network connections to Xsolla endpoints
let endpoints = [
"https://secure.xsolla.com",
"https://sandbox-secure.xsolla.com" // include in debug builds
]
let urls = endpoints.compactMap { URL(string: $0) }
prewarmSessions = SFSafariViewController.prewarmConnections(to: urls)
// 2. Trigger catalog load early to warm the auth handshake
loadProducts()
}
}
```
Call `prewarm()` during app initialization-not when the store UI opens. The goal is to have the warm sessions ready by the time the player's thumb reaches the buy button.
## Step 2: Loading Your Catalog
Before your app can display prices or initiate purchases, it needs to fetch the corresponding [SKProduct](https://developer.apple.com/documentation/storekit/skproductsrequest) objects from Apple. SDK 3 doesn't add a new catalog API-you use the standard [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest). The SDK's role here is ensuring that the product identifiers in your app match those registered in the Xsolla Publisher Account.
### Creating Items in Publisher Account
Log in to [Publisher Account](https://publisher.xsolla.com/), select your project, and navigate to its Items Catalog.
![342d483c-3495-4eae-b4fd-79ec1ce3d25d.png]
For SDK 3 native integration, you must use the **Virtual Items** type-other item types such as **Currency Packages** are not returned by the SDK's StoreKit path.
![d8093b98-f877-459e-9aa0-18bbf485991c.png]
For each item, you'll need to provide:
- A SKU matching one of your `.storekit`
- Name, description, and optionally an image
- A default price (e.g., $0.99 for your entry-level package)
![751b1805-3309-40e7-b130-1618c76cb5bd.png]
You can populate the catalog manually, import via JSON, or migrate from [App Store Connect](https://appstoreconnect.apple.com/) or Google Play directly. Once your catalog is set up, flip every item to Available before testing.
Status must be set to **Available**-unavailable items are silently excluded from query results
![a49732cc-cce2-492f-a8a4-b3dcc51c830d.png]
### Requesting Products via SKProductsRequest
After authentication is initialized, create an [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest) with the set of SKUs you want to load. Product identifiers are case-sensitive strings-they must match exactly what's in both [App Store Connect](https://appstoreconnect.apple.com/) and your Publisher Account catalog.
**Log `.invalidProductIdentifiers` in development:** SKProductsResponse includes an `invalidProductIdentifiers` array containing any SKUs Apple couldn't resolve. In production this array is silent-nothing is returned and nothing fails. Log it during development; a non-empty array almost always means a SKU mismatch between your app, [App Store Connect](https://appstoreconnect.apple.com/), and Publisher Account.
```swift
import StoreKit
class ProductLoader: NSObject, SKProductsRequestDelegate {
var loadedProducts: [SKProduct] = []
func loadProducts(skus: [String]) {
let identifiers = Set(skus)
let request = SKProductsRequest(productIdentifiers: identifiers)
request.delegate = self
request.start()
}
// SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest,
didReceive response: SKProductsResponse) {
loadedProducts = response.products
if !response.invalidProductIdentifiers.isEmpty {
print("[Xsolla] Invalid SKUs: \(response.invalidProductIdentifiers)")
}
}
}
```
**💡 Best Practice: Hardening the Request for Real-World Conditions**
In production, [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest) can fail silently on poor connections or mid-session network changes. A minimal hardening strategy adds a small delay after initialization and wraps the request in error handling with retry capability:
```swift
func loadProductsWithRetry(skus: [String], attempt: Int = 0) {
// Brief delay on first load to let SDK initialization settle
let delay: TimeInterval = attempt == 0 ? 0.5 : 2.0
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
let request = SKProductsRequest(productIdentifiers: Set(skus))
self.activeRequest = request
request.delegate = self
request.start()
}
}
func request(_ request: SKRequest, didFailWithError error: Error) {
print("[Xsolla] Product request failed: \(error.localizedDescription)")
// Retry up to 3 times with exponential backoff
if currentAttempt < 3 {
loadProductsWithRetry(skus: pendingSKUs, attempt: currentAttempt + 1)
}
}
```
![7711f5a1-155b-490e-a8a4-1c6ab0840a50.png]
*A catalog loaded in-game*
### Catalog Troubleshooting Checklist
![82fe8dee-248a-4262-a4e7-1a18ab027874.png]
If your catalog loads but returns no products, work through this list before digging deeper:
- **Item availability -** every item in Publisher Account must be explicitly set to Available. Draft and inactive items are excluded from query results.
- **Item type -** only Virtual Items are returned via the SKProductsRequest path. Currency Packages and Bundle types will not appear.
- **Project ID and Login ID -** verify both against [Publisher Account](https://developers.xsolla.com/sdk/publisher-account/getids). An incorrect ID produces a successful connection but zero results.
- **SKU case sensitivity -** `com.yourcompany.stardust_pack` is a different identifier than `com.yourcompany.Stardust_Pack`. Match character-for-character. - **App Store Connect sync -** confirm the same product identifiers exist in [App Store Connect](https://appstoreconnect.apple.com/) and are in a Ready to Submit or Approved state.
# Step 3: Purchasing Products
With products loaded, initiating a purchase is a single line. The SDK wraps the familiar [SKPayment](https://developer.apple.com/documentation/storekit/skpayment) API and routes the request through Pay Station when payment processing begins. The main threading requirement and observer pattern remain exactly as they are in vanilla StoreKit.
### Initiating a Purchase
Pass the [SKProduct](https://developer.apple.com/documentation/storekit/skproduct) for the selected item into [SKPayment](https://developer.apple.com/documentation/storekit/skpayment) and add it to the queue. The critical constraint is that [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) interacts with UIKit and must always be called from the main thread:
```swift
func purchase(_ product: SKProduct) {
// SKPaymentQueue calls UIKit-always dispatch to main thread
DispatchQueue.main.async {
// Set the root view controller so Pay Station has a presentation anchor
if let windowScene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first,
let root = windowScene.windows.first?.rootViewController {
SKPaymentQueue.default().rootViewController = root
}
// Kick off payment, passing in the product to be purchased
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
}
```
**Always set rootViewController before adding to the queue:** Pay Station is presented as a Safari view over your app's window. Without a `rootViewController` set on [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue), the payment UI has no anchor to present from and the purchase will fail or produce unexpected behavior. Set it immediately before calling `add()`.
### Handling Transactions in the Observer
Your class registered via [SKPaymentQueue.default().add(self)](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue) receives every transaction state change. The key behavioral rule: always call [SKPaymentQueue.default().finishTransaction(_:)](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver) for every state-purchased, failed, and restored alike.
Unfinished transactions are durable. They redeliver on every app launch until consumed. Failing to call finishTransaction is a common source of duplicate fulfillment bugs that are extremely difficult to reproduce in testing but very visible to players.
```swift
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
let sku = transaction.payment.productIdentifier
switch transaction.transactionState {
case .purchased:
// Grant items and call finishTransaction to consume
grantItem(sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// Surface genuine errors; ignore user cancellations
if let error = transaction.error as? SKError,
error.code != .paymentCancelled {
handlePurchaseError(error, sku: sku)
}
// Always finish-even on failure
SKPaymentQueue.default().finishTransaction(transaction)
@unknown default:
break
}
}
}
}
```
**Treat .failed and .cancelled differently:** [SKError.paymentCancelled](https://developer.apple.com/documentation/storekit/skerror) is the normal code when a player dismisses the purchase sheet. It does not indicate a problem and should not be shown as an error to the user. All other [SKError](https://developer.apple.com/documentation/storekit/skerror) codes are genuine failures worth surfacing or logging. **💡 Best Practice: Customizing Pay Station Theming**
The [SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) object exposes Pay Station UI parameters. While optional, matching Pay Station's appearance to your game's visual style creates a more seamless experience and signals to players they haven't left your product:
```swift
// Constructor parameters for Pay Station visual customization
let settings = SKPaymentSettings(
...
payStationUIThemeId: .dark, // or .light
payStationUISize: .medium // or .small, .large
...
)
```
![b8202083-c162-4425-9fbb-a1a5d16c36cc.png]
*Pay Station on device*
## Step 4: Finalizing the Purchase
Finalizing a purchase has two components: calling [finishTransaction](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver) (required, covered in Step 3) and calling [validateTransaction](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) before granting the item (strongly recommended). Validation confirms with Xsolla's servers that the payment was processed successfully-it's your defense against replayed or manipulated receipts.
### Client-Side Validation
For client-side validation, call [validateTransaction](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) on the payment queue, wrapping your item-granting logic inside its completion handler. This ensures items are only awarded after Xsolla confirms the transaction:
```swift
func validateAndGrant(transaction: SKPaymentTransaction, sku: String) {
// Call .validateTransaction and handle appropriately
SKPaymentQueue.default().validateTransaction(transaction) { result in
switch result {
case .success:
// Safe to grant the item
self.grantItem(sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
case .failure(let error):
// Validation failed-do not grant the item
// Log for investigation; optionally surface a support prompt
print("[Xsolla] Validation failed for \(sku): \(error)")
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
// Replace non-validated pass in case .purchased with validation helper
func paymentQueue(_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction]) {
...
case .purchased:
// Validate before granting
validateAndGrant(transaction: transaction, sku: sku)
case .failure:
...
...
}
```
**Always finishTransaction inside the validation callback:** Notice that `finishTransaction` is called inside both the success and failure branches of the validation callback. This matters: you don't want an unvalidated transaction looping forever. If validation fails, finish the transaction, log it, and let your support team investigate via the [Publisher Account](https://publisher.xsolla.com/) transaction logs.
**Server-side validation for production:** Client-side validation is a good starting point and appropriate for many games. For high-value economies or competitive games where fraudulent item grants would have meaningful impact, consider migrating to server-side validation using [Xsolla's webhook system](https://developers.xsolla.com/sdk/publisher-account/webhooks). Server-side validation is harder to intercept or tamper with, as the receipt never passes through client code you don't control.
## Putting It All Together
Here's the complete initialization sequence, condensed to show how all four steps connect:
```swift
import XsollaMobileSDK
import StoreKit
import SafariServices
class XsollaStoreManager: NSObject {
static let shared = XsollaStoreManager()
var products: [SKProduct] = []
func configure() {
// Step 1: Authentication
let settings = SKPaymentSettings(
projectId: YOUR_PROJECT_ID,
loginProjectId: "YOUR-LOGIN-UUID",
platform: .standalone
)
settings.enablePayments = true
settings.openExternalBrowser = true
settings.useSandbox = ProcessInfo.processInfo.environment["XSOLLA_SANDBOX"] == "1"
settings.customUserId = resolvedPlayerID()
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
// Best practice: pre-warm before the player opens the store
prewarm()
// Step 2: Load Catalog
loadProducts(["com.yourcompany.item1", "com.yourcompany.item2", ...])
}
// Retrieve persisted player ID, create on first launch
private func resolvedPlayerID() -> String {
let key = "xsolla_player_id"
if let existing = UserDefaults.standard.string(forKey: key) { return existing }
let newID = UUID().uuidString
UserDefaults.standard.set(newID, forKey: key)
return newID
}
// Prewarm connections
private func prewarm() {
// 1. Pre-warm Safari's network connections to Xsolla endpoints
let endpoints = [
"https://secure.xsolla.com",
"https://sandbox-secure.xsolla.com" // include in debug builds
]
let urls = endpoints.compactMap { URL(string: $0) }
SFSafariViewController.prewarmConnections(to: urls)
}
private func loadProducts(_ skus: [String]) {
let request = SKProductsRequest(productIdentifiers: Set(skus))
request.delegate = self
request.start()
}
}
// Step 3: Process Purchase Events
extension XsollaStoreManager: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
let sku = transaction.payment.productIdentifier
switch transaction.transactionState {
case .purchased: validateAndGrant(transaction: transaction, sku: sku)
case .failed:
handleError(transaction.error, sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
@unknown default: break
}
}
}
// Step 4: Validation
func validateAndGrant(transaction: SKPaymentTransaction, sku: String) {
SKPaymentQueue.default().validateTransaction(transaction) { result in
if case .success = result { self.grantItem(sku: sku) }
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
extension XsollaStoreManager: SKProductsRequestDelegate {
func productsRequest(_ r: SKProductsRequest,
didReceive response: SKProductsResponse) {
products = response.products
if !response.invalidProductIdentifiers.isEmpty {
print("[Xsolla] Invalid SKUs: \(response.invalidProductIdentifiers)")
}
}
}
```
## Summary
Xsolla SDK 3 integrates with native iOS through four steps, each building directly on StoreKit primitives you likely already have:
- **Authenticate -** create [SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) with your Project ID and Login Project ID, set `enablePayments = true` and `openExternalBrowser = true` for U.S. compliance, configure a stable custom user ID for anonymous auth, and register your URL scheme for Pay Station callbacks.
- **Load Catalog -** use [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest) to pull your items, making sure every Virtual Item in [Publisher Account](https://publisher.xsolla.com/) is set to Available. Log `invalidProductIdentifiers` in development to catch SKU mismatches early.
- **Purchasing -** dispatch to the main thread before calling [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue).add(), set `rootViewController` on the queue as a presentation anchor, and handle all transaction states in your observer-including deferred and failed.
- **Finalizing -** wrap your item-granting logic inside `validateTransaction` to confirm payment server-side before fulfilling. Always call [finishTransaction](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver) in every branch of the validation callback.
The full SDK documentation, including advanced topics like [storefront detection](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront) and server-side webhooks, lives at [developers.xsolla.com/sdk/mobilesdk](https://developers.xsolla.com/sdk/mobilesdk/). The [SDK Explorer](https://developers.xsolla.com/sdk/demo/) is worth revisiting whenever you add new item types or change payment configuration-it gives you a live event log that makes the SDK's behavior visible in a way that debugger logs alone can't match.
## Where to Go Next
There are a couple of natural steps to take from here:
- *Move to [server-side validation](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation) or [Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api)* - Note: Currently you will need to speak to your account manager or email [[email protected]](mailto:[email protected]) to get the Events API configured for your project
- *Explore other [authentication and login methods](https://developers.xsolla.com/api/login/getting-user-token)*
- [*Configure your Pay Station*](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works)
## Resources
| | |
| --- | --- |
| Xsolla Mobile SDK Documentation | Installation, configuration, and advanced integration options |
| SDK Explorer | Configurable interactive demo with live event log for visualizing the full payment flow, and quick-references for all steps |
| iOS Quick Start Guide | Minimal integration to process your first test payment |
| iOS Installation Details | SPM setup including Package.swift configuration |
| iOS Configuration Reference | All SKPaymentSettings properties and payment integration options |
| Finding Your Project IDs | Locating Project ID and Login Project ID in Publisher Account |
| Pay Station Test Cards | Card numbers available to use for testing in Sandbox |
| Setting Up the Transaction Observer | Apple's reference for SKPaymentTransactionObserver |
| SFSafariViewController.prewarmConnections | Pre-warming network connections for faster Pay Station launches |
| SKError - Apple | full list of StoreKit error codes including paymentCancelled |
Unity Mobile — Xsolla SDK 3 Integration Guide
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-mobile
## What We're Building
By the end of this walkthrough, you'll have a fully working Xsolla payment flow integrated into a Unity iOS project - from package installation through to a completed test transaction.
We're using the [*Unity 2D Game Kit*](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098?srsltid=AfmBOoortrFfstSIcxJ_7cOY0gSeNUuf16wGDlP9GXWiqEabgiRvXEDI) as our demo project. The scenario is deliberately simple: a player dies, a popup appears with two options - restart and lose progress, or buy full health and respawn from the latest checkpoint. That's an impulse-buy moment, and it's a perfect fit for the Pay Station implementation.
Here's a quick summary of some specifics used for this walkthrough:
- *Unity version:* 6.3.5
- *Demo project:* Unity 2D Game Kit
- *Xsolla SDK* - *Authentication Method:* Client side Device ID (no login required) - *Payment UI:* Xsolla Pay Station opening in an external browser (Safari), which is the compliant path for iOS in the US right now - *Purchase validation:* Client-side only
**iOS:** Following the April 30, 2025 U.S. court decision, developers may include external payment links in iOS apps. The Xsolla SDK for Mobile is fully compliant with Apple's revised App Store guidelines, supporting both in-app Pay Station flows and link-out payments via Web Shop.
**Android:** Following the October 29, 2025 Epic v. Google injunction, U.S. Google Play apps may use alternative billing solutions, external payment links, and are no longer subject to anti-steering restrictions. The SDK supports out-of-store APK distribution, Google Play Billing, and browser-based checkout - all in one integration.
## Prerequisites
Before picking up this guide, make sure you have the following sorted:
- A Unity project, ideally with your payment trigger already in place. This walkthrough doesn't cover building your game UI - we assume you already know where in your project the Xsolla payment flow is going to live (a popup, a store menu, a button, etc.).
- Unity IAP package installed. The Xsolla SDK builds on top of Unity's In-App Purchasing framework. The advantage of this is that interacting with the Xsolla SDK will feel very familiar, but it does mean that you'll need the Unity IAP package installed in your project before continuing.
- An active Xsolla Publisher Account. We'll walk through everything you need to do *inside* your Publisher Account as part of this guide, but creating and activating the account itself isn't covered here. If you haven't done that yet, head to the Xsolla [Publishing Account Sign Up Page](https://publisher.xsolla.com) and get that set up first.
## Your Reference Resources
The two resources you'll want open as you work through this are the SDK Explorer and its Integration Widget. The [Integration Widget](https://developers.xsolla.com/sdk/integration-widget) is a page on the Xsolla SDK site and a tab within the [SDK Explorer](https://developers.xsolla.com/sdk/demo/) that gives you the full, ready-to-use code for each integration step - that's what we'll be copying directly into our project throughout this guide. We'll also reference the SDK Explorer itself occasionally for configuration and context along the way.
![8b45e7a1-da58-4f13-a4b5-98f15c21348b.png]
*SDK Explorer - Integration Widget View (Large)*
## The Four Stages of Integration
Before we dive in, it's worth understanding the framework we're working within. The Xsolla SDK and SDK Explorer organizes a complete payment integration into four distinct stages:
- Authenticate -> establishing who the player is. Before any transaction can happen, the SDK needs a valid user identity. In our case this is handled silently using Device ID, so the player never sees a login screen.
- Load Catalog -> fetching your products. This is where the SDK pulls your item catalog from Xsolla's backend and registers those products with Unity's IAP layer, making them available for purchase at runtime.
- Purchase Product -> initiating the transaction. This is the moment the player hits buy. The SDK hands off to the Xsolla Pay Station, which handles the payment UI, processes the transaction, and returns a success or failure signal along with your purchase receipt.
- Finalize Purchase -> acting on the result. This is where your game responds to a completed transaction - validating it, granting the item (along with any relevant game code), updating game state, and closing the transaction cleanly.
Each of the four integration steps in this guide maps directly to one of these stages - and both the SDK Explorer and Integration Widget is organized around this same framework, so the relevant code for each stage is always easy to find.
## Step 0: Install the Xsolla SDK Package
In order to even begin monetizing with Xsolla, and before any of the 4 monetization steps can be applied, we need the Xsolla SDK package installed in our Unity project.
The Integration Widget and SDK Explorer both give you the exact Git URL you need. Grab it from there, or directly from the [Github Repo Installation](https://github.com/xsolla/xsolla-sdk-unity#installation) section then in Unity:
- Go to *Window > Package Management > Package Manager*
- Click the *+* icon
- Select *Install package from Git URL*
- Paste the URL and click Install - At time of writing ```text https://github.com/xsolla/xsolla-sdk-unity.git ```
You should now see the Xsolla SDK listed in your Package Manager.
![a39a23ac-02a0-4be0-b0af-24473f42b4b6.png]
*Unity Package Manager confirming Xsolla SDK is installed*
## Step 1: Authenticate
### Set Up the Script
Create an empty GameObject in your scene - we're calling ours *XsollaPay Station*. Tuck it into a sensible spot in your hierarchy, then add a new C# script to it as a component with the same name.
![a9076865-9bb9-41d1-bea5-ba0764301aef.png]
*Adding Empty Game Object to project hierarchy*
![4570c4b6-d845-4433-9c28-07902a354821.png]
*Attaching Script to Game Object*
Clear out the default Unity script boilerplate, then head to the SDK Explorer to understand what is required for authentication. When your ready to write some code, head to the Integration Widget. Select the *Authentication* tab and copy the full class it gives you - this is the code in the right context, rather than just a snippet.
![99bd602a-076e-4efb-bc80-368e633b5abd.png]
*Integration Widget with code for Step 1: Authenticate*
Paste that into your script file, then update the class name to match your file name, as this will have been overwritten when you pasted the widget code in.
### A Note on Errors at This Stage
You'll likely see some compile errors straight away. Don't worry - this is expected. The Unity IAP framework requires certain method signatures to be present (in this case `ProcessPurchase` and `OnPurchaseFailed`) even though those methods aren't implemented yet. The SDK Explorer and Integration Widget however, build these up step by step, and so some functions aren't included and explained until future steps where they become relevant. Unfortunately, Unity needs at least the shells of those methods now, to compile cleanly, and so if you want to build and run the project before completing all 4 steps we need to add the require code now.
![3cba3cb4-38a6-463d-ab85-6dbf960016be.png]
*Errors thrown*
Fix this by jumping ahead briefly to the *Purchase Product* and *Finalize Purchase* steps in the SDK Explorer, copying the shells of the `ProcessPurchase` and `onPurchaseFailed` (x2) functions from the Integration Widget, and adding them to your class with their bodies commented out. Once Unity can see the right method signatures, the errors will clear.
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
// Logic to be added here in Step 4
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here (Reviewed in Step3/4)
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here (Reviewed in Step3/4)
return;
}
}
```
We'll come back and implement these functions properly in Steps 3 and 4.
**Info:** This is a known friction point when using the Integration Widget step-by-step. You're not doing anything wrong - it's just how the Unity IAP framework works. Grab the shells early, and you can test each stage as you go.
### Configure Your Project ID and Login ID
Inside the copied code you'll see `SetProjectId` and `SetLoginId` calls with default placeholder values. These point to a generic Xsolla demo account complete with dummy catalog - fine for a quick sanity check, but you'll want to replace them with your own credentials and products. For that you will need to set up your project in your [Publisher Account](https://publisher.xsolla.com).
#### Creating a new project in Publisher Account:
Setting up a project connects your game to your desired Xsolla store configuration which enables you to sell your own catalog and manage that catalog whilst also configuring your payment and monetization settings. To create one:
##### 1. Log into your Publisher Account and click Create Project
![77c304c5-ce02-4dcc-b87e-ea051e921cb9.png]
*Navigating to the Project section of the Publisher Account to create a new project*
##### 2. Fill in the basics
For our demo:
- Project Type: Game
- Release Platforms: Mobile
- Monetization Options: in-game transactions
- Development Stage: Production
- Genre: Action
- Game Engine: Unity
![7a63311f-b6a8-4f73-8e7a-fe10e39e67c2.png]
*Example of completing your project details*
##### 3. Create the project and take note of your new Project ID
#### Setting up a Login Project:
A login project tells your SDK which authentication setup you want to use for your app. This can be configured by both authentication type, but also platform and generally helps you organize how you want to separate and manage your various player bases. To create one:
##### 1. Navigate to the Player section and click Login
In a Publisher Account Project, navigate to the *Player* section in the left side bar and click *Login*.
![652b6676-6212-4285-a40d-a811f60ceb9d.png]
*Navigating to the Login Project dashboard in the Publisher Account*
##### 2. Create a new Login Project
Give it a memorable name reflecting its purpose (we used "client-auth").
![b5aea25c-e995-4388-a1ec-7ea5e87e3488.png]
*Creating a new Login Project*
##### 3. Select Classic Login as the base method
We'll override this in a moment.
![2e8dca45-c0fb-4dad-8eb7-014b8172dab6.png]
*Configuring login project as Classic Login - this will be superseded by Device ID authentication but a default method is required*
##### 4. Enable Login API Integration
This is the critical toggle that unlocks Device ID (client-side) authentication and bypasses the standard login flow.
![43b40fea-3dde-4f94-9031-92d6335b49d9.png]
![35b608ee-1bc1-4991-9f0e-06117a7192b7.png]
*Toggling on API Integration which enables Device ID authentication*
Save those settings and return to your Publisher Account dashboard. You'll now see both your *Project ID* and your *Login ID*.
Head back to VS Code and replace the placeholder values:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(XXXXXX)
.SetLoginId("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.Build();
```
### Set Sandbox to True
While you're in the code, make sure this is set:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
....
.SetSandbox(true)
.Build();
```
Sandbox mode lets you run test transactions without using real money. *Remember to remove this before going live.*
**Warning:** Leaving `IsSandbox = true` in production means real purchases won't process. Set a reminder to flip this when you ship.
### Verify Authentication is Working
Run your game and check the Unity Console. The key things to look for are the ***Initialize finished*** log confirming the store is ready, and ***Authenticate By Saved Token onSuccess*** confirming auth completed. You may also see some intermediate log entries during the auth process - these are normal. The final confirmation you want is ***IsBasedOnDeviceId: True***, which tells you Device ID authentication is working correctly.
You'll also see an error saying something like *"no products were returned from the store"* - that's completely expected at this stage as we haven't set up a catalog yet. That's Step 2.
![bc0104cb-59c8-4670-b147-13e456c2167f.png]
*No products received Error*
## Step 2: Load Catalog
### Create Your Item in Publisher Account
Head to your Project in your Publisher Account and navigate to *Items Catalog > All Items* in the left side panel.
![005f85e4-4301-4d30-8a26-3a9e86496909.png]
*Navigating to the Catalog manager in the Publisher Account Dashboard*
For a new item, click *Create Item > Virtual Item*. Fill in the details:
![a82de719-ed8f-47d8-9b0d-62d63fc535b1.png]
*Creating new Virtual Item*
- *Name:* What players will see during the purchase flow
- *SKU:* The ID you'll use to reference this product in code
- *Description:* Optional, but good practice
- *Price:* Set in real currency (we used $1.99)
- Leave the remaining options as defaults for now
*Important:* Before saving, make sure you mark the item as *Available (at top of page)*. If you don't, the item won't be accessible in your game even if the SKU is correct. This is also the first thing to check if you later see a "no products found" error when you're sure the item exists.
![0d26341a-8583-481c-80b0-3865064b90ea.png]
*Adding a new Virtual Item properties and making it available*
### Connect the Catalog to Your Game
Return to the Integration Widget and select the *Load Catalog* step. You'll see two new pieces of code are being added to your class in this section.
*In your* `Start` function, register your product with Unity's IAP layer:
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("product-sku", ProductType.Consumable);
```
A quick note on what this is doing: the Xsolla backend manages your catalog, but Unity's IAP layer also needs to know at runtime which products to initialize and fetch. `AddProduct` is how you tell Unity's layer what to expect. The `ProductType.Consumable` flag tells Unity that this item can be purchased more than once - important for something like a health upgrade that players might buy repeatedly.
*In your* `OnInitialized` callback, you can optionally iterate through the returned product data to do something with it - for example, populating a store UI with live prices and descriptions on load. We cover an alternative way to utilize this in Step 3 to drive our dynamic price button, so won't be using this code but have shared it here for reference.
```csharp
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
...
// Products available via _storeController.products.all
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
// Display product to user
}
}
```
### Verify the Catalog is Loading
Run the game and check the Console. Look for a log entry confirming *retrieved products finished successfully*, showing retrieved count of 1 (or however many items you added) and the no-products error from Step 1 should now be gone. At this stage it will likely be one of the final logs present.
![9906f29f-0661-42e5-a9b1-deb87f8426b6.png]
*Unity logs confirming products were requested and retrieved successfully*
## Step 3: Initiate a Purchase
### Add the Purchase Code
Head back to the Integration Widget - select the *Purchase Product* step. The key addition here is the `InitiatePurchase` call.
```csharp
public void PurchaseSku(string productID)
{
_storeController.InitiatePurchase(productID);
}
```
This single line is what kicks off the entire Xsolla purchase flow. When called, control hands over to Xsolla's backend: it launches Pay Station and provides all the necessary item information, handles the transaction and interaction, and then fires either `ProcessPurchase` or `OnPurchaseFailed` when it's done. It's intentionally thin - all the real logic lives in your callbacks and on the backend.
**Info:** The external browser behavior (Safari on iOS) is configured in the SDK Explorer under the *Configuration* tab for the Purchase Product step. This is set to *External Browser* by default, which is the correct and compliant choice for iOS in the US right now. Native and Buy Button implementations are also available if you need them.
### Wire Up Your Game Logic
The SDK Explorer code gets you a working purchase trigger - but you still need to connect it to your actual game. For our demo we made a couple of adaptations:
- *Made the initiate purchase dynamic* - instead of hardcoding a product ID in `InitiatePurchase`, we pass it in as a parameter: ```csharp public void PurchaseSku(string productID) { _storeController.InitiatePurchase(productID); } ```
- *Added a* `GetProductPrice` function - this fetches the live price for a given SKU from the initialized product data and returns it as a formatted string: ```csharp public string GetProductPrice(string productId) { if (_storeController == null) return "..."; var product = _storeController.products.WithID(productId); return product != null ? product.metadata.localizedPriceString : "..."; } ```
- *Made the class a Singleton* - since our project uses multiple scenes, we needed global access to the `XsollaPayStation` class from other scripts: ```csharp public class XsollaPayStation : MonoBehaviour, IDetailedStoreListener { public static XsollaPayStation Instance { get; private set; } ... void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); } } ```
- *UI Popup* - In a separate class we then built out a UI pop up which displays the price returned from the `GetProductPrice` function, and selecting this will trigger the `InitiatePurchase` call. Selecting respawn triggers a full reset with all progress lost.
![9207c81d-9382-4ec0-9734-3bad0549579d.jpg]
*Screenshot of the in game UI popup to buy more health and trigger purchase flow*
### Test Your Purchase Flow
Run the game and trigger your purchase. You should see Pay Station open in an external browser window showing:
![3221c7f3-efdb-4148-acad-daea6c56c450.png]
*Xsolla Pay Station opening in the external browser*
- Your product image
- Your game name
- Product name and price (including taxes) from your catalog
- Payment options
For sandbox testing, there's a link to [*test card details*](https://developers.xsolla.com/dev-resources/testing/test-cards/) directly in Pay Station - use these rather than your own card details during development.
Complete the purchase and check your Unity Console. You should see the purchase flow complete: the purchase initiating, Xsolla's backend confirming the order, and Unity IAP closing the transaction (FinishTransaction). You won't see your game react yet because `ProcessPurchase` is still to be implemented in Step 4.
## Step 4: Finalize the Purchase
### Understanding the Return Value
Before we look at the code, one thing worth flagging: `ProcessPurchase` returns different values depending on your validation method. Since we're using client-side validation, we return `PurchaseProcessingResult.Complete` immediately - there's no external system to wait on, so we confirm and close the transaction right away. If you were using server-side validation, you'd return `Pending` instead, holding the transaction open until a backend confirmation arrives.
**Note:** The SDK Explorer defaults to showing the Events API / server-side code. Make sure you check the Configuration tab in the Finalize Purchase step and select Client-Side Only to see the correct code for our approach.
### Implement ProcessPurchase
Here's the `ProcessPurchase` implementation for client-side validation:
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (success)
{
// Purchase is valid - grant the item to the player, then confirm:
}
else
{
// Purchase validation failed - do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Complete;
}
```
**Info:** Note this code snippet is reflective of client side purchase validation only. Server-side or Events API based validation will have additional code.
**Note: Server-side validation for production** — Client-side validation is a good starting point and appropriate for many games. For high-value economies or competitive games where fraudulent item grants would have meaningful impact, consider migrating to server-side validation using [Xsolla's webhook system](https://developers.xsolla.com/sdk/publisher-account/webhooks). Server-side validation is harder to intercept or tamper with, as the receipt never passes through client code you don't control.
### A Note on OnPurchaseFailed
You may notice there are two versions of the `OnPurchaseFailed` callback. That's because Unity IAP has two different listener interfaces, each of which fires a slightly different version of the method. Having both present just means you're covered regardless of which interface is in play. For our project and a client-side validation, no additional logic is needed in either at this time so we can keep the Integration Widget defaults.
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
### Add Your Game Logic
With the Xsolla plumbing done, add whatever your game needs to do following a successful purchase inside the `ProcessPurchase` block. In our demo, that's closing the popup and calling the player respawn function with full health from the latest checkpoint. This will be entirely specific to your project - the key point is that `ProcessPurchase` is where it lives.
### Verify the Complete Flow
Run the game end-to-end. Trigger your purchase flow, complete the transaction in Pay Station, and this time you should see your game react - in our case, the player respawning at the checkpoint with full health.
Check the Console for the finalized purchase confirmation log. You should see the full finalization sequence play out: validation firing (confirming your `ProcessPurchase` implementation triggered the client-side validation path correctly), FinishTransaction closing the transaction on the Unity IAP side, and potentially your own Purchase successful log confirming your game logic ran.
![f62d93da-2076-4f6b-8168-37aea9ef3b7f.gif]
*GIF showcasing key features and flow of final working integration*
## You're Done
That's a complete Xsolla payment integration in Unity for iOS - Device ID authentication, a dynamic catalog, Pay Station via external browser, and client-side purchase validation.
The final class structure you should have:
- *Initialization and authentication* configured with your Project ID and Login ID
- *Catalog registration* with your product SKU(s) declared to Unity IAP
- `InitiatePurchase` wired up to your game UI trigger
- `ProcessPurchase` returning `Complete` immediately and triggering your game's post-purchase logic
- `OnPurchaseFailed` (both variants) present and handling failure gracefully
## Where to Go Next
A few natural next steps from here:
- *Add more products* - extend `AddProduct` and your store UI to support a full catalog
- *Move to* [*server-side validation*](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation) *or* [*Events API*](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api) - if security is a priority (and for real-money transactions it usually should be), the Xsolla Events API or webhook-based server validation is the upgrade path. The SDK Explorer makes it easy to see exactly what changes - Note: Currently you will need to speak to your account manager or email [[email protected]](mailto:[email protected]) to get the Events API configured for your project
- *Explore other* [*authentication and login methods*](https://developers.xsolla.com/api/login/getting-user-token) - Device ID is quick to set up but doesn't persist across device changes. Xsolla supports a full range of login options including email, social, and platform-native auth
- [*Configure your Pay Station*](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works) - Publisher Account gives you control over payment methods, UI theming, and regional settings
- *Your reference resources* - the [Xsolla SDK Site](https://developers.xsolla.com/sdk/) has detailed walkthroughs, quick guides, and videos for every feature covered here and beyond. The [SDK Explorer](https://developers.xsolla.com/sdk/) is worth spending time in once you have a working integration - filtering by stage and watching the logs update in real time gives you a much deeper understanding of what the SDK is doing under the hood.
Good luck - and if you run into anything, the Xsolla developer community and support team are there to help.
Unity Web — Xsolla SDK 3 Integration Guide
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-web
![Demo game - "Buy full health" popup after the player loses their last life triggering a spontaneous purchase opportunity]
*Demo game - "Buy full health" popup after the player loses their last life triggering a spontaneous purchase opportunity*
## What We're Building
By the end of this article, you'll have a fully working Xsolla payment flow integrated into your Unity Web project - from package installation through to a completed test transaction.
We're using the [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098) as our reference project throughout this article. The scenario is deliberately simple: the moment the player loses their last life, a popup appears with two options - buy full health and carry on from where they left off, or restart and lose their game progress. That's a spontaneous purchase moment, and a perfect fit for a Pay Station integration.
When the purchase button is selected, it opens the Xsolla Pay Station natively inside the game. For web that's the recommended route, but you can configure it to behave differently if you'd rather. Once the purchase completes, the player respawns with full health from the latest checkpoint.
![Pay Station]
*Pay Station*
Here's a quick summary of the specifics of this integration:
- **Authentication method:** Server-side, via Custom ID (no login or sign-up for the player)
- **Catalog Management:** Manual
- **Purchase validation method:** Client-side only
> **Note:** Prefer to watch? A video walkthrough of this integration is available here: [Xsolla SDK 3 for Unity Web](https://www.youtube.com/watch?v=RDa6b4O98L8)
## Prerequisites
Before reading this article, make sure you have the following sorted:
- **Unity** - the reference project used in this article uses version 6.3.5 of the Unity Game Engine.
- **A game project that's ready to take a payment flow.** We assume you already know where in your project the Xsolla payment flow is going to go. In our demo it's a game event that fires when the player dies - you want something similar in your own game, wherever it makes sense to offer the player a purchase.
- **Unity IAP package installed.** The Xsolla SDK builds directly on top of Unity's In-App Purchasing framework. If you don't already have it, the Xsolla package install will take care of it for you. *At the time of writing, Unity IAP version 5 isn't supported yet - so if you're installing it separately, check which version you're using.*
- **An active Xsolla Publisher Account.** We'll walk through everything you need to configure inside it, but creating the account itself isn't covered here. If you haven't done that yet, head to the [Xsolla Publisher Account sign-up page](https://publisher.xsolla.com/signup?integration_type=SDK) and get that set up first.
- **A server.** Custom ID authentication on web needs a backend to request tokens from Xsolla. Building that server is outside the scope of this guide - we'll cover what it needs to do at a high level only.
## Your Reference Resources
There are three resources worth having open as you work through this, and worth keeping as a reference for later:
- [**Xsolla SDK docs**](https://developers.xsolla.com/sdk/) - everything you need to understand SDK 3, with documentation for each platform and all the key concepts.
- [**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) - think of this as your interactive documentation. On the left is a game you can play in real time. On the right, by default, you get the real-time log output for your payment flow, where each entry can be opened up and inspected. Along the bottom are four tabs, one for each of the four steps of a payment flow - each gives you the relevant documentation and code for that step, and you can configure each step to match the implementation you're building. The code and docs update in real time to match.
- [**Publisher Account**](https://publisher.xsolla.com) - where you manage everything in your Xsolla ecosystem, such as your authentication system, catalog and payment preferences.
![SDK Explorer - default view]
*SDK Explorer - default view*
There's one more resource that lives inside both the SDK docs and the SDK Explorer worth knowing about: the [**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget). For the simplest implementation path, it hands you complete, *drag-and-droppable* code for each of the four steps of a payment flow, allowing you to set up a working payment flow in a few clicks.
*(This is possible due to the use of template project credentials tied to a template catalog, so be sure to update your login and project IDs before going live.)*
In this guide we use the Integration Widget for the **code structure only**, then update it to use our own project, catalog and configuration.
![Integration Widget window inside the SDK Explorer]
*Integration Widget window inside the SDK Explorer*
## The Four Stages of Integration
The Xsolla SDK and SDK Explorer organize a complete payment integration into four stages, and each step in this guide maps directly to one of them:
- **Authenticate** -> establishing who the player is. For this project, we do this in the background using a Custom ID and a server-issued access token, so the player never sees a login screen.
- **Load Catalog** -> registering your products with Unity's IAP layer so they're available for purchase at runtime.
- **Purchase Product** -> initiating the transaction. The SDK hands off to Pay Station, which handles the payment UI and status, and returns success or failure.
- **Finalize Purchase** -> acting on the result, validating the purchase and granting the item to your player.
## Step 0: Install the Xsolla SDK Package
Before any of the four steps, the Xsolla SDK package needs to be in your Unity project.
To check, open **Window > Package Management > Package Manager** and search for "Xsolla".
![Unity Package Manager with Xsolla SDK listed as installed]
*Unity Package Manager with Xsolla SDK listed as installed*
If you don't have it installed, open the Integration Widget in the SDK Explorer and copy the Git URL command from the Install sidebar panel. Then in the Package Manager:
- Click the **+** icon.
- Select **Install package from Git URL**.
- Paste the URL* and click **Install**.
```text
https://github.com/xsolla/xsolla-sdk-unity.git
```
**Correct at time of writing - always grab the latest URL from the Integration Widget or the [GitHub repo installation section](https://github.com/xsolla/xsolla-sdk-unity#installation).*
![Integration Widget showing the Git install command]
*Integration Widget showing the Git install command*
## Step 1: Authenticate
### Set Up the Script
Create an empty GameObject in your scene - we're calling ours **XsollaPayStation**. Add a new C# script to it as a component, then open the script and remove the template code.
![Hierarchy with the XsollaPayStation GameObject and its script component in the Inspector]
*Hierarchy with the XsollaPayStation GameObject and its script component in the Inspector*
Head to the SDK Explorer, open the Integration Widget and copy **everything** in the **Authenticate** tab into your class. This gives us the initial code structure.
### A Note on Errors at This Stage
You'll see a compile error straight away. That's expected - we're building on Unity IAP, which expects certain functions to be present that are covered in subsequent steps. Hovering over the error tells you exactly which ones are missing: `OnPurchaseFailed` and `ProcessPurchase`.
![VS Code with hover tooltip listing the missing interface members on IDetailedStoreListener]
*VS Code with hover tooltip listing the missing interface members on IDetailedStoreListener*
There's a note at the bottom of the copied code that says these functions come from the Purchase Product and Finalize Purchase steps. So:
- In the Integration Widget, open **Purchase Product** and copy all three functions it includes into your class (`PurchaseSku` and both `OnPurchaseFailed` variants). - The `PurchaseSku` isn't a missing function as far as Unity IAP is concerned, but it is a function we need to make the payment flow work, so you might as well include it now.
- Open **Finalize Purchase** and copy in the `ProcessPurchase` function.
With that, the errors clear and you have the basic structure of the complete payment flow. We'll configure these properly in Steps 3 and 4.
> **Tip:** Now's a good time to rename the class to match your script component (in our case `XsollaPayStation`) - the pasted widget code uses `YourSDKIntegrationBehaviour`.
### Switch to Server-Side Authentication
The Integration Widget is set up for the simplest path, which in most cases is client-side authentication via Device ID. **That isn't available for web**, so we need the web equivalent: authentication via Custom ID, which requires a server. This method is the lowest-friction experience for the player, and the simplest path for web integrations, as it involves no login or sign-up screens and happens completely in the background.
To see what's involved in setting it up, head back to the SDK Explorer, make sure you're on the **Authenticate** step, and open the **Configure** tab where you can set it to **Server-Side Auth**.
![SDK Explorer, Authenticate Step > Configure with Server-Side Auth selected]
*SDK Explorer, Authenticate Step > Configure with Server-Side Auth selected*
Scroll down to the code. There are two things worth calling out:
```csharp
var settings = XsollaClientSettings.Builder.Create()
.SetProjectId(<project-id>)
.Build();
var configuration = XsollaClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("<server-token>")
.SetSandbox(true)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
UnityPurchasing.Initialize(this, builder);
```
- `SetSandbox(true)` - this lets your payment flow run with test transactions and test card details, so you can test quickly without needing to use real money. Remember to remove this before going live or in any production builds.
- `SetAccessToken` - this is where your server hands over the access token, which you pass into your configuration to authenticate the user.
### Defer the Access Token
Follow the `SetAccessToken` link in the SDK Explorer through to the **Configuration** docs page, and go to the **Assign Xsolla access token to the configuration** section.
The **Default** approach passes the token straight in - but for this to work, a valid token has to be known *before* the SDK initializes. That works if you have a login platform that runs before the player enters the game, but for authentication via Custom ID we don't, so we need to pass the token in *after* initialization. For this we need to switch to the **Delayed (deferred)** tab.
![Docs - "Assign Xsolla access token to the configuration" with the Delayed (deferred) tab selected]
*Docs - "Assign Xsolla access token to the configuration" with the Delayed (deferred) tab selected*
The idea is that you build the configuration first, then add the access token asynchronously once it's available. To do this, the original configuration sets a delayed configuration task that calls a `DelayedTask` function, and that function then waits for the server to return the token before updating the configuration:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetDelayedConfigurationTask( DelayedTask() )
.Build();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
var result = await Server.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetSettings(
XsollaStoreClientSettings.Builder.Update(configuration.settings)
.SetProjectId(result.projectId)
.Build()
)
.SetAccessToken(result.accessToken)
.Build();
}
```
With the delayed configuration task set up, we need two more things for this process to work: a server, and something on the client that asks the server for a token.
### The Server (High Level)
If you haven't got a server already, you'll need to set one up. Once you have your basic server running, head back to the SDK Explorer. Making sure you are still in the **Authenticate** step, you'll see the **Overview**, **Server Token**, **Custom ID** and **User Token** tabs. Between them, these cover what your server needs to do, and therefore the code you need to add to run the Xsolla payment flow.
![SDK Explorer Authenticate > Server Token tab with the implementation code]
*SDK Explorer Authenticate > Server Token tab with the implementation code*
In short, some of the key things your server needs to do:
- Request an Xsolla access token using your OAuth client credentials.
- Use that authorization to create the **user** access token for the player's Custom ID.
- Return the token to the game client.
Xsolla's response will include the access token plus a refresh token and expiry times. *In our demo we only forward the access token on, but a production server should store and use all of these so the session persists across timeouts.*
Finally, to connect to Xsolla, the server needs your **client credentials** - which means setting up your project in Publisher Account.
### Set Up Your Project in Publisher Account
**Create the project.** In Publisher Account, create a new project and fill in the basic information. For our demo:
- **Monetization options:** In-game transactions
- **Development stage:** In production
- **Genre:** Action
- **Game engine:** Unity
- Then click **Create**
![Publisher Account - new project details form]
*Publisher Account - new project details form*
Then, **create the Login project.** Go to the **Player** section and create a Login project - this is the system that handles verified player identities.
- A **Standalone** project is fine for our demo. Rename it to reflect what it's doing (we used "AuthViaCustomID").
- Choose **Classic Login** - authorization by Custom ID overrides this base configuration so we won't go into any further detail about what Classic Login normally does.
- Go to **Security**, and create a new **OAuth 2.0 client**. - Make sure **server-to-server connection** is enabled.
- Create and then copy the **Client ID** and **Secret key** into the relevant sections of the server code you took from the SDK Explorer.
![Login project Security > OAuth 2.0 client section]
*Login project Security > OAuth 2.0 client section*
> **Warning:** The client secret belongs on your server only - never put it in your Unity client code.
Back in the Login dashboard you'll now see your **Login ID** and **Project ID**. These need adding to **both** the server and the `XsollaPayStation` class (`SetProjectId` / `SetLoginId`*).
**Technically your Login ID is only needed in your server; however, there's no harm in adding it in your client as well.*
![Login dashboard showing the Login ID and Project ID]
*Login dashboard showing the Login ID and Project ID*
Now everything references your own game project rather than the Xsolla template one.
### Request the Token from the Client
The last task in this process is the client-side of the contract - something that tells the server a new access token is needed for this player. In the SDK Explorer code this is handled by the `Server.GetXsollaTokenAsync()` call in the `DelayedTask` function. It does two key things:
- **Generates or retrieves the player ID** - in our project, we do this via a `GetOrCreatePlayerId` function that stores a GUID in `PlayerPrefs`.
- **Sends it to the server and waits for the token** - which it then passes back to `XsollaPayStation` to feed into the configuration and authenticate the user.
Here's the class from our demo for reference - please note yours will likely differ depending on your setup. The request and response shapes (`gameId` in, `token` out) and `_localServerUrl` match **our** demo server - swap them for whatever your own server expects:
```csharp
using System;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class <your-classname>
{
// Your server's token endpoint
private readonly string _localServerUrl = "<your-server-token-endpoint>";
[Serializable]
private class LoginRequest { public string gameId; }
[Serializable]
private class LoginResponse { public string token; }
public async Task<string> GetXsollaTokenAsync()
{
string gameId = GetOrCreatePlayerId();
var requestBody = new LoginRequest { gameId = gameId };
byte[] bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(requestBody));
using (var request = new UnityWebRequest(_localServerUrl, "POST"))
{
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
await request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
throw new Exception($"Custom ID login failed: {request.error}\n{request.downloadHandler.text}");
var response = JsonUtility.FromJson<LoginResponse>(request.downloadHandler.text);
if (string.IsNullOrEmpty(response.token))
throw new Exception("Login response did not contain a token.");
return response.token;
}
}
public string GetOrCreatePlayerId()
{
const string key = "xsolla_game_id";
if (!PlayerPrefs.HasKey(key))
PlayerPrefs.SetString(key, Guid.NewGuid().ToString());
return PlayerPrefs.GetString(key);
}
}
```
Then point your `DelayedTask` at this class. The documentation shows both the access token and Project ID being returned by the server, which is why its snippet reads `result.accessToken` and `result.projectId`. In our example our server only returns the access token, so this class gives it back as a plain string - which can then be passed straight into `SetAccessToken`. Your Project ID is already set via `SetProjectId` in your initial configuration, so the `SetSettings` block found in the documentation isn't needed.
`GetXsollaTokenAsync` is an instance method, so create an instance of the class in `XsollaPayStation` and call it from there:
```csharp
private readonly <your-classname> _authenticator = new <your-classname>();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
string token = await _authenticator.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetAccessToken(token)
.Build();
}
```
*This is just one way to do it - the details depend on your server. The two key points are what matter.*
### Verify Authentication is Working
The loop's now complete and we're feeding the access token into the SDK asynchronously. A build at this point won't do much, but to check it's working, you can make a WebGL build, open it in the browser, and filter the developer console by "Xsolla" to look for logs that say something like:
- `XsollaToken created (access only); IsBasedOnDeviceId: False` - the token from your server was received (`False` confirms it's not using Device ID as this is not applicable to web builds. This is separate from Custom ID).
- `Authenticate By Saved Token onSuccess` - authentication completed.
- `[XsollaPurchasingStore]: Initialize finished` - the SDK is ready.
These are debug-level logs, so make sure your configuration keeps `.SetLogLevel(XsollaLogLevel.Debug)` from the Integration Widget code.
You'll also see an error highlighting **no products are currently available**. That's expected as we've switched from the Integration Widget's test credentials and project to our own, but haven't created any items in it yet. We will fix that in the next step so you can ignore any error like that for now.
## Step 2: Load Catalog
### Configure the Step
In the SDK Explorer, go to the **Load Catalog** step, open **Configure** and select **Manual entry** - for our demo we're not syncing products from an existing platform store or making programmatic changes to the catalog, so manual entry is the quickest way to get it up and running.
![SDK Explorer Load Catalog > Configurator with Manual entry selected]
*SDK Explorer Load Catalog > Configurator with Manual entry selected*
Back on the **How to** tab, the relevant code is effectively one line - `AddProduct`:
```csharp
var builder = ConfigurationBuilder.Instance(module);
builder.AddProduct("product_sku1", ProductType.Consumable);
builder.AddProduct("product_sku2", ProductType.Consumable);
builder.AddProduct("product_sku3", ProductType.Consumable);
// ...
UnityPurchasing.Initialize(this, builder);
```
This tells Unity IAP which products to include and make accessible in your game. The Integration Widget code you copied earlier already has this in place, however it adds several template products (e.g. `ticket.10`). Add or remove the extra lines depending on how many products you need.
*The Integration Widget's Load Catalog step also adds a loop to* `OnInitialized` *that stores product info for use programmatically, like populating a storefront. We don't need that in our example and so will ignore it.*
Now we need to create our own item in our catalog to call.
### Create Your Item in Publisher Account
In your Publisher Account project, go to **Items catalog > All items** and choose **Create manually**.
![Create new item with Virtual item selected]
*Create new item with Virtual item selected*
Our health pack is a **Virtual item**, so select that and click **Continue**. Then complete the prompts:
- Upload an image.
- Add the name, SKU, description etc. - The SKU is the product ID you will use to call it in game.
- Make it a **paid** item, priced in **real currency**, and set the prices you want.
Leave everything else as default and hit create.
![New virtual item form with the SKU, name and image filled in]
*New virtual item form with the SKU, name and image filled in*
> **Important:** New items are **Unavailable** by default - they won't show up in your game even if you query the correct SKU. Set the item to **Available** when you create it. If you missed that as part of the creation flow, or need to update it after the fact, don't worry - you can change it from the item catalog after it's created. This is also the first thing to check if you get a "no products" error later.
![Select item status dialog with Available selected]
*Select item status dialog with Available selected*
### Connect the Item to Your Game
Take your new SKU(s) and drop them into your `AddProduct` line(s):
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("buy-full-health", ProductType.Consumable);
```
### Verify the Catalog is Loading
If you were to build the project again now, the "no products" error from Step 1 should be gone and instead you'll see something similar to:
- `ProductsRequest: products=["product-sku"]` - the product being requested.
- `RetrieveProducts finished successfully. Restored: 0, Retrieved: n` - followed by the product data you've just added (SKU, title, price).
![Console showing RetrieveProducts finished successfully with the buy-full-health product data]
*Console showing RetrieveProducts finished successfully with the buy-full-health product data*
## Step 3: Purchase Product
### Configure the Step
In the SDK Explorer, open the **Purchase Product** step. Here the configuration controls how Pay Station is presented to the player. We're using **Native in-app UI**, which opens Pay Station inside the game - that's the default and suggested path for web projects because it's a much nicer experience for the player.
*If you'd rather use an external browser or a Buy Button through to a Web Shop, select those to see what you'd change in your code.*
![SDK Explorer Purchase Product > Configurator with Native in-app UI selected]
*SDK Explorer Purchase Product > Configurator with Native in-app UI selected*
The **How to** tab breaks down the code needed into three functions:
- **Initiate the purchase** - this triggers the payment flow and is what your game trigger will need to call. - In our demo this will be triggered on the buy button listener.
- `ProcessPurchase` - the logic to run once the purchase completes. This is mostly handled in Step 4. - In our demo this will trigger the player respawn and max health reset.
- `OnPurchaseFailed` - the failure pathway.
You already copied these functions from the Integration Widget in Step 1. You'll notice there are **two** `OnPurchaseFailed` functions - that's because Unity IAP has two callback signatures, one with a reason and one with a description.
### Update the Purchase Code
Back in your code, swap your new item SKU into the `PurchaseSku` function.
```csharp
public void PurchaseSku()
{
_storeController.InitiatePurchase("<your-product-sku>");
}
```
In the `OnPurchaseFailed` functions, add any logic you need to handle the failure pathway.
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
Debug.Log("Purchase Process has been cancelled by the user");
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
Debug.Log("Purchase Process has been cancelled by the user");
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
### Add a Dynamic Price
In our demo, we pull the price on the button straight from our item in our catalog. To do that we added a `GetProductPrice` function to `XsollaPayStation`:
```csharp
public string GetProductPrice(string productId)
{
if (_storeController == null) return "...";
var product = _storeController.products.WithID(productId);
return product != null ? product.metadata.localizedPriceString : "...";
}
```
Our popup UI class uses this to set the button price, and calls `PurchaseSku` from the button's click listener. *The rest of that logic depends heavily on your project, so we won't cover it here.*
By this stage the player is authenticated via server-side Custom ID, a custom catalog is loading from our Publisher Account project, and the player can initiate a purchase. This will automatically trigger the Pay Station to open and a payment can complete successfully* - which leaves the last step.
*(*It's worth noting if you are building here, that when in sandbox mode the Pay Station UI includes a link to test cards that can be used to verify the flow - please see our "Build and Test" section below for more detail.)*
## Step 4: Finalize Purchase
### Configure the Step
In the SDK Explorer, open the **Finalize Purchase** step and go to **Configure**. For the simplest path, select **Client-side validation**, which means we will be handling the validation without the use of a server or event system.
![SDK Explorer Finalize Purchase > Configurator with Client-side validation selected]
*SDK Explorer Finalize Purchase > Configurator with Client-side validation selected*
Since we copied the code from the Integration Widget earlier, the only relevant code is `ProcessPurchase`. This function calls `Validate`, which uses the Pay Station receipt to verify the purchase. If it's successful, it's then down to your game logic to grant the item.
The Integration Widget code uses Unity IAP's standard deferred confirmation: `ProcessPurchase` returns `PurchaseProcessingResult.Pending` straight away, and `ConfirmPendingPurchase` is called only once validation succeeds:
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
// Validate the receipt before granting items
validator.Validate(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is valid - grant the item to the player, then confirm (unconfirmed
// transactions persist and are redelivered on each app launch).
_storeController.ConfirmPendingPurchase(product);
Debug.Log($"Purchase Validation successful");
}
else
{
// Purchase validation failed - do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
// Returned immediately while the async validation callback is pending
return PurchaseProcessingResult.Pending;
}
```
### Why Keep Pending
Validation runs asynchronously, so `ProcessPurchase` returns before the `Validate` callback fires. Returning `Pending` tells Unity IAP not to finish the transaction yet. If validation fails, or the player closes the game before it completes, the purchase stays unconfirmed and is delivered again on the next launch instead of being lost.
Leave this code as it is - don't switch to `PurchaseProcessingResult.Complete`. That would consume the purchase before your game has validated it and granted the item.
> **Note - server-side validation for production:** Client-side validation is a good starting point, but for high-value economies or competitive games, consider moving to server-side validation or client-side via the Events API.
### Add Your Game Logic
All that's left is to make the game react when the purchase completes. This is specific to your game - in our demo, when validation succeeds we close the popup and respawn the player with full health from the latest checkpoint. The key point is that it lives inside the `success` block of the `ProcessPurchase` function, before the `ConfirmPendingPurchase` call.
## Build and Test
Return to Unity and create a clean build, making sure all your changes are saved. Then:
- Start your server.
- Open your browser and the developer console, and filter by "Xsolla".
- Go to your localhost port.
Straight away you should see the console logs appear: initialize, the token being acquired, authentication, and initialization completing. Further down you'll see the product request going out and the products being retrieved.
![Browser with the build running and the dev console filtered by "Xsolla" showing init/auth/product logs]
*Browser with the build running and the dev console filtered by "Xsolla" showing init/auth/product logs*
Play the game through to your trigger and start the purchase flow. Verify the logs show the purchase initiating, then Pay Station opening in-game (or however you have it configured). You should see your catalog item's info - image and price etc. - alongside the payment details form.
![Pay Station open in-game showing the item image, price and payment form]
*Pay Station open in-game showing the item image, price and payment form*
Because we're in sandbox mode, there's a [**test card**](https://developers.xsolla.com/dev-resources/testing/test-cards/) link right in the Pay Station window. It takes you to a set of test card details you can use to test the payment flow quickly without having to worry about using real card details and money.
![Xsolla docs page with test card details]
*Xsolla docs page with test card details*
Return to your Pay Station window and enter the test card credentials, complete the purchase, and verify your game reacts as expected, signifying visually that the purchase flow completes. In our demo this shows the player respawning from the latest checkpoint with full health. Back in the logs, you can verify the logs confirming the finalization sequence:
- `[XsollaPurchasingStore]: Purchase finished`
- `[XsollaPurchasingStoreValidator]: Validate`
- `FinishTransaction: consuming sku=buy-full-health`
- `Consume finished: sku=buy-full-health quantity=1 consumed.`
- `FinishTransaction finished: sku=buy-full-health consumed 1 unit(s)`
![Player respawned with full health, console showing the transaction finished and product consumed logs]
*Player respawned with full health, console showing the transaction finished and product consumed logs*
## Integration Complete
That's a complete Xsolla payment integration in a Unity Web project - server-side Custom ID authentication, a custom catalog, Pay Station opening natively in-app, and client-side purchase validation.
The final class structure you should have:
- Initialization configured with your Project ID and Login ID, plus a delayed configuration task that sets the access token from your server.
- Catalog registration with your product SKU(s) declared to Unity IAP.
- `PurchaseSku` wired up to your game UI trigger.
- `ProcessPurchase` returning `Pending`, triggering your post-purchase game logic and calling `ConfirmPendingPurchase` once validation succeeds.
- Both `OnPurchaseFailed` variants in place.
Hello Money, Your First Integration with Unreal SDK 3
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unreal-pc
Xsolla SDK 3 reduces every purchase, on any platform, to the same four steps: authenticate the player, load a catalog, start a purchase, and finalize it. This article is the talk Hello Money, Your First Integration with Unreal SDK 3, written out step by step; if you would rather watch it than read it, [the recording is available here](https://youtu.be/zbnJbwVVi9s). Unreal Engine is the newest addition to that lineup, currently available as a pilot release, and this article walks through what those four steps look like there specifically. We will build a complete example from scratch: a real Xsolla Publisher Account, a real catalog item, and a real Pay Station purchase, wired into Crop Out, one of Epic Games' own sample projects.
By the end, there will be a working purchase, confirmed inside a running game, built starting from a completely empty Publisher Account. The walkthrough is built in Blueprints from start to finish, and each step also includes the equivalent C++, since the SDK supports both equally and most teams end up reaching for each at different points in a real project.
**WALKTHROUGH SPECIFICS**
| | |
| --- | --- |
| Engine version | Unreal Engine 5.8 |
| Demo project | Crop Out, a free official sample project from Epic Games |
| Authentication | Silent Device ID sign-in (the player is signed in automatically, with no login form) |
| Payment UI | Xsolla Pay Station, opened in the system's default browser |
| Validation | Client-side, confirmed with Get Inventory Items after the order finalizes |
> **Before you start.** This walk-through builds the whole integration in Blueprints, and Blueprints alone are enough to follow it start to finish. Alongside every step, you will also find what that same step looks like written in C++: not because both are required, but because plenty of developers reading this will want to see it in code rather than nodes. Treat each C++ snippet as a second way of looking at the same idea, worth a look if that is how you prefer to work, and easy to skip entirely if it is not. The C++ itself is worth reading the same way: it is one reasonable way to write each step, not the only correct one. Structure the class differently, name things differently, store the access token somewhere else entirely, and it would still work, as long as the same handful of SDK calls happen in roughly the same order.
## What we're building
We are building on top of [Crop Out](https://www.unrealengine.com/blog/cropout-casual-rts-game-sample-project), one of Epic Games' own official sample projects, available for free from the Samples section of the Epic Games Launcher, or on Fab. It is a small village economy: villagers need food to keep working, and the more they work, the more the village can build, eventually finishing its own monument once enough food is banked. That loop gives us a natural place to hook in a real purchase, since food is something the player can watch grow immediately after paying for it.
Right now, the **Buy Food** button already exists in the game, but it does nothing beyond triggering normal gameplay. By the end of this guide, pressing it will open a real Xsolla checkout, and completing that purchase will drop food straight into the village's economy, the same way any other in-game reward would.
![Crop Out's Buy Food button, currently backed by nothing but normal gameplay.]
*Crop Out's Buy Food button, currently backed by nothing but normal gameplay.*
## Prerequisites
A few things need to be in place before starting:
- Unreal Engine 5.8.
- On Windows, Visual Studio 2022 with the **Game Development with C++** workload installed. On Linux, the standard clang toolchain is enough. Xsolla SDK 3 ships as source code rather than a compiled binary, so your project's own build compiles the plug-in the first time you open it, even if every line of your own gameplay code stays in Blueprints.
- An active Xsolla Publisher Account. If you don't have one yet, the next section walks through setting one up.
> **Note.** That toolchain is only there to compile the plugin itself. A project built entirely in Blueprints still needs it, since the SDK compiles from source the same way either way. It has no bearing on whether you ever open the C++ shown alongside each step below.
## The four stages of integration
However complicated a game's economy eventually becomes, every purchase built on Xsolla SDK 3 breaks down into the same four steps. This guide follows that order from here on.
> **Authenticate**
>
> Establish who the player is. Handled silently here through Device ID, so the player never sees a login screen.
> **Load Catalog**
>
> Fetch your products. The catalog comes from Xsolla's backend, ready to reference the moment the player wants to buy something.
> **Purchase Product**
>
> Start the transaction. Pay Station takes over from here, handling the payment UI and returning a token and an order ID.
> **Finalize Purchase**
>
> Act on the result. Confirm the order's final state, check the item is actually owned, then credit the reward in-game.
These four steps are the smallest complete loop that still does something real. Once this works end to end, you have the whole shape of the integration, and everything else, additional login methods, virtual currency, bundles, coupons, and deeper inventory tools, builds on the same foundation. The SDK's own documentation in the pilot repository on GitHub covers those in more depth; access is granted by [joining the Unreal Engine pilot](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program).
![Unreal SDK GitHub Page]
*Unreal SDK GitHub Page*
## Set up your Xsolla Publisher Account
Every Xsolla integration, on any engine, begins in the same place: the Xsolla Publisher Account. It is the dashboard behind your whole commerce setup. Your catalog lives there, your pricing lives there, and it looks the same whether you are shipping on Unreal, Unity, or something else entirely. Before opening Unreal at all, there are three IDs to collect from it, walked through step by step below.
### Create a project
A project connects your game to its own store configuration: your own catalogue, your own pricing, kept separate from anything else on the account.
- Log into your Publisher Account. This is the dashboard you will land on. ![The Publisher Account dashboard, right after logging in.] *The Publisher Account dashboard, right after logging in.*
- Click **Create Project**, and fill in the basics: a name, your monetization type (in-game purchases, for this walkthrough), your genre, and your engine. None of these choices are permanent, so there is no need to overthink them. ![Filling in the project basics.] *Filling in the project basics.*
- Create the project, and take note of your new **Project ID**. It will be needed shortly, back in Unreal. ![Project ID] *Project ID*
### Create a Login project
Your Project handles what you are selling; a separate Login project handles who your players are. Keeping the two apart is deliberate, since a single game might eventually support several sign-in methods without ever touching its catalog. This is also the step that trips people up first, mostly because that separation is not obvious the first time through.
- Under **Player**, then **Login**, you'll land on a short welcome screen the first time. ![Login's welcome screen, the first time you open it.] *Login's welcome screen, the first time you open it.*
- Create a new Login project. For this walk-through, players sign in using **Device ID**, meaning they are authenticated automatically the moment the game opens, with nothing to type and no form to fill in. A Standard Login project is all that requires. ![Standard Login project, the right choice for Device ID sign-in.] *Standard Login project, the right choice for Device ID sign-in.*
- Inside the new Login project, find **Login API Integration**, off by default. ![Login API Integration, still off, sitting inside the Login project dashboard.] *Login API Integration, still off, sitting inside the Login project dashboard.*
- Switch **Login with device ID** on, and save. ![Switched on. This is what unlocks Device ID sign-in.] *Switched on. This is what unlocks Device ID sign-in.*
> **Easy to miss.** Leaving this toggle off means sign-in fails, with nothing obvious pointing back at this setting as the cause. Turning it on also generates your **Login ID**, a UUID rather than a short number, so it is worth not confusing it with the Project ID from the previous section.
### Grab your OAuth Client ID
- Still inside the Login project, open **Security**, then **OAuth 2.0**, and note the Client ID shown there.
> **Not the same as your Login ID.** This value is easy to overlook, and it is not the same as the Login ID. The Login ID is a UUID; the OAuth Client ID is a separate numeric identifier that the OAuth2 endpoint expects. Mixing the two up tends to pass casual testing and then fail quietly once real traffic hits the game, which makes it a frustrating thing to debug later if it is not caught here.
### Create a virtual item
Finally, something real to sell.
- In the Items catalog, create a new virtual item. This walkthrough uses **Golden Crop**, with a clean SKU such as `golden_crop`, avoiding spaces or special characters that could cause issues later when referencing it from code. ![Golden Crop, taking shape in the Items catalog.] *Golden Crop, taking shape in the Items catalog.*
- Set a real price rather than zero. A free item skips the checkout screen entirely, so a zero price would mean never actually seeing Pay Station later in this walkthrough. ![Pricing Golden Crop, with a live preview of the storefront card.] *Pricing Golden Crop, with a live preview of the storefront card.*
- Mark the item **Available** before saving, the setting people forget most often. ![Mark the item available.] *Mark the item available.*
> 🚫 **Worth double-checking.** Skipping **Available** means the item simply will not appear later, no matter how correct its SKU is, and there is no error message to point you back here.
With that, the setup guide Publisher Account shows for a new project is essentially done: a project, a Login project with Device ID enabled, and one item ready to sell.
![The project's own setup checklist, for reference.]
*The project's own setup checklist, for reference.*
Three IDs collected (Project ID, Login ID, and OAuth Client ID) and one item ready to sell, all done from inside a browser, without opening Unreal yet.
> 💡 **Tip.** Publisher Account's screens are updated from time to time, so if a field looks slightly different by the time you follow this yourself, the official Publisher Account documentation will reflect whatever the current layout is.
## Install and configure the plugin
With those three IDs ready, it is time to bring the plugin into the project itself.
![Crop Out project folder in Windows Explorer, with the Plugins folder and XsollaCropoutSample.uproject]
> **What "ships as source" means.** Xsolla SDK 3 ships as source code rather than a compiled binary. There is no ready-made plugin file to drop in. Instead, the project's own build compiles the plugin the first time it opens, which is why the Visual Studio or clang requirement from earlier matters here specifically, and nowhere else in the project.
- Inside the project's `Plugins` folder, create a new folder for the plugin. This walkthrough uses `Plugins/XsollaSDK`.
- Download a source-only release from the SDK's GitHub releases page, and extract it into that folder. The repository is available to pilot participants; [join the Unreal Engine pilot](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program) to get access. ![Unreal SDK GitHub Page] *Unreal SDK GitHub Page*
- Add the plugin to the project's `.uproject` file. This is the one line that tells Unreal the plugin needs to load.
- Open the project. Unreal prompts you to compile the plugin the first time; accept, and let it finish. ![Unreal prompt listing missing Xsolla modules and asking to rebuild them]
- Open **Edit**, then **Plugins**, and confirm **XsollaSDK** shows up there as **Enabled**.
![Unreal Editor Edit menu with the Plugins entry highlighted]
![Plugins window showing the Xsolla SDK 3 plugin enabled]
Next, the credentials. Open `DefaultGame.ini`, found in the project's `Config` folder, and add a section called `[/Script/XsollaSettings.XsollaSDKSettings]`. The same fields are also available inside the editor itself, under **Project Settings**, then **Plugins**, then **Xsolla SDK**, which writes to the same file automatically. Either way, this is where the three IDs from the Publisher Account go: `ProjectId`, `LoginId`, and `OauthClientId`, alongside an `Environment` field set to `Sandbox`, which routes every call to Xsolla's sandbox endpoints instead of production, so testing never risks spending real money.
![DefaultGame.ini, where ProjectId, LoginId, OauthClientId, and Environment live.]
*DefaultGame.ini, where ProjectId, LoginId, OauthClientId, and Environment live.*
```ini
[/Script/XsollaSettings.XsollaSDKSettings]
ProjectId=<your Project ID>
LoginId=<your Login project UUID>
OauthClientId=<your OAuth2 client_id, an integer>
Environment=Sandbox
```
> **A bSandbox line may also appear.** Once the editor writes to this file, you may notice a `bSandbox` line sitting in the same block. That field is a deprecated leftover, kept only so older code that reads it directly still works, and Unreal keeps it in sync with `Environment` automatically. There is no need to edit it by hand. `Environment` is the setting that actually controls which endpoints the SDK talks to.
> **Before you ship.** Remember to switch `Environment` to `Production` before release. Leaving `Sandbox` set in a live build means real purchases will never actually process.
## How this demo is built
Before working through the four steps themselves, it is worth being upfront about how this particular demo is put together, and just as importantly, about what that structure is and is not.
Every Xsolla call in this demo lives inside a single Actor Component, all of it kicked off from one **Event Begin Play**. That is not because it is the right way to build this, or even a particularly good one; it is simply the easiest structure for watching all four steps happen in one place while learning what each one does. Nothing about the SDK cares where these calls come from. A real project just as often spreads them across a widget, a Game Mode, a subsystem of its own, or wherever else actually fits how that project is organized. Read what follows as one way to see the whole cycle work, not as a pattern to copy into production.
The one piece worth carrying forward regardless of structure is how Login and Store are exposed: both are **Game Instance Subsystems**.
![Xsolla Login Subsystem node in a Blueprint graph]
Unreal creates exactly one instance of each automatically the moment the game starts, and keeps that instance alive for the entire session, so there is never a need to spawn one manually. Wherever a project ends up calling these from, the subsystem itself is always reached the same way: call **Get Game Instance Subsystem**, and pick the class.
![BAC_XsollaPurchaseFlow, one Actor Component walking through all four steps, chosen here for simplicity rather than as a recommended structure.]
*BAC_XsollaPurchaseFlow, one Actor Component walking through all four steps, chosen here for simplicity rather than as a recommended structure.*
This particular Actor Component happens to resolve both subsystems once, track the access token, the loaded catalog items, and the current order ID, and report progress through two events: **On Progress Updated** and **On Flow Failed**. Any HUD or UI listening to those events can react to what is happening without needing to know anything about how Xsolla works underneath, regardless of what ends up calling them in your own project.
> 💡 **Tip.** Subsystems are a general Unreal Engine concept, worth reading up on beyond what is covered here. The engine's own documentation goes deeper into the pattern, including other ways to structure access to them across a project.
**STEP 1 OF 4**
## Authenticate
On **Event Begin Play**, get the Login subsystem, and call **Login With Current Device**: the Device ID path described earlier, with no form and no typed credentials, since the player is simply signed in. Placing a breakpoint on this call marks the exact point where control leaves the Blueprint and hands off to Xsolla. Everything downstream then waits for a genuine round trip to a server, rather than something that resolves instantly.
![Login With Current Device, then OnLoginCompleted, then the access token saved for every step after this one.]
*Login With Current Device, then OnLoginCompleted, then the access token saved for every step after this one.*
> **Login With Current Device and Login With Device ID.** Login With Current Device is a convenience node. It reads the current device's identity for you and passes it to Login With Device ID, the call it wraps. That makes it a good fit for a demo like this one. In a real project, calling Login With Device ID directly lets your own code decide which device information gets sent.
**On Login Completed** fires once that round trip finishes, carrying both a token and an error. On success, the token is broken apart, the access token is saved to a variable (every step from here on needs it), and success is reported through **On Progress Updated**. On failure, execution routes to **On Flow Failed** instead, carrying the error message along with it.
Running the game at this point, with only this much wired up, would succeed and then simply stop, since there is no catalog loaded yet. That is expected.
![Login With Current Device, then OnLoginCompleted, then the access token saved for every step after this one.]
*Login With Current Device, then OnLoginCompleted, then the access token saved for every step after this one.*
#### C++ equivalent
This is the first C++ block in the guide, so a word on how to read it: what follows is not a separate implementation to choose between, it is the authentication step described above, written in code instead of nodes, for anyone who would rather follow along that way. There is more than one reasonable way to structure this in a real project; what matters is resolving the Login Subsystem and calling `LoginWithCurrentDevice`, much like the Get Login Subsystem node does. This particular version reaches the subsystem through `GetWorld()` rather than a direct `GetGameInstance()` call, since the code lives inside an Actor Component rather than an Actor itself, and only Actors expose that shortcut directly.
```cpp
UXsollaLoginSubsystem* LoginSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaLoginSubsystem>();
FOnLoginCompleted OnCompleted;
OnCompleted.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnLoginCompleted);
LoginSubsystem->LoginWithCurrentDevice(OnCompleted);
```
`OnCompleted` here is a dynamic delegate, Unreal's way of providing a callback for an operation that finishes later, in a form that can also be wired up from Blueprints. Binding it with `BindDynamic`, instead of looking the function up by name at runtime, lets the compiler check that `OnLoginCompleted` actually matches the delegate's expected signature, catching a mismatch immediately rather than leaving it to fail later.
Inside `OnLoginCompleted`, an error check comes first. If nothing went wrong, the access token gets saved for use in every step that follows.
```cpp
void UBAC_XsollaPurchaseFlow::OnLoginCompleted(const FXsollaAuthToken& Token, const FXsollaError& Error)
{
if (Error.IsError())
{
return;
}
AccessToken = Token.AccessToken;
}
```
**STEP 2 OF 4**
## Load Catalog
For a setup this simple, one button pointed at one item already known in advance, loading the whole catalog is not strictly necessary; the SKU could just be referenced directly. It is included here anyway because it is part of the pattern, and worth seeing work correctly before relying on it elsewhere.
![Get Virtual Items]
*Get Virtual Items*
Get the Store subsystem, and call **Get Virtual Items**. The same reasoning from Step 1 applies here too: this is another network boundary, with the Blueprint handing off to Xsolla and waiting for a response. Unlike Step 1, this call does not need an access token, since the sandbox catalog can be read anonymously, though a production project might require one depending on how it is configured.
On success, the returned list is stored in an Items variable. This is also where the **Available** toggle from earlier actually matters: forgetting to mark an item available means this list comes back empty, with no other obvious symptom, so it is worth checking first if a catalog ever looks unexpectedly bare.
![Breakpoints landing across Authenticate and Load Catalog, each one a real round trip to Xsolla.]
*Breakpoints landing across Authenticate and Load Catalog, each one a real round trip to Xsolla.*
#### C++ equivalent
Worth repeating here too: this is one way to write the step in C++, not something you need to match exactly. It resolves the Store Subsystem through the Game Instance, much like the Get Store Subsystem node does above, and calls `GetVirtualItems` to pull the catalog down. The function that ends up handling the result is called `OnCatalogLoaded` in this version, though the name itself does not matter here, what matters is the call itself.
```cpp
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnStoreItemsUpdate OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnCatalogLoaded);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->GetVirtualItems(OnSuccess, OnError);
```
Once the call finishes, `OnCatalogLoaded` runs with the full list of items, and the only thing it needs to do is save that list into `CachedItems`, ready to search through the moment the player wants to buy something.
```cpp
void UBAC_XsollaPurchaseFlow::OnCatalogLoaded(const FXsollaStoreItems& Items)
{
CachedItems = Items;
}
```
**STEP 3 OF 4**
## Purchase Product
This is the step where the player actually does something. The Buy Food button is wired to a custom event called **Purchase Product**, and pressing it kicks off everything described below.
Golden Crop is pulled out of the catalog first, and both its SKU and its free flag are checked before anything else happens. That check matters because a free item still returns a perfectly valid response, just with an empty payment token, so skipping it could mean trying to open a checkout screen for something that was never going to produce one.
![Create Payment Token.]
*Create Payment Token.*
Golden Crop is not free in this walkthrough, so **Create Payment Token** is called next, using the SKU and the access token, which creates the actual order on Xsolla's side. A breakpoint here marks that handoff.
#### C++ equivalent: Create Payment Token
Same as before: this C++ is one way to write it, not the only correct way. It searches `CachedItems` for the entry whose SKU matches Golden Crop, and checks `bIsFree`, mirroring what the Blueprint checks first, before doing anything else. If the item isn't free, `CreatePaymentToken` gets called on the Store Subsystem with the SKU and the access token, and `OnPaymentTokenReady` picks up the result.
```cpp
const FXsollaStoreItem* GoldenCrop = CachedItems.Items.FindByPredicate(
[](const FXsollaStoreItem& Item) { return Item.Sku == TEXT("golden_crop"); });
if (!GoldenCrop || GoldenCrop->bIsFree)
{
return;
}
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnPaymentTokenSuccess OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnPaymentTokenReady);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->CreatePaymentToken(GoldenCrop->Sku, OnSuccess, OnError, AccessToken, GoldenCrop->bIsFree);
```
> **If you do sell a free item elsewhere in your game.** Golden Crop is deliberately priced for this walkthrough, so the early return above only ever runs if the SKU lookup itself fails. A genuinely free item in your own catalog is still worth selling through this same flow, just handled slightly further downstream: `CreatePaymentToken` returns a valid order with an empty payment token for a free item, and the correct handling is to skip Open Purchase UI entirely and call `AwaitOrderFinalization` directly, since there is no Pay Station session to open in that case.
On success, a payment token and an order ID come back together. The order ID is held onto for Step 4, and the token is passed into **Open Purchase UI**, the line that actually opens Pay Station.
![Open Purchase UI]
*Open Purchase UI*
#### C++ equivalent: the payment token callback and Open Purchase UI
Once more, since it is easy to forget by this point in a long guide: what follows is an example, not a rule. This callback picks up once `CreatePaymentToken` succeeds, and does what the Blueprint does right after: it holds onto the order ID for Step 4, then passes the token into `OpenPurchaseUI` to actually open Pay Station.
```cpp
void UBAC_XsollaPurchaseFlow::OnPaymentTokenReady(const FXsollaPaymentToken& Token)
{
CurrentOrderId = Token.OrderId;
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
StoreSubsystem->OpenPurchaseUI(Token.Token);
}
```
On desktop, this opens Pay Station in the system's default browser, the same approach other platforms fall back to whenever an external browser is the available option. This call does not freeze the game; only a breakpoint does that. Left running on its own, the game continues normally while the player is on the checkout page, with Unreal simply waiting for a signal to come back. Golden Crop, at its sandbox price, can be paid for with a test card, since nothing in Sandbox ever touches a real payment method.
![Pay Station checkout for Golden Crop in the browser]
**STEP 4 OF 4**
## Finalize Purchase
This last step involves a decision worth explaining, since it is not obvious from the Blueprint alone. Unreal's standalone build has no way to detect a browser window closing, so there is no close event to simply wait for. Instead, the game asks.
**Await Order Finalization** is called with the access token and the order ID, with **On Order Finalized** bound before that call goes out. Underneath, this checks the order's status roughly every two seconds until it reaches a final state, paid, done, or cancelled, then fires once.
![Await Order Finalization]
*Await Order Finalization*
> **Polling and webhooks, in short.** Two terms worth defining before going further, since they come up here without much introduction. Polling means the game itself asks Xsolla, again and again on a timer, whether an order is finished yet. A webhook works the other way around: a server you control sits and waits, and Xsolla sends it a message the moment an order finishes, with nothing to ask for. Explaining either concept in real depth is outside what this guide sets out to do; Xsolla's own documentation on [webhooks and the Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks) is the better place for that.
> 💡 **Polling versus webhooks, here specifically.** This polling happens automatically and needs no extra configuration, which is what makes Await Order Finalization convenient for a first integration like this one. If a project already has its own backend, that backend can observe order completion a different way instead, either through real Xsolla webhooks or through the Events API, configured separately through a setting called `WebhooksMode`. That setting lives in `DefaultEngine.ini` rather than `DefaultGame.ini`, since it belongs to the project's server-side deployment choices rather than its Publisher Account identity, and it is worth reaching for once a backend actually exists to listen. Until then, polling is the simpler and entirely valid place to be.
![The breakpoint hitting on Await Order Finalization, waiting for a final order status]
*The breakpoint hitting on Await Order Finalization, waiting for a final order status*
Once a final status comes back, **Get Inventory Items** confirms the item shows up as owned: real proof the purchase went through, rather than just a status that happened to come back green.
![Get Inventory Items]
*Get Inventory Items*
#### C++ equivalent
Just to say it again, since this is the last one: nothing below is the one correct way to write it. The waiting step translates fairly directly into C++. It binds `HandleOrderFinalized` to `OnOrderFinalized` first, using `AddDynamic` rather than `BindDynamic` since `OnOrderFinalized` is a multicast delegate that can notify more than one listener, then calls `AwaitOrderFinalization` with the access token and the order ID, achieving the same result as the node above.
```cpp
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
StoreSubsystem->OnOrderFinalized.AddDynamic(this, &UBAC_XsollaPurchaseFlow::HandleOrderFinalized);
StoreSubsystem->AwaitOrderFinalization(AccessToken, CurrentOrderId);
```
Once `HandleOrderFinalized` fires, it calls `GetInventoryItems` with the access token, matching the Get Inventory Items node. `OnInventoryLoaded` is where the item's presence actually gets confirmed, checking the returned list for the same SKU purchased earlier, and only once that check passes does the reward get credited in the game.
```cpp
void UBAC_XsollaPurchaseFlow::HandleOrderFinalized(int32 OrderId, EXsollaOrderTerminalStatus TerminalStatus)
{
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnInventoryItemsLoaded OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnInventoryLoaded);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->GetInventoryItems(AccessToken, OnSuccess, OnError);
}
void UBAC_XsollaPurchaseFlow::OnInventoryLoaded(const FXsollaInventoryItems& Items)
{
const bool bOwnsGoldenCrop = Items.Items.ContainsByPredicate(
[](const FXsollaInventoryItem& Item) { return Item.SKU == TEXT("golden_crop"); });
if (bOwnsGoldenCrop)
{
// Confirmed: credit the reward here, the equivalent of Add Resource in Blueprint.
}
}
```
From here, **Get Game Mode** leads into **Add Resource**, set to Food.
![Add Resource]
*Add Resource*
> **This is where your own logic takes over.** Add Resource is a testing command that already exists inside Crop Out, meant originally for the sample project's own QA, and borrowed here as a stand-in for real reward logic. Everything before this node is portable to any Unreal project. This is the exact point where a real project's own inventory or currency system would plug in instead. A failed inventory check routes through On Flow Failed, the same as every other step in this flow.
## Seeing it work
Before running this end to end, clear all four breakpoints, otherwise the game keeps pausing the moment play begins. At this point, the player is authenticated, a real catalog is loaded, a real purchase is wired to a real button, and that purchase gets confirmed before anything is credited. That is the complete cycle: four steps, running back to back, with nothing skipped.
The moment that final node resolves, food jumps immediately, the villagers keep working, and, since there is now enough food banked, the village goes on to finish its monument. That is this integration doing exactly what a real purchase should do: turning a payment into something the player can see and enjoy right away.
![The loop, closed: a completed purchase, reflected immediately in the village's food count.]
*The loop, closed: a completed purchase, reflected immediately in the village's food count.*
## What you've built
That is a complete Xsolla SDK 3 integration in Unreal Engine, built from an empty Publisher Account up to a real, working purchase, following the same four steps every time, regardless of where each call ends up living in an actual project.
- Authentication configured with a real Project ID, Login ID, and Device ID sign-in
- A real catalog, loaded from the Publisher Account and gated by the Available toggle
- A real purchase, wired to the game's own UI and confirmed through Get Inventory Items before anything gets credited
- A C++ equivalent for every step, for projects that live outside Blueprints, or that mix both
## Where to go next
- **Add more products.** Extend past a single SKU into a full catalog, the same way Step 2 already supports it.
- **Move to server-side validation.** Once a backend exists to receive them, switching to real webhooks or the Events API, through `WebhooksMode` in `DefaultEngine.ini`, is generally a better fit for real-money economies than client-side polling.
- **Explore other login methods.** Device ID is fast to set up, but it does not persist across a player switching devices. Xsolla supports a full range of other options, including email, social, and platform-native authentication.
- **Configure Pay Station itself.** The Publisher Account also controls payment methods, UI theming, and regional settings for the checkout screen players actually see.
- **Read the source.** The full plugin and its own documentation, including the API reference for every subsystem covered here, are available on GitHub to pilot participants. [Join the Unreal Engine pilot](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program) to get access.
- **Working in Unity instead?** A companion walkthrough covers these same four steps: [SDK 3 for Unity Mobile](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-mobile/) and [SDK 3 for Unity PC](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-unity-pc/).
Good luck, and if anything here does not behave as described, the Xsolla developer community and support team are there to help.
Unity PC — Xsolla SDK 3 Integration Guide
https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-unity-pc
*Xsolla Purchase Flow Demo*
This guide primarily benefits developers targeting off-platform PC distribution and Epic Games Store with dual billing. For testing and release, you'll want to set up a web shop and/or the Xsolla Game Launcher via your Publisher Account. For this guide though, you can follow along without them.
## What We're Building
We're using the [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098) as our demo project. The scenario is simple: a player dies, a popup appears offering two options. Restart and lose progress, or buy a full health restoration and respawn from the last checkpoint. That's a classic impulse-buy moment, and it's a perfect fit for Pay Station.
This guide covers the complete integration: *Authenticate*, *Load Catalog*, *Purchase Product*, and *Finalize Purchase*. Follow it end-to-end to build the flow yourself, or jump to the step you need. Either way, everything here maps directly to the SDK Explorer and Integration Widget, so you'll always know where to find more detail.
Here's what we're working with:
- *Unity version:* 6.3.5
- *Demo project:* Unity 2D Game Kit
- *Xsolla SDK*
- *Authentication method:* Device ID (no login required)
- *Payment UI:* Xsolla Pay Station opening in the user's default browser (desktop default)
- *Purchase validation:* Client-side only
## Prerequisites
Before you get started, make sure you've taken care of the following:
- **Unity installed.** This guide uses Unity 6.3.5. Unity 2022.3+ with IAP support should work.
- **A Unity project to work with.** If you don't have a project ready, you can follow along with the [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098), which is what we use throughout this guide.
- **Unity IAP package installed.** The Xsolla SDK integrates with Unity's In-App Purchasing framework and requires the IAP package as a dependency.
- An **active Xsolla Publisher Account.** We'll walk through everything you need to do inside your Publisher Account as part of this guide, but creating the account itself isn't covered. If you haven't done that yet, head to the [Xsolla Publisher Account Sign Up Page](https://publisher.xsolla.com) and get that set up first.
## Your Reference Resources
Whether you're following along with this article or going deeper afterwards, there are three places you'll want to know about.
The [**Xsolla SDK Documentation**](https://developers.xsolla.com/sdk) is your main reference. From here, you can find guides for creating your Publisher Account, other integration flows, and links to the tools below.
The [**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) is a playable, interactive demo of the SDK. You can walk through the four steps of monetization by testing purchases in-game and seeing the logs output in real-time.
The [**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget) is an interactive code reference available in the sidebar of the SDK documentation. It lets you step through each stage of the integration and see exactly what code gets added at each point. This is what we'll be copying from throughout this guide.
![fe51f1dc-037a-4b4b-ad6e-8da36ce1f13e.png]
*SDK Explorer - Integration Widget View (Large)*
In summary, SDK Explorer is the playable demo, while Integration Widget serves as the code reference. Both cover the same four steps but address different needs.
## The Four Stages of Integration
The Xsolla SDK organizes a complete payment integration into four distinct stages:
- **Authenticate:** establishing who the player is. Before any transaction can happen, the SDK needs a valid user identity.
- **Load Catalog:** fetching your products. The SDK pulls your item catalog from Xsolla's backend and registers those products with Unity's IAP layer, making them available for purchase at runtime.
- **Purchase Product:** initiating the transaction. The moment the player hits buy, the SDK hands off to Pay Station, which handles the payment UI, processes the transaction, and returns a success or failure signal along with your purchase receipt.
- **Finalize Purchase:** acting on the result. Your game responds to a completed transaction by validating it, granting the item, updating game state, and closing the transaction cleanly.
If you keep these four stages in mind, you'll always know where you are in the process and where to look in the SDK Explorer or Integration Widget for reference.
## Step 0: Install the Xsolla SDK Package
The Integration Widget gives you the exact Git URL you need. Grab it from there, or directly from the [GitHub repo](https://github.com/xsolla/xsolla-sdk-unity#installation):
```text
https://github.com/xsolla/xsolla-sdk-unity.git
```
Then in Unity:
- Go to *Window > Package Manager*
- Click the **+** icon in the top left
- Select *Install package from Git URL*
- Paste the URL and click **Install**
You should now see the Xsolla SDK listed in your Package Manager.
![51c47e41-8da6-4897-af39-1f8c66a51414.png]
*Add SDK via Github URL*
![591ca407-bf4e-43d5-b25e-060617cc184b.png]
*Xsolla SDK Installed via Package Manager*
## Step 1: Authenticate
### Set Up the Script
Create a new empty GameObject in your scene hierarchy (we placed ours under a "System" label) and add a new C# script to it as a component. We're calling ours `XsollaPayStation`.
![cc9e346f-8426-4bcf-856f-75f83c50066f.png]
*Create an Empty Object*
![5edab766-969c-455f-90c9-ebffdc6fbd88.png]
*Add XsollaPayStation.cs to your object*
Head to the Integration Widget and select the **Authenticate** tab. This step provides the full class. Copy it and paste it over your script file, then update the class name to match your file name. Later steps will provide snippets to add to this class.
```csharp
using System;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using Xsolla.SDK.Store;
using Xsolla.SDK.Common;
using Xsolla.SDK.UnityPurchasing;
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
IStoreController _storeController;
IExtensionProvider _storeExtensions;
void Start()
{
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder.Instance(module)
// ... product registration (see "Load Catalog" step)
;
UnityPurchasing.Initialize(this, configurationBuilder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_storeExtensions = extensions;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
Debug.LogError($"Initialization failed: {error}");
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
Debug.LogError($"Initialization failed: {error}. Details: {message}");
}
// ... ProcessPurchase, OnPurchaseFailed (see "Purchase Product" and "Finalize Purchase" steps)
}
```
![338f6d3f-ef47-420f-8ae6-a91ac0d806dd.png]
*Step 1. Authentication*
**Expected Compilation Errors:** The code from the Authenticate step does not satisfy the full Unity IAP interface contract. You'll see compile errors because `PurchaseProcessingResult` and `OnPurchaseFailed` are not yet implemented. Add the following placeholder methods to resolve them. We'll add the proper implementation for `OnPurchaseFailed` in Step 3: Initiate a Purchase and `PurchaseProcessingResult` in Step 4: Finalize Purchase.
**Placeholder methods to resolve compile errors**
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
throw new NotImplementedException();
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
throw new NotImplementedException();
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
throw new NotImplementedException();
}
```
This is a known friction point when using the Integration Widget step-by-step. The Widget builds up these methods across multiple steps, so some interface requirements won't be satisfied until later.
### Configure Your Project ID and Login ID
Inside the copied code you'll see `SetProjectId` and `SetLoginId` calls with default placeholder values. These point to a generic Xsolla demo project. Fine for a quick sanity check, but you'll want to replace them with your own credentials to work with your own catalog. For that, you need to set up your project in your [Publisher Account](https://publisher.xsolla.com).
#### Creating a New Project in Publisher Account
- Log into your Publisher Account and click **Create Project** in the sidebar
![32dd095f-82ea-4c1e-a00b-368078285eee.png]
*Publisher Account: Create New Project*
- Fill in the basics. For this guide:
- Project Type: Game
- Release Platforms: PC
- Monetization: In-game transactions
- Development Stage: Concept
- Genre: Adventure
- Game Engine: Unity
![5e8ae1cc-0851-4568-9111-5c0ebe288afa.png]
*Completed Project Details*
- Click **Create Project** and take note of your new **Project ID**
![f0c2fa2a-8058-468b-9173-50ee1133a0e1.png]
#### Setting Up a Login Project
A login project tells your SDK which authentication setup you want to use for your app. This can be configured by authentication type and platform. To create one:
- In your Publisher Account project, navigate to **Players > Login** in the sidebar
![0f5e74d8-5b51-414e-bef3-570fbacbe5f0.png]
- Create a new Login Project
![ed468261-aabb-4c45-a9ec-24815e9d8d10.png]
*Standard Login Project*
- Select **Classic Login** as the base method.
![0cfe4ce8-58ad-45f0-8dee-95cd22a9ae17.png]
*Configuring default method for login project as Classic Login*
- Click **Configure** and navigate to **Login API Integration**
![cab0aaff-3804-4c1e-a549-15d4c11b3091.png]
- Make sure **Login with Device ID** is enabled
![6d437782-10c4-4678-95ed-e29d0ce10e4d.png]
*Toggling on API Integration to enable Device ID authentication*
**Device ID is not the standard PC login flow:** Device ID authentication is not the typical approach for PC, but it gets us up and running the fastest for this guide. For a production release, see authentication methods for all available options.
Save your settings and return to the login dashboard. You'll now see both your **Project ID** and your **Login ID**.
![2c7e1788-8d42-4e12-b9b9-fbd449e36466.png]
Head back to your editor and replace the placeholder values:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(YOUR_PROJECT_ID)
.SetLoginId("YOUR-LOGIN-UUID")
.Build();
```
### Verify Authentication is Working
Run your game and check the Unity Console. You're looking for log entries confirming that the store initialized successfully and authentication completed.
You'll also see an error about no products being returned. That's completely expected at this stage since we have not loaded the catalog yet.
![8b7b445e-e128-4d28-89d9-44022466a116.png]
*Error: No Products Available*
## Step 2: Load Catalog
### Create Your Item in Publisher Account
- Head to your project in your Publisher Account and navigate to **Item Catalog > All Items** in the sidebar.
![216553c1-e6b5-433c-bd53-b0bc9f8cdf82.png]
*Navigating to the Catalog manager in the Publisher Account Dashboard*
- Click **Create Manually > Virtual Item**.
![5cd34a17-e0fa-4efe-91d6-a6cae7e6764a.png]
![3db58e33-96f1-4ca7-8f27-e8f33b99b982.png]
- Fill in the details:
- **SKU:** This maps to your item ID in-game.
- **Name:** What players should see during the purchase flow.
- **Price:** Set in real currency.
- Leave the remaining options as defaults for now
![2c605619-5d63-4d80-809c-2616c7c15594.png]
**Mark the item as Available!** Before saving, make sure you toggle the item to Available at the top right of the page. Without this, the item won't appear in your game even if the SKU is correct. This is the first thing to check if you later see a "no products found" error.
- Scroll down and click **Create Item**.
### Connect the Catalog to Your Game
Return to the Integration Widget and select the **Load Catalog** step. There are two pieces of code to add.
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
void Start()
{
// ... settings, configuration, module initialization (see "Authenticate" step)
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("ticket.10", ProductType.Consumable)
.AddProduct("ticket.20", ProductType.Consumable)
.AddProduct("ticket.30", ProductType.Consumable);
// ... UnityPurchasing.Initialize() invocation (see "Authenticate" step)
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
// ... callback initialization (see "Authenticate" step)
// Products available via _storeController.products.all
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
// Display product to user
}
}
}
```
**First**, in your `Start` function, set up the configuration builder to register your product with Unity's IAP layer:
**Register your product SKU**
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("full-health", ProductType.Consumable);
```
`ProductType.Consumable` tells Unity this item can be purchased more than once. Important for something like a health upgrade that players might buy repeatedly. If the Integration Widget includes multiple sample products, strip them down to just yours.
**Second**, the `OnInitialized` callback is where you capture references to the store controller and extensions. Storing these as class fields (`_storeController` and `_storeExtensions`) makes them available to the rest of your code for initiating purchases, looking up prices, and validating transactions in later steps.
**Store references in OnInitialized**
```csharp
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_storeExtensions = extensions;
}
```
**Retrieving product info from the controller:** Once the controller is stored, you can iterate through the loaded catalog to pull each product's ID, title, price, and currency. Not required for the integration, but useful for verifying your catalog loaded correctly or for building store UI later. **Optional: log loaded products**
```csharp
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
Debug.Log($"Product: {id}, Title: {title}, Price: {price} {currency}");
}
```
### Verify the Catalog is Loading
Run the game and check the Console. You should see your product listed with its details, and the "no products" error from Step 1 should now be gone.
![1f2a1a84-c22d-4f3d-91c3-91f920b25bc7.png]
*Confirm products were requested and retrieved successfully*
## Step 3: Purchase Product
### Add the Purchase Code
Head back to the Integration Widget and select the **Purchase Product** step. The key addition is the `PurchaseSku()` function:
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
// Example purchase method
public void PurchaseSku()
{
_storeController.InitiatePurchase("ticket.10");
}
// Purchase result arrives in ProcessPurchase (see "Finalize Purchase" step)
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
}
```
**Purchase trigger function**
For this example, we modified the original function to except a `productID`.
```csharp
public void PurchaseSku(string productID)
{
_storeController.InitiatePurchase(productID);
}
```
The `productID` parameter means the same function works for any SKU in your catalog. When called, `InitiatePurchase()` launches Pay Station in the player's default browser to complete the checkout. There's no in-app web view. The player completes payment in their browser and returns to the game afterwards. Once the transaction finishes, Unity IAP fires `ProcessPurchase()` on success or `OnPurchaseFailed()` on failure.
### Implement OnPurchaseFailed
The **Purchase Product** step also provides the failure handlers. Copy these from the Integration Widget to replace the `NotImplementedException()` placeholders from Step 1:
**Replace both OnPurchaseFailed placeholders**
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
Both methods check for user cancellation first (the player closed Pay Station without completing the purchase) and log an error for any other failure reason. The second variant includes a more detailed failure description. Two versions exist because Unity IAP has two listener interfaces, each firing a slightly different signature. Having both means you're covered regardless of which interface is in play. These are complete as-is for this guide.
### Wire Up Your Game Logic
The Integration Widget covers the purchase mechanics, but how you *trigger* `PurchaseSku` is up to you. Here's what we did for the 2D Game Kit demo project:
#### Singleton pattern.
We made the class a singleton so it's accessible from any script in the project. Quick to set up, though you might prefer a different pattern for your final release.
```csharp
public class XsollaPayStation : MonoBehaviour, IDetailedStoreListener
{
public static XsollaPayStation Instance { get; private set; }
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
```
#### Live pricing helper
We added a `GetProductPrice` function that pulls the current price for a given SKU from the store controller. Updating the price in your Publisher Account means the in-game price updates the next time the catalog loads. Keep in mind: if the catalog isn't reloaded during a session, players will still see the previous price.
```csharp
public string GetProductPrice(string productId)
{
if (_storeController == null) return "...";
var product = _storeController.products.WithID(productId);
return product != null ? product.metadata.localizedPriceString : "...";
}
```
#### UI Implementation
In a separate UI class, we wired the purchase button to call `XsollaPayStation.Instance.PurchaseSku("full-health")` on click, and used a co-routine to update the price text via `GetProductPrice()`.
![c3f96843-18b1-400e-a732-e1e85bdfb2dd.png]
*Buy Health Button Implementation*
### Test Your Purchase Flow
Run the game and trigger your purchase. Your default browser should open with Pay Station showing your product name, price, and payment options.
Since we're in sandbox mode, you'll have access to test cards directly within Pay Station. Use these rather than your own card details. You can find the full list of [test card details](https://developers.xsolla.com/dev-resources/testing/test-cards/) in the Xsolla developer resources.
Complete the purchase and check your Unity Console for the purchase confirmation in the logs.
![5516124d-81c6-4efd-b590-05abec78d351.png]
*Browser Checkout*
At this point, nothing has happened in-game yet. The purchase was processed, but the game doesn't know what to do with it. That's the final step.
## Step 4: Finalize Purchase
### Understanding Client-Side vs Server-Side Validation
There are two validation approaches available.
**Server-side validation** uses webhooks or the Xsolla Events API. Unity IAP is told the purchase is pending and your code polls an event queue waiting for external confirmation. When that confirmation arrives, `ConfirmPendingPurchase` fires and consumes the transaction.
**Client-side validation**, which is what we're using, skips all of that. We confirm the purchase directly within the client the moment the transaction succeeds. No waiting, no polling, no pending state.
**Why straight to Purchase Processing Complete?** Our ProcessPurchase returns PurchaseProcessingResult.Complete immediately, rather than Pending. This is intentional. The Pending + ConfirmPendingPurchase pattern provides no additional benefit in a client-side only setup. There is no server or Events API maintaining a persistent transaction queue. Returning Complete is the correct approach when you're validating and fulfilling entirely on the client.
**Server-side validation for production:** Client-side validation is a good starting point and appropriate for many games. For high-value economies or competitive games where fraudulent item grants would have meaningful impact, consider migrating to server-side validation using Xsolla's webhook system . Server-side validation is harder to intercept or tamper with, as the receipt never passes through client code you don't control.
### Implement Finalize Purchase
Head to the Integration Widget, select **Finalize Purchase**, and copy the `PurchaseProcessingResult()` function.
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension().GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is valid — grant the item to the player, then confirm:
_storeController.ConfirmPendingPurchase(product);
}
else
{
// Purchase validation failed — do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Pending;
}
}
```
Here's what our final implementation looks like after adapting it for **Client-side Validation:**
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions
.GetExtension()
.GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (success)
{
Debug.Log($"Purchase successful: {product.definition.id}");
// Your game logic goes here: grant the item, update state, etc.
}
else
{
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Complete;
}
```
Compared to the Integration Widget default, we've stripped out the server-side validation code and are using only the client-side path. We return `Complete` immediately and handle the result inside the `Validate` callback.
### Add Your Game Logic
The success branch inside the `Validate` callback is where your game responds to a confirmed purchase. The key point is that this is where it lives.
For our 2D Game Kit demo project, we:
- Destroyed the purchase UI popup
- Triggered the player respawn function with full health from the last checkpoint
**Example game logic in success branch**
```csharp
if (success)
{
Debug.Log($"Purchase successful: {product.definition.id}");
// Destroy the purchase popup
if (purchaseUI != null)
{
Destroy(purchaseUI);
}
// Trigger respawn with full health
PlayerController.Instance.RespawnWithFullHealth();
}
```
### Verify the Complete Flow
Run the game end-to-end. This is the full test:
- Player dies. Popup appears with the purchase option showing the live price
- Click the purchase button. Default browser opens with Pay Station
- Complete the purchase using a test card
- Return to Unity. Player respawns with full health, UI popup is dismissed
*Xsolla Purchase Flow Demo* Check the Console for the full finalization sequence: validation firing, the purchase confirmation log, and the transaction being closed.
## What You've Built
That's a complete Xsolla payment integration in Unity for PC. Device ID authentication, a dynamic catalog, Pay Station via external browser, and client-side purchase validation.
The final class structure you should have:
- *Initialization and authentication* configured with your Project ID and Login ID
- *Catalog registration* with your product SKU(s) declared to Unity IAP
- `PurchaseSku` wired up to your game UI trigger
- `ProcessPurchase` returning `Complete` immediately and triggering your game's post-purchase logic
- `OnPurchaseFailed` (both variants) present and handling failure gracefully
**Remember to disable sandbox before release:** If you've been testing with SetSandbox(true), make sure to set it to false before shipping. Leaving sandbox enabled in production means real purchases won't process.
## Where to Go Next
Next steps from here:
- **Add more products.**
- Extend `AddProduct` and your store UI to support a full catalog
- **Move to **[**server-side validation**](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation)** or **[**Events API**](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api)**.**
- For a production release, the Xsolla Events API or webhook-based server validation is the recommended upgrade from the client-side approach used in this guide. The SDK Explorer makes it easy to see exactly what changes
- You may need to contact your account manager or email [[email protected]](mailto:[email protected]) to get the Events API configured for your project
- **Explore other **[**authentication methods**](https://developers.xsolla.com/api/login/getting-user-token)**.**
- Device ID is quick to set up but doesn't persist across device changes. Xsolla supports email, social, and platform-native authentication
- [**Configure your Pay Station**](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works)**.**
- Publisher Account gives you control over payment methods, UI theming, and regional settings
- **Set up a Web Shop and/or the Xsolla Game Launcher.**
- For off-platform PC distribution and release, these are some of your options
The [Xsolla SDK site](https://developers.xsolla.com/sdk/) has detailed walkthroughs, quick guides, and videos for every feature covered here and beyond. The [SDK Explorer](https://developers.xsolla.com/sdk/demo/) is worth revisiting once you have a working integration.
Good luck, and if you run into anything, the Xsolla developer community and support team are there to help.
Xsolla SDK for Unity
https://developers.xsolla.com/sdk/unity
AvailableXsolla SDK for Unity[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
The **Xsolla SDK for Unity** empowers developers to seamlessly integrate in-game payments via **Xsolla Pay Station** across **mobile**, **PC**, and **web** Unity projects, supporting monetization for both in-store builds (e.g., App Store iOS and Google Play builds in the USA) and out-of-store distributed game builds (e.g., Android APK, Notarized iOS, standalone PC) — all through a single integration. Connect directly with players, maintain control over the checkout experience, and keep up to 95% of your revenue. Games automatically benefit from updates for new monetization tools, regulatory compliance, and global policy changes.
Trusted by the studios behind *Crossout*, *Modern Warship*, and *Fantasy Tales: Sword and Magic* to power cross-platform commerce across iOS, Android, PC, Web, and in-store ecosystems.
## Platform Support
### iOS & Android
In the **United States** (*Epic v. Apple*), **Japan** (Mobile Software Competition Act), and **Brazil** (Apple's CADE settlement), developers may direct players to external web payments in iOS apps. Following the **October 29, 2025** Epic v. Google injunction, U.S. Google Play apps may use alternative billing and link-outs. The **Xsolla SDK for Unity** aligns with both Apple's revised App Store guidelines and Google Play's updated billing policies.
### Comprehensive Coverage
- **iOS**: Full support with compliant link-out payment options
- **Android**: Out-of-store distribution and alternative billing support
- **Windows**: Desktop monetization support
- **macOS**: macOS application support
- **Web**: WebGL monetization support
## Key Benefits for Unity Developers
**One Integration, Every Platform**
Get up and running on iOS, Android, Windows, macOS, and Web with a single SDK. Wherever your Unity game ships, your monetization stays consistent — and in your control.**DMA & Court-Order Compliant**
Full compliance with Apple's revised App Store guidelines and Google Play's updated billing policies — including link-out payments and alternative billing solutions, out-of-the-box.**Up to 95% Revenue Retention**
Connect directly with players outside the app stores. Bypass platform fees, maintain pricing control, and build direct player relationships that drive long-term engagement.**1,000+ Payment Methods**
Global payment infrastructure covering 200+ regions, 130+ currencies, and 25+ UI languages — with localized checkout flows and advanced anti-fraud included.**Built for Unity Workflows**
Native Unity IAP integration, easy install via Package Manager, and support for Unity 2022.3+ and Unity 6+ across all targets. Compliance and policy updates ship automatically — no manual SDK updates required.
## Getting Started
Ready to integrate the Xsolla SDK into your Unity project? Follow the Quick Start guide to process your first test payment in minutes, or contact your Account Manager for personalized implementation guidance. **Xsolla Buy Button**Fast Path
One-tap Web Shop purchase flows with 1,000+ payment methods — no SDK installation required. Launch browser-based checkout directly from your Unity game across PC, mobile (compliant with platform policies where applicable), and web.[Learn more →](https://developers.xsolla.com/sdk/unity/mobile/buy-button/) [QUICK START**Integration Guide**Process your first test payment in 5 steps→](https://developers.xsolla.com/sdk/unity/quick-start/)[FAST PATH**Buy Button**One-tap external payments — no full SDK required→](https://developers.xsolla.com/sdk/unity/mobile/buy-button/)[REFERENCE**Full SDK Docs**Advanced features, retry policies, custom UI→](https://developers.xsolla.com/sdk/unity/sdk/installation/)
Xsolla SDK for Unity - Mobile
https://developers.xsolla.com/sdk/unity/mobile
ℹ️External payment link-outs and alternative billing — iOS and Android
**iOS:** In the U.S., Japan, and Brazil, Apple now lets developers direct players to external web payments. The **Xsolla SDK** aligns with Apple's updated guidelines.
**Android — Effective Oct 29, 2025:** Following the **Epic v. Google** injunction, U.S. **Google Play** apps may guide users to **external payment methods via link-outs**, use **alternative billing solutions**, and are no longer subject to **anti-steering restrictions**.
For both platforms, the fastest recommended non-SDK approach is the [**Buy Button via link-outs to Web Shop** ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase) ([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)).
⚡ **Seamless mobile commerce**: Integrate DMA-compliant billing, out-of-store distribution, and access to over **1,000 local payment methods**—all within your Unity mobile builds.
This guide helps you integrate the Xsolla SDK for Unity to start accepting payments in your Unity game on Android and iOS. By the end, you'll have a fully functioning payment system in your game and experience firsthand how Xsolla streamlines monetization.
Let's dive in and get your game ready to accept payments in just a few easy steps!
## Quick start
This quick start guide makes it simple to integrate the *Xsolla SDK for Unity* and start accepting payments in your *Unity* game. We'll use a pre-configured test project to cover all the essentials: setting up basic user authentication, importing your products (SKUs), and processing a test payment.
For detailed instructions, please refer to the [**Quick start**](https://developers.xsolla.com/sdk/unity/quick-start/).
## Setting up a Publisher Account
Before you begin integrating Xsolla SDK into your game, you'll need to register a Publisher Account.
The Publisher Account is the primary tool for configuring Xsolla features, working with analytics and transactions similar to Google Play Console and App Store Connect for SKU management.important
You'll need to have an active Publisher Account to obtain a Project ID you'd use throughout the whole SDK integration process.
For detailed instructions, please refer to [**Setting up a Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/).
## Install the SDK
Now that you've set up your Publisher Account, the next step is to install the Xsolla SDK for Unity plugin in your Unity project.
For general installation instructions, see the [**Installation Guide**](https://developers.xsolla.com/sdk/unity/sdk/installation/).
#### Platform-specific Details
For platform-specific instructions, follow the links below:
The SDK installation process on Android requires resolving project dependencies.
To learn how to do that, see [**Resolving Android dependencies ↗**](https://developers.xsolla.com/sdk/unity/sdk/installation/resolving-android-dependencies/)
No additional steps required for iOS
## Configure the SDK
Once you've installed the SDK, the next step is configuration.
For detailed instructions, please refer to the [**Configuration Guide**](https://developers.xsolla.com/sdk/unity/sdk/configuration/).
#### Platform-specific Details
For platform-specific instructions, follow the links below:
### Buy Button Solution or Web Shop Link-outs (Recommended)
important
To enable **U.S.-only** link-outs **effective October 29, 2025**, first detect the **Google Play** storefront country code using the guide provided [**here**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detect-gpb-storefront-android/).
For details on configuring the *Buy Button* solution or *Web Shop Link-outs*, see [**here**](https://developers.xsolla.com/sdk/unity/mobile/buy-button/).
### Standard
When distributing your app through alternative channels outside of Google Play Store, you may need to detect where your app was installed from.
To learn how to do that, see [**How to detect store installation**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore/).
For directing players to external web payments in the U.S., Japan, and Brazil, and/or in-app payment compliance in Europe under the DMA, see:
- [**How to detect iOS Storefront**](https://developers.xsolla.com/sdk/unity/sdk/advanced/ios-storefront/)
- [**Configuration - iOS**](https://developers.xsolla.com/sdk/unity/sdk/configuration/ios/)
## Initialize the SDK
With configuration complete, you're now ready to initialize the SDK in your Unity project.
For detailed steps and best practices, refer to [**Initialization**](https://developers.xsolla.com/sdk/unity/sdk/initialization/).
## Make a Purchase
Now that the SDK is initialized, your app is ready to start processing payments.
For detailed instructions, please refer to [**Make Purchase**](https://developers.xsolla.com/sdk/unity/sdk/purchase/).
## Collect Payment
The SDK leverages **Xsolla Pay Station** for *secure* payment collection.
These steps will guide you through a test payment collection flow:
- Choose the **Card** payment method (use one of the test cards listed [**here ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards))) and click **Pay** to initiate the payment: ![quick start3]
- Wait for the payment to go through: ![quick start3]
- Once the payment is completed, you'll see a confirmation: ![quick start3]
- Choose the **Card** payment method: ![quick start3]
- Use one of the test cards listed [**here ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) and click **Pay** to confirm the payment: ![quick start3]
- Once the payment goes through, you'll see a confirmation: ![quick start3]
## Purchase Validation
After setting up payments, you might want to validate your purchase to ensure transaction security and reliability.
For detailed instructions, please refer to [**Purchase Validation**](https://developers.xsolla.com/sdk/unity/sdk/validation/).
## Testing & Sandbox
As a final step, use the sandbox environment to safely test your entire payment integration without real transactions.
For detailed instructions, please refer to the [**Testing & Sandbox**](https://developers.xsolla.com/sdk/unity/sdk/testing/).
## What's next?
Congratulations! 🎉 You've successfully integrated **Xsolla SDK for Unity**!
This achievement unlocks access to over 1000 global payment methods and sets the foundation for integrating more Xsolla solutions, including our powerful Web Shop.
Buy Button - Unity
https://developers.xsolla.com/sdk/unity/mobile/buy-button
Two simple ways to add external payments to your Unity app: redirect users to your Web Shop, or launch Pay Station's native in-app UI. Both are production-ready — pick the one that fits your workflow. Recommended
#### Web Shop Link-outs
Redirect users to your existing Xsolla Web Shop in the browser.
- Already have an Xsolla Web Shop
- Want minimal code changes
- Need web and mobile payment consistency
- Doing a phased migration from web
#### Buy Button Solution
Full payment UI handled natively inside your app — no browser redirect.
- Want a fully native integration
- Need 1,000+ payment methods out of the box
- Prefer Xsolla to manage the payment UI
- Want automatic regional compliance
important
To enable link-outs only where they're permitted, first detect the storefront country code: [**Android**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detect-gpb-storefront-android/) (U.S., effective Oct 29, 2025) · [**iOS**](https://developers.xsolla.com/sdk/unity/sdk/advanced/ios-storefront/) (U.S., Japan, and Brazil).
```csharp
// Provide Web Shop URL in settings
var settings = XsollaClientSettings.Builder.Create()
// An URL to your Xsolla-based web shop.
.SetWebShopUrl("https://yourwebshop.xsolla.site")
// A deeplink URL used to return the purchase result to your app.
// E.g. `myapp://open`.
.SetRedirectUrl("<schema>://<host>")
.Build();
// Enable Web Shop simple mode and pass user identifier
var configuration = XsollaClientConfiguration.Builder.Builder.Create()
.SetSettings(settings)
// Make sure the mode is switched to `XsollaClientConfiguration.SimpleMode.WebShop` for link-outs.
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.WebShop)
// User ID to be associated with the purchase.
.SetUserId("<USER_ID>")
.Build();
```
This opens your Web Shop in the device browser. Fulfillment happens via your server-side webhooks — see [webhook setup](https://developers.xsolla.com/sdk/publisher-account/webhooks/).
```csharp
var settings = XsollaClientSettings.Builder.Create()
// It's important to set this setting to `true`.
.SetUseBuyButtonSolution(true)
// .. your other settings
.Build();
var configuration = XsollaClientConfiguration.Builder.Builder.Create()
.SetSettings(settings)
// Make sure the mode is switched to `XsollaClientConfiguration.SimpleMode.Off` for the `Buy Button` solution.
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.Off)
// .. your other settings
.Build();
```
Enable this once in your SDK configuration — Buy Button activates automatically for all [default purchase flows](https://developers.xsolla.com/sdk/unity/sdk/purchase/). See [configuration docs](https://developers.xsolla.com/sdk/unity/sdk/configuration/) for advanced options. Still not sure?
**Web Shop** is great if you have an existing store or want to start with minimal changes. **Pay Station** is the fastest path to a fully native integration. Both support the same payment methods and regions worldwide.
Xsolla SDK for Unity - PC
https://developers.xsolla.com/sdk/unity/pc
info
**Xsolla SDK for Unity** is an evolution of the enterprise-level Xsolla SDK solution, which was designed for integration into large-scale projects.
💡 **Global-ready PC monetization**: leverage Xsolla's payment engine for compliant, localized checkout—via Web Shop, Buy Button, or direct API—to maximize revenue in premium and F2P models alike.
This guide helps you integrate the Xsolla SDK for Unity to start accepting payments in your Unity game on PC. By the end, you'll have a fully functioning payment system in your game and experience firsthand how Xsolla streamlines monetization.
Let's dive in and get your game ready to accept payments in just a few easy steps!
## Quick start
This quick start guide makes it simple to integrate the *Xsolla SDK for Unity* on PC and start accepting payments in your *Unity* game. We'll use a pre-configured test project to cover all the essentials: setting up basic user authentication, importing your products (SKUs), and processing a test payment.
For detailed instructions, please refer to the [**Quick Start Guide**](https://developers.xsolla.com/sdk/unity/quick-start/).
## Setting up a Publisher Account
Before you begin integrating Xsolla SDK into your game, you'll need to register a Publisher Account.
The Publisher Account is the primary tool for configuring Xsolla features, working with analytics and transactions similar to Google Play Console and App Store Connect for SKU management.important
You'll need to have an active Publisher Account to obtain a Project ID you'd use throughout the whole SDK integration process.
For detailed instructions, please refer to [**Setting up a Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/).
## Install the SDK
Now that you've set up your Publisher Account, the next step is to install the Xsolla SDK for Unity plugin in your Unity project.
For detailed installation instructions, see the [**Installation Guide**](https://developers.xsolla.com/sdk/unity/sdk/installation/).
## Configure the SDK
Once you've installed the SDK, the next step is configuration.
For detailed instructions, please refer to the [**Configuration Guide**](https://developers.xsolla.com/sdk/unity/sdk/configuration/).info
For Unity Editor, Windows, and macOS builds, the `WebViewType` will default to `Auto` and will launch in the system's default external browser.
This behavior ensures compatibility and consistency during development and testing across platforms.
## Initialize the SDK
With configuration complete, you're now ready to initialize the SDK in your Unity project.
For detailed steps and best practices, refer to the [**Initialization Guide**](https://developers.xsolla.com/sdk/unity/sdk/initialization/).
## Make a Purchase
Now that the SDK is initialized, your app is ready to start processing payments.
For detailed instructions, please refer to [**Make Purchase**](https://developers.xsolla.com/sdk/unity/sdk/purchase/).
## Collect Payment
The SDK leverages **Xsolla Pay Station** for *secure* payment collection.
These steps will guide you through a test payment collection flow:
- Choose the **Card** payment method: ![quick start3]
- Use one of the test cards listed [**here ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) and click **Pay** to confirm the payment: ![quick start3]
- Once the payment goes through, you'll see a confirmation: ![quick start3]
## Purchase Validation
After setting up payments, you might want to validate your purchase to ensure transaction security and reliability.
For detailed instructions, please refer to [**Purchase Validation**](https://developers.xsolla.com/sdk/unity/sdk/validation/).
## Testing & Sandbox
As a final step, use the sandbox environment to safely test your entire payment integration without real transactions.
For detailed instructions, please refer to the [**Testing & Sandbox**](https://developers.xsolla.com/sdk/unity/sdk/testing/).
## What's next?
Congratulations! 🎉 You've successfully integrated **Xsolla SDK for Unity** on PC!
This achievement unlocks access to over 1000 global payment methods and sets the foundation for integrating more Xsolla solutions, including our powerful Web Shop.
Quick Start — Unity SDK
https://developers.xsolla.com/sdk/unity/quick-start
Get the **Xsolla SDK for Unity** integrated and process your first test payment. We'll use pre-configured test credentials so you can start in minutes.
🔥 **Proven in production**: follow the exact integration path used by games like *Crossout* and *Modern Warship*, complete with **DMA-compliant billing** and **1,000+ payment methods** ready out of the box.
## Getting Started
Install the SDK via Unity Package Manager:
- In the Unity Editor, click **Window** > **Package Manager**.
- Click the ➕ icon and select **Add package from git URL...**.
- Enter `https://github.com/xsolla/xsolla-sdk-unity.git` and click **Add**.
Then configure your project credentials:
- Go to **Window > Xsolla > SDK > Edit Settings**.
- In the Inspector panel, set these test values:
| Property | Value |
| --- | --- |
| Project ID | 301871 |
| Login ID | dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a |
![Settings asset]
See [installation details](https://developers.xsolla.com/sdk/unity/sdk/installation/) for information on more installation possibilities. PREREQUISITE
Make sure Unity **In-App Purchasing `4.15+`** is installed.
See the official [Unity IAP setup guide ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)).
⚠️ Unity **In-App Purchasing `5.x`** is **NOT** supported at this moment.
## Authenticate
Add this to your `MonoBehaviour`'s `Start()` method:
```csharp
using UnityEngine.Purchasing;
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener {
void Start() {
var settings = XsollaStoreClientSettingsAsset.Instance().settings;
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
// Continue with Load Catalog
}
}
```
This loads your project settings and creates a `Configuration` with sandbox mode and debug logging. For production, replace the test project ID and login ID with your own from [**Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/). See [configuration docs](https://developers.xsolla.com/sdk/unity/sdk/configuration/) for advanced options.important
If you are using your own **Project/Login IDs**, make sure to enable **Device ID login** in your Project. Learn how to enable it here: [https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)iOS
In the U.S., Japan, and Brazil, use `WebViewType.External`; for the EU (DMA) in-app flow, use `WebViewType.Auto`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.External) // or .Auto for EU
.Build();
```
## Load Catalog
Register your products and initialize Unity IAP. Unlike native mobile SDKs where catalog loading is a separate async call, Unity IAP fetches your products automatically during initialization — just declare your SKUs.
```csharp
// Inside Start(), after creating configuration:
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("money.100", ProductType.Consumable); // Test product SKU
UnityPurchasing.Initialize(this, configurationBuilder);
```
This registers your test product and starts the purchasing system. When `OnInitialized` fires, your catalog is loaded and ready to purchase. See [initialization docs](https://developers.xsolla.com/sdk/unity/sdk/initialization/) for Unity IAP setup and advanced options.
## Purchase Product
The `OnInitialized` callback fires when the catalog is loaded. Use it to launch a purchase:
```csharp
// IDetailedStoreListener callback — catalog loaded and ready:
public void OnInitialized(IStoreController controller, IExtensionProvider extensions) {
controller.InitiatePurchase("money.100");
}
```
This opens **Xsolla Pay Station** where users complete payment. For testing, use a [test card ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/dev-resources/testing/test-cards/](https://developers.xsolla.com/dev-resources/testing/test-cards/)):
![Choose payment method]
![Processing payment]
![Payment confirmed]
## Finalize Purchase
Once the purchase completes, process it and award the product to the user:
```csharp
// IDetailedStoreListener callback — purchase completed:
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
if (args.purchasedProduct.definition.id == "money.100") {
Debug.Log("Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
}
return PurchaseProcessingResult.Complete;
}
```
Returning `PurchaseProcessingResult.Complete` acknowledges the transaction. See [purchase flow docs](https://developers.xsolla.com/sdk/unity/sdk/purchase/) for error scenarios and advanced options.
## What's next?
You've built a complete payment integration: authentication, catalog loading, purchase flow, and fulfillment. Your app now has access to 1,000+ payment methods across 200+ countries.
- **[Set up your project](https://developers.xsolla.com/sdk/publisher-account/)** — create your Publisher Account and replace the sandbox test credentials with production ones
- **[Buy Button](https://developers.xsolla.com/sdk/unity/mobile/buy-button/)** — fastest path to external payments
- **[Extended example](https://developers.xsolla.com/sdk/unity/quick-start/extended-example/)** — complete working implementation
- **[Full SDK docs](https://developers.xsolla.com/sdk/unity/sdk/installation/)** — advanced features, retry policies, custom UI
Extended Example (IAP)
https://developers.xsolla.com/sdk/unity/quick-start/extended-example
**Xsolla SDK for Unity** plugs into *Unity InAppPurchasing* through an extension module.
It works the same way on iOS and Android.
All you need to do is configure and initialize the module anywhere in your code before attempting to make a purchase.
## Configuration & Initialization
PREREQUISITE
Make sure Unity **In-App Purchasing `4.15+`** is installed.
See the official [Unity IAP setup guide ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)).
⚠️ Unity **In-App Purchasing `5.x`** is **NOT** supported at this moment.
```csharp
public class MyIAPManager
{
// ...
public MyIAPManager()
{
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.SetSandbox(true)
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
builder.AddProduct("money.100", ProductType.Consumable, new IDs
{
{ "money.100", XsollaPurchasingModule.StoreName },
{ "money_100_google", GooglePlay.Name },
{ "money_100_mac", MacAppStore.Name }
});
UnityPurchasing.Initialize(this, builder);
}
// ...
}
```
important
If you are using your own **Project/Login IDs**, make sure to enable **Device ID login** in your Project. Learn how to enable it here: [https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account) tip
The official **Unity IAP** initialization guide can be found [**here ↗**](https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html](https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html)).
## A fully-fledged implementation
We'll base our code on the existing official Unity IAP sample called **"01 Buying Consumables"**:
[![publisher account 6]](https://developers.xsolla.com/sdk/assets/files/example-6b727680d84cf9a5e89ca70611261c35.png/)
The code:
```csharp
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using UnityEngine.UI;
using Xsolla.SDK.Common;
using Xsolla.SDK.Store;
using Xsolla.SDK.UnityPurchasing;
namespace Samples.Purchasing.Core.BuyingConsumables
{
public class BuyingConsumables : MonoBehaviour, IDetailedStoreListener
{
IStoreController m_StoreController; // The Unity Purchasing system.
//Your products IDs. They should match the ids of your products in your store.
public string moneyProductId = "money.100";
public string ticketProductId = "ticket.10";
public Text MoneyCountText;
public Text TicketCountText;
int m_MoneyCount;
int m_TicketCount;
void Start()
{
InitializePurchasing();
UpdateUI();
}
void InitializePurchasing()
{
//Remove this line from the original code.
//var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
//Add these lines here..
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.SetSandbox(true)
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
//Add products that will be purchasable and indicate its type.
builder.AddProduct(moneyProductId, ProductType.Consumable);
builder.AddProduct(ticketProductId, ProductType.Consumable);
UnityPurchasing.Initialize(this, builder);
}
public void BuyMoney()
{
m_StoreController.InitiatePurchase(moneyProductId);
}
public void BuyTicket()
{
m_StoreController.InitiatePurchase(ticketProductId);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
Debug.Log("In-App Purchasing successfully initialized");
m_StoreController = controller;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
OnInitializeFailed(error, null);
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
var errorMessage = $"Purchasing failed to initialize. Reason: {error}.";
if (message != null)
{
errorMessage += $" More details: {message}";
}
Debug.Log(errorMessage);
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
//Retrieve the purchased product
var product = args.purchasedProduct;
//Add the purchased product to the players inventory
if (product.definition.id == moneyProductId)
{
AddMoney();
}
else if (product.definition.id == ticketProductId)
{
AddTicket();
}
Debug.Log($"Purchase Complete - Product: {product.definition.id}");
//We return Complete, informing IAP that the processing on our side is done and the transaction can be closed.
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
Debug.Log($"Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
Debug.Log($"Purchase failed - Product: '{product.definition.id}'," +
$" Purchase failure reason: {failureDescription.reason}," +
$" Purchase failure details: {failureDescription.message}");
}
void AddMoney()
{
m_MoneyCount++;
UpdateUI();
}
void AddTicket()
{
m_TicketCount++;
UpdateUI();
}
void UpdateUI()
{
MoneyCountText.text = $"Your Money: {m_MoneyCount}";
TicketCountText.text = $"Your Tickets: {m_TicketCount}";
}
}
}
```
How to detect Google Play storefront (Unity/Android)?
https://developers.xsolla.com/sdk/unity/sdk/advanced/detect-gpb-storefront-android
When distributing your app through **Google Play**, you may need to detect the current storefront to implement region-specific functionality. The storefront represents the Google Play region associated with the user’s account, identified by a two-letter country code in **ISO-3166-1 alpha-2** format (e.g., `"US"` for United States). important
This detection is particularly important in light of the **Epic v. Google** injunction effective **October 29, 2025**, which permits U.S. **Google Play** apps to guide users to **external payment methods via link-outs**, use **alternative billing solutions**, and prohibits **anti-steering restrictions**.
You can use storefront detection to:
- Enable alternative billing options specifically for U.S. users
- Implement region-specific payment flows
- Control feature availability based on local billing regulations
- Ensure compliance with U.S. court-mandated requirements
You can use the following snippet to retrieve the country code of the Google Play storefront: important
This snippet is most useful, when **distributing** and **installing** your app **through Google Play store**. To check whether the app has been installed from Google Play store or side-loaded (third-party stores or APK distribution) you can use the `XsollaStoreClientInfo.IsInstalledFromGooglePlayStore()` utility function. tip
Prior to retrieving the Google Play storefront country code, it's advised (but not mandatory) to verify whether Google Play Store is installed on the device as the query function will result in error if the store is not available. For this purpose you can rely on `XsollaStoreClientInfo.IsGooglePlayStoreInstalled()` utility function.
```csharp
XsollaStoreClientInfo.QueryGooglePlayCountryCodeAsync(
onSuccess: countryCode =>
{
if (countryCode.IsCode("us"))
{
// Handle the US storefront.
}
else
{
// Handle all other storefront variants.
}
},
onError: err =>
{
// Handle the error here.
}
);
```
How to detect store installation?
https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore
When distributing your app through alternative channels outside of official app stores (like Google Play Store or Apple's App Store), you may need to detect where your app was installed from. This is particularly important for:
- Implementing different payment flows for alternative distribution channels
- Adjusting app behavior based on the installation source
- Ensuring compliance with platform-specific requirements
- Managing features that should only be available in certain distribution channels
To detect whether the game is running in alternative distribution (outside official app stores), use the snippets below:
Below are helper snippets you can use to adjust your app's behavior depending on various factors like the installer's package name, Google Play Store's country code, etc.
### How to check if Google Play Store is installed?
Can be useful in scenarios, when a part of functionality shouldn't even be attempted to be run outside Google Play Store ecosystem. This snippet will allow you to determine, if the device has **Google Play Store** installed.
```csharp
if (XsollaStoreClientInfo.IsGooglePlayStoreInstalled())
{
Debug.Log("Google Play Store found!");
}
else
{
Debug.Log("Google Play Store NOT found!");
}
```
### Checking if the App is Installed from Google Play Store
This snippet helps to determine whether the app was installed directly from the *Google Play Store* or side-loaded (e.g. installed from an APK).
```csharp
if (XsollaStoreClientInfo.IsInstalledFromGooglePlayStore())
{
Debug.Log("App was installed from Google Play Store");
}
else
{
Debug.Log("App was NOT installed from Google Play Store");
}
```
### Querying the installer's package name
If you need to know the exact package name of your app's installer, use the following code below.
```csharp
var installerPackageName = XsollaStoreClientInfo.GetInstallerPackageName();
var matched = installerPackageName.Equals("com.xxx.yyy.zzz", StringComparison.OrdinalIgnoreCase);
if (matched)
{
Debug.Log($"Expected installer package name: {installerPackageName}");
}
else
{
Debug.Log($"Unexpected installer package name: {installerPackageName}");
}
```
Or if you prefer a simplified approach, where you don't care about the actual installer's package name, use this code:
```csharp
var matched = XsollaStoreClientInfo.IsInstallerPackageName("com.xxx.yyy.zzz");
if (matched)
{
Debug.Log("Expected installer package name found!");
}
else
{
Debug.Log("Expected installer package name NOT found!");
}
```
### Reporting a custom install source
Every purchase carries the channel the app was installed from. The SDK detects it from the installer package name.
For a build distributed outside an app store, such as an APK downloaded from your website, the OS reports the browser, the system package installer or no installer at all. Set the channel yourself and purchases are attributed to it instead of the detected one:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetInstallSource("website")
.Build();
```
```csharp
XsollaPurchasingStoreInfo.GetAppleDistributionStatus((isRunningInAlternativeDistribution, error) =>
{
if (error != null)
Debug.LogError($"Failed to get Apple Distribution: {error}");
else
Debug.Log("Apple Distribution is alternative: " + isRunningInAlternativeDistribution);
});
```
How to detect iOS Storefront?
https://developers.xsolla.com/sdk/unity/sdk/advanced/ios-storefront
When distributing your app through Apple's App Store, you may need to detect the current storefront to implement region-specific functionality. The storefront represents the App Store region that the user is currently using, identified by a three-letter country code (e.g., "USA" for United States).
This detection is particularly important because several storefronts now permit developers to direct players to external payment pages — the **United States** (*Epic v. Apple*), **Japan** (Mobile Software Competition Act), **Brazil** (CADE settlement), and the **European Union** (Digital Markets Act). You can use the storefront detection to:
- Enable external payment links for the storefronts that permit them
- Implement region-specific payment flows
- Control feature availability based on regional requirements
- Ensure compliance with local regulations
note
If the app is installed via **alternative distribution** (for example, an alternative marketplace/web distribution under the DMA), the Storefront country code may be unavailable and returned as an **empty string**. In that case, use the [**store installation detection**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore/) guide to determine whether the app is running in an alternative distribution environment.
To determine the current iOS storefront and control SDK functionality based on the region, use the following code snippet:
```csharp
XsollaStoreClientInfo.GetAppleStorefront((storefront, error) =>
{
if (error != null)
{
Debug.LogError($"Failed to get Apple Storefront: {error}");
return;
}
// Storefronts where Apple permits external payments, using an external browser.
// In the EU either flow is allowed, so add its codes here only if you route out to the web.
bool allowsExternalPayments = storefront == "USA" || storefront == "JPN" || storefront == "BRA";
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(allowsExternalPayments
? XsollaClientSettings.WebViewType.External
: XsollaClientSettings.WebViewType.Auto)
.Build();
});
```
Trusted Web Activity (Unity/Android)
https://developers.xsolla.com/sdk/unity/sdk/advanced/trusted-web-activity
A [**Trusted Web Activity (TWA) ↗**](https://developer.chrome.com/docs/android/trusted-web-activity) ([https://developer.chrome.com/docs/android/trusted-web-activity](https://developer.chrome.com/docs/android/trusted-web-activity)) enables Android apps to display web content in full-screen mode using Chrome, without any browser UI elements. Unlike WebView, *TWAs* run in the user's browser context, allowing better performance, access to browser features (like push notifications and background sync), and shared cookies, permissions, and storage between the app and the browser. important
To enable *Trusted Web Activity*, contact your integration manager with the app’s package name and certificate hash. DID YOU KNOW?
*Trusted Web Activity* support is project-independent and applies at the app level — based on the package name and signing certificate only.
### Configuring for Trusted Web Activity in the SDK
When configuring the SDK, supply an activity setting to the config like this:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
// ...other settings
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Trusted)
// ...other settings
.Build();
```
This ensures that the *Trusted Web Activity* will be used by the payment flow. warning
*Trusted Web Activity* availability depends on the device's system configuration, i.e. a compatible browser needs to be installed. If *TWA* support is not available, then the SDK falls back to one of the default activity types for payments (e.g. *Custom Tabs* or *WebView*, depending on the environment).
An example of the *TWA* in action: [](https://developers.xsolla.com/sdk/assets/images/twa-1-737175ed3a44e80fb60131748dda4361.jpg)
### (Optional) Orientation locking
*Trusted Web Activity* natively supports orientation locking when it's shown on the screen. This can be set up during the configuration step with these lines:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
// ...other settings
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
// ...other settings
.Build();
```
Orientation setting is one of the following values:
- `XsollaStoreClientSettings.OrientationLock.Portrait` - forces the *TWA* to be displayed in *portrait* mode.
- `XsollaStoreClientSettings.OrientationLock.Landscape` - forces the *TWA* to be displayed in *landscape* mode.
- `XsollaStoreClientSettings.OrientationLock.Auto` - disables the orientation locking.
### (Optional) Adding a customizable splash screen
*Trusted Web Activity* also supports a customizable splash screen that's shown right before the *TWA* itself.
To enable it, you need to modify the [configuration setting](https://developers.xsolla.com/sdk/unity/sdk/advanced/trusted-web-activity#configuring-for-trusted-web-activity-in-the-sdk) we added earlier by specifying a custom splash screen image using one of the supported approaches.
An example of the *TWA* splash screen: [](https://developers.xsolla.com/sdk/assets/images/twa-2-fd93e4a14c1a92ff7574a04d1a7abf15.jpg)
#### Setting an image for the splash screen
Image can be supplied via two methods: a *drawable ID* and a filepath to the image:
- A *drawable ID*: important The drawable needs to be added to the Android resource manually beforehand. ```csharp var settings = XsollaStoreClientSettings.Builder.Create() // ...other settings .SetWebViewSplashScreenDrawableIdAndroid(<your_splash_screen_drawable_id>) // ...other settings .Build(); ``` tip SVG format is also supported, but needs to be wrapped into a valid drawable XML.
- A filepath: important The image file needs to be discoverable. Supports all major raster image formats. ```csharp var settings = XsollaStoreClientSettings.Builder.Create() // ...other settings .SetWebViewSplashScreenImage(<filepath_to_your_splash_screen_image>) // ...other settings .Build(); ```
note
If you're using the SDK for Android directly, consider visiting this page for more details: [**Trusted Web Activity - Android**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/trusted-web-activity/).
Configuration
https://developers.xsolla.com/sdk/unity/sdk/configuration
In Unity, settings can be set up either using a **settings asset** or via **code**:
- The asset allows for a **codeless** approach, where you don't have to modify the code to adjust the configuration.
- The **code** approach works better for apps, where the configuration is modified dynamically (e.g., flags and values are received from the app's backend).
In the **Unity Editor**:
- Go to **Window** > **Xsolla** > **SDK** > **Edit Settings** from the main menu.
- Go to the **Inspector** panel.
- Fill in the **Project ID** and **Login ID** fields.
[![publisher account 6]](https://developers.xsolla.com/sdk/assets/files/settings-5b8f2955492ac0b0b88f04d06f6382a2.png/)tip
To access the asset's settings from the code, use the following snippet:
```csharp
var settings = XsollaStoreClientSettingsAsset.Instance().settings;
```
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetLocalPurchasesRestore(true)
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Auto)
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
.SetUIThemeSize(XsollaStoreClientSettings.ThemeSize.Auto)
.SetUIThemeStyle(XsollaStoreClientSettings.ThemeStyle.Auto)
.SetUICustomTheme("")
.SetUseCloseButton(XsollaStoreClientSettings.CloseButton.Auto)
.SetUIControlTintColor(Color.clear)
.SetUIBarTintColor(Color.clear)
.SetRedirectUrl("")
.SetRedirectButtonText("")
.SetRedirectDelay(6)
.SetEmailCollectionConsentOptIn(null)
.Build();
```
### Android
For platform-specific settings, including Custom Tabs / TWA browser provider controls, see [**Configuration - Android**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/).
### iOS
important
For directing players to external web payments in the U.S., Japan, and Brazil, and/or in-app payment compliance in Europe under the DMA, see [**Configuration - iOS**](https://developers.xsolla.com/sdk/unity/sdk/configuration/ios/).
### Buy Button Solution
The Buy Button Solution provides a complete, native payment experience with minimal integration effort. This approach handles the entire payment flow within your app using Xsolla's optimized UI components.
For a full guide (including Web Shop link-outs vs Pay Station, platform notes, and examples), see [**Buy Button ⚡**](https://developers.xsolla.com/sdk/unity/mobile/buy-button/).
**When to use Buy Button Solution:**
- You want a quick, native payment integration
- You prefer Xsolla to handle payment UI and optimization
- You need support for multiple payment methods out of the box
- You want automatic compliance with regional payment regulations
To enable the Buy Button Solution for your payments (works with **default purchase flows** only), use the snippet below:
```csharp
var settings = XsollaClientSettings.Builder.Create()
.SetUseBuyButtonSolution(true)
.Build();
```
note
Make sure `XsollaClientConfiguration.SimpleMode` is set to `Off`. The Buy Button Solution won't work in Web Shop link-out mode (`SimpleMode.WebShop`).
### Web Shop Link-outs
Use Web Shop link-outs when you want minimal code changes by redirecting the user to your existing Xsolla Web Shop to complete the purchase. caution
In Web Shop link-out mode, the SDK does not execute its native in-app payment flow. It only opens the Web Shop and cancels any SDK purchase callbacks. Handle fulfillment and post-payment updates via your Web Shop processes (for example, webhooks or server-side logic), not via SDK purchase callbacks.
Configure by providing the Web Shop URL to settings and enabling the Web Shop simple mode in configuration:
```csharp
// Provide Web Shop URL in settings
var settings = XsollaClientSettings.Builder.Create()
.SetWebShopUrl("https://yourwebshop.xsolla.site")
.Build();
// Enable Web Shop simple mode and pass user identifier
var configuration = XsollaClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.WebShop)
.SetUserId("<USER_ID>")
.Build();
```
### Purchase Restoration Settings
By default, the SDK automatically handles local purchase restoration to ensure users can recover their purchases when reinstalling your app or when the app crashes or goes out of memory during payment processing. However, this behavior should be adjusted based on your backend integration architecture.
Alternatively, if you prefer a serverless approach without maintaining webhooks, you can enable the **Xsolla Events API** for purchase restoration (see the subsection below) while keeping local purchase restoration enabled.
For webhook-based integrations where your backend receives and processes purchase notifications directly from Xsolla, disable local restoration to prevent conflicts with server-side transaction management:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetLocalPurchasesRestore(false)
.SetLocalPurchasesRestoreInterval(0)
.Build();
```
- `SetLocalPurchasesRestore`: Enables or disables local purchase restoration (`true` by default).
- `SetLocalPurchasesRestoreInterval`: Interval in seconds between local purchase restoration attempts (`0` by default — uses SDK defaults).
warning
**When to disable local purchase restoration:**
- Your backend uses webhooks to receive purchase notifications from Xsolla
- You handle transaction lifecycle management on your server
- You want to avoid duplicate purchase processing between local and server-side systems
**Important limitations:**
- Restored purchases cannot be validated through the standard validation flow
- Restored purchases don't carry the identifiers of the original Xsolla order unless restoration runs through the Events API
- Transaction finishing must be handled by your backend when webhooks are used
- If local purchase restoration is disabled, the SDK will not perform restoration via either local restoration or the Events API
This setting directly impacts transaction finishing behavior. When local restoration is disabled, your backend becomes responsible for managing the complete transaction lifecycle through webhook notifications. Note that with local restoration disabled, unfinished transactions will not reappear on app relaunch, making proper backend handling essential.
#### Using Xsolla Events API for Restoration
The **Xsolla Events API** serves as an alternative to webhook-based integrations, where the integrator's backend usually handles most of the logic (purchase validation, awarding, etc.). Instead of sending webhooks directly, the API intercepts them and stores their payloads in a remote queue managed by Xsolla. This approach enables serverless integrations for projects that lack backend capacity or don't require one, yet still prefer handling the entire transaction flow directly from the app.
Restoring through the Events API also gives you the order identifier from the original Xsolla purchase, so you can match a restored purchase against your own records. Inventory-backed restoration has no order to reference. CAUTION
Opting for the *Xsolla Events API* disables your project's webhooks. In other words, you cannot simultaneously handle webhooks on your backend and use the *Events API* in your app.
To enable it, open your project in *Publisher Account*, go to **Project settings** > **Integration settings**, select **Use API** and click **Save**. See [**Events API in Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api) for details.
##### Enabling Events in the Unity SDK
Enable Events-based purchase restoration in the SDK configuration:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebhooksMode(XsollaStoreClientSettings.WebhooksMode.EventsApi)
.Build();
```
info
For additional information, see the [**webhooks page**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api). note
Events-based restoration requires `SetLocalPurchasesRestore(true)`. If you disable local purchase restoration, the SDK will not query or use the Events API for restoration.
### Custom Pay Station Domains
Override the default Pay Station domains for production and sandbox environments. This is useful when you have custom domain setup for your Pay Station.
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetCustomPayStationDomain(
domainProduction: "pay.yourdomain.com",
domainSandbox: "sandbox-pay.yourdomain.com"
)
.Build();
```
note
Both domains must be valid absolute URIs. Invalid domains will be logged and ignored. You can pass empty strings or null for either domain to use defaults.
### Logo Visibility
Control the visibility of the Xsolla logo in Pay Station using the `VisibleLogo` setting:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetVisibleLogo(XsollaClientSettings.VisibleLogo.Auto) // Auto (default)
// .SetVisibleLogo(XsollaClientSettings.VisibleLogo.Show) // Always show
// .SetVisibleLogo(XsollaClientSettings.VisibleLogo.Hide) // Always hide
.Build();
```
**Options:**
- `Auto` - Automatically determine whether to show the logo (default behavior)
- `Show` - Always display the Xsolla logo
- `Hide` - Never display the Xsolla logo
### Build configuration from the settings
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// Set the settings object you've acquired in previous step here..
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.SetLocale("en")
.SetFallbackToDefaultLocaleIfNotSet(true)
.SetFetchProductsWithGeoLocale(false)
.SetFetchPersonalizedProductsOnly(true)
.SetTrackingId("")
.Build();
```
Below is the full list of configuration builder methods:
| Setting | Value | Description |
| --- | --- | --- |
| SetSettings | XsollaClientSettings | The settings object built in the previous step. |
| SetAccessToken | string | Access token for authentication (see Assign access token). |
| SetSandbox | bool | Enables sandbox mode for test payments (default false). |
| SetLogLevel | XsollaLogLevel | Controls the verbosity of SDK logging (None, Error, Warning, Debug). |
| SetDelayedConfigurationTask | Task<OnDelayedConfiguration> | Task for deferred configuration when the access token is not yet available (see Delayed access token). |
| SetLocale | string | Override locale for pricing and formatting (empty string for automatic). |
| SetFallbackToDefaultLocaleIfNotSet | bool | Use the default locale if no override is specified (default false). |
| SetFetchProductsWithGeoLocale | bool | Fetch products using geo-detected locale (default false). |
| SetFetchPersonalizedProductsOnly | bool | Return only personalized products, excluding items whose per-user purchase limit has been reached (default true). |
| SetUserId | string | Your user identifier, required for Web Shop link-out mode. Sent as custom_parameters.custom_user_id and returned in purchase webhooks; not used for attribution (see SetAttributionUserId). |
| SetAttributionUserId | string | The ID that purchase events reported to attribution platforms (AppsFlyer, Adjust, etc.) are keyed on, sent to Pay Station as custom_parameters.custom_id. It must equal the customer user ID your attribution SDK reports, or purchases won't match up with that user. If left empty, events are matched on the user ID in the payment token, which by default is the player's Xsolla Login user ID.1 |
| SetInstallSource | string | (Android, iOS) The channel your build was distributed through, such as your website or launcher. Purchases made in the build are attributed to it instead of the detected channel (see Reporting a custom install source). With an empty string, Android uses the OS installer, and iOS detects the channel only on iOS 17.4 and later (App Store, web distribution, alternative marketplace), sending none on earlier versions. Android trims the value (blank counts as empty); iOS sends it as is. Ignored in standalone builds. |
| SetTrackingId | string | Tracking ID for analytics (empty string to omit). |
| SetSimpleMode | SimpleMode | Simple mode setting (Off, WebShop, ServerTokens). |
| SetCustomPayStationDomain | string, string | Override production and sandbox Pay Station domains (see Custom Pay Station Domains). |
1 If your project authenticates players through server-side custom ID login or PlayFab, or maps the user ID to a custom JWT claim, the payment token carries that value instead of the Login user ID. Call `SetAttributionUserId`, or purchase events won't match your attribution platform.
### Assign Xsolla access token to the configuration
note
The access token [**JWT-structure ↗**](https://developers.xsolla.com/api/login/overview/#section/JWT-structure) ([https://developers.xsolla.com/api/login/overview/#section/JWT-structure](https://developers.xsolla.com/api/login/overview/#section/JWT-structure)). warning
A valid **access token** must already be known before the SDK initialization step.
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("< your access token >")
.Build();
```
If the **access token** is not known yet, when building the configuration, you can easily feed it into the SDK asynchronously using a `Task`. This works best for apps, where the **access token** might be acquired at some later point (e.g., from the app's backend) and cannot be provided right away.
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetDelayedConfigurationTask( DelayedTask() )
.Build();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
var result = await Server.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetSettings(
XsollaStoreClientSettings.Builder.Update(configuration.settings)
.SetProjectId(result.projectId)
.Build()
)
.SetAccessToken(result.accessToken)
.Build();
}
```
### Updating access token at runtime
If you need to update the access token during the session (for example, after token refresh), use the `UpdateAccessToken` method:
```csharp
storeClient.UpdateAccessToken("<new_access_token>", error =>
{
if (error != null)
{
Debug.LogError($"Failed to update access token: {error.message}");
return;
}
Debug.Log("Access token updated successfully");
});
```
tip
This is useful when your access token expires and you need to refresh it without reinitializing the entire SDK.
### Using device ID instead of the access token
Below is an example with the fields required to be set for the device ID authentication approach to work:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
// ..other properties
.Build();
```
### Using OAuth2 instead of the access token
Below is an example with the fields required to be set for the OAuth2 authentication approach to work:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetOAuthClientId("< your_oauth_client_id >")
// ..other properties
.Build();
```
note
On Android, every sign-in through an OAuth 2.0 client, including the social provider flow with OAuth2 below, sends a redirect URI that must be registered on that client, or the server rejects the sign-in. See [**Sign-in redirect URIs**](https://developers.xsolla.com/sdk/unity/sdk/configuration/android/#sign-in-redirect-uris) for the URI each sign-in method uses.
### Using a third-party social provider's access token
Below is an example of the settings required for the social provider authentication approach to work:
- **With OAuth2** ```csharp var settings = XsollaStoreClientSettings.Builder.Create() .SetProjectId("< your_project_id >") .SetLoginId("< your_login_id >") .SetOAuthClientId("< your_oauth_client_id >") .SetSocialProvider(new XsollaClientSettings.SocialProvider() { name = "epicgames", accessToken = "<social-access-token>" }) // ..other properties .Build(); ```
- **Without OAuth2** ```csharp var settings = XsollaStoreClientSettings.Builder.Create() .SetProjectId("< your_project_id >") .SetLoginId("< your_login_id >") .SetSocialProvider(new XsollaClientSettings.SocialProvider() { name = "epicgames", accessToken = "<social-access-token>" }) // ..other properties .Build(); ```
### Deep Links Configuration
Deep links are used to return the player back to your game after completing the payment flow.
By default, the SDK handles redirects automatically. You only need to configure the settings below if you want to **override** the default redirect behavior (for example, use your own redirect URL, change the auto-redirect timing, or override the redirect button/link text). tip
On **iOS**, you can use **Universal Links** (HTTPS) for redirects back to the game to avoid the “Open in *App Name*?” prompt when returning from an external browser. See [**iOS Universal Links**](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-universal-links/).
**Setting up redirect URL and delay:**
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetRedirectUrl("myapp://payment")
.SetRedirectDelay(6)
.SetRedirectButtonText("Back to the game")
.Build();
```
**Parameter explanation:**
- `SetRedirectUrl`: Overrides the URL used to redirect the player back to the game after purchase completion.
- `SetRedirectDelay`: The delay (in seconds) before Pay Station **automatically redirects** the player back to the game (so the user doesn't need to tap a redirect button).
- `SetRedirectButtonText`: Overrides the text shown on the redirect button/link in Pay Station.
tip
If you override `SetRedirectUrl`, it can be either a **custom scheme** (for example, `myapp://...`) or a **universal link** (HTTPS). Ensure your app is configured to handle the chosen type in the platform-specific project settings (iOS / Android). If you keep the SDK defaults, you typically don't need to configure anything additional.
### Email Collection Consent
Enable opt-in for collecting the user's email as part of the payment flow (for example, newsletter consent):
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetEmailCollectionConsentOptIn(true)
.Build();
```
Pass `true` to enable, `false` to disable, or `null` to use the default behavior.
### Testing purchase flow in sandbox mode
See [**Testing**](https://developers.xsolla.com/sdk/unity/sdk/testing/) guide for more details on how to enable the sandbox mode and avoid spending real money while testing the integration.
Configuration - Android
https://developers.xsolla.com/sdk/unity/sdk/configuration/android
### Sign-in redirect URIs
Sign-in methods that use an OAuth 2.0 client (`SetOAuthClientId`) send a redirect URI, and the server rejects the sign-in unless that URI is registered on the client. On Android, the URI is fixed per sign-in method and can't be changed from Unity:
| Sign-in method | Settings / call | Redirect URI to register |
| --- | --- | --- |
| Device ID with OAuth 2.0 | SetOAuthClientId, no access token or social provider | app://xlogin.<applicationId> |
| Xsolla Login widget | XsollaLoginClient.Login / LoginSilently | app://xlogin.<applicationId> |
| Token refresh | XsollaLoginClient.RefreshToken, automatic refresh | app://xlogin.<applicationId> |
| Social provider's access token with OAuth 2.0 | SetOAuthClientId + SetSocialProvider, or XsollaLoginClient.LoginWithSocialAccount | https://login.xsolla.com/api/blank |
| Device ID or social provider's access token without OAuth 2.0, your own access token (SetAccessToken) | — | None |
`<applicationId>` is your app's package name (**Player Settings > Other Settings > Package Name**), for example `app://xlogin.com.example.mygame`. If you ship builds under several package names, register the URI for each of them.
To register a URI, open your Login project in Publisher Account, go to **Security > OAuth 2.0**, and add it to the redirect URIs of the client whose ID you pass to `SetOAuthClientId`.
### Custom Tabs / Trusted Web Activity browser selection
Use `WebViewType.System` or `WebViewType.Trusted` to enable browser provider controls for Custom Tabs / TWA. Configure provider blacklists, priority weights, and TWA fallback via advanced Android settings:
| Setting | Value | Description |
| --- | --- | --- |
| SetUserBlacklistedProviders | HashSet<string> | Exclude specific Custom Tabs/TWA providers from being used. |
| SetInternalProviderBlacklistEnabled | bool | Apply the SDK's internal provider blacklist in addition to user-provided exclusions. |
| SetUserBlacklistedTWAProviders | HashSet<string> | Exclude specific TWA providers; lower priority than SetUserBlacklistedProviders. |
| SetInternalTWAProviderBlacklistEnabled | bool | Apply the SDK's internal TWA provider blacklist in addition to user-provided exclusions. |
| SetUserProviderPriorityWeights | Dictionary<string, float> | Adjust provider selection priority via per-package weights (higher weight = higher priority). |
| SetFallbackToFirstAvailableTWAProvider | bool | If requested provider lacks TWA support, fall back to the first available TWA-compatible provider. |
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetUserBlacklistedProviders(new HashSet<string>{ "com.android.chrome" })
.SetInternalProviderBlacklistEnabled(true)
.SetUserBlacklistedTWAProviders(new HashSet<string>{ "com.custom.browser" })
.SetInternalTWAProviderBlacklistEnabled(true)
.SetUserProviderPriorityWeights(new Dictionary<string, float>{{ "com.google.android.apps.chrome", 2.0f }})
.SetFallbackToFirstAvailableTWAProvider(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Trusted)
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### Cancellation Reason Querying
When enabled, the SDK distinguishes between a user closing the payment screen without paying (`Cancelled`) and a payment that was attempted but failed (reported as an error). When disabled (default), both cases report `Cancelled`.
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetQueryCancellationReasonEnabled(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### External browser app relaunch
When the app is killed during a payment flow in an external browser, the return-to-app button in Pay Station silently fails by default. Enable this setting so the redirect brings the user back to the app instead. Requires **`WebViewType.External`**.
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetRedirectAppRelaunchEnabled(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetWebViewType(XsollaStoreClientSettings.WebViewType.External)
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### WebView splash screen
Set a splash screen image displayed in the Android WebView while Pay Station loads:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebViewSplashScreenImage("path/to/splash.png")
.SetWebViewSplashScreenDrawableIdAndroid(0x7f080001) // your Android drawable resource ID
.Build();
```
- `SetWebViewSplashScreenImage`: File path to the splash screen image.
- `SetWebViewSplashScreenDrawableIdAndroid`: Android drawable resource ID for the splash screen image.
Configuration - iOS
https://developers.xsolla.com/sdk/unity/sdk/configuration/ios
### Redirecting players to external web payments (US, Japan, Brazil)
In the United States, Japan, and Brazil, Apple lets developers direct players to external web payments. Use `WebViewType.External`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.External)
.Build();
```
### In-app payment compliance in Europe under the DMA
In the EU either works: keep the flow in the app, or send the player to the web with `WebViewType.External`. Apple charges a different commission for each, and from **October 1, 2026** you have to keep whichever you pick for 12 months.
To keep the flow in the app, use `WebViewType.Auto`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.Auto)
.Build();
```
For more advanced compliance scenarios, you can programmatically detect the user's region and distribution channel to automatically configure the appropriate settings. Learn how to [**detect iOS storefront**](https://developers.xsolla.com/sdk/unity/sdk/advanced/ios-storefront/) to enable external payments for the regions that permit them, or [**detect alternative app distribution status**](https://developers.xsolla.com/sdk/unity/sdk/advanced/detectstore/) for enabling EU-specific compliance flows based on the app's installation source.
Initialization
https://developers.xsolla.com/sdk/unity/sdk/initialization
After [configuring](https://developers.xsolla.com/sdk/unity/sdk/configuration/), the **Xsolla SDK for Unity** needs to be initialized and connected to **Xsolla** services. PREREQUISITE
Make sure Unity **In-App Purchasing `4.15+`** is installed.
See the official [Unity IAP setup guide ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)).
⚠️ Unity **In-App Purchasing `5.x`** is **NOT** supported at this moment.
```csharp
public class App : MonoBehaviour, IDetailedStoreListener
{
private IStoreController _storeController;
void Start()
{
// See the configuration step for more details on how to prepare a config.
var configuration = ...
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder
.Instance(module)
.AddProduct("product1", ProductType.Consumable)
.AddProduct("product2", ProductType.Consumable)
.AddProduct("product3", ProductType.Consumable)
.AddProduct("product4", ProductType.Consumable);
UnityPurchasing.Initialize(this, configurationBuilder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
// handle initialized
}
public void OnInitializeFailed(InitializationFailureReason error)
{
// handle initialization failed
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
// handle initialization failed
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// implement purchase flow
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
// handle purchase failed
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
// handle purchase failed
}
}
```
```csharp
var storeClient = XsollaStoreClient.Builder.Create()
.SetConfiguration(configuration)
.SetOnRestore((item, error) => {
if (error != null)
{
// handle error
return;
}
// handle delayed purchased item
})
.AddProducts(productIds)
.AddProduct("product1")
.AddProduct("product2")
.AddProduct("product3")
.AddProduct("product4")
.Build();
storeClient.Initialize((products, error) =>
{
if (error != null)
{
// handle error
return;
}
// products contains all requested products
});
```
The SDK loads only Virtual Items from your Xsolla Catalog — Virtual Currency, Bundles, and other catalog types are not returned.
Installation
https://developers.xsolla.com/sdk/unity/sdk/installation
There are multiple ways to install the **Xsolla SDK for Unity** plugin in **Unity**. All of them use the *Unity's Package Manager*.
### Option 1: From a Git URL
- In Unity, go to **Window** > **Package Manager**.
- Click ➕ > **Add package from git URL...**.
- Enter: ```text https://github.com/xsolla/xsolla-sdk-unity.git ```
- Click **Add**.
note
For more information on installing plugins from a Git URL, visit the official Unity documentation [here ↗](https://docs.unity3d.com/Manual/upm-ui-giturl.html) ([https://docs.unity3d.com/Manual/upm-ui-giturl.html](https://docs.unity3d.com/Manual/upm-ui-giturl.html)).
### Option 2: From a Unity package (.unitypackage)
- Choose **Assets** > **Import Package** > **Custom Package**. A file browser appears, prompting you to locate the *.unitypackage* file.
![install 1] note
For more information on installing plugins from Unity packages, visit the official Unity documentation [here ↗](https://docs.unity3d.com/Manual/AssetPackagesImport.html) ([https://docs.unity3d.com/Manual/AssetPackagesImport.html](https://docs.unity3d.com/Manual/AssetPackagesImport.html)).
### Option 3: From a tarball
- Open your Unity project or create a new one.
- Go to **Window** > **Package Manager**.
- Add a package as a dependence: - Click the ➕ icon and select **Add package from tarball**. - Select the downloaded SDK package. - Click **Open** and wait for the import to finish.
- If you don't have **EDM4U** (Google External Dependency Manager) installed, get the latest version (external-dependency-manager-latest.unitypackage) into the project from [GitHub ↗](https://github.com/googlesamples/unity-jar-resolver) ([https://github.com/googlesamples/unity-jar-resolver](https://github.com/googlesamples/unity-jar-resolver)).
note
For more information on installing plugins from tarballs, visit the official Unity documentation [here ↗](https://docs.unity3d.com/Manual/upm-ui-tarball.html) ([https://docs.unity3d.com/Manual/upm-ui-tarball.html](https://docs.unity3d.com/Manual/upm-ui-tarball.html)).
Resolving Android dependencies
https://developers.xsolla.com/sdk/unity/sdk/installation/resolving-android-dependencies
To resolve the Android dependencies, follow these steps:
- From the main menu of **Unity editor**, go to **Assets** > **External Dependency Manager** > **Android Resolver** and click on **Resolve**. ![external dependency1]
- Wait for the dependency manager to finish.
- Once the process is done, a popup notifying of completion will appear on the screen. ![external dependency2]
- All dependencies are now resolved and the popup can be safely closed.
warning
All external dependencies are resolved through Google's **External Dependency Manager** (EDM4U), which comes prepackaged with the SDK plugin. This helps to alleviate the need to specify any of the native Android library dependencies by editing project's Gradle template scripts directly. Preferably, EDM4U should be run every time the SDK plugin is either installed anew or updated to a newer release.
Xsolla SDK for Unity - Migrating from 2.x to 3.x
https://developers.xsolla.com/sdk/unity/sdk/migration2xto3x
info
**Xsolla SDK for Unity** is an evolution of the enterprise-level Xsolla SDK solution, designed for integration into large-scale projects.
A step-by-step guide for migrating your Unity project from **Xsolla SDK 2.x** to **Xsolla SDK 3.x**, suitable for developers at any experience level.
## Prerequisites
- Unity 2022.3+ (including Unity 6).
- Backup your project (e.g., via Git).
## 1. Remove the Old SDK (2.x)
### 1.1 via Unity Package Manager
- Open **Packages/manifest.json**.
- Remove the line: ```json "com.xsolla.mobilesdk": "<version>" ``` VERSION `<version>` could look something like **2.0.22**.
- Save the file.
### 1.2 Manual install (UnityPackage)
- In the **Project** window, delete: ```plaintext Assets/Xsolla.MobileSDK ```
- If present, also remove: ```plaintext Packages/com.xsolla.mobilesdk ```
## 2. Install the New SDK (3.x)
Xsolla SDK 3.x is distributed as a `.unitypackage` or `.tar`.
Follow the [**installation guide**](https://developers.xsolla.com/sdk/unity/sdk/installation/) to install the new SDK version (3.x).
## 3. Resolve Android Dependencies (Optional)
After installing the 3.x release, you may want to resolve Android dependencies if you're explicitly targeting Android in your project.
Follow the [**Android dependency resolving guide**](https://developers.xsolla.com/sdk/unity/sdk/installation/resolving-android-dependencies/) to resolve Android dependencies. info
Xsolla SDK relies on Android AARs; the resolver automatically sets up all required libraries.
## 4. Update Namespaces and Assembly Definitions
All namespaces have changed from `Xsolla.MobileSDK.*` to `Xsolla.SDK.*`. To update:
- In your code editor, open **Find and Replace**.
- Set the search scope to your *project folder*.
- Replace all occurrences, for example: ```diff - using Xsolla.MobileSDK.Common; + using Xsolla.SDK.Common; ```
- Repeat for sub-namespaces: Store, Login, UnityPurchasing, etc.
**Assembly Definition files (.asmdef)**
If you explicitly referenced **Xsolla.MobileSDK** in one of your assembly definition files (.asemdef), you will need to update those definitions with **Xsolla.SDK** now.
## 5. Updated SDK Configuration
### 5.1 Code-based Configuration
If your project configures the SDK using `XsollaClientSettings`:
- Ensure all `using` directives reference the 3.x namespace: ```diff - using Xsolla.MobileSDK.Common; + using Xsolla.SDK.Common; ```
- Instantiate the settings object with the new type: ```csharp var settings = new Xsolla.SDK.Common.XsollaClientSettings(projectId, storeId, accessToken); ```
### 5.2 Asset-based Configuration
If you're using [**asset-based settings**](https://developers.xsolla.com/sdk/unity/sdk/configuration/) (under the *Asset* tab) there's no need to take any extra steps as migration of the settings will be automatic. tip
It's highly recommended to double-check the parameters after migration to assure their correctness.
## 6. Test & Validate
- Restart Unity to refresh all assets.
- Open **Window ▶ Package Manager** and confirm **Xsolla SDK 3.x** is installed.
- Build your project with the Xsolla SDK 3.x and in case of errors: - Make sure you located and updated all of the namespaces. - Check whether assembly definitions point at 3.x now and no 2.x entries remain. - *(Optional)* Open the Xsolla SDK settings from the menu and double-check the parameters. - *(Optional)* Verify Android dependencies resolved correctly.
## 7. Additional Resources
- **SDK Documentation:** [https://developers.xsolla.com/sdk/mobilesdk/](https://developers.xsolla.com/sdk/mobilesdk/)
- **Unity Manual (Importing Packages):** [https://docs.unity3d.com/Manual/CustomPackages.html](https://docs.unity3d.com/Manual/CustomPackages.html)
For further assistance, contact **[[email protected]](mailto:[email protected])**.
Purchase Flow
https://developers.xsolla.com/sdk/unity/sdk/purchase
Purchasing flow is a multistage process, which involves [payment collection](https://developers.xsolla.com/sdk/unity/quick-start/#purchase-product), purchase [validation](https://developers.xsolla.com/sdk/unity/sdk/purchase#validating-purchases-recommended) and [consumption](https://developers.xsolla.com/sdk/unity/sdk/purchase#consuming-purchased-goods).
### Starting Purchasing Flow
Use one of the snippets below to launch a purchasing flow depending on whether you use *Unity InApp Purchasing* or not:
```csharp
_storeController.InitiatePurchase(product);
// ...
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// handle the purchased item here
return PurchaseProcessingResult.Complete;
}
```
**Advanced Settings**
Pass purchase arguments through the Xsolla store extension. The result arrives in `ProcessPurchase`, as with `InitiatePurchase` on the store controller.
```csharp
private IXsollaPurchasingStoreExtension _xsollaExtension;
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_xsollaExtension = extensions.GetExtension<IXsollaPurchasingStoreExtension>();
}
// ...
var args = XsollaStoreClientPurchaseArgs.Builder.Create()
.SetDeveloperPayload("<your-custom-developer-payload>")
.Build();
_xsollaExtension.InitiatePurchase(product, args);
```
| Builder method | Details |
| --- | --- |
| SetDeveloperPayload(string) | Developer Payload |
| SetExternalId(string) | External ID |
| SetExternalTransactionToken(string) | External Transaction Token |
| SetPaymentMethodId(int?) | Forcing a Payment Method |
```csharp
storeClient.PurchaseProduct(productId, (product, error) =>
{
if (error != null)
{
// handle error
return;
}
var receipt = product.ToReceipt();
// handle the purchased product here (e.g. validate or consume)..
});
```
**Advanced Settings**
Use a more complete `XsollaStoreClient.PurchaseProduct()` variant for extended functionality:
```csharp
XsollaStoreClient.PurchaseProduct(
string productId,
XsollaStoreClientPurchaseArgs args,
Action<XsollaStoreClientPurchasedProduct, XsollaStoreClientError> completionHandler
)
```
### Developer Payload
Use the example below to set your custom developer payload for a purchasing flow:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
developerPayload = "<your-custom-developer-payload>"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### External ID
Allows providing your own custom unique ID for a transaction.BEWARE
You need to enable external ID support in your *Publisher Account* beforehand or purchasing will fail.
Use the example below to set the external ID for a purchasing flow:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
externalId = "<your-custom-unique-external-id"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### External Transaction Token
Attaches an external transaction token to the launched purchasing flow, so it carries through to your order for reporting back to the platform. The setter is shared across platforms; what it's used for depends on the target:
| Platform | Supported | Used for |
| --- | --- | --- |
| Android | ✅ | Google Play external transaction token, for User Choice Billing / alternative billing reporting — see Reporting External Transactions to Google Play |
| iOS | ❌ | — |
| Windows | ❌ | — |
| macOS | ❌ | — |
| Web | ❌ | — |
Setting `externalTransactionToken` on a platform not listed as supported above fails the purchase call with an error, rather than dropping the value silently. Also don't confuse it with `externalId` above: that's Xsolla's own merchant ID for matching orders, not a platform token.
Use the example below to attach the token for a purchasing flow:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
externalTransactionToken = "<google-play-external-transaction-token>"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### Forcing a Payment Method
Allows selecting a specific payment method for a purchasing flow.tip
Payment method IDs can be found in your *Publisher Account*.
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
paymentMethodId = <payment-id>
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### Handling User Cancellation
When a player cancels a purchase, handle it separately from actual errors.
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// User cancelled the purchase — don't show an error
return;
}
// Handle other failure reasons
}
// Or (newer API)
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// User cancelled the purchase — don't show an error
return;
}
// Handle other failure reasons
}
```
```csharp
void OnPurchase(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
if (error?.code == XsollaStoreClientPurchaseErrorCode.Cancelled)
{
// User cancelled the purchase — don't show an error
return;
}
if (error != null)
{
// Handle other errors
return;
}
// Handle successful purchase
}
```
### Validating Purchases (Recommended)
warning
Although validation is **NOT** a mandatory step, yet it's highly recommended to minimize the chance of fraud and any other malevolent intents.
For instructions on how to validate your purchases, see [**Purchase Validation**](https://developers.xsolla.com/sdk/unity/sdk/validation/) guide.
### Consuming Purchased Goods
The very final step in the chain of purchasing flow stages is to award the purchased goods to the user and mark these goods as "awarded". The process also known as **purchase consumption**.
Use the code below to do just that:
```csharp
_storeController.InitiatePurchase(product);
// ....
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// handle purchased item
return PurchaseProcessingResult.Pending;
}
// ....
_storeController.ConfirmPendingPurchase(product);
```
```csharp
storeClient.ConsumeProduct(item.sku, item.quantity, item.transactionId, error => {
if (error != null)
{
return;
}
// handle purchased item
});
```
important
It's highly recommended to perform at least some form of [**validation**](https://developers.xsolla.com/sdk/unity/sdk/purchase#validating-purchases-recommended) before consuming the purchased goods.
Testing & Sandbox
https://developers.xsolla.com/sdk/unity/sdk/testing
This section provides various snippets and examples of how to configure the sandbox environment to be able to make test payments, make logging more verbose, and so on.
### Enabling sandbox mode
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetSandbox(true)
.Build();
```
#### Testing in Unity Editor
Testing in the Unity Editor uses the current platform's implementation (e.g., Windows or macOS). warning
Remember to turn the **sandbox** mode **OFF** before going **LIVE**.
### Enabling additional logging
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
warning
Make sure the debug **logging** is **OFF** before going **LIVE**.
### Test cards
For a list of cards to simulate payments in sandbox mode, see [here ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)). important
The test cards won't work outside the **sandbox mode**.
Purchase Validation
https://developers.xsolla.com/sdk/unity/sdk/validation
Each purchase should be validated before awarding it to the end-user. This assists in preventing unauthorized purchases and ensures the integrity of your in-app economy. Validating purchases is a critical security measure to prevent fraud, protect your revenue, and ensure fair user experiences.
Essentially, that are two distinct validation approaches readily available.
### Server-side Validation
The most secure and reliable way to validate purchases is by using **server-to-server** (**S2S**) communication, with the client completely removed from the validation process. This minimizes security risks and ensures that entitlements are only granted based on verified data received directly from Xsolla.
With Xsolla, server-side validation is implemented through a **webhook-based model**:
- Once a user completes a purchase through your app, Xsolla services automatically trigger a [**webhook event**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#user_validation) to your backend.
- This webhook contains all the necessary purchase data, including the **Xsolla** `order ID`, enabling your server to validate and process the purchase asynchronously.
- Your backend can then use this data to update the user’s entitlements, balance, inventory, etc., without requiring any additional input from the client.
This flow ensures that the client has no role in deciding the outcome of a purchase — all validation logic lives on the server, using trusted data that originates from Xsolla itself. tip
For more information about how webhooks work, see [**here**](https://developers.xsolla.com/sdk/publisher-account/webhooks/).
### Client-side Validation
Provides means of validating a purchase on the user's device without a need for a backend (server). It's better than nothing, but has its own drawbacks, i.e. anything that runs on the client can potentially be exploited.
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = purchaseEvent.purchasedProduct;
var validator = extensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
validator.ValidatePurchase(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
```csharp
void MyOnPurchaseCallback(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
_storeClient.ValidatePurchase(product.ToReceipt(), (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
Xsolla SDK for Unity - Web
https://developers.xsolla.com/sdk/unity/web
info
**Xsolla SDK for Unity** is an evolution of the enterprise-level Xsolla SDK solution, which was designed for integration into large-scale projects.
This guide helps you integrate the Xsolla SDK for Unity to start accepting payments in your Unity game on Web. By the end, you'll have a fully functioning payment system in your game and experience firsthand how Xsolla streamlines monetization.
Let's dive in and get your game ready to accept payments in just a few easy steps!
## Quick start
This quick start guide makes it simple to integrate the *Xsolla SDK for Unity* on Web and start accepting payments in your *Unity* game. We'll use a pre-configured test project to cover all the essentials: setting up basic user authentication, importing your products (SKUs), and processing a test payment.
For detailed instructions, please refer to the [**Quick Start Guide**](https://developers.xsolla.com/sdk/unity/quick-start/).
## Setting up a Publisher Account
Before you begin integrating Xsolla SDK into your game, you'll need to register a Publisher Account.
The Publisher Account is the primary tool for configuring Xsolla features, working with analytics and transactions similar to Google Play Console and App Store Connect for SKU management.important
You'll need to have an active Publisher Account to obtain a Project ID you'd use throughout the whole SDK integration process.
For detailed instructions, please refer to [**Setting up a Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/).
## Install the SDK
Now that you've set up your Publisher Account, the next step is to install the Xsolla SDK for Unity plugin in your Unity project.
For detailed installation instructions, see the [**Installation Guide**](https://developers.xsolla.com/sdk/unity/sdk/installation/).
## Configure the SDK
Once you've installed the SDK, the next step is configuration.
For detailed instructions, please refer to the [**Configuration Guide**](https://developers.xsolla.com/sdk/unity/sdk/configuration/).info
Using **a device ID** to log in is not supported on the Web platform. You must provide an access token instead. For more information, please refer to [**Authentication via custom ID**](https://developers.xsolla.com/sdk/publisher-account/login/#login-on-game-server)
Alternatively, you can use the [**Delayed configuration**](https://developers.xsolla.com/sdk/unity/sdk/configuration/#assign-xsolla-access-token-to-the-configuration) feature to postpone SDK initialization until an access token is obtained.
## Initialize the SDK
With configuration complete, you're now ready to initialize the SDK in your Unity project.
For detailed steps and best practices, refer to the [**Initialization Guide**](https://developers.xsolla.com/sdk/unity/sdk/initialization/).
## Make a Purchase
Now that the SDK is initialized, your app is ready to start processing payments.
For detailed instructions, please refer to [**Make Purchase**](https://developers.xsolla.com/sdk/unity/sdk/purchase/).
## Collect Payment
The SDK leverages **Xsolla Pay Station** for *secure* payment collection.
These steps will guide you through a test payment collection flow:
- Choose the **Card** payment method: ![quick start3]
- Use one of the test cards listed [**here ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) and click **Pay** to confirm the payment: ![quick start3]
- Once the payment goes through, you'll see a confirmation: ![quick start3]
## Purchase Validation
After setting up payments, you might want to validate your purchase to ensure transaction security and reliability.
For detailed instructions, please refer to [**Purchase Validation**](https://developers.xsolla.com/sdk/unity/sdk/validation/).
## Testing & Sandbox
As a final step, use the sandbox environment to safely test your entire payment integration without real transactions.
For detailed instructions, please refer to the [**Testing & Sandbox**](https://developers.xsolla.com/sdk/unity/sdk/testing/).
## What's next?
Congratulations! 🎉 You've successfully integrated **Xsolla SDK for Unity** on Web!
This achievement unlocks access to over 1000 global payment methods and sets the foundation for integrating more Xsolla solutions, including our powerful Web Shop.
Xsolla SDK 3 for Unreal Engine: Early Access Pilot
https://developers.xsolla.com/sdk/unreal-pilot
Early AccessUnreal Engine 4.27, 5.0–5.8 · Windows & Linux
Xsolla SDK 3 for Unreal Engine is in early access. It handles the commercial layer of your game: signing players in, showing them your catalog, taking their money, and delivering what they bought. This page covers what the pilot is, what we are asking of you, and where to start.
Sign-in works through an **Xsolla account**, **Steam**, or **EOS**, with full **Blueprint** support throughout.[Join the pilot program](https://developers.xsolla.com/sdk/unreal-pilot#join-the-pilot-program)
## What the pilot is
SDK 3 for Unreal is complete through its MVP feature set and is in internal verification. It has been tested against first-party standards, but a test suite only proves the paths we thought to write. Real games bring permutations we did not anticipate: different engine versions, unusual sign-in and inventory setups, partial scopes, and design decisions we would never have made ourselves.
If you have an Unreal project on hand, or you are starting one, integrate SDK 3 and put it through its paces. Every project runs a slightly different setup, so each one shows us something the last did not.
**Partial scope is welcome.** A title that only exercises Steam sign-in is still a valuable pilot. Run the gates your project supports and file a report.
## The four capability gates
A gate is one part of the SDK working end to end in a real game. There are four, and each has a walkthrough in the repo.
| Gate | What it proves |
| --- | --- |
| C1 Auth | A player logs in, closes and reopens the game, and is still signed in |
| C2 Catalog Sync | Your in-game storefront renders your catalog: items and currencies |
| C3 Purchase | Checkout launches from inside Unreal for a catalog item |
| C4 Finalize | The order reaches a final state and the item appears in the player's inventory |
Install is a prerequisite. C1 starts once your project compiles.
Players can sign in three ways: with an Xsolla account, through Steam, or through EOS. We want all three proven in a live game, and we need at least one project covering each. After that, the more the better.
## What SDK 3 gives you
**One Purchase Path**
However a player signs in, the purchase code you write is the same. Steam and EOS hand over an authentication ticket that resolves into a single Xsolla session, and everything downstream of that is identical.**Cross-Engine Consistency**
The core is structurally 1:1 with the Unity 3.x SDK, with each Unity package assembly mapping to an Unreal plugin module. If your studio ships on both engines, the mental model transfers.**A Lean Core**
Pure code, minimal dependencies, with an online-subsystem dependency only in the IAP module. The test suite ships alongside the SDK as a companion plugin and runs against Valve's and Epic's own sample projects. **Your Online Subsystem Stays Yours**
The SDK coexists with Steam or EOS while holding the Xsolla session for commerce. Steam Wallet and EOS Ecom work as real IAP backends behind a common interface, with per-provider pricing.**Launcher Handoff in One Step**
A player who launches from Xsolla Launcher arrives already signed in. Call `LoginWithLauncherToken` and the SDK uses the session token as-is.**Everything Works in Blueprint**
Every capability the SDK exposes is reachable from Blueprint, not just C++.
## Platforms and distribution
Windows (Win64) is the primary development host, with full platform dispatch, all Pay Station web-view paths, a sandbox and production runtime toggle, and locale resolution. Linux is supported alongside it, including dedicated-server builds. macOS, iOS, and Android are next-milestone scope.
Distribution is source-only. There is no prebuilt binary and no Fab listing. Your project's own Unreal build compiles the plugin, which keeps packages platform-neutral and version-neutral.
## Where to start
Setup guides — the documentation index, architecture overview, installation steps, and the Steam/EOS integration walkthroughs — live in the pilot repo. Access to the repo and code is granted by [joining the pilot program](https://developers.xsolla.com/sdk/unreal-pilot#join-the-pilot-program) below.
## Reporting
File a GitHub issue with the `pilot-ready` label, or bring it to the pilot [Discord](https://discord.gg/25DNbVVNng). Either one reaches the SDK team inside the pilot window.
Blunt, critical feedback is welcome.
One thing worth knowing up front: parts of the repo still carry leftover planning and tracking content from development, and some of it has yet to see human eyes. If you hit duplicated docs, stale plans, or orphaned content, flag that too.
## Join the pilot program
Native Android — Xsolla SDK 3 Integration Video
https://developers.xsolla.com/sdk/video-guides/video-sdk3-native-android
A step-by-step video walkthrough for integrating the Xsolla SDK into a native Android game (Java). Using a simple clicker-game demo, it shows how to launch a secure Pay Station checkout overlay natively inside the app — giving players access to 1,000+ localized payment options without routing out to a browser.
The video covers setup plus the four stages of a complete integration:
- **Set Up the SDK** — add the Xsolla Maven repo and dependency in Gradle, then import the package in your main activity.
- **Authenticate** — initialize `Config` and the `BillingClient` (with Project ID, Login ID, sandbox enabled) in `onCreate()`.
- **Load Catalog** — query product details with `queryProductDetailsAsync`.
- **Purchase Product** — launch the billing flow (`launchBillingFlow`) to open the Xsolla Pay Station overlay.
- **Finalize Purchase** — listen for the result and `consumeAsync` the transaction token to award the item.
Native iOS — Xsolla SDK 3 Integration Video
https://developers.xsolla.com/sdk/video-guides/video-sdk3-native-ios
A step-by-step video walkthrough for Swift developers integrating the Xsolla SDK into a native iOS game — without abandoning StoreKit. The SDK slots in as a thin wrapper around the familiar `SKPaymentQueue` API, adding authentication, Pay Station, and purchase validation on top of the StoreKit flow developers already know.
The video covers the four stages of a complete integration:
- **Authenticate** — build an `SKPaymentSettings` object with your Project ID and Login Project ID; enable payments, open Pay Station in external Safari (U.S. compliance), and configure a persistent anonymous user ID.
- **Load Catalog** — fetch products with `SKProductsRequest`, matching SKUs across App Store Connect and Publisher Account (Virtual Items only).
- **Purchasing** — dispatch on the main thread, set the `rootViewController` anchor, and add the `SKPayment` to the queue.
- **Finalizing** — call `validateTransaction` before granting the item, and always `finishTransaction` in every branch.
Unity Mobile — Xsolla SDK 3 Integration Video
https://developers.xsolla.com/sdk/video-guides/video-sdk3-unity-mobile
A step-by-step video walkthrough for Unity developers integrating the Xsolla SDK into a mobile (iOS/Android) game. Built on the Unity 2D Game Kit demo, it implements a buy-full-health impulse purchase and routes checkout through Pay Station in an external browser — the compliant path for U.S. iOS and Google Play following the 2025 court rulings.
The video covers the four stages of a complete integration:
- **Authenticate** — initialize the SDK with your Project ID and Login ID using client-side Device ID auth.
- **Load Catalog** — register product SKUs with Unity IAP and pull the catalog from Xsolla's backend.
- **Purchase Product** — call `InitiatePurchase`, handing off to Pay Station in the mobile browser.
- **Finalize Purchase** — run client-side validation in `ProcessPurchase` and grant the item on success.
Unity PC — Xsolla SDK 3 Integration Video
https://developers.xsolla.com/sdk/video-guides/video-sdk3-unity-pc
A step-by-step video walkthrough for Unity developers integrating the Xsolla SDK into a PC game for off-platform distribution. Using the Unity 2D Game Kit as a demo, it builds a classic impulse-buy moment — a player dies and can buy a full-health respawn — wired end-to-end through Pay Station.
The video covers the four stages of a complete integration:
- **Authenticate** — initialize the SDK with your Project ID and Login ID using Device ID (no login screen).
- **Load Catalog** — register your product SKUs with Unity's IAP layer and fetch the catalog from Xsolla.
- **Purchase Product** — trigger `InitiatePurchase`, launching Pay Station in the player's default browser.
- **Finalize Purchase** — validate the transaction client-side and grant the item on success.
Core Concepts (Android)
https://developers.xsolla.com/sdk/welcome/core-concepts-android
Going beyond the Google Play Billing Library, to **Xsolla SDK** involves a few essential steps to ensure seamless integration and functionality. Below is a structured breakdown of the **three core concepts** required for supporting expanded range of payments.
## Authentication and Login
- [**Google Play Sign-In ↗**](https://support.google.com/googleplay/answer/3129346) ([https://support.google.com/googleplay/answer/3129346](https://support.google.com/googleplay/answer/3129346)): Users are automatically logged into the Google Play ecosystem via Google Play Services, which naturally happens in background, providing developers with an ID for billing (in a private but hidden way).
- [**Xsolla Login**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#authentication): Xsolla provides developers a way to implement specific login authentication SDK APIs, integrating it with developer's server or relying on client-side authentication methods for simpler games, e.g., *hypercasual*. These APIs are crucial for passing the user's ID or device ID to Xsolla services, ensuring that users are properly recognized within the Xsolla products (e.g., for seamless recurring payments). Upon successful authentication, Xsolla provides a token that is essential for initiating purchasing flows.
## SKU and In-App Purchases (IAP)
Product Terminology
In this documentation:
- **IAP (In-App Purchase)** = Google Play Billing's purchase mechanism
- **SKU (Stock Keeping Unit)** = Product identifier used in code
- **Virtual Items** = Items in your Xsolla Catalog (IAPs)
When migrating from Google Play to Xsolla, your IAPs become Virtual Items in the Xsolla Catalog, each with its own SKU for code references.
- [**Google Play Billing ↗**](https://developer.android.com/google/play/billing/getting-ready#products) ([https://developer.android.com/google/play/billing/getting-ready#products](https://developer.android.com/google/play/billing/getting-ready#products)): In Google Play Billing, products (also known as SKUs or IAPs) are identified by a unique **Product ID** (e.g., '*com.company.gameapp.keys_1*') and a descriptive **Product Name** (e.g., '*5 Keys*'). For instance, '*5 Keys*' might represent a key pack priced at $1.
- **Xsolla Catalog**: The Xsolla Catalog contains your digital goods as [**Virtual Items**](https://developers.xsolla.com/sdk/publisher-account/virtual-items/) (IAPs). To transition from Google Play Billing, developers import their existing Product IDs from Google Play Console. Each product becomes a Virtual Item with its own SKU identifier for use in code.
## Initializing the Pay Station
- **The Pay Station** serves as the gateway for your users' purchases. It requires both the access token and the specific SKU (e.g., '*keys_1*') identifying which Virtual Item (IAP) to purchase. Developers must ensure these elements are correctly configured, enabling users to buy items seamlessly, mirroring the purchase experience they would have via Google Play Billing.
- With your [*Virtual Items*](https://developers.xsolla.com/sdk/publisher-account/virtual-items/) (IAPs) set up and an [*access token*](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/android/#authentication) obtained (e.g., based on user/device ID or via your server), the next crucial step is to [*initialize the Pay Station*](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android/). This is where the actual transaction process begins by forming an order.
## Webhooks
[Webhooks](https://developers.xsolla.com/sdk/publisher-account/webhooks/) are notifications about events occurring in the system. When a specific event occurs, Xsolla sends an HTTP request, transmitting event data to your game server (or client, in case of simplified client-only integration e.g. for *hypercasual games*). These webhooks are essential for the game client and/or server to receive notification on successful/unsuccessful payments and user authentication attempts.
In several regions Google charges a commission on external transactions and requires you to report them. That reporting is part of your integration, built from the webhook data above. See [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/).
## Conclusion
By following these steps, developers can effectively map the Xsolla ecosystem to expand beyond Google Play Billing library, providing a comprehensive alternative that opens up a broader array of payment options globally. This expansion not only supports a more diversified monetization strategy but also enhances user engagement by leveraging Xsolla's extensive set of value-add solutions.
For guidance on regulated Google Play billing programs, see the [Google Play User Choice Billing reference](https://developers.xsolla.com/sdk/mobilesdk/addendum/android/google-play-user-choice-billing/).
Core Concepts (iOS)
https://developers.xsolla.com/sdk/welcome/core-concepts-ios
Expanding from Apple's StoreKit Framework to **Xsolla SDK** involves several key steps to ensure seamless integration and functionality. Here's a structured breakdown of **the core concepts** required for supporting an expanded range of payments on iOS:
## Authentication and Login
- **Awareness of Apple ID / Account**: iOS users are typically signed in to their Apple ID on their devices, providing a seamless identity layer for transactions.
- [**Xsolla Login**](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/): Xsolla provides developers a way to implement specific login authentication SDK APIs, integrating it with developer's server or relying on client-side authentication methods for simpler games, e.g. hypercasual. These APIs are crucial for passing the user's ID or device ID to Xsolla services, ensuring that users are properly recognized within the Xsolla products (e.g. for seamless recurring payments). Upon successful authentication, Xsolla provides a token that is essential for initiating purchasing flows.
## SKU and In-App Purchases (IAP)
Product Terminology
In this documentation:
- **IAP (In-App Purchase)** = StoreKit's purchase mechanism
- **SKU (Stock Keeping Unit)** = Product identifier used in code
- **Virtual Items** = Items in your Xsolla Catalog (IAPs)
When migrating from App Store to Xsolla, your IAPs become Virtual Items in the Xsolla Catalog, each with its own SKU for code references.
- [**In-app Purchases sold via StoreKit Framework ↗**](https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases) ([https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases](https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases)): Products within an iOS app are identified via a "Product ID" (e.g., `com.game.key_1`) accompanied by a "Reference Name" (e.g., "Key Pack 1"). In this example, it refers to a key pack worth $1.
- **Xsolla Catalog**: The Xsolla Catalog contains your digital goods as [**Virtual Items**](https://developers.xsolla.com/sdk/publisher-account/virtual-items/) (IAPs). To transition these products to Xsolla, developers import their **App Store Connect Product IDs** from App Store Connect. Each product becomes a Virtual Item with its own SKU identifier for use in code, ensuring that products from the App Store ecosystem are accurately represented and synchronized.
## Initializing the Pay Station
- After [setting up SKUs](https://developers.xsolla.com/sdk/publisher-account/virtual-items/) and [obtaining an access token](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios/) (e.g. based on user/device ID, or via server), the next step is to [initialize the Pay Station](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/ios/). This is where the actual transaction process begins by forming an order.
- The Pay Station requires both the access token and the specific SKU (e.g., "key_1") identifying which Virtual Item (IAP) to purchase. Developers need to ensure that both elements are correctly configured to allow users to buy items seamlessly, mirroring the purchase experience they would have via StoreKit Framework.
## Webhooks
[Webhooks](https://developers.xsolla.com/sdk/publisher-account/webhooks/) are notifications about events occurring in the system. When a specific event occurs, Xsolla sends an HTTP request, transmitting event data to your game server (or client, in case of simplified client-only integration e.g. for *hypercasual games*). These webhooks are essential for the game client and/or server to receive notification on successful/unsuccessful payments and user authentication attempts.
## Alternative Payments and App Store Policies
With recent changes in App Store policies, developers now have more options for implementing alternative payment methods, especially in certain regions. *Xsolla SDK* is designed to help navigate these new possibilities while ensuring compliance with Apple's guidelines. note
To implement region-specific payment methods, you can use the [iOS Storefront detection](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront/) feature. This allows you to enable or disable payment methods based on the user's current App Store region, ensuring compliance with regional policies and requirements.
In some regions Apple charges a commission on external purchases and requires you to report them. That reporting is part of your integration, built from the webhook data above. See [Reporting External Purchases to Apple](https://developers.xsolla.com/sdk/compliance/ios/).
## Conclusion
By following these steps, developers can effectively map the Xsolla ecosystem to expand beyond the StoreKit, providing a comprehensive alternative that opens up a broader array of payment options globally. This expansion not only supports a more diversified monetization strategy but also enhances user engagement by leveraging Xsolla's extensive set of value-add solutions, all while maintaining compliance with iOS platform requirements.
Mobile Game Distribution Glossary: The DMA Era and U.S. Court Rulings
https://developers.xsolla.com/sdk/welcome/glossary
## Introduction
The Digital Markets Act (DMA) and U.S. court rulings have introduced new concepts in mobile game distribution and monetization. This glossary explains these terms and how **Xsolla SDK** supports developers in this evolving landscape.
As the industry adapts to regulatory changes, understanding new distribution methods and payment options is crucial. **Xsolla SDK** empowers developers to navigate this new ecosystem, providing compliant solutions that open up new monetization avenues.
**Xsolla SDK** supports the following key concepts:
## iOS / Apple App Store:
- **External Payment Links (United States, Japan, Brazil, European Union)**: - Apple now lets developers direct players to external web payments in the **United States** (*Epic v. Apple*, April 2025), **Japan** (Mobile Software Competition Act, effective December 18, 2025), **Brazil** (Apple's CADE antitrust settlement, effective June 18, 2026), and the **European Union** (Digital Markets Act) - Implement link-outs to Xsolla Pay Station or Web Shop for users in these markets - Use iOS storefront detection to identify the user's storefront and enable region-specific payment flows - **Xsolla SDK** aligns with Apple's updated guidelines - Configure `openExternalBrowser = true` when redirecting players to web payment pages - The rules are **not the same in every market**. On the United States storefront no entitlement is required and Apple currently charges no commission on these transactions. In **Japan**, **Brazil** and the **EU** you need an Apple entitlement, Apple takes a commission, and you must report the transactions back to Apple. See [Reporting External Purchases to Apple](https://developers.xsolla.com/sdk/compliance/ios/)
- [**Alternative App Marketplaces ↗**](https://developer.apple.com/support/alternative-app-marketplace-in-the-eu) ([https://developer.apple.com/support/alternative-app-marketplace-in-the-eu](https://developer.apple.com/support/alternative-app-marketplace-in-the-eu)) on iOS: - Apple's term for alternative App Stores, available in EU markets and, since June 2026, in Brazil - Implement Xsolla Pay Station for in-app payments outside App Store - Power your Marketplace wallet with top-up solution via Xsolla Pay Station - Apple applies its own commission to apps distributed this way, and marketplace operators have their own reporting duties. Check Apple's current terms for your region. In the EU this is the **Core Technology Commission** from October 1, 2026, a share of digital sales replacing the old per-install Core Technology Fee
- [**Web Distribution ↗**](https://developer.apple.com/support/web-distribution-eu) ([https://developer.apple.com/support/web-distribution-eu](https://developer.apple.com/support/web-distribution-eu)) on iOS: - Apple's term for side-loading on iOS via official publisher websites - Distribute your app directly to users from your website - Implement direct in-app payments via Xsolla Pay Station, outside App Store billing - Apple still charges its own fee on digital goods sold this way — in the EU, the **Core Technology Commission** from October 1, 2026. Check Apple's current terms before modelling your margins
- [**Notarization ↗**](https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization) ([https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization](https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization)) for iOS: - Light approval process by Apple for distribution outside of App Store - Ensures basic safety and integrity checks for your app - **Xsolla SDK** is compatible with notarized apps, maintaining security standards
- [**Alternative Payment Options ↗**](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) ([https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu)) on the App Store: - Integrate Xsolla Pay Station within App Store apps via **Xsolla SDK**, in the regions where Apple permits it - Offer users 1,000+ payment methods across 200+ countries - Apple takes a commission on these transactions and requires you to report them. See [Reporting External Purchases to Apple](https://developers.xsolla.com/sdk/compliance/ios/) - In the EU from **October 1, 2026** you can offer Apple In-App Purchase alongside alternative payments, but your choice of payment options is locked for 12 months, so plan it before you ship
## Android / Google Play:
- **External Payment Methods via Link-outs and Alternative Billing Solutions (United States)** — live since October 29, 2025: - Following the **Epic v. Google** injunction — affirmed by the Ninth Circuit on July 31, 2025 (147 F.4th 917), and denied a stay by the U.S. Supreme Court on October 6, 2025 — U.S. **Google Play** apps may guide users to **external payment methods via link-outs** and use **alternative billing solutions**. In July 2026, Epic and Google withdrew only their joint motion to modify this injunction to match a proposed settlement — not the settlement itself, whose commercial terms (fee schedule, Registered App Stores) still apply separately. The original October 2024 injunction remains the operative court order; its written term runs three years from issuance, but implementation delays mean sources disagree on the practical end date (some cite November 2027, others later) — don't plan against either without checking the docket - Developers are no longer subject to **anti-steering restrictions** in the United States - Developers must enroll in the applicable Google program and accept updated terms of service: [**External Content Links Program ↗**](https://support.google.com/googleplay/android-developer/answer/16470497) ([https://support.google.com/googleplay/android-developer/answer/16470497](https://support.google.com/googleplay/android-developer/answer/16470497)) for link-outs to external purchase pages, and/or [**Alternative Billing Program ↗**](https://support.google.com/googleplay/android-developer/answer/16497028) ([https://support.google.com/googleplay/android-developer/answer/16497028](https://support.google.com/googleplay/android-developer/answer/16497028)) for using non-Google billing within the app. Developers can participate in both programs simultaneously - Google isn't collecting fees or requiring reports on these U.S. transactions yet — both start October 1, 2026 - Similar programs are already live and fee-bearing elsewhere — User Choice Billing, external offers (EEA), billing choice (UK/EEA), and external payments (Japan). Google takes a commission on those transactions today and requires you to report them, see [Reporting External Transactions to Google Play](https://developers.xsolla.com/sdk/compliance/android/) - Implement link-outs to Xsolla Pay Station or Web Shop for U.S. users - Use Google Play storefront detection to identify U.S. users (country code "US") and enable region-specific payment flows - **Xsolla SDK** ensures full compliance with Google's revised requirements for U.S. apps
- [**Side-loading on Android ↗**](https://developer.android.com/distribute/marketing-tools/alternative-distribution) ([https://developer.android.com/distribute/marketing-tools/alternative-distribution](https://developer.android.com/distribute/marketing-tools/alternative-distribution)): - Install apps (APKs) directly from websites or third-party sources - Implement payments with 0% fees to Google - Retain full control over your app distribution and monetization - **Xsolla SDK** seamlessly integrates with side-loaded apps - **Developer verification requirement (upcoming):** Starting March 2026, Google requires all developers to [**register and verify their identity ↗**](https://developer.android.com/developer-verification) ([https://developer.android.com/developer-verification](https://developer.android.com/developer-verification)), including for sideloaded apps. Enforcement begins September 2026 in select regions (Brazil, Indonesia, Singapore, Thailand), with global rollout planned for 2027 and beyond. Apps from unverified developers will be blocked on certified Android devices. See [**Google's verification guide ↗**](https://support.google.com/android-developer-console/answer/16561738) ([https://support.google.com/android-developer-console/answer/16561738](https://support.google.com/android-developer-console/answer/16561738)) for details
- APK Marketing & Distribution: - Leverage partnerships with channels like *Digital Turbine* for wider reach and enable instant APK installation on Android devices - Tap into new user acquisition channels beyond Google Play and pave your own way - Xsolla is compatible with attribution tools for your APK distribution, ensuring you can continue optimizing your performance
## Conclusion
The mobile gaming landscape is rapidly changing due to regulations like the DMA, U.S. court rulings (including the April 30, 2025 iOS decision and the Epic v. Google injunction, effective October 29, 2025), new external-payment laws in Japan and Brazil, and evolving platform policies. **Xsolla SDK** offers a comprehensive toolkit to navigate these changes, helping you maximize revenue and reach across all available channels.
We update this information regularly. For the most current details, see the [News](https://developers.xsolla.com/sdk/documentation-changelog/). For tailored guidance, please consult your Business Development representative or Customer Success Manager.
By using **Xsolla SDK**, you're positioning your game to thrive in this dynamic environment, unlocking new revenue streams and innovative distribution channels.
Xsolla SDK for Windows
https://developers.xsolla.com/sdk/windows
AvailableXsolla SDK for Windows[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
The **Xsolla SDK for Windows** brings out-of-store commerce, in-app purchases, and global payments to games on the Microsoft platform. With a **single integration**, the SDK empowers developers to connect directly with players, maintain control over the checkout experience, and keep up to 95% of their revenue. It supports side-by-side in-store checkout where allowed, enabling flexible billing strategies and loyalty incentives. Games automatically benefit from updates for new monetization tools, regulatory compliance, and global policy changes.
With built-in **IAP catalog sync**, streamlined tax onboarding for **flexible payouts**, and support for **more payment methods and local currencies**, the Xsolla SDK makes scaling Windows games across stores and regions simple. Developers can focus on building their game, while Xsolla handles the complexity of payments, payouts, and compliance.
## Platform Support
### Epic Games Store & 3rd-Party Commerce
Epic Game Store policy allows developers to use alternative payment methods, including browser-based flows, provided they handle processing and fulfillment. See Epic's official documentation for details.
That means developers can run their own payment system alongside—or instead of—the Store's commerce, giving full control over offers to players via features like dual billing, Web Shop purchases, and player incentives. Explore **[this article](https://developers.xsolla.com/sdk/windowstores/epic/)** for more details.
### Game Engine Coverage
info
If you are using *Unity* for your project, we recommend integrating the **Xsolla SDK for Unity**. For more details, please visit [**this page**](https://developers.xsolla.com/sdk/unity/).
- **Unity**: Use the [**Xsolla SDK for Unity**](https://developers.xsolla.com/sdk/unity/) for Windows games built with *Unity*.
- **Custom Engines**: [**Native SDKs**](https://developers.xsolla.com/sdk/windowstores/sdk/installation/) available in C++ and C# for full flexibility.
- **Defold**: Integrate payments quickly with the **Xsolla SDK for Defold**, available on *Defold Asset Portal*.
- **More Coming Soon**: Support for additional engines is in progress — stay tuned!
## Key Benefits for Windows Developers
**One Integration, Many Stores**
Get up and running on Epic Games Store and other Windows stores with a single SDK. Wherever your game lives, your monetization strategy stays consistent — and in your control.**Dual Billing Support**
Offer players side-by-side checkout options to let them choose how they pay. Reward loyalty, encourage competition, let commerce become a feature. See [best practices](https://developers.xsolla.com/sdk/windowstores/epic/dual-billing/) for more.**Catalog Sync Across Platforms**
Sync your IAPs to your Xsolla Catalog (as Virtual Items with SKUs) effortlessly. Avoid juggling dev portals and managing redundant item definitions across multiple stores.**Flexible Payouts Without the Paperwork**
Onboarding and tax compliance can be a time sink — Xsolla offers a smooth, global tax interview process and payout flexibility to get you monetizing faster.**More Payment Options, Global Reach**
Xsolla supports more global payment methods, more local currencies, localized checkout flows, advanced anti-fraud, and compliant payment processing out-of-the-box.
## Getting Started
**Xsolla Buy Button**Fast Path
One-tap Web Shop purchase flows with 1,000+ payment methods — no SDK installation required. Launch browser-based checkout directly from within your Windows game.[Learn more →](https://xsolla.com/mobile-buy-button) [EPIC GAMES**Epic Games Store**Enable commerce on Epic with dual billing and Web Shop→](https://developers.xsolla.com/sdk/windowstores/epic/)[SDK DOCS**Installation Guide**Step-by-step SDK integration for C++ and C# engines→](https://developers.xsolla.com/sdk/windowstores/sdk/installation/)
Xsolla SDK: Powering Commerce for Games on Epic Games Store
https://developers.xsolla.com/sdk/windowstores/epic
Epic Games Store policy allows developers to use alternative payment options, giving studios the freedom to choose the tools that best fit their business. Xsolla’s SDKs and services are designed to work alongside or in place of Epic’s native commerce system—empowering you to optimize checkout, streamline operations, and build stronger relationships with your players.
## Player-Centric Opportunities
**Dual Billing with Player-Centric Benefits**: Xsolla SDK supports **dual billing**, allowing you to offer your own Xsolla-powered checkout side by side with the Store's commerce. Incentivize adoption with bonuses, rewards, or extra in-game currency—while keeping the experience compliant and transparent. For more information see **[best practices for dual billing](https://developers.xsolla.com/sdk/windowstores/epic/dual-billing/)**. Example messaging
"Pay with Xsolla – Get 10% more!"
You can also choose to replace platform commerce with Xsolla’s SDK for greater control over your monetization, pricing, catalog, and player data.
**Enable Web-Based Purchases via Buy Button**: Xsolla **[Buy Button](https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop/#buy-button-seamless-web-shop-integration)** lets you launch secure, custom payment flows from within your game. This redirects the player to a web checkout experience that runs in the browser, taking advantage of frictionless checkout and saved payment methods.
Buy Button is simple to implement and integrates seamlessly with your in-game logic and backend systems.
**Add a Web Shop with Epic Login Support**: You can also offer direct purchases through a **[Web Shop](https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop/)** powered by Xsolla Site Builder and Pay Station. Players can now log in with their *Epic Account*, or enable **[authentication with device ID](https://developers.xsolla.com/sdk/publisher-account/login/)**, making the experience seamless and account-linked.
## Integration Options for Epic Games Store
Xsolla provides a growing number of SDKs to support games distributed via the Epic Games Store:
- **Unity SDK**: The **[Xsolla SDK for Unity](https://developers.xsolla.com/sdk/unity/)** is the ideal drop-in option for *Unity*-based games.
- **Windows SDK**: Native **[Windows SDK](https://developers.xsolla.com/sdk/windowstores/sdk/installation/)** (C++ and C#) for custom tech stacks.
- **Defold SDK**: Lightweight integration for games using the Defold engine, available in the *Defold Asset Portal*.
- **Mobile SDK**: Native **[iOS and Android SDKs](https://developers.xsolla.com/sdk/mobilesdk/quick-start/)** designed for use with the **Epic Games Mobile Store**, supporting one-tap purchases outside traditional app store billing.
- **Web Shop + *Sign in with Epic***: **[Web Shop](https://developers.xsolla.com/sdk/mobilesdk/quick-start/webshop/)** complements Xsolla SDK and enables direct-to-player commerce.
## Your Game, Your Players
Xsolla’s tools are built to reduce overhead—not add it. With centralized SKU management, global payments, and player-friendly checkout flows, you can focus on your game and offer your players choices while Xsolla tackles the complexities in the new era of game commerce.
## What's Next?
- **[SDK Documentation](https://developers.xsolla.com/sdk/windowstores/sdk/installation/)** - Follow a step-by-step guide to integrate the SDK into your Windows game
- **[Contact Support ↗](https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk)** ([https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk](https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk)) - Reach out to your Account Manager for personalized implementation guidance
Simplifying SKU & IAP Catalog Management with Xsolla
https://developers.xsolla.com/sdk/windowstores/epic/catalog-sync
Managing in-game product catalogs across multiple systems is one of the more tedious—but critical—tasks in game commerce. Every platform has its own requirements for defining virtual items, managing SKUs, and keeping catalogs up to date. This process often involves repeated manual work across dev portals, backend services, and in-game logic.
With Xsolla's catalog sync, developers can centralize their IAP definitions in a single source of truth—**Publisher Account**—and automatically keep their game's product catalog consistent across systems. See how in **[this article](https://developers.xsolla.com/sdk/publisher-account/virtual-items/)**.
## How It Works
When you connect your game to Xsolla, you define your Xsolla Catalog (Virtual Items/IAPs with SKUs, pricing, item types, bundles, etc.) once in the Publisher Account. These definitions can then be pulled directly into:
- Your game client (via SDK or API)
- Your backend services
- Your Web Shop or Buy Button setup
The result is that any updates made to item names, prices, availability, or configuration only need to be made in one place—Publisher Account—and those changes propagate automatically.
## Benefits
- **Reduces Human Error**: Manual catalog entry across multiple systems is prone to typos, misconfigured prices, or mismatched SKUs. Syncing eliminates that risk.
- **Saves Time**: Avoid duplicating work across every platform or dev environment. One update syncs everywhere.
- **Improves Consistency Across Channels**: Whether a player is buying an item in one of your game versions or through your web store, they see the same items at the same prices.
- **Supports A/B Testing and Live Ops**: Since catalog changes can be deployed centrally and in real-time, it's easier to test offers, update pricing for events, or roll out new bundles quickly.
- **Easier Maintenance**: Teams can hand off catalog responsibilities to Live Ops, Product Management, or Monetization roles without requiring engineering work or access to platform portals.
## When to Use It
If you're running your game on more than one store, offering web-based purchases, or frequently updating your IAPs, syncing through Publisher Account helps reduce overhead and improve the quality of your monetization setup. Even for games on a single storefront, it's a useful tool to simplify your operations and future-proof your backend.
Best Practices for Dual Billing
https://developers.xsolla.com/sdk/windowstores/epic/dual-billing
Implementing a dual billing experience in your Windows game gives players more choice at checkout—and that choice should feel meaningful. As Epic Games has outlined in their own guidance, developers are encouraged to offer players multiple payment options and to allow those options to compete on value.
If you're presenting players with both Epic's built-in payment system and an external option like Xsolla, it's important to ensure that both feel fair and rewarding. One best practice is to match or exceed any benefits the platform provides.
It's recommended to offer at least the same effective bonus—either as additional in-game currency, extra content, or a clear incentive like: "*Pay with Xsolla – Get 5% more!*"
This approach gives players more value for their money and positions your game as one that respects player choice, while also creating a reason to explore the alternative checkout option.
When implementing dual billing, keep the following in mind:
- **Be transparent**: Make the bonus clear at the point of checkout. A well-placed message or icon can guide player behavior without being disruptive.
- **Keep rewards in balance**: Don't over-optimize toward one payment flow. The goal is to offer a choice, not a hard sell.
- **Test what resonates**: A small bonus (even 5-10%) can shift player behavior significantly. Try A/B testing different offers and phrasing to find what works best for your audience.
Above all, your billing experience should reflect a relationship toward the player of choice, fairness, and trust. Dual billing is not about steering players away from one provider—it's about giving them the power to decide which option delivers more value.
Configuration
https://developers.xsolla.com/sdk/windowstores/sdk/configuration
To Configure SDk please use following code:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetRestorePurchasesOnInit(true)
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Auto)
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
.SetUIThemeSize(XsollaStoreClientSettings.ThemeSize.Auto)
.SetUIThemeStyle(XsollaStoreClientSettings.ThemeStyle.Auto)
.SetUICustomTheme("")
.SetUseCloseButton(XsollaStoreClientSettings.CloseButton.Auto)
.SetUIControlTintColor(Color.clear)
.SetUIBarTintColor(Color.clear)
.SetRedirectUrl("")
.SetRedirectButtonText("")
.SetRedirectDelay(6)
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
```
### Events
The **Xsolla Events API** serves as an alternative to webhook-based integrations, where the integrator’s backend usually handles most of the logic (purchase validation, awarding, etc.). Instead of sending webhooks directly, the API intercepts them and stores their payloads in a remote queue managed by Xsolla. This approach enables serverless integrations for projects that lack backend capacity or don't require one, yet still prefer handling the entire transaction flow directly from the app.
Restoring through the Events API also gives you the order identifier from the original Xsolla purchase, so you can match a restored purchase against your own records. Inventory-backed restoration has no order to reference. CAUTION
Opting for the *Xsolla Events API* disables your project's webhooks. In other words, you cannot simultaneously handle webhooks on your backend and use the *Events API* in your app.
To enable it, open your project in *Publisher Account*, go to **Project settings** > **Integration settings**, select **Use API** and click **Save**. See [**Events API in Publisher Account**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api) for details.
Below is the minimal events configuration required to enable the events functionality in the SDK:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebhooksMode(XsollaStoreClientSettings.WebhooksMode.EventsApi)
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
//..
settings->SetWebhooksMode(CXsollaClientSettings::WebhooksMode::EventsApi);
```
info
For additional information, see the [**webhooks page**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#enabling-xsolla-events-api).
### Build configuration from the settings
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// Set the settings object you've acquired in previous step here..
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
configuration->SetSettings(settings);
configuration->SetSandbox(true);
configuration->SetLogLevel(CXsollaClientConfiguration::XsollaLogLevel::Debug);
```
### Assign Xsolla access token to the configuration
note
The access token [**JWT-structure ↗**](https://developers.xsolla.com/api/login/overview/#section/JWT-structure) ([https://developers.xsolla.com/api/login/overview/#section/JWT-structure](https://developers.xsolla.com/api/login/overview/#section/JWT-structure)). warning
A valid **access token** must already be known before the SDK initialization step.
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("< your access token >")
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
configuration->SetSettings(settings);
configuration->SetAccessToken("< your access token >");
```
### Using device ID instead of the access token
Below is an example with the fields required to be set for the device ID authentication approach to work:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
```
### Using OAuth2 instead of the access token
Below is an example with the fields required to be set for the OAuth2 authentication approach to work:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetOAuthClientId("< your_oauth_client_id >")
// ..other properties
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
settings->SetOAuthClientId("< your_oauth_client_id >")
```
### Testing purchase flow in sandbox mode
See [**Testing**](https://developers.xsolla.com/sdk/windowstores/sdk/testing/) guide for more details on how to enable the sandbox mode and avoid spending real money while testing the integration.
Initialization
https://developers.xsolla.com/sdk/windowstores/sdk/initialization
After [configuring](https://developers.xsolla.com/sdk/windowstores/sdk/configuration/), the **Xsolla SDK for Windows** needs to be initialized and connected to **Xsolla** services.
```csharp
var storeClient = XsollaStoreClient.Builder.Create()
.SetConfiguration(configuration)
.SetOnRestore((item, error) => {
if (error != null)
{
// handle error
return;
}
// handle delayed purchased item
})
.AddProducts(productIds)
.AddProduct("product1")
.AddProduct("product2")
.AddProduct("product3")
.AddProduct("product4")
.Build();
storeClient.Initialize((products, error) =>
{
if (error != null)
{
// handle error
return;
}
// products contains all requested products
});
```
```cpp
auto products = std::vector<std::string>{
"product1",
"product2",
"product3",
};
auto client = new CXsollaStoreClient(configuration, products, [](std::shared_ptr<CXsollaStoreClientPurchasedProduct> product, std::shared_ptr<CXsollaStoreClientError> error) {
std::cout << "C++ Restore successful for product: " << product->GetSku() << "\n";
});
client->Initialize([client](std::vector<std::shared_ptr<CXsollaStoreClientProduct>> products, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Initialization successful.\n";
} else {
std::cout << "C++ Initialization failed with error code: " << error->GetMessage() << "\n";
}
});
```
The SDK loads only Virtual Items from your Xsolla Catalog — Virtual Currency, Bundles, and other catalog types are not returned.
Installation
https://developers.xsolla.com/sdk/windowstores/sdk/installation
#### Option 1: From archive
- Extract SDK to you project
- Add dependencies to you project
Purchase flow
https://developers.xsolla.com/sdk/windowstores/sdk/purchase
Purchasing flow is a multistage process, which involves [payment collection](https://developers.xsolla.com/sdk/windowstores/sdk/purchase#starting-purchasing-flow), purchase [validation](https://developers.xsolla.com/sdk/windowstores/sdk/purchase#validating-purchases-recommended) and [consumption](https://developers.xsolla.com/sdk/windowstores/sdk/purchase#consuming-purchased-goods).
### Starting purchasing flow
Use one of the snippets below to launch a purchasing flow depending on whether you use *Unity InApp Purchasing* or not:
```cs
storeClient.PurchaseProduct(productId, (product, error) =>
{
if (error != null)
{
// handle error
return;
}
var receipt = product.ToReceipt();
// handle the purchased product here (e.g. validate or consume)..
});
```
```cpp
client->PurchaseProduct(productId,
[](std::shared_ptr<CXsollaStoreClientPurchasedProduct> product, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Purchase successful for product: " << product->GetSku() << "\n";
auto receipt = CXsollaStoreClientHelpers::ConvertToReceipt(product)
// handle the purchased product here (e.g. validate or consume)..
}
else {
std::cout << "C++ Purchase failed with error code: " << error->GetMessage() << "\n";
}
}
);
```
### Validating purchases (recommended)
warning
Although validation is **NOT** a mandatory step, yet it's highly recommended to minimize the chance of fraud and any other malevolent intents.
For instructions on how to validate your purchases, see [**Purchase Validation**](https://developers.xsolla.com/sdk/windowstores/sdk/validation/) guide.
### Consuming purchased goods
The very final step in the chain of purchasing flow stages is to award the purchased goods to the user and mark these goods as "awarded". The process also known as **purchase consumption**.
Use the code below to do just that:
```cs
storeClient.ConsumeProduct(item.sku, item.quantity, item.transactionId, error => {
if (error != null)
{
return;
}
// handle purchased item
});
```
```cpp
client->ConsumeProduct( item->GetSku(), item->GetQuantity(), item->GetTransactionId(),
[](std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Consume successful.\n";
} else {
std::cout << "C++ Consume failed with error code: " << error->GetMessage() << "\n";
}
}
);
```
important
It's highly recommended to perform at least some form of [**validation**](https://developers.xsolla.com/sdk/windowstores/sdk/purchase#validating-purchases-recommended) before consuming the purchased goods.
Testing & Sandbox
https://developers.xsolla.com/sdk/windowstores/sdk/testing
This section provides various snippets and examples of how to configure the sandbox environment to be able to make test payments, make logging more verbose, and so on.
### Enabling sandbox mode
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetSandbox(true)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
// ...
configuration->SetSandbox(true);
```
#### Testing in Unity Editor
Testing in the Unity Editor uses the current platform's implementation (e.g., Windows or macOS). warning
Remember to turn the **sandbox** mode **OFF** before going **LIVE**.
### Enabling additional logging
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
// ...
configuration->SetLogLevel(CXsollaClientConfiguration::XsollaLogLevel::Debug);
```
warning
Make sure the debug **logging** is **OFF** before going **LIVE**.
### Test cards
For a list of cards to simulate payments in sandbox mode, see [here ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)). important
The test cards won't work outside the **sandbox mode**.
Purchase Validation
https://developers.xsolla.com/sdk/windowstores/sdk/validation
Each purchase should be validated before awarding it to the end-user. This assists in preventing unauthorized purchases and ensures the integrity of your in-app economy. Validating purchases is a critical security measure to prevent fraud, protect your revenue, and ensure fair user experiences.
Essentially, that are two distinct validation approaches readily available.
### Server-side Validation
The most secure and reliable way to validate purchases is by using **server-to-server** (**S2S**) communication, with the client completely removed from the validation process. This minimizes security risks and ensures that entitlements are only granted based on verified data received directly from Xsolla.
With Xsolla, server-side validation is implemented through a **webhook-based model**:
- Once a user completes a purchase through your app, Xsolla services automatically trigger a [**webhook event**](https://developers.xsolla.com/sdk/publisher-account/webhooks/#user_validation) to your backend.
- This webhook contains all the necessary purchase data, including the **Xsolla** `order ID`, enabling your server to validate and process the purchase asynchronously.
- Your backend can then use this data to update the user’s entitlements, balance, inventory, etc., without requiring any additional input from the client.
This flow ensures that the client has no role in deciding the outcome of a purchase — all validation logic lives on the server, using trusted data that originates from Xsolla itself. tip
For more information about how webhooks work, see [**here**](https://developers.xsolla.com/sdk/publisher-account/webhooks/).
### Client-side Validation
Provides means of validating a purchase on the user's device without a need for a backend (server). It's better than nothing, but has its own drawbacks, i.e. anything that runs on the client can potentially be exploited.
```csharp
void MyOnPurchaseCallback(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
_storeClient.ValidatePurchase(product.ToReceipt(), (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
```cpp
client->ValidatePurchase(
CXsollaStoreClientHelpers::ConvertToReceipt(product),
[client, product](bool valid, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Purchase validation successful. Valid: " << (valid ? "true" : "false") << "\n";
} else {
std::cout << "C++ Purchase validation failed with error code: " << error->GetMessage() << "\n";
}
}
);
```
欢迎使用艾克索拉 SDK 3
https://developers.xsolla.com/sdk/zh
艾克索拉 SDK 3 专为希望实现游戏变现,并在 App Store、Google Play、Android APK、iOS、艾克索拉启动器及独立 PC 端等多个分发渠道上线的开发者打造。该 SDK 基于**艾克索拉支付收银台**,内置多平台支持与直连分发能力。1,000+支付方式200+国家/ 地区130+货币25+用户界面语言
## SDK Explorer
**交互式演示**:在真实的交互环境中,逐步体验从身份认证、商品目录加载、购买到交易完成的每一个集成环节。
- ✓无需创建帐户
- ✓无需编写代码
- ✓ 调用真实 API,而非模拟
[试用 SDK Explorer](https://developers.xsolla.com/sdk/demo/)[![SDK Explorer 界面——按步骤体验艾克索拉 SDK 的支付流程]](https://developers.xsolla.com/sdk/demo/)
## 购买按钮:即时访问网充商店
在 Epic v. Apple 案中,2025 年 4 月的藐视法庭裁定要求 Apple 允许美国 iOS 应用提供外部支付链接;2025 年 12 月的上诉裁定调整允许 Apple 就此类交易收取佣金,具体费率正由法院审查。在美国以外地区,日本《移动软件竞争法》(2025 年 12 月 18 日起生效)以及 Apple 在巴西与 CADE 达成的反垄断和解协议(2026 年 6 月 18 日起生效),同样要求 Apple 允许开发者在 iOS 上提供外部支付与 Web 跳转链接。在欧盟,Apple 的统一商业条款(2026 年 10 月 1 日起生效)允许应用在提供 Apple APP 内购的同时提供官方支付体系之外的支付方案。Epic v. Google 案的禁令(2025 年 10 月 29 日起生效)要求 Google Play 允许美国用户使用替代计费选项和外部支付链接;2026 年 7 月,Epic 与 Google 仅撤回了修改该禁令的动议,并未撤回双方另行达成的和解协议,因此原禁令仍为现行有效的法院命令,其终止日期在不同来源间存在争议。艾克索拉 SDK 完全符合 Apple 修订后的 App Store 指南和 Google Play 更新后的支付与结算政策。
[**购买按钮 ↗**](https://xsolla.com/mobile-buy-button) [(xsolla.com)](https://xsolla.com/mobile-buy-button) 功能支持直接访问网充商店支付 UI: **一键购买流程**
玩家可立即进入特定商品的支付 UI,无需额外跳转。**无缝集成**
直接在游戏内唤起 Web 支付 UI,不打断用户流程。**更丰富的支付选项**
覆盖网充商店的全部支付方式,包括 Apple Pay 和全球各类替代支付方式。**提升转化率**
精简购买流程,减少操作阻碍并提高完成率。**高级分析**
借助 [Adjust ↗](https://developers.xsolla.com/solutions/web-shop/analytics/adjust/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/adjust/)、[AppsFlyer ↗](https://developers.xsolla.com/solutions/web-shop/analytics/appsflyer/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/appsflyer/)、[Airbridge ↗](https://developers.xsolla.com/solutions/web-shop/analytics/airbridge/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/airbridge/) 和 [Singular ↗](https://developers.xsolla.com/solutions/web-shop/analytics/singular/) [(developers.xsolla.com)](https://developers.xsolla.com/solutions/web-shop/analytics/singular/) 完成 MMP 归因,全面掌握投放活动与收入情况。
## 支持多种变现模式
作为 **Equal Access for Everyone(人人平等接入)** 倡议的一部分,**艾克索拉 SDK** 让所有开发者都能轻松完成接入,大幅简化前期集成流程,同时支持后续进一步微调与自定义。将项目与**艾克索拉 SDK** 配置并集成 后,即可自动开通功能完整、可高度自定义的**艾克索拉网充商店**,在应用之外建立直连玩家的渠道。
SDK 概览⸺集支付流程、游戏分发与玩家直连于一体的一站式平台
**商店外支付**允许开发者在传统应用商店之外分发自己的应用程序文件,例如 Android APK,或已通过 Apple 认证的 iOS 应用版本(如通过 Web 分发)。当开发者选择以直达玩家的方式独立分发游戏时,可以更好地掌控利润。不断演进的监管要求(如 **《数字市场法》(DMA)**)也在支持这种做法,扩大了开发者提供替代支付方式的自由度。**艾克索拉支付收银台**正是应对上述复杂问题的解决方案,可直接通过**艾克索拉 SDK** 接入。
## 解决方案
**艾克索拉支付收银台**专为帮助开发者高效实现应用程序变现而设计,可留存更高比例的收入。凭借超过 1,000 种支付选项,艾克索拉支付收银台可覆盖平台原生支付体系通常不支持的地区与支付方式,拓展变现机会,帮助开发者进入新市场并触达更广泛的受众。
此外,将**艾克索拉 SDK** 与 Digital Turbine 等分发解决方案搭配使用,可进一步放大这一优势。Digital Turbine 与主要运营商和设备制造商合作,实现大规模 APK 分发,让游戏直接触达全球数以百万计的设备。除预装外,其 SingleTap 技术还支持用户通过广告、链接或消息,从您选择的 CDN 即时安装应用,绕过安全警示页面,减少应用商店流程带来的阻力,并提升转化率。借助这一组合,开发者可大规模直连玩家、保持 UA 流程不变,并获得更高比例的收入。
请联系您的客户经理或商务拓展团队,获取行之有效的最佳实践,借助最新实用技巧强化商店外分发策略。
### 替代支付选项
若有意在 App Store 接入 [Apple 以外的支付方式 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) [(developer.apple.com)](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) 或接入 [Google Play 以外的支付方式 ↗](https://developer.android.com/google/play/billing/alternative) [(developer.android.com)](https://developer.android.com/google/play/billing/alternative),请联系客户经理或商务拓展团队,获取指导与实施支持。 [SDK**Mobile SDK**iOS · Android→](https://developers.xsolla.com/sdk/zh/mobilesdk/)[SDK**Unity SDK**iOS · Android · Windows · macOS · Web→](https://developers.xsolla.com/sdk/zh/unity/)[SDK**Windows Stores SDK**Windows · Epic Games→](https://developers.xsolla.com/sdk/zh/windows/)
向 Google Play 报告外部交易
https://developers.xsolla.com/sdk/zh/compliance/android
当您在 Google 允许外部交易的商店地区通过**艾克索拉**进行销售时,Google 仍要求您上报这些交易。本文说明 Google 的具体要求,以及如何基于**艾克索拉**已发送给您的数据生成该报告。
## 各自负责哪些内容
报告是您方集成的一部分,并非**艾克索拉**代您完成的事项。
| | 由谁处理 |
| --- | --- |
| 处理支付、税费计算、退款 | 艾克索拉 |
| 就每笔订单通知您的后端 | 艾克索拉 (Webhook) |
| 在您的应用中获取 Google 的外部交易令牌 | 您 |
| 向 Google 提交报告 | 您(从您自己的服务器) |
Google Play 的报告 API 使用**您自己的**服务帐户凭证进行认证,并与 Play Console 中**您的**应用条目绑定,因此任何支付服务商都无法代您提交。**艾克索拉**提供的是用于构建报告的交易数据。
## 适用场景
Google 的各项计划因地区而异,且适用范围仍在不断扩大。在动手开发前,请先确认实际发行的地区适用哪些计划。
| 计划 | 适用地区 | 是否需要报告 |
| --- | --- | --- |
| 外部内容链接与备选结算系统 | 美国 | 尚未开始 — 自 2026 年 10 月 1 日起1 |
| 结算方式选择 | 英国、欧洲经济区 (EEA) | 是 |
| 外部优惠 | 欧洲经济区 (EEA) | 是 |
| 外部支付 | 日本 | 是 |
| 用户自选结算方式 | 35+ 个国家/地区,包括欧洲经济区 (EEA)、英国、澳大利亚、巴西、印度尼西 亚、日本和南非 | 是 |
备注
费率、截止时间和适用资格经常变动,且会因计划和地区而不同。本文刻意不重复 Google 的数字。请始终查阅 Google 的官方页面以获取当前条款:[用户自选结算方式 ↗](https://support.google.com/googleplay/android-developer/answer/13821247)、[结算方式选择(英国/EEA)↗](https://support.google.com/googleplay/android-developer/answer/17161464)、[外部优惠 (EEA) ↗](https://support.google.com/googleplay/android-developer/answer/14372887)、[外部内容链接与备选结算系统(美国)↗](https://support.google.com/googleplay/android-developer/answer/16470497)以及[外部支付(日本)↗](https://support.google.com/googleplay/android-developer/answer/16787536)。 important
每项计划都需要在 Play Console 中单独注册,并附带各自更新后的《开发者分发协议》条款。请在编写代码前完成这些步骤,否则下文的 Billing Library API 会报告该计划不可用。
如需仅在允许外部交易的商店地区启用外部交易,请参阅[如何检测 Google Play 商店地区 (Android)?](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detect-gpb-storefront-android/)。
## 端到端流程
- 您的应用检查计划可用性,并向 Play Billing Library 请求**外部交易令牌**。
- 您的应用将该令牌发送至后端,由后端关联到对应用户并保存。
- 玩家照常通过**艾克索拉**完成购买⸺在用户自选结算方式和备选结算系统中为应用内购买;在外部优惠、外部内容链接、外部支付和结算方式选择中为外链跳转后购买。
- **艾克索拉**向您的后端发送包含该订单财务明细的 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_paid) Webhook。
- 您的后端将令牌与订单数据配对并向 Google 上报该交易⸺多数计划要求在固定时限内(以小时计而非以天计)完成,远比按月上报紧凑,因此应按每条 Webhook 触发任务而非批量处理。各计划的具体截止时 间参见 Google 的[报告指南 ↗](https://developer.android.com/google/play/billing/outside-gpb-backend)。
- 退款和拒付会通过 [`order_canceled`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_canceled) 送达,并作为原交易的退款上报给 Google。
## 获取令牌
令牌来自 Play Billing Library,而非**艾克索拉 SDK**。调用哪个接口取决于所参与的计划。 各活动的 API 不同
`enableUserChoiceBilling` 是用于**用户自选结算方式**的接口。外部优惠、外部内容链接、外部支付和结算方式选择则改用较新的统一接口⸺`isBillingProgramAvailableAsync`、`createBillingProgramReportingDetailsAsync` 和 `launchExternalLink`。仅限备选结算系统(不显示选择界面)的集成使用第三种方法 `createAlternativeBillingOnlyReportingDetailsAsync`。如需确认您所参与的计划对应哪套接口与 Billing Library 版本,请参阅 [Google 的备选结算系统概览 ↗](https://developer.android.com/google/play/billing/alternative)。
即便在该统一接口下,这四项计划也不可互 换。下方的外链跳转示例针对**外部优惠**编写,也可原样用于**外部内容链接**。**外部支付**需将 `LaunchExternalLinkParams` 替换为 `DeveloperBillingOptionParams`;**结算方式选择**还额外需要 `setDeveloperBillingType`,并且必须先对可用性响应调用 `getBillingChoiceAvailabilityDetails()` 校验通过后,方可跳转外链。
```java
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.PurchasesUpdatedListener;
// Application context, and Google Play Billing's own purchase-update listener.
final Context context = // ...
final PurchasesUpdatedListener purchasesUpdatedListener = // ...
final BillingClient googlePlayBillingClient = BillingClient.newBuilder(context)
.setListener(purchasesUpdatedListener)
.enableUserChoiceBilling(userChoiceDetails -> {
// Called when the player picks your alternative over Google Play Billing.
final String token = userChoiceDetails.getExternalTransactionToken();
// Send the token to your own backend and store it before continuing.
sendTokenToYourServer(token);
// ...then start your Xsolla purchase, attaching the token as shown below.
})
.build();
```
```java
import com.android.billingclient.api.BillingClient;
import com.android.billingclient.api.BillingClient.BillingProgram;
import com.android.billingclient.api.BillingClient.BillingResponseCode;
import com.android.billingclient.api.BillingProgramReportingDetailsParams;
import com.android.billingclient.api.LaunchExternalLinkParams;
// Application context, the activity to launch the external link from, and the
// Xsolla Pay Station or Web Shop URL to send the player to.
final Context context = // ...
final Activity activity = // ...
final String checkoutUrl = // ...
// Use EXTERNAL_CONTENT_LINK instead for external content links.
final int billingProgram = BillingProgram.EXTERNAL_OFFER;
final BillingClient googlePlayBillingClient = BillingClient.newBuilder(context)
.enableBillingProgram(billingProgram)
.build();
googlePlayBillingClient.isBillingProgramAvailableAsync(billingProgram, (billingResult, availability) -> {
if (billingResult.getResponseCode() != BillingResponseCode.OK) return;
final BillingProgramReportingDetailsParams params = BillingProgramReportingDetailsParams.newBuilder()
.setBillingProgram(billingProgram)
.build();
googlePlayBillingClient.createBillingProgramReportingDetailsAsync(params, (reportingResult, details) -> {
if (reportingResult.getResponseCode() != BillingResponseCode.OK) return;
final String token = details.getExternalTransactionToken();
// Send the token to your own backend and store it before continuing.
sendTokenToYourServer(token);
final LaunchExternalLinkParams linkParams = LaunchExternalLinkParams.newBuilder()
.setBillingProgram(billingProgram)
.setLinkUri(Uri.parse(checkoutUrl))
// A checkout page is a digital content offer. LINK_TO_APP_DOWNLOAD is
// billed per install instead of per transaction, and its reports require
// installedAppPackage and installedAppCategory.
.setLinkType(LaunchExternalLinkParams.LinkType.LINK_TO_DIGITAL_CONTENT_OFFER)
.setLaunchMode(LaunchExternalLinkParams.LaunchMode.LAUNCH_IN_EXTERNAL_BROWSER_OR_APP)
.build();
googlePlayBillingClient.launchExternalLink(activity, linkParams, launchResult -> {
// The player leaves the app here and finishes the purchase on your own
// site (Pay Station or Web Shop). See "Correlating the token" below.
});
});
});
```
这两套接口返回的令牌都是不透明字符串⸺`externalTransactionToken`,Google 会用它与您稍后提交的报告进行关联。适用的令牌类型、请求时机以及有效期均因地区和计划而异。请参阅 Google 的[报告指南 ↗](https://developer.android.com/google/play/billing/outside-gpb-backend)获取最新规则。 每笔交易都使用新的令牌
请在每次购买或外链跳转前即时请求新令牌,切勿缓存后在多笔交易间复用。只有自动续订订阅的首笔付款会携带令牌;续订交易需改为通过 `initialExternalTransactionId` 关联上报。各计划的具体规则参见 Google 的[报告指南 ↗](https://developer.android.com/google/play/billing/outside-gpb-backend)。
### 将令牌与艾克索拉订单关联
如何将令牌与订单绑定取决于购买路径。
**在应用内完成的购买**(用户自选结算方式与备选结算系统)通过**艾克索拉 SDK** 进行,因此在启动流程时,请将令牌连同所售商品直接传入 `BillingFlowParams.Builder.setExternalTransactionToken`:
```java
import com.xsolla.android.mobile.BillingFlowParams;
import com.xsolla.android.mobile.ProductDetails;
// token is the one your app just got from the Play Billing Library above, and
// mBillingClient the com.xsolla.android.mobile.BillingClient you initialized earlier.
final ProductDetails productDetails = // ...
final String token = // ...
final Activity activity = // ...
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.setExternalTransactionToken(token)
.build()
);
```
其余 `BillingFlowParams.Builder` 设置请参阅[启动结算流程](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#starting-purchasing-flow)。
**外链跳转的购买**(外部优惠、外部内容链接、外部支付和结算方式选择)会在玩家付款前离开应用,因而没有**艾克索拉 SDK** 调用来附加令牌。请自行完成关联:以买家的用户 ID 为键存储令牌,并 在 Webhook 到达时与订单配对。Google 也建议将令牌作为查询参数附在链接 URI 中,使您的结算页能拿到同一关联键⸺但通过这种方式传递的令牌仍不会进入艾克索拉订单,因此仍需在后端将二者关联起来。
通过 `setExternalTransactionToken` 附加令牌后,艾克索拉会为该订单生成 `ucb_report` 对象⸺即预先组装好的 Google `externalTransactions` 请求体(`originalPreTaxAmount`、`originalTaxAmount`、`transactionTime`、`userTaxAddress`,以及位于 `oneTimeTransaction.externalTransactionToken` 下的令牌本身)⸺并将其附加到订单 Webhook 上。在合并的 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_paid) / `order_canceled` 通知模式中,它位于 `billing.ucb_report`;在旧 [`payment`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#payment) / [`refund`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#refund) Webhook 中,它位于顶层。无论哪种情况,都应直接使用 `ucb_report` 上报,而不是自行重建这些字段。
## 基于 Webhook 数据生成报告
Google 交易报告所需的大部分内容已在 `ucb_report` 中为您组装好⸺在 `order_paid` / `order_canceled` 中位于 `billing.ucb_report`,在旧 `payment` / `refund` 模式中位于顶层 `ucb_report`(见上文)。如需自行构建,`order_paid` 负载的 `billing.payment_details` 下同样包含这些数据 。无论采用哪种方式,各字段的数据来源如下。
| Google 交易字段 | 来源 |
| --- | --- |
| externalTransactionId | 由您生成并持久化;退款和续费会引用它 |
| externalTransactionToken | 来自 Play Billing Library 的令牌,经由您的艾克索拉订单转发(见上文 setExternalTransactionToken) |
| transactionTime | billing.transaction.payment_date,转换为 RFC 3339 |
| originalPreTaxAmount | billing.payment_details.payment.amount 减去下方的 originalTaxAmount,并转换为 micros |
| originalTaxAmount | 美国和加拿大以外使用 billing.payment_details.vat.amount;美国和加拿大使用 sales_tax.amount。见下方说明 |
| userTaxAddress.regionCode | user.country⸺已是 Google 要求的双字母代码,无需转换 |
| 交易类型 (oneTimeTransaction / recurringTransaction / otherRecurringProduct) | 取决于 billing.purchase.subscription 是否存在及其类型 |
| externalSubscription.subscriptionType | RECURRING 或 PREPAID,来自 billing.purchase.subscription |
报告玩家支付的金额, 而不是您的到手金额
`billing.payment_details.payout` 是扣除**艾克索拉**费用后的您的分成。Google 的报告要求填写向玩家收取的金额,因此 `originalPreTaxAmount` 和 `originalTaxAmount` 必须基于 `billing.payment_details.payment` 计算。使用 `payout` 会少报交易金额。
`vat` 虽名为增值税,但并非仅限欧盟使用⸺它是美国和加拿大以外通用的消费税字段,因此在日本承载 JCT,在其他适用上述计划的地区则承载 GST。 印度交易需提供邦代码
对于发生在印度的交易,Google 专门要求除 `regionCode` 外还须提供 `userTaxAddress.administrativeArea`⸺其他地区均为可选,且该字段仅接受 Google 固定的印度各邦与联邦属地列表。`user.country` 不包含这一层级的细分信息,因此如果您基于上述字段自行组装报告,请针对印度交易从自有数据中获取玩家所在邦。`ucb_report`(见上文)已准确包含该字段,因为尽管 `user.country` 未对外暴露,艾克索拉出于税务目的已在内部保存了玩家所在邦信息。
### 金额与取整
Webhook 中的金额为十进制小数,而 Google 要求传入以 **micros**(微单位)计的整数⸺即货币单位的百万分之一,而非 Apple 报告所用的最小货币单位(分)。请使用高精度十进制类型而非浮点数进行转换;税前金额 `originalPreTaxAmount` 应通过“含税金额减去已上报税额”得出,而不是按税率重新计算,以确保两项相加严格对齐。 免费试用也计入
Google 要求将免费试用产生的 0 美元交易与付费交易一样上报。不要因为 `billing.payment_details.payment.amount` 为 0 而在报告任务中过滤掉这些交易。
### 退款
`order_canceled` 同时涵盖退款与拒付。两者均使用 `refundexternaltransaction` 上报,并引用原始的 `externalTransactionId`⸺对于订阅,需引用被退款的那期续订对应的 `externalTransactionId`。对于已上报过的 `order.id` 请予以忽略,因为 [Webhook 会重试](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#retries),重复投递不得再次触发退款上报。
与 Apple 的报告不同,您无需自行维护累计净额:一旦针对某笔交易上报了退款,Google 会自动重新计算 `currentPreTaxAmount` 和 `currentTaxAmount`。
## 艾克索拉无法提供的信息
Google 的部分要求涉及**艾克索拉**无法获取的信息,需要由您的后端自行处理:
- **未产生购买的令牌**:Google 同样要求上报这类令牌。由于未产生订单,也就不会触发 Webhook,因此您的令牌存储是唯一的记录来源。
- **通过外链跳转完成的应用安装**:美国的外部内容链接计划与 EEA 的外部优惠计划还要求使用 `externalOfferDetails` 字段块(`installedAppPackage`、`installedAppCategory`)上报成功的应用安装,而不仅是购买。安装并非购买,因此**艾克索拉**完全无从获知⸺必须由您自己的归因追踪系统提供。
- **交易唯一标识**:`externalTransactionId` 的值由您自行生成并持久化保存。若无该标识,退款与续订将无法关联所属的原始交易。
## 测 试
通过 Play Billing Library 上报的许可测试人员交易会在 Google 侧标记为 `testPurchase`,且不会出账计费。**艾克索拉**测试订单则单独标记⸺在 `order_paid` / `order_canceled` 中为 `order.mode: "sandbox"`,在旧版 `payment` / `refund` Webhook 中为 `transaction.dry_run: 1`⸺请务必区分这两套标记,二者互不代表对方。
## 延伸阅读
- [Google Play Developer API — externaltransactions ↗](https://developers.google.com/android-publisher/api-ref/rest/v3/externaltransactions) — 报告端点与交易数据结构
- [报告 Google Play 结算系统之外的交易 ↗](https://developer.android.com/google/play/billing/outside-gpb-backend)
- [备选结算系统概览 ↗](https://developer.android.com/google/play/billing/alternative)
- [艾克索拉 Webhook](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) — 负载参考与签名校验
- [如何检测 Google Play 商店地区 (Android)?](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detect-gpb-storefront-android/)
## 脚注
- 本文唯一明确给出的日期,因为这是 Google 已发布的开始对美国外部交易收取费用并要求上报的时间。在依据该日期设定任何截止时间前,请再次前往 Google 的[外部内容链接计划页面 ↗](https://support.google.com/googleplay/android-developer/answer/16470497)确认⸺对于这类可能变动的细节,本文有意避免直接作出明确说明。 [↩](https://developers.xsolla.com/sdk/zh/compliance/android#user-content-fnref-1)
向 Apple 报告外部购买
https://developers.xsolla.com/sdk/zh/compliance/ios
当您在 Apple 允许外部购买的商店地区通过**艾克索拉**进行销售时,Apple 仍要求您上报这些交易。本文说明 Apple 的具体要求,以及如何基于**艾克索拉**已发送给您的数据生成该报告。
## 各自负责哪些内容
报告是 您方集成的一部分,并非**艾克索拉**代您完成的事项。
| | 由谁处理 |
| --- | --- |
| 处理支付、税费计算、退款 | 艾克索拉 |
| 就每笔订单通知您的后端 | 艾克索拉 (Webhook) |
| 在您的应用中获取 Apple 的外部购买令牌 | 您 |
| 向 Apple 提交报告 | 您(通过您自己的服务器) |
Apple 的报告 API 通过**您的** App Store Connect 密钥进行认证,并绑定到**您的**应用记录,因此任何支付提供方都不能代您提交。**艾克索拉**提供的是用于构建报告的交易数据。
## 适用场景
Apple 的规定在不同商店地区差异很大,因此在动手开发前请先确认实际发行的地区。
| 商店地区 | 权限 | Apple 佣金 | 是否需要报告 |
| --- | --- | --- | --- |
| 美国 | 不需要 | 目前不收取 | 否 |
| 日本 | 需要 | 是 | 是 |
| 巴西 | 需要 | 是 | 是 |
| 欧盟 | 需要 | 是 | 是 |
备注
费率、截止时间和资格经常变化,并且因地区和开发者计划而异。本文有意不重复 Apple 的具体数值。请始终查看 Apple 官方页面以获取当前条款:[日本的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-japan/)、[巴西的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-brazil/)、[欧盟的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/)。
Apple 的欧盟条款将于 **2026 年 10 月 1 日**变更,包括可在同一应用中组合哪些支付选项。如果您在欧盟发行应用,请在敲定方案前重新查阅 Apple 的官方页面。 important
该权限由您向 Apple 申请并由 Apple 授予,并附带您的开发者协议的补充条款。在编写代码前先处理好这些事项,否则下面提到的 StoreKit API 在没有权限时不会返回任何内容。
如需仅在允许外部购买的商店地区启用外部支付,请参阅[如何检测 iOS 商店地区?](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/)。
## 端到端流程
- 您的应用检查适用资格,并向 StoreKit 请求**外部购买令牌**。
- 您的应用将该令牌发送至后端,由后端关联到对应用户并保存。
- 玩家照常通过**艾克索拉**完成购买。
- **艾克索拉**向您的后端发送包含该订单财务明细的 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_paid) Webhook。
- 您的后端将令牌与订单数据配对,并向 Apple 提交报告。
- 退款和拒付会通过 [`order_canceled`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_canceled) 送达,并作为退款行项目上报给 Apple。
## 获取令牌
令牌来自 StoreKit,而不是**艾克索拉 SDK**。Apple 的 `ExternalPurchaseCustomLink` API 是当前用于自定义链接和应用内替代支付的接口。Apple 要求按固定顺序调用:`canMakePayments`,然后 `isEligible`,再显示披露页。 仅限 Swift
`ExternalPurchaseCustomLink` 是带有 `async` 成员的 Swift 枚举,因此没有对应的 Objective-C 接口。这与**艾克索拉 SDK** 所沿用的 `SKPaymentQueue` 风格 API 不同,后者同时提供两种语言版本。如果您的应用使用 Objective-C 编写,请向应用的 target 添加一个小型 Swift 文件并用 `@objc` 暴露接口,如下方 Objective-C 选项卡所示。
```swift
// Whether this player is allowed to pay at all. Must come first.
guard AppStore.canMakePayments else { return }
// False when the app lacks the entitlement, or the storefront doesn't permit external purchases.
guard await ExternalPurchaseCustomLink.isEligible else { return }
// Token type depends on your region and flow. Apple defines several,
// including in-app alternative payment and link-out variants.
guard let token = try await ExternalPurchaseCustomLink.token(for: "LINK_OUT") else { return }
// Send token.value to your own backend and store it before continuing.
await sendTokenToYourServer(token.value)
// Required. Must follow a deliberate action such as a button tap.
// Use .browser when leaving the app, .withinApp for a web view or native flow inside it.
let notice = try await ExternalPurchaseCustomLink.showNotice(type: .browser)
guard case .continued = notice else { return }
// ...then start your Xsolla purchase or link-out.
```
将此 Swift 文件添加到应用的 target:
```swift
import StoreKit
@objc(XSExternalPurchaseBridge)
public final class ExternalPurchaseBridge: NSObject {
/// Returns the token string, or nil when the app isn't eligible or no active token exists.
@objc(requestTokenOfType:completion:)
public static func requestToken(ofType tokenType: String,
completion: @escaping (String?, Error?) -> Void) {
Task { @MainActor in
do {
guard SKPaymentQueue.canMakePayments(),
await ExternalPurchaseCustomLink.isEligible else {
completion(nil, nil)
return
}
let token = try await ExternalPurchaseCustomLink.token(for: tokenType)
completion(token?.value, nil)
} catch {
completion(nil, error)
}
}
}
/// Shows Apple's disclosure sheet. Continue only when `shouldContinue` is YES.
@objc(showNoticeForBrowserWithCompletion:)
public static func showNoticeForBrowser(completion: @escaping (Bool, Error?) -> Void) {
Task { @MainActor in
do {
let result = try await ExternalPurchaseCustomLink.showNotice(type: .browser)
switch result {
case .continued: completion(true, nil)
default: completion(false, nil)
}
} catch {
completion(false, error)
}
}
}
}
```
然后在 Objective-C 中调用:
```objectivec
#import "YourApp-Swift.h"
[XSExternalPurchaseBridge requestTokenOfType:@"LINK_OUT"
completion:^(NSString *token, NSError *error) {
if (token == nil) { return; }
// Send the token to your own backend and store it before continuing.
[self sendTokenToYourServer:token];
[XSExternalPurchaseBridge showNoticeForBrowserWithCompletion:^(BOOL shouldContinue, NSError *e) {
if (!shouldContinue) { return; }
// ...then start your Xsolla purchase or link-out.
}];
}];
```
令牌的 `value` 是一个 Base64URL 编码的 JSON 字符串。解码后可以读取 `externalPurchaseId`,Apple 的报告以此字段为键。将其发送到您的后端并保存。
适用的令牌类型、何时请求以及有效期因地区而异。请参阅 Apple 的[接收并解码外部购买令牌 ↗](https://developer.apple.com/documentation/storekit/receiving-and-decoding-external-purchase-tokens)以获取当前规则。 披露页
在日本、巴西和欧盟,Apple 还要求在引导到外部购买前,应用内显示一张披露页,告知玩家他们与您而非 Apple 进行交易。该页由系统提供,因此只需调用 `showNotice`。
玩家可以选择不再显示该页,因此请根据调用返回的结果来分支,而不是根据是否显示。静默返回并不表示失败。
Apple 在“应用内披露页”部分提供了所需文案和可下载素材,详见[日本的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-japan/)、[巴西的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-brazil/)和[欧盟的支付选项 ↗](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/)。
## 基于 Webhook 数据生成报告
Apple 的报告以单个令牌及其关联的交易为单位。行项目所需的大部分信息已经包含在 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#order_paid) 的负载中,位于 `billing.payment_details`。
下方映射适用于一次性购买,即**艾克索拉 SDK** 所售的商品类型。Apple 将订阅作为单独的行项目类型上报,拥有独立的专属字段(包括续订以及免费试用开始等零扣款事件)。如果您通过网充商店外链跳转销售订阅,请勿直接套用此映射⸺请参阅 Apple 的[报告指南 ↗](https://developer.apple.com/documentation/externalpurchaseserverapi/reportwithtransactions)了解订阅行项目的要求。
| Apple 行项目字段 | 来源 |
| --- | --- |
| externalPurchaseId | 从您保存的 Apple 令牌中解码得到 |
| lineItemId | 您生成。需要持久化,退款会引用它 |
| creationDate | billing.transaction.payment_date,转换为纪元毫秒数 |
| eventType | order_paid 表示购买,order_canceled 表示退款 |
| productType | items[].type,或存在 billing.purchase.subscription |
| productIdentifier | items[].sku |
| quantity | items[].quantity |
| amountTaxInclusive | billing.payment_details.payment.amount,转换为最小货币单位 |
| taxAmount | billing.payment_details.vat.amount |
| amountTaxExclusive | 含税金额减去税额 |
| netAmountTaxExclusive | 该行项目在购买与退款间的税前净额累计 |
| reportingCurrency | billing.payment_details.payment.currency |
| pricingCurrency | order.currency |
| taxCountry | user.country,转换为三字母代码 |
| referenceLineItemId | 在退款中,原始购买的 lineItemId |
报告玩家支付的金额,而不是您的到手金额
`billing.payment_details.payout` 是扣除**艾克索拉**费用后的您的分成。Apple 的报告期望的是向玩家收取的金额,即 `billing.payment_details.payment`。使用 `payout` 会少报交易,导致佣金计算错误。 税务字段
尽管名为 VAT,`billing.payment_details.vat` 是通用的流转税字段。它在日本承载 JCT,在巴西承载当地税种,在欧盟承载 VAT。因此在 Apple 要求上报的所有市场,都应使用此字段作为 `taxAmount`。
`user.country` 表示缴税辖区,也正是 Apple 的 `taxCountry` 所需。唯一需要的转换是格式:`user.country` 使用两位 ISO 3166-1 alpha-2 代码,而 Apple 期望三位 alpha-3 形式,例如 `ES` 变为 `ESP`。
以上字段只是 Apple 报告所需的子集。负载中还包含丰富得多的信息⸺订阅与礼物对象、促销活动、优惠券、费用明细拆分⸺且同一个 Webhook 也驱动着您的订单履约流程。如需了解完整结构、投递保证与签名校验方式,请参阅 [Webhook 文档](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/)。
### 金额与取整
Webhook 金额是小数,而 Apple 期望最小货币单位的整数。请使用十进制类型而非浮点数进行转换;税前金额应通过“含税金额减去您已上报的税额”得到,而不是按百分比重新计算,确保三者能严格相加对齐。
### 退款
`order_canceled` 同时涵盖退款和拒付。两者均应作为退款行项目上报,并引用原始购买的 `lineItemId`。对于已上报过的 `order.id` 应予以忽略,因为 [Webhook 会重试](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#retries),重复投递不得生成第二条退款行项目。
## 艾克索拉无法提供的信息
Apple 的部分要求涉及**艾克索拉**无法获取的信息,需要由您的后端自行处理:
- **未产生购买的令牌**:Apple 同样要求上报这类令牌。由于未产生订单,也就不会触发 Webhook,因此您的令牌存储是唯一的记录来源。
- **Apple 已知但您系统未见过的令牌**:Apple 可能会通知您系统从未记录过的令牌,这类令牌有其独立的上报状态。
- **行项目唯一标识**:`lineItemId` 的值由您自行生成并持久化保存;若无该标识,退款将无法关联所冲销的原始购买。
- **累计净额**:行项目的净额会在购买与退款之间持续累加,无法仅凭单条 Webhook 独立推算。
## 测试
External Purchase API 会返回特定环境的令牌。在沙盒中创建的令牌,其 `externalPurchaseId` 以 `SANDBOX` 开头,因此您的后端可以将其从生产上报中分流。**艾克索拉**的测试订单会单独标记,在 Webhook 中为 `order.mode: "sandbox"`。
## 延伸阅读
- [External Purchase Server API ↗](https://developer.apple.com/documentation/externalpurchaseserverapi) — 报告端点与行项目数据结构
- [接收并解码外部购买令牌 ↗](https://developer.apple.com/documentation/storekit/receiving-and-decoding-external-purchase-tokens)
- [向 Apple 报告令牌和交易 ↗](https://developer.apple.com/help/app-store-connect/making-payments-to-apple/reporting-tokens-and-transactions)
- [艾克索拉 Webhook](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) — 负载参考与签名校验
- [如何检测 iOS 商店地区?](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/)
更新动态
https://developers.xsolla.com/sdk/zh/documentation-changelog
艾克索拉 SDK 的文档更新与发布说明。
此页面包含**艾克索拉 SDK** 文档的新增或更新信息。
### [3.1.24] - 2026-11-19
- (Unity) 补充了使用 Unity IAP 购买时通过艾克索拉商店扩展传递购买参数的说明,例如开发者载荷或[**外部交易令牌**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/?integration-method=with#starting-purchasing-flow)。
### [3.1.23] - 2026-11-17
- 指向可折叠小节(例如[**高级设置**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/?integration-method=without#external-id))或未激活选项卡内标题的链接,现在会自动展开该小节或切换到对应选项卡,并滚动到该标题。
### [3.1.22] - 2026-11-04
- (Unity) 补充了 Android [**登录重定向 URI**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/#sign-in-redirect-uris):说明各登录方式会发送哪个重定向 URI,并且必须在发布商帐户的 OAuth 2.0 客户端中注册,否则服务器会拒绝登录。
### [3.1.21] - 2026-11-02
- (iOS, Unity) 在 [**iOS**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#install-source) 文档中补充了 iOS 安装来源说明:除非您自行设置 `installSource`,否则仅在 iOS 17.4 及更高版本上自动检测,且该值会按原样发送。[**Unity**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#build-configuration-from-the-settings) 的 `SetInstallSource` 条目现已列出各平台差异。
### [3.1.20] - 2026-11-02
- (Android, Unity) 补充了安装来源 ([**Android**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#payments), [**Unity**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#build-configuration-from-the-settings)):让在应用商店之外分发的版本包(例如从您的网站下载的 APK)能够上报自定义分发渠道,而非使用操作系统安装程序检测到的渠道。另见 [**Android**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/#reporting-a-custom-install-source) 和 [**Unity**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore/#reporting-a-custom-install-source)。
### [3.1.19] - 2026-10-05
- (Android, iOS, Unity) 补充了归因用户 ID ([**Android**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#payments), [**iOS**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#attribution-user-id), [**Unity**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#build-configuration-from-the-settings)):用于将发送到 AppsFlyer 等归因平台的购买事件与您的归因 SDK 上报的同一用户 ID 进行关联。
### [3.1.18] - 2026-10-01
- (Android, iOS, Unity, Windows) 更正了在发布商帐户中[**启用 Events API**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api) 的步骤,该设置现位于**项目设置** > **集成设置**下。
### [3.1.17] - 2026-09-17
- (iOS) 更新了 SDK 3.11.0 的[**恢复的购买内容**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/#restored-purchases)文档:已恢复的购买记录现会指向对应的原始购买,并携带真实数量与支付日期。
- 精简了多个页面的表述,核心指引保持不变。
### [3.1.16] - 2026-09-14
- (iOS) 在购买文档中新增了[**恢复的购买内容**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/#restored-purchases)章节,说明恢复交易包含的信息、物品库不会恢复的内容,以及跳过恢复的条件。
- (iOS) 更正了[**配置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings)文档,明确列出由 Events API 填充的 iOS 属性,并说明基于物品库的恢复会使这些属性保持为 `nil`。
### [3.1.15] - 2026-09-09
- (Android) 新增 [**Inventory API 与 Events API 对比**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api/)附录,介绍 SDK 如何选择恢复后端、各模式下购买记录携带的信息,以及迁移线上项目所涉及的工作。
- (Android) 在[**购买流程**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#restored-purchases)文档中将购买恢复提升为独立章节 ,并按不同后端逐字段拆解恢复后的 `Purchase`。
- (Android) 说明了通过 Inventory API 不会恢复捆绑包⸺**包括虚拟货币套餐**(商品目录将其归类为捆绑包而非货币)⸺同时也会排除限时商品。
- (Android) 更正了配置文档中“基于物品库的恢复没有可引用订单”的说法:SDK 会在设备端合成订单与发票标识符,这些标识符在发布商帐户或订单查询中均无对应记录。
- (Android) 在配置文档中新增[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#purchase-restoration-settings)与[**单笔恢复购买的单位数量**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#units-per-restored-purchase),涵盖后端选择与 `withCollapseRestoredMultiUnitPurchases`。
- (Android) 在[**配置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#common)文档的每个设置表中新增**默认值**列,补充 5 项此前未记录的 `Config.Common` 设置,并说明将重试覆盖参数设为 `null` 时会回退为重试 12 次(间隔 750 ms),而非禁用重试。
### [3.1.14] - 2026-09-07
- (Android, iOS, Unity, Windows) 说明仅在通过 [**Events API**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#using-xsolla-events-api-for-restoration) 执行恢复时,已恢复购买才会携带原始艾克索拉订单的标识符。
### [3.1.13] - 2026-08-19
- (iOS, Android) 新增**平台合规**章节,说明在相关平台允许外部交易的商店地区通过艾克索拉销售时,如何向 [**Apple**](https://developers.xsolla.com/sdk/zh/compliance/ios/) 报告外部购买以及向 [**Google Play**](https://developers.xsolla.com/sdk/zh/compliance/android/) 报告外部交易。
- (iOS, Unity) 针对 Apple 自 2026 年 10 月 1 日起生效的欧盟条款更新了 iOS 外部支付指引:在欧盟,您可以将支付流程保留在应用内或跳转至网页端,该选择会影响 Apple 的佣金费率。
- (Android) 鉴于该方法现已公开,将 [**`setExternalTransactionToken`**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#starting-purchasing-flow) 添加至 `BillingFlowParams` API 参考。
- (Android) 更正了[术语表](https://developers.xsolla.com/sdk/zh/welcome/glossary/)中的 **Epic 诉 Google** 案件时间线:修正第九巡回上诉法院维持原判的日期,澄清 2026 年 7 月撤回修改禁令动议的情况,并移除了未经核实的禁令到期日。
- (Unity) 鉴于该属性现已公开,将 [**`externalTransactionToken`**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/#starting-purchasing-flow) 添加至 `XsollaStoreClientPurchaseArgs.Builder` API 参考⸺目前仅适用于 Android。
### [3.1.12] - 2026-07-23
- (Unity) 更正支持的 Unity Editor 版本为 2022.3+ 和 Unity 6+。
### [3.1.11] - 2026-07-16
- 将原“技术文章”分类重命名为**集成文章**。
- 翻新了 SDK 3 集成指南。
- 新增**视频指南**板块,提供集成实操演示视频。
### [3.1.10] - 2026-07-07
- (iOS, Unity) 将 iOS 外部支付合规指引扩展至同时覆盖**巴西**与美国(涵盖 iOS 与 Unity 文档),并将 iOS SDK 的[**区域合规配置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#regional-compliance-configuration)整合为按市场划分的统一章节。
- (iOS) 在[**购买验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/ios/)文档中明确:进行服务器侧验证时,SDK 的交易回调仍会触发,但仅用于界面反馈⸺后端应根据 Webhook 发放权益。
### [3.1.9] - 2026-07-06
- (iOS) 新增[**故障排查**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/troubleshooting/ios/)页面,涵盖商品目录为空、购买恢复、URL scheme 设置、登录错误、主线程警告,以及需加入防火墙白名单的主机名。
- (iOS) 在[**配置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings)与[**购买**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/)文档中说明:`restoreCompletedTransactions()` 为空操作,且必须结束交易以避免下次启动时重复触发。
- (iOS) 说明 [**`useSandbox`**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#testing-in-sandbox-mode) 默认值为 `true`,上线前必须关闭。
### [3.1.8] - 2026-06-02
- (Android, iOS, Unity, Windows) 在**初始化**文档中明确:SDK 仅加载**虚拟物品**。
### [3.1.7] - 2026-05-08
- 修复了[**集成小组件**](https://developers.xsolla.com/sdk/zh/integration-widget/)的布局,去除强制的水平内边距,防止浏览器窗口较窄时出现内容溢出。
### [3.1.6] - 2026-04-02
- (Android) 在 `Config.Payments` 的 API 参考中新增 [**`withRedirectAppRelaunch`**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#payments)。
- (Unity) 新增 Android 专用的[**从外部浏览器重新拉起应用**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/#external-browser-app-relaunch)设置文档。
### [3.1.5] - 2026-04-01
- 导航栏新增**下载 SDK** 按钮。
- (Android) 扩充了[**核销**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/)章节,更新购买流程图。
- (Android) 更新了[**客户端侧验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)流程图,加入向艾克索拉服务发起的核销请求。
- (Android) 在配置文档中新增[**事件监听器**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#xsolla-events-api) API 参考。
- 更新了[**集成小组件**](https://developers.xsolla.com/sdk/zh/integration-widget/),修正 Android GitHub Maven 的**如何安装**链接。
### [3.1.4] - 2026-03-18
- 更新 SDK 可用性链接。
- (Android) 新增[**结算流程取消 API**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/) 与基于令牌的参数构建器。
- (Android) 新增 [**GitHub 仓库安装**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/android/),提供 GitHub/Maven Central 选项卡布局。
- (Unity) 更新[**配置**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/),加入邮件营销同意、恢复间隔、语言区域设置,以及完整的构建器参数表。
- (Unity) 新增 Android 专用的[**取消原因查询**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/#cancellation-reason-querying)与 [**WebView 启动画面**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/#webview-splash-screen)设置。
### [3.1.3] - 2026-03-05
- 新增交互式 [**SDK 集成小组件**](https://developers.xsolla.com/sdk/zh/integration-widget/)。
- (Android, Unity) 更新配置 API 参考与方法名称。
- (iOS) 新增 [**SPM 安装**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios/)说明。
- 采用新布局重构了落地页与发布商帐户页面。
- 采用时间线布局重构了快速开始指南。
- 统一全套文档的术语与专有名词大小写。
### [3.1.2] - 2025-12-22
- (Unity) 更新了[**配置**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/),涵盖移动端购买设置、购买恢复和深度链接覆盖。
- (iOS, Unity) 在购买流程文档中新增“购买已取消”的处理示例。
- (iOS, Unity) 明确了替代分发安装场景下 iOS 商店地区的行为。
- (iOS) 新增 **Universal Links** 高级指南,并在深度链接配置文档中添加了链接。
### [3.1.1] - 2025-10-16
- (Unity) 修复了[**扩展示例**](https://developers.xsolla.com/sdk/zh/unity/quick-start/extended-example/#configuration--initialization)中的产品注册。
### [3.1.0] - 2025-10-07
ℹ️ANDROID
鉴于美国最高法院拒绝暂缓执行该裁决,**自 2025 年 10 月 29 日起**,Google 必须允许美国地区的 **Google Play** 应用**通过外链跳转引导用户使用外部支付方式**,并允许使用**备选结算方案**。此项变更使开发者能够规避 Google 的费用,并告知用户 Google Play 之外成本更低的支付选项,从而促进更具竞争力的定价并增强营收掌控力。
前往艾克索拉博客阅读更多内容:[**Android 的新平台规则⸺开发者需要了解的内容 ↗**](https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know) ([https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know](https://xsolla.com/blog/new-platform-rules-for-android-and-what-developers-need-to-know))
了解有关购买按钮的更多信息:[**艾克索拉购买按钮 ↗**](https://xsolla.com/mobile-buy-button) ([https://xsolla.com/mobile-buy-button](https://xsolla.com/mobile-buy-button))
- (Android) 新增[**购买按钮**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#buy-button-solution)相关信息。
- (Android) 新增[**网充商店外链跳转**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/?purchase-method=linkout-webshop#starting-purchasing-flow)相关信息。
### [3.0.4] - 2025-09-23
- (Android) 新增 [**Events API 高级设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#xsolla-events-api)相关信息。
### [3.0.3] - 2025-09-02
- (Android) 新增集成[**辅助工具**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/?platform=android)相关信息。
- (Unity) 新增[**面向 Android 的集成辅助工具**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore/?platform=android)相关信息。
- (Android) 新增更多[**购买流程启动方式**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#starting-purchasing-flow)说明。
- (Android) 在 [**`Default`**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow) 购买方式选项卡下新增可折叠小节,介绍高级设置。
- (Unity) 在 [**`Unity InAppPurchasing-less`**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/?integration-method=without) 集成方式选项卡下新增包含高级购买流程设置的可折叠小节。
### [3.0.2] - 2025-08-21
- 在 [iOS 配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#web-shop-link-outs)中说明网充商店外链跳转行为:SDK 会打开网充商店并取消 SDK 购买回调;订单履约应通过 Webhook/服务端处理。
- 新增 [Unity 配置:网充商店外链跳转](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#web-shop-link-outs)章节,并提供配置示例代码。
### [3.0.1] - 2025-08-18
- 补充了 iOS 端支付收银台默认支付方式的[配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#default-payment-method)说明。
### [3.0.0] - 2025-08-12
- 围绕全新的**艾克索拉 SDK** 进行了大幅文档重构,取代旧版**艾克索拉 Mobile SDK**。
- **Unity** 现为独立的顶级章节,涵盖所有支持平台(移动端、PC、Web)的集成指南。
- **移动端**文档按平台拆分为独立页面:分别提供 Android 与 iOS 的快速开始、安装、初始化、配置、购 买、测试、购买验证与高级主题指南。
- 新增使用第三方社交登录提供商访问令牌进行身份认证的相关说明。
### [1.1.4] – 2025-08-06
- **Events API**:在发布商帐户 Webhook 以及 Android 与 Unity SDK 配置指南中提供了完整文档,包含设置步骤、代码示例和注意事项。
- **Trusted Web Activity**:新增 Android 与 Unity 章节,涵盖 TWA 配置、启动画面选项、回退行为及相关资源。
- **iOS 配置**:扩充了已购内容恢复设置、自动与手动深度链接处理(含 URL scheme 设置)以及屏幕方向管理示例。
- **快速开始与概览页面**:更新顶层 README 与快速开始指南,补充有关 DMA 合规、全球支付方式与快速接入的简要说明。
### [1.1.3] - 2025-07-16
- 完善了 [iOS 配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/):优化文档组织与结构,补充深度链接处理指南、网充商店外链跳转与购买按钮解决方案文档,以及已购内容恢复设置说明。
### 2025-06-26
6 月 26 日,[Apple 发布](https://developer.apple.com/news/?id=awedznci)了针对欧盟地区 App Store 分发应用的以下变更。开发者现在可以针对数字商品或服务**宣传和推广优惠**,包括通过 **StoreKit External Purchase Link Entitlement** 将用户引导至外部支付选项。
虽然您可以使用艾克索拉 Mobile SDK 提供外部支付,并通过 Apple 的 **Alternative Terms Addendum for Apps in the EU** 或 **StoreKit External Purchase Link Entitlement (EU) Addendum**(请联系客户经理获取开通权限与实施指导)来满足欧盟的这些新要求,但我们建议**将[网充商店](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop/)作为更可行、更精简的替代方案**,以便在当前监管环境下获得最大的灵活性并降低复杂度。
[了解更多 Apple 的欧盟支付规则 ↗](https://developer.apple.com/support/communication-and-promotion-of-offers-on-the-app-store-in-the-eu/)
### [1.1.2] - 2025-06-25
- Unity 现已拥有独立的子章节 (`Unity`)。
- 将移动平台 (Android/iOS) 归入独立章节 (`Mobile`)。
- 在购买验证 (Android) 页面中新增流程图和流程映射对比表。
- 在**发布商帐户** -> **虚拟物品**中新增指向虚拟物品外部文档的链接。
- 将 iOS 的美国与欧盟合规内容迁移到独立页面(**Unity** -> **SDK** -> **配置** -> **iOS**)。
### [1.1.1] - 2025-06-09
- 改进了[快速开始指南](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/),提升组织与结构清晰度。
- 为 Unity 集成补充了[商店检测](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/)文档。
- 完善了[安装指南](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios/),补充 iOS 版本支持细节。
- 更新了[网充商店集成](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop/)文档,加入购买按钮相关信息。
- 在[配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)中新增 iOS 自定义登录令牌配置示例。
- 在 [Unity 集成](https://developers.xsolla.com/sdk/zh/unity/quick-start/extended-example/)示例中添加跨平台兼容性信息。
- 改进了全套文档的导航与外部链接。
- 在落地页补充了有关购买按钮与备选结算选项的信息。
### [1.1.0] - 2025-05-07
- 更新内容以确保符合 Apple 修订后的 App Store 指南。
- 艾克索拉 Mobile SDK 现已稳定,可用于生产环境。
- 新增一篇关于如何检测 iOS 商店地区的[文章](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/)。
- 改进了一篇关于如何检测 iOS 安装来源商店的[文章](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/)。
### [1.0.1] - 2024-07-26
- 新增[术语表](https://developers.xsolla.com/sdk/zh/welcome/glossary/)。
- 扩充了[核心概念 (iOS)](https://developers.xsolla.com/sdk/zh/welcome/core-concepts-ios/)。
- 更新了[核心概念 (Android)](https://developers.xsolla.com/sdk/zh/welcome/core-concepts-android/)。
### [1.0.0]
- 初始版本。
集成
https://developers.xsolla.com/sdk/zh/integration-widget
Loading Integration Widget…
艾克索拉 Mobile SDK
https://developers.xsolla.com/sdk/zh/mobilesdk
可用艾克索拉 Mobile SDK[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
**艾克索拉 Mobile SDK** 支持开发者通过**艾克索拉支付收银台**在 iOS 和 Android 游戏中无缝集成游戏内支付,同时覆盖商店内版本包(如美国区的 App Store iOS 和 Google Play 版本包)以及商店外分发的游戏版本包(如 Android APK、经公证的 iOS 应用)。借助该 SDK,开发者能够直连玩家、自主掌控结算体验,并留存最高 95% 的收入。游戏还可自动同步最新变现工具以及监管合规和全球政策变更的相关更新。
深受 Crossout、Modern Warship 和 Fantasy Tales: Sword and Magic 研发工作室的信赖,助力其在 iOS 与 Android 端面向全球规模化开展直连玩家的商业化业务。
## 平台支持
### iOS
在**美国** (Epic v. Apple)、**日本**(《移动软件竞争法》)和**巴西**(Apple 与 CADE 和解协议),Apple 现已允许开发者将玩家引导至外部网页支付。**艾克索拉 Mobile SDK** 符合 Apple 修订后的 App Store 指南,同时支持应用内支付收银台流程与网充商店外链跳转支付。
### Android
根据 **2025 年 10 月 29 日** Epic v. Google 案的禁令,美国地区的 Google Play 应用可使用 Google Play 以外的支付方式与外部支付链接,且不再受反引导限制。本 SDK 支持商店外 APK 分发、Google Play Billing 以及基于浏览器的结算⸺一次集成即可全部覆盖。
## 面向移动开发者的核心优势
**iOS 与 Android 集成**
专为 iOS (Swift/Obj-C) 和 Android 打造的 SDK,分别适配各平台的分发模式与合规要求,并共用同一套艾克索拉基础设施。**DMA 与法院命令合规**
完全符合 Apple 修订后的 App Store 指南和 Google Play 更新后的支付与结算政策⸺开箱即用,支持外链支付、官方支付体系之外的支付方案及商店外分发。**收入留存率最高 95%**
支持通过 APK、经公证的 iOS 应用或外链流程直接分发。绕过平台抽成,自主掌控定价,构建随玩家规模同步增长的直连玩家变现渠道。**1000+ 种支付方式**
全球支付基础设施覆盖 200+ 个地区、130+ 种货币和 25+ 种用户界面语言⸺内置本地化结算流程与高级反欺诈功能,无需额外费用。**合规更新自动生效**
Apple 和 Google 的政策变更会自动同步至 SDK。无需紧急发版,也不会产生合规债务⸺在不打断开发节奏的前提下始终保持最新状态。
## 开始使用
准备好将艾克索拉 SDK 集成到 iOS 或 Android 项目中了吗?按照“快速开始”指南,几分钟内即可完成首笔测试支付,也可联系您的客户经理获取个性化集成指导。 **艾克索拉购买按钮**快速路径
网充商店一键购买 流程,支持 1,000+ 种支付方式⸺无需安装 SDK。可在 iOS 或 Android 游戏内直接拉起基于浏览器的结算,完全符合 Apple 与 Google 的支付与结算政策。[了解更多 →](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/) [快速开始**集成指南**在 iOS 或 Android 上完成首笔测试支付→](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/)[快速路径**购买按钮**一键外部支付⸺无需完整 SDK→](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/)[参考**完整 SDK 文档**安装、配置与高级功能→](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/)
Google Play 用户自选结算方式
https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/google-play-user-choice-billing
## 概述
- **计划**:Google Play 允许部分国家/地区的获批应用展示用户选择界面,供玩家选择使用 Google Play 结算系统 (GPB) 或第三方支付服务提供商 (PSP)。
- **艾克索拉方案**:保留 GPB,并在玩家选择备选支付方式时启动**艾克索拉支付收银台**。无需单独维护 Android 分支。
## 艾克索拉提供的内容
- 1000+ 种本地化支付方式,可补充 GPB 并在原生支付表现欠佳的市场提升转化率。
- 在艾克索拉商品目录中将 GPB 产品 ID 映射为对应的[虚拟物品](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/) (IAP),保持两边 SKU 一致。
- 通过[艾克索拉登录管理器](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#authentication)或自有令牌服务完成身份认证。
- 与标准支付收银台部署一致的 Webhook 和报表能力⸺但向 Google 上报相关交易仍需由您的接入侧自行完成,请参阅[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/)。
## 更多指引
如对 Google Play 用户自选结算方式有任何疑问,请联系您的艾克索拉客户经理。
Inventory API 与 Events API 对比
https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api
在底层,Android SDK 从艾克索拉的两个后端之一获取购买数据:Inventory API 或 Events API。
物品库会记录每一笔购买。只有在发布商帐户中为项目启用 Events API 后,系统才会开始记录事件⸺自此之后,无论 SDK 本身以何种模式运行,事件都会持续记录。正是这一差异增加了线上项目切换这两个后端的难度:参见[**迁移线上项目**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api#migration)。
## 选择模式
具体使用哪种模式由两项互不关联的设置决定(默认均为关闭):发布商帐户中的项目级开关,以及通过 `.withEvents(...)` 传给 SDK 的 `Events` 配置 (`Config.Integration.Xsolla.Events`)。
两者控制的内容不同。发布商帐户中的开关决定是否**记录**事件。SDK 配置则决定客户端**从哪个后端恢复**⸺客户端独立判断,不会查询项目的开关状态。
| 发布商帐户中的 Events API | SDK 配置中的 Events API | 物品库 有记录 | 事件 有记录 | SDK 恢复来源 |
| --- | --- | --- | --- | --- |
| ✘ | ✘ | ✔ | ✘ | Inventory API |
| ✘ | ✔ | ✔ | ✘ | Events API⸺但从未记录任何事件,因此恢复结果为空 |
| ✔ | ✘ | ✔ | ✔ | Inventory API⸺与此同时事件不断累积但未被读取 |
| ✔ | ✔ | ✔ | ✔ | Events API |
无论哪种方式,物品库都会写入记录。事件只有在打开项目开关后才会生成⸺一旦打开,无论客户端是否读取都会持续记录。第 3 行正是关键所在:项目会累积一整段客户端从未见过的事件历史,而这正是[**迁移线上项目**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api#migration)需要解决的问题。
## 不同模式的差异
两种模式均无 需自建服务器,区别在于查询返回的购买记录包含哪些信息:
| | Inventory API | Events API |
| --- | --- | --- |
| 订单 ID 与发票 ID | 不存储⸺由 SDK 在本地合成 | 永久存储,并完整返回 |
| 购买时间戳 | 无⸺getPurchaseTime() 始终为 0 | 原始支付的真实时间戳 |
| 单条记录涵盖的内容 | 一个 SKU 及玩家持有的数量⸺而非单笔支付 | 单笔支付 |
| 捆绑包购买(包括虚拟货币套餐) | 无法恢复⸺仅返回捆绑包发放的内容 | 按捆绑包内含物品返回 |
两种模式下已恢复 `Purchase` 的逐字段行为详见[**购买流程 → 恢复现有购买**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#restored-purchases)。
为项目启用 Events API 会**禁用该项目的 Webhook**⸺两者不能同时运行。如果您的服务器负责处理支付,或与客户端分担该工作,项目切换后此分工方式将随之失效。
### 为什么通过物品库获取的购买记录无法与任何记录匹配
物品库查询返回的是当前持有量而非交易记录。分 5 次各购买 1 件 `sku_0`,返回时会合并为一条数量为 `5` 的记录:
| 匹配购买所需的信息 | Inventory API 返回的内容 |
| --- | --- |
| 订单 ID | 由 SDK 在本地合成的值 |
| 发票 ID | 相同的合成值 |
| 时间戳 | 无 (0) |
| 每笔支付一条记录 | 无⸺只有每个 SKU 的汇总数量 |
默认情况下,SDK 会将该汇总拆分为 5 个独立的 `Purchase` 对象,每个对象代表 1 个单位;使用 `withCollapseRestoredMultiUnitPurchases` 可关闭此行为,改为返回一个携带总数量的 `Purchase`(参见[**单笔恢复购买的单位数量**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#units-per-restored-purchase))。两种形态都只是呈现方式的选择⸺拆分不会增加任何可识别信息,因此无法借此实现匹配。
## 迁移线上项目
新项目应直接使用 Events API,不会遇到以下问题。下文内容仅适用于已有购买历史的线上项目。
客户端切换到 Events API 后首次启动时,会同时遇到两个问题:
- Events API **会一次性返回全部历史记录**。只要发布商帐户中的开关处于开启状态,它就一直在记录购买⸺包括客户端以物品库为后端运行且从未读取事件的整个时期。所有历史记录都会一次性涌入。
- Inventory API **可能仍有待发放给玩家的商品**。支付虽已完成,但应用在流程中途崩溃、更新或被终止,导致这笔购买尚未核销,对应商品仍需补发。
理想做法是将两组数据匹配起来,把物品库侧已经处理过的购买记录静默结清⸺即只核销、不发放。但这无法实现:事件记录虽然完整,物品库记录却没有任何可用于关联匹配的锚点(见上文)。
### 方案 A — 客户端迁移版本包
在读取任何事件之前,先清空物品库侧尚未核销的购买记录:
- 发布一个版本包,在应用启动时以 Inventory API 模式初始化 SDK。
- 查询待处理的购买记录,完成核销并发放对应商品。
- 写入持久化标记,记录物品库已清空且此后不得再次读取。
- 使用 Events API 配置重新初始化 SDK。
- 将发生时间早于第 2 步清空时间点的所有事件直接丢弃⸺只核销、不发放。
| 优点 | 缺点 |
| --- | --- |
| 完全在设备端运行,无需艾克索拉侧配合,且会在读取任何事件之前结清物品库实际待发放的商品。 | 只能覆盖安装了迁移版本包的玩家。重装应用或清除应用数据会丢失该标记,可能导致清空流程执行两次。第 5 步按时间戳划界而非按订单身份匹配,分界点附近的购买可能会重复发放或漏发。 |
### 方案 B — 由艾克索拉侧处理
由艾克索拉在不涉及客户端的情况下为您结清重叠记录。该方案是否适合您的项目取决于项目历史与规模⸺请向您的集成经理咨询。
| 优点 | 缺点 |
| --- | --- |
| 可覆盖从未安装迁移版本包的玩家,这是方案 A 无法做到的。 | 需要按项目单独安排,无法由您自行排期;且单次处理不会覆盖执行之后新产生的记录。 |
### 针对残留问题的规划
方案 A 完全由您自主可控,无论如何都值得发布。不管采用哪种迁移方式,都应预判会有少量玩家出现漏发或重复发放的情况,请在切换前准备好客服支持与补偿方案。
购买按钮 ⚡
https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button
ℹ️外部支付链接跳转 — iOS 与 Android
**iOS**:在美国、日本和巴西,Apple 现已允许开发者引导玩家跳转至外部网页完成支付。**艾克索拉 SDK** 符合 Apple 更新后的审核指南。
**Android⸺自 2025 年 10 月 29 日起生效**:根据 **Epic v. Google** 禁令,美国区 **Google Play** 应用可通过外链跳转引导用户使用**外部支付方式**,接入**官方支付体系之外的支付方案**,且不再受**反引导限制**约束。
## 最快的非 SDK 方案(推荐)
在这两个平台上,最快且推荐的非 SDK 方案是**通过外链跳转至网充商店的购买按钮**。
通过网充商店链接集成购买按钮,是一种快速、低代码的接入方式,可让玩家从游戏内通过浏览器结算页购买指定商品。该方案具备以下优势:
- 流程顺畅⸺玩家点击购买按钮即可打开对应商品的网充商店结算页,支付成功后会自动返回游戏。
- 支付方式丰富⸺支持包括 Apple Pay 一键支付在内的多种支付方式,提供快速、熟悉的移动端结算体验。
- 快速配置⸺如果已配置好网充商店,只需在游戏内添加带参数的链接即可。
- 即刻开通上线⸺如果尚未开通网充商店,可快速完成商店创建、在游戏内添加支付链接然后直接上线。
提示
如需了解更多信息,请访问:[**通过外链跳转至网充商店的购买按钮** ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)
([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)。](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)%E3%80%82)
## SDK 方案
如果希望尽量减少代码改动,可以使用网充商店外链跳转:将用户重定向至现有的艾克索拉网充商店以完成购买。 警告
在网充商店外链跳转模式下,SDK 不会执行原生的应用内支付流程,而是仅打开网充商店并取消所有 SDK 购买回调。请通过网充商店流程(例如 Webhook 或服务器侧逻辑)处理商品发放及支付后的状态更新,切勿依赖 SDK 购买回调。
选择平台开始集成:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/ios/)
购买按钮 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/android
向您的 Android 应用添加外部支付有两种简便方式:将用户重定向至您的网充商店,或在应用内启动支付收银台的原生 UI。两种方案均可直接投入生产环境⸺请选择最符合您工作流程的方式。 推荐
#### 网充商店外链跳转
在浏览器中将用户重定向至现有的艾克索拉网充商店。
- 已拥有艾克索拉网充商店
- 希望尽量减少代码改动
- 需要 Web 端与移动端的支付一致性
- 正从 Web 端分阶段迁移
#### 购买按钮解决方案
在应用内以原生方式处理完整的支付 UI,无需浏览器重定向。
- 希望完全原生集成
- 需要开箱即用的 1000+ 种支付方式
- 更希望由艾克索拉管理支付 UI
- 希望自动满足各地区合规要求
important
要启用**仅限美国**的外链跳转(**自 2025 年 10 月 29 日起生效**),请先检测 **Google Play** 商店地区的国家/地区代码⸺请参阅[**指南**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detect-gpb-storefront-android/)。其中部分计划需缴纳 Google 佣金并向 Google 上报交易,请参阅[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/)。
```java
final Context context = // Your activity context
final String webshopUrl = "https://yourwebshop.xsolla.site";
final String sku = "money.100"; // Virtual item SKU from your Xsolla Catalog
final String userId = "user_12345"; // Current user's ID
final String redirectUrl = "yourgame://"; // Deep link back to your app
WebShop.launchBillingFlow(context, webshopUrl, sku, userId, redirectUrl,
new WebShop.ILaunchBillingFlowCallback() {
@Override
public void onLaunchBillingFlow(@NonNull final Either<Error, Void> result) {
result.voidFold(
err -> Log.e(TAG, "Link-out error: " + err.getMessage()),
__ -> Log.d(TAG, "Web Shop opened successfully")
);
}
}
);
```
这会在设备浏览器中打开您的网充商店。订单履约通过服务器侧 Webhook 完成⸺请参见 [Webhook 设置](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/)。
```java
final Config.Payments paymentsConfig = Config.Payments.getDefault()
.withBuyButtonSolutionEnabled(true);
```
在 SDK 配置中启用一次后,购买按钮会在所有[默认购买流程](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow)中自动生效。主题、Logo 和自定义域名的设置,请参见[配置文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/)。 还不确定?
**网充商店**适合已拥有商店或希望以最少改动快速起步的场景。**支付收银台**是实现完全原生集成的最快路径。两者在全球范围内支持相同的支付方式和地区。
购买按钮 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/ios
### 购买按钮解决方案(推荐)
ℹ️iOS — 外部支付链接跳转(美国、日本、巴西、欧盟)
**iOS**:在美国、日本、巴西和欧盟,Apple 现在允许开发者引导玩家前往外部 Web 支付。**艾克索拉 SDK** 符合 Apple 的最新指南。在日本、巴西和欧盟,这些交易需要向 Apple 支付佣金,并且必须向 Apple 报告,参见[向 Apple 报告外部购买](https://developers.xsolla.com/sdk/zh/compliance/ios/)。
购买按钮解决方案能够以极少的集成工作量提供完整的原生支付体验,通过艾克索拉优化的 UI 组件在应用内处理整个支付流程。
**何时使用购买按钮解决方案**:
- 希望快速完成原生支付集成
- 希望由艾克索拉负责支付 UI 与体验优化
- 需要开箱即用地支持多种支付方式
- 希望自动满足各地区的支付合规要求
```objectivec
// Enable Buy Button solution
settings.useBuyButtonSolution = YES;
```
```swift
// Enable Buy Button solution
settings.useBuyButtonSolution = true
```
### 网充商店外链跳转
网充商店方案会在浏览器中将用户重定向到您现有的艾克索拉网充商店,购买完成后再返回您的应用。该方式适合渐进式迁移,或希望与现有 Web 支付流程保持一致的场景。
**何时使用网充商店外链跳转**:
- 已拥有正在运营的艾克索拉网充商店
- 希望以最少的代码改动测试艾克索拉集成
- 需要在多平台间保持支付流程一致
- 正在实施从 Web 端向移动端支付的分阶段迁移
警告
在网充商店外链跳转模式下,SDK 不会执行原生的应用内支付流程,而是仅打开网充商店并立即取消所有 SDK 购买回调。该模式旨在尽量减少代码改动:请通过网充商店流程(例如 Webhook 或服务器端逻辑)处理商品发放与支付后状态更新,切勿依赖 SDK 购买回调。
#### 配置网充商店集成
使用辅助方法配置网充商店跳转流程:
```objectivec
[settings setupBuyButtonWebShopWithUrl:[NSURL URLWithString:@"https://yourwebshop.xsolla.site"]
userId:@"<USER_ID>"
returnUrl:@"yourgame://"
openExternally:YES];
```
```swift
settings.setupBuyButtonWebShop(url: URL(string: "https://yourwebshop.xsolla.site")!,
userId: "<USER_ID>",
returnUrl: "yourgame://",
openExternally: true)
```
**参数说明**:
- `url`:您的艾克索拉网充商店 URL,用户在此完成购买
- `userId`:您系统中的用户唯一标识,用 于购买归因和用户跟踪
- `returnUrl`:在购买完成后将用户带回应用的深度链接 URL scheme
- `openExternally`:是否在外部浏览器中打开网充商店(推荐开启,便于满足合规要求并提供更佳用户体验)
#### 发起网充商店购买
完成配置后,调用购买方法并传入您的产品 SKU 发起购买:
```objectivec
// Attempt to purchase an item via Web Shop
BOOL handledExternally = [[SKPaymentQueue defaultQueue] purchaseWithSKU:@"money.100"];
if (handledExternally) {
// Web Shop opened successfully, update UI to reflect the redirect
NSLog(@"Purchase redirected to Web Shop");
// Optionally show a loading indicator or message to the user
}
```
```swift
// Attempt to purchase an item via Web Shop
let handledExternally: Bool = SKPaymentQueue.default().purchase(withSKU: "money.100")
if handledExternally {
// Web Shop opened successfully, update UI to reflect the redirect
print("Purchase redirected to Web Shop")
// Optionally show a loading indicator or message to the user
}
```
快速开始 — Mobile SDK
https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start
本快速开始指南将引导您集成艾克索拉 Mobile SDK,在游戏内接入支付功能。指南使用预配置的测试项目 ID 演示核心接入环节:设置基础用户身份认证、导入 SKU 以及完成一笔测试支付。学完本指南后,游戏内即可跑通完整的支付系统,直观展示艾克索拉如何简化游戏变现流程。立即开始,只需简单几步即可为游戏接入支付能力!
⚡ **支持 DMA 合规并提升收益**:结合 APK/IPA 直连分发与应用内 DMA 合规方案⸺接入 1,000+ 种全球支付方式,绕过应用商店抽成,实现利润率最大化。
## 选择平台
选择平台开始集成:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/ios/)
每个平台指南将引导您完成:
- 安装 SDK
- 配置 SDK
- 初始化 SDK
- 发起购买
- 收款
快速开始 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/android
集成 **艾克索拉 Mobile SDK** 并完成首笔测试支付。本指南使用预配置的测试凭证,几分钟内即可快速上手。
## 开始使用
确保项目目标平台为 **Android 7.0+** (`minSdk 24`),然后添加 Maven Central 和 **艾克索拉 Mobile SDK** 依赖:
```kotlin
// settings.gradle
repositories {
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
```
```kotlin
// build.gradle
dependencies {
def version_mobilesdk = '<version>'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
更多配置选项,参见[安装详情](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/android/#prerequisites)。
## 身份认证
将以下内容添加到 Activity 的 `onCreate()`:
```java
import com.xsolla.android.mobile.*;
@Nullable
private BillingClient mBillingClient;
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(), // Test project
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow() // Test login ID
)
);
final Config config = new Config(
configCommon,
configIntegration,
Config.Payments.getDefault(),
Config.Analytics.getDefault()
);
// Inside onCreate(), after creating Config:
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener((billingResult, purchases) -> {
// Handle purchase completion — see Finalize Purchase
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected from Xsolla services.");
}
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (!billingResult.isSuccess()) {
Log.e(TAG, "Connection failed: " + billingResult.getResponseCode());
return;
}
}
});
```
该代码使用 `AutoJWT` 身份认证、沙盒模式和调试日志创建 `Config`,随后初始化 `BillingClient` 并连接艾克索拉服务。在生产环境中,请将测试项目 ID 和登录管理器 ID 替换为[**发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)中您自己的对应 ID。高级选项请参见[配置文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/)。important
如果您使用自己的**项目 ID/登录管理器 ID**,请确保在项目中启用**设备 ID 登录**。启用方法请参见:[https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
## 加载商品目录
建立连接后查询商品目录:
```java
mBillingClient.queryProductDetailsAsync(
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // Test product SKU
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build(),
(result, productDetailsList) -> {
// Launch purchase — see Purchase Product
}
);
```
该代码会从商品目录中加载商品 `key_1`。重连处理与高级选项请参见[初始化文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/android/)。
## 购买商品
使用商品目录查询返回的商品详情发起购买:
```java
// Inside productDetails callback (from Load Catalog):
if (billingResult.isSuccess() &&
productDetailsList != null && !productDetailsList.isEmpty()) {
mBillingClient.launchBillingFlow(
activity, // Your Activity reference
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetailsList.get(0))
.build()
))
.build()
);
} else {
Log.e(TAG, "No products available: " + billingResult.getResponseCode());
}
```
这将打开**艾克索拉支付收银台**,用户在其中完成支付。测试时,请使用[测试银行卡 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards):
![选择支付方式]
![正在处理支付]
![支付已确认]
## 完成购买
购买完成后,对该笔购买执行消费处理,并向用户发放商品:
```java
// Inside onPurchasesUpdated callback:
if (billingResult.isSuccess() && purchases != null) {
for (Purchase purchase : purchases) {
mBillingClient.consumeAsync(
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build(),
(result, purchaseToken) -> {
if (result.isSuccess()) {
Log.d(TAG, "Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
} else {
Log.e(TAG, "Consumption failed: " + result.getResponseCode());
}
}
);
}
} else {
Log.e(TAG, "Purchase failed or cancelled: " + billingResult.getResponseCode());
}
```
该操作对该笔购买执行消费处理,以便向用户发放所购商品(虚拟物品)。错误场景和高级选项请参见[购买流程文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/)。
## 下一步
您已完成完整的支付集成,涵盖身份认证、商品目录加载、购买流程与履约。应用现可在 200+ 个国家/地区接入 1000+ 种支付方式。
- **[设置项目](https://developers.xsolla.com/sdk/zh/publisher-account/)** — 创建发布商帐户,并将沙盒测试凭证替换为生产环境凭证
- **[购买按钮](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/android/)** — 接入外部支付的最快路径
- **[扩展示例](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/extended-examples/android-example/)** — 完整的可运行接入实现
- **[完整 SDK 文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/android/)** — 涵盖高级功能、重试策略与自定义 UI
Android 扩展示例
https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/extended-examples/android-example
**艾克索拉 Mobile SDK** 的集成只需少量步骤,通常包括:
- 配置并初始化 SDK
- 启动收款流程
- 向用户发放已购内容(即完成核销)
以下是一个完整的示例实现,用不到 **150 行代码**即可实现上述功能:
```java
package com.example.yoursdkintegration;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import com.xsolla.android.mobile.*;
import com.xsolla.android.mobile.common.LogLevel;
import java.util.Arrays;
import java.util.List;
public class YourSDKIntegrationActivity extends Activity {
private static final String TAG = "YourSDKIntegration";
@Nullable
private BillingClient mBillingClient = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(),
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow()
)
);
final Config.Analytics configAnalytics = Config.Analytics.getDefault();
final Config.Payments configPayments = Config.Payments.getDefault();
final Config config = new Config(
configCommon,
configIntegration,
configPayments,
configAnalytics
);
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener(new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull BillingResult billingResult, @Nullable List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
for (int i = 0; i < purchases.size(); ++i) {
final ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchases.get(i).getPurchaseToken())
.build();
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(
@NonNull BillingResult billingResult, String purchaseToken
) {
Log.d(TAG,
"Purchase consumption response: " +
billingResult.getResponseCode()
);
}
});
}
} else {
Log.e(TAG,
"Purchase consumption response: " +
billingResult.getResponseCode()
);
}
}
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected.");
}
@Override
public void onBillingSetupFinished(@NonNull BillingResult billingResult) {
if (billingResult.isSuccess()) {
final QueryProductDetailsParams queryProductDetailsParams =
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100")
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build();
mBillingClient.queryProductDetailsAsync(
queryProductDetailsParams, new ProductDetailsResponseListener() {
@Override
public void onProductDetailsResponse(
@NonNull BillingResult billingResult,
@Nullable List<ProductDetails> productDetailsList
) {
if (billingResult.isSuccess() && productDetailsList != null &&
!productDetailsList.isEmpty()) {
// We'll just use the very first element on the list, but you'd normally
// want to handle the rest of the product details as well.
final ProductDetails productDetails = productDetailsList.get(0);
// Create parameters for the purchasing flow..
final BillingFlowParams billingFlowParams =
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetails)
.build()
))
.build();
// Initiate a purchasing flow.
mBillingClient.launchBillingFlow(
YourSDKIntegrationActivity.this, billingFlowParams
);
} else {
Log.e(TAG,
"Received an invalid product details response: " +
billingResult.getResponseCode()
);
}
}
}
);
} else {
Log.e(TAG, "Failed to connect.");
}
}
});
}
}
```
important
如果您使用自己的**项目 ID/登录管理器 ID**,请确保在项目中启用**设备 ID 登录**。启用方法请参见:[https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
快速开始 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/ios
集成 **艾克索拉 Mobile SDK** 并完成首笔测试支付。本指南使用预配置的测试凭证,几分钟内即可快速上手。
⚡ **支持 DMA 合规并提升收益**:结合 IPA 直连分发与应用内 DMA 合规方案⸺接入 1000+ 种全球支付方式,绕过应用商店抽成,实现利润率最大化。
## 开始使用
ℹ️iOS — 外部支付跳转(美国、日本、巴西)
**iOS**:在美国、日本和巴西,Apple 现已允许开发者引导玩家使用外部网页支付。**艾克索拉 SDK** 符合 Apple 更新后的指南。
使用 Swift Package Manager 将 **艾克索拉 Mobile SDK** 添加到项目:
- 在 Xcode 中,前往 **File → Add Package Dependencies…**。
- 输入仓库 URL:`https://github.com/xsolla/xsolla-sdk-ios`。
- 将依赖规则设为 **Up to Next Major Version**,然后点击 **Add Package**。
- 选择 **XsollaMobileSDK** 并将其添加到目标。
然后为目标设置 URL Scheme:
- 选择目标并打开 *Info* 选项卡。
- 在 *URL Types* 区域点击 ➕。
- 将 URL Scheme 设为 `$(PRODUCT_BUNDLE_IDENTIFIER)`。
![URL 方案]
更多配置选项,请参见[安装详情](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios/)。
## 身份认证
使用测试凭证配置 SDK,启动支付队列,并注册交易观察者:
```swift
import XsollaMobileSDK
let settings = SKPaymentSettings(projectId: 301871,
loginProjectId: "dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a",
platform: .standalone)
settings.useSandbox = true
settings.openExternalBrowser = true // External web payment (US, Japan, Brazil); either is allowed in the EU
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self) // Handle purchase completion — see Finalize Purchase
```
```objectivec
#import <XsollaMobileSDK/StoreKitWrapper.h>
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: 301871
loginProjectId:@"dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a"
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
settings.useSandbox = YES;
settings.openExternalBrowser = YES; // External web payment (US, Japan, Brazil); either is allowed in the EU
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
[queue addTransactionObserver: self]; // Handle purchase completion — see Finalize Purchase
```
该代码使用沙盒模式和测试凭证创建设置,随后启动 `SKPaymentQueue` 并注册交易监听器 (observer)。在生产环境中,请将测试项目 ID 和登录管理器 ID 替换为从[**发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)获取的您自己的对应 ID。高级选项(含[商店入口检测](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/))请参见[配置文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)。important
如果您使用自己的**项目 ID/登录管理器 ID**,请确保在项目中启用**设备 ID 登录**。启用方法请参见:[https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)
## 加载商品目录
建立连接后查询商品目录:
```swift
let skus: Set<String> = ["money.100", "ticket.10"]
let req = SKProductsRequest(productIdentifiers: skus)
req.delegate = self
req.start()
// Conform your class to SKProductsRequestDelegate
extension YourClass: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
self.products = response.products
// Launch purchase — see Purchase Product
}
}
```
```objectivec
NSSet *skus = [NSSet setWithArray:@[@"money.100", @"ticket.10"]];
SKProductsRequest* req = [[SKProductsRequest alloc] initWithProductIdentifiers:skus];
req.delegate = self;
[req start];
// Conform your class to SKProductsRequestDelegate
@interface YourClass (SKProductsRequestDelegate) <SKProductsRequestDelegate>
@end
@implementation YourClass (SKProductsRequestDelegate)
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
self.products = response.products;
// Launch purchase — see Purchase Product
}
@end
```
按 SKU 加载商品。关于重连处理和高级选项,请参见[初始化文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/ios/)。
## 购买商品
使用商品目录查询返回的商品详情发起购买:
```swift
let product = products.first! // Previously fetched product
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
```
```objectivec
SKProduct *product = ...; // Previously fetched product
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
这将打开**艾克索拉支付收银台**,用户在其中完成支付。测试时,请使用[测试银行卡 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards):
![选择支付方式]
![处理支付]
![支付已确认]
## 完成购买
在 `SKPaymentTransactionObserver` 中处理已完成的交易,并逐一完成每笔交易:
```swift
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .purchased:
// Award the product (virtual item) to the user here
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// Handle error
SKPaymentQueue.default().finishTransaction(transaction)
default:
break
}
}
}
}
```
```objectivec
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStatePurchased:
// Award the product (virtual item) to the user here
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStateFailed:
// Handle error
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
default: break;
}
}
}
```
这将处理购买结果并完成交易。务必调用 `finishTransaction` 确认每笔交易。错误场景与高级选项请参见[购买流程文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/)。
## 下一步
您已完成完整的支付集成,涵盖身份认证、商品目录加载、购买流程与履约。应用现可在 200+ 个国家/地区接入 1000+ 种支付方式。
- **[设置项目](https://developers.xsolla.com/sdk/zh/publisher-account/)** — 创建发布商帐户,并将沙盒测试凭证替换为生产环境凭证
- **[购买按钮](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/ios/)** — 接入外部支付的最快路径
- **[完整 SDK 文档](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios/)** — 涵盖高级功能、配置与自定义 UI
网充商店与艾克索拉 SDK:相辅相成
https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop
**艾克索拉网充商店**与**艾克索拉 SDK** 协同运作,助您在游戏内外构建强大的变现生态,不仅能升级变现策略,还能简化两套方案的集成流程。
📈 **提升全渠道收入**:结合网充商店与艾克索拉 SDK,依托超过 1,000 种支付方式、现成的购买按钮和统一后端触达全球玩家,以极少额外投入拉动更高转化率。
### 从网充商店到艾克索拉 SDK:顺势拓展
如果您的游戏已接入艾克索拉网充商店,只需极少投入即可轻松集成艾克索拉 SDK:
- 现有基础设施:既有的网充商店集成意味着服务端回调与后端对接已经就绪,可直接支撑用户身份认证、物品库管理和购买处理。
- 商品同步映射:要通过艾克索拉 SDK 实现 APP 内购,主要只需将现有网充商店商品同步映射为 APP 内购商品。由于底层基础已经打通,整个流程十分简捷。
- 统一后端:依托网充商店,您的后端已具备处理艾克索拉 SDK 请求的能力,只需少量调整即可支持 APP 内购交易。
### 从艾克索拉 SDK 到网充商店:轻松拓展新渠道
反之,如果您已集成艾克索拉 SDK,上线网充商店同样轻而易举:
- 现成的基础设施:集成艾克索拉 SDK 意味着游戏已与艾克索拉后端服务打通,可处理用户身份认证和购买流程。
- 艾克索拉商品目录已就绪:您的 APP 内购商品(带有 SKU 的虚拟物品)已在艾克索拉系统中配置妥当,可轻松拓展至网页端商店页面。
- 极少额外配置:依托艾克索拉 SDK 已完成的核心集成,只需自定义网页界面、配置网页专属优惠等少量调整,即可快速上线网充商店。
### 集成的优势
结合使用艾克索拉 SDK 与网充商店,即可构建全方位变现生态,带来以下优势:
- 在各个平台为玩家提供一致的购买体验
- 统一的商品目录(包含虚拟物品的艾克索拉商品目录),便于集中管理
- 灵活推出平台专属优惠与促销活动
- 按需收集数据,深入洞察玩家行为
- 拓展玩家触点,提升互动度与变现能力
### 购买按钮:网充商店集成
购买按钮支持从游戏内直接跳转至指定商品页面,让游戏与网充商店的衔接更加紧密 :
- **精简的购买流程**:玩家在游戏内点击购买按钮即可直达对应商品的网充商店支付界面,省去多余的跳转步骤。
- **熟悉的支付体验**:支持包括 Apple Pay 在内的网充商店全量支付方式,为玩家提供熟悉、可信的结算体验。
- **简便的集成方式**:购买按钮依托现有的网充商店基础设施构建,只需极少投入即可接入。
- **更高的转化表现**:一键直达支付流程,减少购买阻力,有效提升转化率。
- **深度的数据分析**:通过 AppsFlyer 等移动归因合作伙伴 (MMP) 追踪购买并衡量用户生命周期价值 (LTV),全面掌握投放活动成效与收入表现。
备注
如需了解 Android/iOS 商店地区检测、URL 参数及分析工具集成等具体接入说明,请参阅[购买按钮文档 ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/) ([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/)。](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase/)%E3%80%82)
无论您从网充商店还是艾克索拉 SDK 起步,接入另一项方案都十分便捷,助您快速拓展变现渠道,为玩家提供更多参与和支持游戏的方式。 important
如需了解更多信息,请访问:
[艾克索拉移动网充商店 ↗](https://xsolla.com/mobile-web-shop) ([https://xsolla.com/mobile-web-shop](https://xsolla.com/mobile-web-shop))
如何检测 Google Play 商店地区 (Android)?
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detect-gpb-storefront-android
通过 **Google Play** 分发应用时,您可能需要检测当前的商店地区,以实现特定地区的功能。商店地区指与用户帐户关联的 Google Play 地区,由 **ISO-3166-1 alpha-2** 格式的两位国家/地区代码标识(例如美国为 `"US"`)。 important
鉴于**自 2025 年 10 月 29 日起生效的 Epic 诉 Google 案禁令**,此项检测尤为重要;该禁令允许美国区 Google Play 应用通过外链跳转引导用户使用外部支付方式,并禁止施加反引导限制。
通过商店地区检测,您可以:
- 专门面向美国用户启用备选结算方案
- 实现面向不同地区的支付流程
- 根据当地支付与结算法规控制功能可用性
- 确保符合美国法院裁定的合规要求
备注
Google 在不同商店地区的计划与要求各不相同,其中多项计划会收取佣金,并要求您向 Google 上报相关交易。在新市场启用外部交易前,请先参阅[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/)。
可以使用以下代码片段获取 Google Play 商店地区的国家/地区代码:
```java
final Context context = ...
IntegrationUtils.queryGooglePlayCountryCodeAsync(context, result -> {
result.voidFold(
error -> {
// Handle the error here.
},
countryCode -> {
if (countryCode.equalsIgnoreCase("us")) {
// Handle the US storefront.
} else {
// Handle all other storefront variants.
}
}
);
});
```
important
当**通过 Google Play 商店分发并安装**应用时,此代码片段最为实用。如需检查应用是自 Google Play 商店安装还是通过侧载(第三方应用商店或 APK 分发)安装,可使用 `IntegrationUtils.isInstalledFromGooglePlayStore()` 工具函数。 提示
在获取 Google Play 商店地区的国家/地区代码之前,建议(非强制)先确认设备上是否已安装 Google Play 商店,否则商店不可用时查询函数会报错。为此可以使用 `IntegrationUtils.isGooglePlayStoreInstalled()` 工具函数。
如何检测应用商店安装来源?
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore
通过官方应用商店(如 Google Play 商店或 Apple App Store)以外的替代渠道分发应用时,您可能需要检测应用的安装来源。这在以下场景中尤为重要:
- 为不同的替代分发渠道实现差异化支付流程
- 根据安装来源调整应用行为
- 确保符合特定平台的合规要求
- 管控仅在特定分发渠道开放的功能
要判断游戏的安装来源,请使用以下代码片段。
### 如何检查是否已安装 Google Play 商店?
当某些功能不应在 Google Play 生态系统之外运行时,此方法很有用。以下代码片段可用于检查设备是否安装了 **Google Play 商店**:
```java
final Context context = ...
if (IntegrationUtils.IsGooglePlayStoreInstalled(context)) {
// The store is installed on the device..
} else {
// The store is NOT installed on the device..
}
```
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean installed = IntegrationUtils.isGooglePlayStoreInstalled(context);
if (installed) {
// Google Play Store is installed.
} else {
// Google Play Store couldn't be found on the device.
}
```
### 检查应用是否通过 Google Play 商店安装
以下代码片段可用于判断应用是直接通过 **Google Play 商店**安装,还是通过侧载方式安装(即通过第三方应用商店或 APK 安装):
```java
final Context context = ...
if (IntegrationUtils.IsInstalledFromGooglePlayStore(context)) {
// The app was installed from Google Play Store..
} else {
// The app was NOT installed (side-loaded) from Google Play Store..
}
```
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean installed = IntegrationUtils.isInstalledFromGooglePlayStore(context);
if (installed) {
// The app was installed from Google Play Store.
} else {
// The app wasn't installed from Google Play Store.
}
```
### 查询 Google Play 商店的国家/地区代码
使用此代码片段查询 Google Play 商店地区的国家/地区代码。important
国家/地区代码格式基于 ISO-3166-1 alpha-2(联合国国家/地区代码)。
[https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html](https://unicode.org/cldr/charts/latest/supplemental/territory_containment_un_m_49.html)
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
import com.xsolla.android.mobile.Either;
import com.xsolla.android.mobile.Error;
```
```java
final Context context = ...;
IntegrationUtils.queryGooglePlayCountryCodeAsync(
context, new IntegrationUtils.IQueryGooglePlayCountryCodeCallback() {
@Override
public void onQueryGooglePlayCountryCode(@NonNull final Either<Error, String> result) {
result.voidFold(
err -> {
// Handle the error here.
},
countryCode -> {
if (countryCode.equalsIgnoreCase("us")) {
// Handle the US storefront.
} else {
// Handle all other storefront variants.
}
}
);
}
}
);
```
### 查询安装程序的包名
如果需要知道应用安装程序的准确包名,请使用以下代码。
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
import com.xsolla.android.mobile.Either;
import com.xsolla.android.mobile.Error;
```
```java
final Context context = ...;
final Either<Error, String> result = IntegrationUtils.getInstallerPackageName(context);
result.voidFold(
err -> {
// Handle the error.
},
packageName -> {
if (packageName.equalsIgnoreCase("com.xxx.yyy.zzz")) {
// Handle the expected package name.
} else {
// Handle the unknown package name.
}
}
);
```
如果您更喜欢省略错误处理的简化方式,请使用下面的代码:
```java
import android.content.Context;
import com.xsolla.android.mobile.IntegrationUtils;
```
```java
final Context context = ...;
final boolean matched = IntegrationUtils.isInstallerPackageName(
context, "con.xxx.yyy.zzz"
);
if (matched) {
// The package name matched.
} else {
// The package name didn't match.
}
```
### 上报自定义安装来源
每笔订单都会携带应用的安装来源渠道 (`user.mobile_app.install_source`)。SDK 会根据安装程序的包名自动识别该值:`google_play`、`aptoide`、`epic_games_store`;若为其他安装程序,则直接记录其包名本身。
对于在应用商店之外分发的版本包(例如从您的网站下载的 APK),操作系统上报的可能是浏览器、系统软件包安装程序,或根本没有安装程序。此时请手动设置安装渠道,系统将上报您设置的值,而非自动检测到的结果:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withInstallSource("website");
```
要判断应用的替代分发状态,请使用以下代码片段:
```objectivec
[SKPaymentQueue checkIfRunningInAlternativeDistributionWithCompletion:^(BOOL isRunningInAlternativeDistribution) {
settings.enablePayments = isRunningInAlternativeDistribution;
[[SKPaymentQueue defaultQueue] startWithSettings:settings];
}];
```
```swift
SKPaymentQueue.checkIfRunningInAlternativeDistribution { isInAlternativeStore in
settings.enablePayments = isInAlternativeStore
SKPaymentQueue.default().start(settings)
}
```
您也可以实现 [Apple 官方文档 ↗](https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms) ([https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms](https://developer.apple.com/documentation/appdistribution/distributing-your-app-on-an-alternative-marketplace#Enable-your-app-to-run-on-other-platforms)) 中介绍的官方方法来检测替代应用分发。以下实现使用 Swift 编写,同时兼容 Objective-C。调用 `getMarketplaceOrWeb()` 后,如果应用通过替代 App 市场或网页分发渠道分发,回调将返回 `true`。
```swift
getMarketplaceOrWeb { isAlternative in
settings.enablePayments = isAlternative
SKPaymentQueue.default().start(settings)
}
@objc
@MainActor
public static func getMarketplaceOrWeb(_ callback: @escaping ((Bool) -> Void)) {
Task(priority: .high) {
let flag = await isMarketplaceOrWeb()
callback(flag)
}
}
static func isMarketplaceOrWeb() async -> Bool {
if #available(iOS 17.4, *) {
#if canImport(MarketplaceKit)
do {
let currentDistributor = try await AppDistributor.current
switch currentDistributor {
case .appStore:
return false
case .testFlight:
return false
case .marketplace(let bundleId): // Alternative App Marketplace; the argument String identifies the marketplace app bundle ID
return true
case .web: // Alternative Web distribution
return true
case .other:
return false
@unknown default:
return false
}
} catch { return false }
#endif
}
return false
}
```
如何检测 iOS 商店地区?
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront
通过 Apple App Store 分发应用时,您可能需要检测当前的商店地区,以实现特定地区的功能。商店地区代表用户当前使用的 App Store 地区,由三位字母的国家/地区代码标识(例如“USA”代表美国)。
这项检测尤为重要,因为目前已有多地的商店地区允许开发者将玩家引导至外部支付页面⸺**美国**(Epic 诉 Apple 案)、**日本**(《移动软件竞争法》)、**巴西**(CADE 和解协议)以及**欧盟**(《数字市场法案》)。通过商店地区检测,您可以:
- 在允许外部支付的商店地区启用外部支付链接
- 实现特定地区的支付流程
- 根据地区要求控制功能可用性
- 确保符合当地法规
备注
Apple 在不同商店地区的要求各不相同。日本、巴西和欧盟需要申请 Apple 专项授权,并要求将相关交易上报给 Apple,而美国商店地区目前无此两项要求。下方代码片段未列出欧盟各商店地区,请按实际发行范围自行补充。在新市场启用外部支付前,请先参阅[向 Apple 报告外部购买](https://developers.xsolla.com/sdk/zh/compliance/ios/)。 备注
如果应用通过**替代分发渠道**安装(例如 DMA 框架下的替代 App 市场或网页分发),商店地区的国家/地区代码可能无法获取,并会返回**空字符串**。这种情况下,请参阅[**替代渠道安装来源检测**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/)指南,判断应用是否运行在替代分发环境中。
要确定当前的 iOS 商店地区并按地区控制 SDK 功能,请使用以下代码片段:
```objectivec
[SKPaymentQueue loadCurrentStorefrontCountryCodeWithCompletion:^(NSString* _Nullable countryCode) {
// Storefronts where Apple permits external payments. Add EU codes if you ship there.
NSSet<NSString*>* externalPaymentStorefronts = [NSSet setWithObjects:@"USA", @"JPN", @"BRA", nil];
settings.enablePayments = countryCode && [externalPaymentStorefronts containsObject:countryCode];
[[SKPaymentQueue defaultQueue] startWithSettings:settings];
}];
```
```swift
SKPaymentQueue.loadCurrentStorefrontCountryCode { countryCode in
// Storefronts where Apple permits external payments. Add EU codes if you ship there.
let externalPaymentStorefronts: Set = ["USA", "JPN", "BRA"]
settings.enablePayments = countryCode.map(externalPaymentStorefronts.contains) ?? false
SKPaymentQueue.default().start(settings)
}
```
`loadCurrentStorefrontCountryCode` 方法会异步获取当前商店地区的三位字母国家/地区代码。您可以据此为特定地区启用或禁用 SDK 功能。
此外,您也可以直接使用 Apple 的 [Storefront ↗](https://developer.apple.com/documentation/storekit/storefront) ([https://developer.apple.com/documentation/storekit/storefront](https://developer.apple.com/documentation/storekit/storefront)) 类,如下所示: 备注
我们不建议使用 Objective-C 的 `SKStorefront` 实现,因为它会进行同步加载并阻塞主线程。这可能导致用户界面卡顿并带来不佳的体验,Apple 的[官方文档 ↗](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront)中也有说明。
```swift
let storefront = await Storefront.current
let countryCode = storefront?.countryCode
settings.enablePayments = countryCode == "USA"
SKPaymentQueue.default().start(settings)
```
如需了解更多信息,请参阅 Apple [官方文档 ↗](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront) ([https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront](https://developer.apple.com/documentation/storekit/skpaymentqueue/storefront)) 中的实现说明。
iOS 通用链接
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-universal-links
使用**外部浏览器**支付流程时,如果通过**自定义 URL Scheme** 从支付收银台返回应用,iOS 可能会弹出确认对话框(例如:“在 App Name 中打开此页面?”)。改用**通用链接** (HTTPS) 可避免弹出该提示,让返回游戏的跳转体验更加顺畅。
SDK 支持使用通用链接将用户重定向回应用。
## 要求
要使用通用链接,必须在 iOS 项目和域名中完成以下配置:
- **Associated Domains(关联域)**:在 Xcode 中启用并完成配置。参阅 Apple 文档:[支持关联域](https://developer.apple.com/documentation/xcode/supporting-associated-domains)。
- **通用链接**支持:参阅 Apple 文档:[在应用中支持通用链接](https://developer.apple.com/documentation/xcode/supporting-universal-links-in-your-app)。
## SDK 处理方式(自动与手动)
如果启用了 SDK 的自动 URL 处理(方法交换,即 Swizzling),SDK 会自动处理通用链接。
如果关闭自动 URL 处理,则必须把通用链接转发给 SDK,由其处理回调(与手动处理深度链接相同,但 URL 来自 `NSUserActivity.webpageURL`)。
### AppDelegate
```objectivec
- (BOOL)application:(UIApplication *)application
didFinishLaunchingWithOptions:(NSDictionary<UIApplicationLaunchOptionsKey, id> *)launchOptions {
// Cold start (optional): app was launched by a Universal Link
NSDictionary *userActivityDict = launchOptions[UIApplicationLaunchOptionsUserActivityDictionaryKey];
NSUserActivity *activity = userActivityDict[UIApplicationLaunchOptionsUserActivityKey];
NSURL *url = activity.webpageURL;
if (url) {
[[SKPaymentQueue defaultQueue] openWithUrl:url];
}
return YES;
}
// Warm start: app receives a Universal Link while running/suspended
- (BOOL)application:(UIApplication *)application
continueUserActivity:(NSUserActivity *)userActivity
restorationHandler:(void (^)(NSArray<id<UIUserActivityRestoring>> * _Nullable))restorationHandler {
NSURL *url = userActivity.webpageURL;
if (!url) { return NO; }
// Forward to SDK
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
return handledBySDK;
}
```
```swift
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
// Cold start (optional): app was launched by a Universal Link
if let userActivityDict = launchOptions?[.userActivityDictionary] as? [AnyHashable: Any],
let activity = userActivityDict["UIApplicationLaunchOptionsUserActivityKey"] as? NSUserActivity,
let url = activity.webpageURL {
_ = SKPaymentQueue.default().open(url: url)
}
return true
}
// Warm start: app receives a Universal Link while running/suspended
func application(_ application: UIApplication,
continue userActivity: NSUserActivity,
restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
guard let url = userActivity.webpageURL else { return false }
// Forward to SDK
let handledBySDK = SKPaymentQueue.default().open(url: url)
return handledBySDK
}
```
### SceneDelegate
```objectivec
// Cold start: app was launched by a Universal Link
- (void)scene:(UIScene *)scene willConnectToSession:(UISceneSession *)session options:(UISceneConnectionOptions *)connectionOptions {
for (NSUserActivity *activity in connectionOptions.userActivities) {
NSURL *url = activity.webpageURL;
if (!url) { continue; }
// Forward to SDK
[[SKPaymentQueue defaultQueue] openWithUrl:url];
break;
}
}
// Warm start: app receives a Universal Link while running/suspended
- (void)scene:(UIScene *)scene continueUserActivity:(NSUserActivity *)userActivity {
NSURL *url = userActivity.webpageURL;
if (!url) { return; }
// Forward to SDK
[[SKPaymentQueue defaultQueue] openWithUrl:url];
}
```
```swift
// Cold start: app was launched by a Universal Link
func scene(_ scene: UIScene,
willConnectTo session: UISceneSession,
options connectionOptions: UIScene.ConnectionOptions) {
if let userActivity = connectionOptions.userActivities.first,
let url = userActivity.webpageURL {
_ = SKPaymentQueue.default().open(url: url)
}
}
// Warm start: app receives a Universal Link while running/suspended
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {
guard let url = userActivity.webpageURL else { return }
// Forward to SDK
_ = SKPaymentQueue.default().open(url: url)
}
```
Trusted Web Activity (Android)
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/trusted-web-activity
[**Trusted Web Activity (TWA) ↗**](https://developer.chrome.com/docs/android/trusted-web-activity) ([https://developer.chrome.com/docs/android/trusted-web-activity](https://developer.chrome.com/docs/android/trusted-web-activity)) 支持 Android 应用通过 Chrome 以全屏模式展示网页内容,不显示任何浏览器界面元素。与 WebView 不同,TWA 在用户的浏览器环境中运行,性能更佳,可调用浏览器功能(如推送通知和后台同步),并能在应用与浏览器之间共享 Cookie、权限和存储。 important
要启用 Trusted Web Activity,请联系您的集成经理,并提供应用的包名和证书哈希值。 您知道吗?
Trusted Web Activity 支持与具体项目无关,直接在应用级别生效⸺仅取决于包名和签名证书。
### 在 SDK 中配置 Trusted Web Activity
配置 SDK 时,按如下方式向配置中传入 Activity 设置:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forTrustedWebActivity());
```
这样可确保支付流程使用 Trusted Web Activity。 注意
Trusted Web Activity 是否可用取决于设备的系统配置,即设备上必须安装兼容的浏览器。如果当前环境不支持 TWA,SDK 会自动回退为默认的支付 Activity 类型(例如 Custom Tabs 或 WebView ,具体视运行环境而定)。
TWA 实际效果示例: [](https://developers.xsolla.com/sdk/zh/assets/images/twa-1-737175ed3a44e80fb60131748dda4361.jpg)
### 屏幕方向锁定(可选)
Trusted Web Activity 在显示时原生支持屏幕方向锁定,可在配置阶段通过以下代码进行设置:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivityOrientationLock(
// orientation setting
);
```
方向设置可选以下值:
- `Config.Payments.ACTIVITY_ORIENTATION_LOCK_PORTRAIT` - 强制以竖屏模式显示 TWA。
- `Config.Payments.ACTIVITY_ORIENTATION_LOCK_LANDSCAPE` - 强制以横屏模式显示 TWA。
- `null` - 禁用方向锁定。
### 添加可自定义的启动画面(可选)
Trusted Web Activity 还支持在打开 TWA 前展示可自定义的启动画面。如需启用,请修改[前文](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/trusted-web-activity#configuring-for-trusted-web-activity-in-the-sdk)添加的配置项:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage(
// image settings go here
));
```
TWA 启动画面示例: [](https://developers.xsolla.com/sdk/zh/assets/images/twa-2-fd93e4a14c1a92ff7574a04d1a7abf15.jpg)
#### 为启动画面设置图片
可以通过两种方式提供图片:drawable ID 或图片文件路径:
- 使用 drawable ID: important 需要事先手动将该 drawable 添加到 Android 资源中。 ```java final Config.Payments configPayments = Config.Payments.getDefault() .withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage( Config.Payments.Activity.TrustedWebActivity.Image.forDrawableId( <your_drawable_id> ) )); ``` 提示 也支持 SVG 格式,但需要封装为有效的 drawable XML。
- 使用文件路径: important 图片文件必须位于应用可访问的路径下。支持所有主流光栅图像格式。 ```java final Config.Payments configPayments = Config.Payments.getDefault() .withActivity(Config.Payments.Activity.forTrustedWebActivityWithImage( Config.Payments.Activity.TrustedWebActivity.Image.forFilepath( <filepath_to_your_splash_screen_image> ) )); ```
备注
如果使用 **Unity**,请访问此页面了解详情:[**Trusted Web Activity - Unity (Android)**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/trusted-web-activity/)。
配置
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)
配置 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android
Android 版**艾克索拉 Mobile SDK** 将配置划分为 4 个主要设置子类别,每个子类别均对应一个专用类:
- [**Common**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#common) - 定义 SDK 通用属性的设置。
- [**Integration**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#integration) - 定义 SDK 如何与**艾克索拉**服务集成的设置。 - [**Authentication**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#authentication) - 定义 SDK 如何与**艾克索拉**服务进行身份认证的设置。 - [**Events**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#xsolla-events-api) - 定义 SDK 如何与**艾克索拉 Events API** 协作的设置。
- [**Payments**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#payments) - 定义**艾克索拉支付收银台**行为(外观、重定向等)的设置。
- [**Analytics**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#analytics) - 定义 SDK 分析相关元数据的设置。
要组合上述所有子类别来创建 SDK 的 `Config`,请使用以下代码片段:
```java
final Config config = new Config(
configCommon,
configIntegration,
configPayments,
configAnalytics
);
```
## 通用
调用 `Config.Common.getDefault()` 获取默认配置。下面是一个更适合测试的示例:
```java
final Config.Common configCommon = Config.Common.getDefault()
.withSandboxEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withDebugEnabled(true);
```
下表列出了 `Config.Common` 支持的所有设置:
| 设置 | 值 | 默认值 | 说明 |
| --- | --- | --- | --- |
| withSandboxEnabled | boolean | false | 是否启用测试支付?启用后不会发生真实交易。要使沙盒生效,项目不能处于 LIVE 模式。 |
| withLogLevel | enum LogLevel (VERBOSE, DEBUG, INFO, WARN, ERROR) | ERROR | 控制日志的详细程度(如果遇到问题并希望了解底层情况,可使用 DEBUG)。 |
| withSkipNonExistentProductsOnQuery | boolean | true | queryProductDetailsAsync() 在查询时是安全忽略所请求但不存在的产品,还是立即报错失败? |
| withDeferredAuthenticationEnabled | boolean | true | 控制是否将身份认证推迟到 SDK 功能真正需要时再执行,从而有望加快初始化流程。 |
| withDebugEnabled | boolean | false | 启用调试模式(更多日志、性能分析等)。 |
| withLocaleOverride | LocaleInfo | null | 用于返回的产品及支付收银台定价与展示格式的指定区域设置(为 null 时自动匹配)。 |
| withFallbackToDeviceLocale | boolean | false | 未显式指定区域覆盖时,是否使用设备当前的区域设置(否则由支付收银台自动推断)? |
| withFetchPersonalizedProductsOnly | boolean | true | 仅返回个性化产品;如需获取通用商品目录,请将其设为 false。 |
| withUseGeoLocaleOnProductQuery | boolean | false | 在查询产品时强制使用地理区域设置。 |
| withRetryPolicies | RetryPolicies | null | 全局或按操作(身份认证、创建订单、查询产品等)覆盖重试行为。 |
| withCollapseRestoredMultiUnitPurchases | boolean | false | 在恢复时,是否将同一 SKU 的多个拥有单位合并为一个 Purchase 返回?参见下文已购内容恢复设置。 |
| withProductCacheTtlMillis | Long | 3600000 | queryProductDetailsAsync() 的产品缓存有效期(毫秒,默认 1 小时),自写入缓存时开始计时。null 或非正值表示在当前进程内永不过期⸺此时只能通过重启应用来刷新旧缓存。 |
| withMaxItemsPerProductRequest | Integer | null | 获取尚未缓存的产品时,queryProductDetailsAsync() 单次调用请求的 SKU 数量。null 使用后端分页上限 50;取值会限制在 1–50 范围内,因为该上限属于后端硬性限制而非可调参数。 |
| withMaxParallelProductRequests | Integer | 4 | 单次 queryProductDetailsAsync() 调用可并发发起的产品拉取请求数上限,用于避免触发后端速率限制。设为 1 表示按顺序请求;设为 null 或非正值则会一次性并发发送所有分批请求。 |
| withAllowBundlesAsInApp | boolean | false | 当按 INAPP 请求时,接受解析为捆绑包的 SKU,而不是报告其与所请求类型不匹配。让不区分两者的调用方在一次查询中同时获取两类产品。 |
| withAllowVirtualCurrencyAsInApp | boolean | false | 对在 INAPP 请求中解析为虚拟货币的 SKU 进行同样的放宽。 |
这两项放宽限制的适用范围很窄且单向生效:仅在 `INAPP` 请求中接受对应的一种类型,`SUBS` 或任何其他类型不匹配仍会报错失败。返回的产品仍会报告其**真实**类型⸺`getProductType()` 返回 `bundle` 或 `virtual_currency`,绝不会返回 `inapp`⸺因此下游任何按产品类型做分支判断的逻辑都必须兼容这一点。
### 重试策略与配置方案
按操作覆盖重试策略:
| 设置 | 值 | 默认值 | 说明 |
| --- | --- | --- | --- |
| withDefaultRetryProfileOverride | RetryProfile | null | 未提供特定操作的配置方案时应用的默认回退配置方案。 |
| withAuthenticateRetryProfileOverride | RetryProfile | null | 覆盖身份认证的重试行为。 |
| withCreateOrderRetryProfileOverride | RetryProfile | null | 覆盖创建订单的重试行为。 |
| withPendingOrderStatusQueryRetryProfileOverride | RetryProfile | null | 覆盖轮询待处理订单状态时的重试行为。 |
| withQueryProductsRetryProfileOverride | RetryProfile | null | 覆盖查询产品列表的重试行为。 |
| withQueryPurchasesRetryProfileOverride | RetryProfile | null | 覆盖查询购买列表的重试行为。 |
| withConsumePurchasesRetryProfileOverride | RetryProfile | null | 覆盖核销已购项的重试行为。 |
此处的 `null` 并不表示“无重试”⸺而是表示“不覆盖”,操作会回退到内置配置方案:**固定间隔 750 ms 延迟,最多尝试 12 次**。仅在需要修改此默认行为时才需设置覆盖。
使用不同的 `RetryProfile` 类型为特定操作或全局默认行为构建覆盖配置:
尝试之间的延迟固定。
```java
final RetryProfile retryProfile = RetryProfile.uniform(
PositiveInteger.create(6).getRightOrThrow(),
PositiveInteger.create(1000).getRightOrThrow()
);
```
| 参数 | 说明 |
| --- | --- |
| maxNumAttempts | 正整数;允许的总尝试次数(初始尝试 + 重试)。 |
| intervalMillis | 尝试之间的固定延迟(毫秒)。 |
延迟从基础间隔按指数增长,可选设置上限和抖动。
```java
final RetryProfile retryProfile = RetryProfile.exponentialBackout(
PositiveInteger.create(5).getRightOrThrow(),
PositiveInteger.create(500).getRightOrThrow(),
PositiveInteger.create(4000).getRightOrThrow(),
null // optional jitter cap
);
```
| 参数 | 说明 |
| --- | --- |
| maxNumAttempts | 正整数;允许的总尝试次数(初始尝试 + 重试)。 |
| baseIntervalMillis | 初始延迟(毫秒);后续尝试将从该基础值按指数增长。 |
| maxIntervalMillis(可选) | 退避延迟上限(毫秒);若省略,延迟可持续增长直至耗尽尝试次数。 |
| maxRandomExtraDelayMillis(可选) | 每次退避延迟最多增加的随机抖动时长(毫秒);设为 null 则禁用抖动。 |
```java
final RetryPolicies retryPolicies = RetryPolicies.getDefault()
.withDefaultRetryProfileOverride(retryProfile) // pick from a tab above
.withAuthenticateRetryProfileOverride(retryProfile);
final Config.Common configCommon = Config.Common.getDefault()
.withRetryPolicies(retryPolicies);
```
## 集成
### 身份认证
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
LoginUuid.parse(<your_login_id>).getRightOrThrow()
)
);
```
使用有效的自定义登录 **JWT** 进行身份认证。适用于在外部生成或获取 JWT(例如通过应用后端或艾克索拉登录管理器等服务)后再传入 SDK 的场景。
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
JWT.parse(<jwt>).getRightOrThrow()
)
);
```
**手动更新 JWT 令牌**:
如果在连接支付与结算客户端后,JWT 令牌过期且需要刷新,请使用 `JWTRefresher` 参数:
```java
final JWTRefresher jwtRefresher = new JWTRefresher();
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forJWT(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
JWT.parse(<jwt>).getRightOrThrow(),
jwtRefresher
)
);
// Later, when you need to update the token:
jwtRefresher.update(JWT.parse(<new_jwt>).getRightOrThrow());
```
使用 OAuth2 进行身份认证。
```java
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forOAuth2(
ProjectId.parse(<your_project_id>).getRightOrThrow(),
LoginUuid.parse(<your_login_id>).getRightOrThrow(),
OAuth2ClientId.parse(<oauth2_client_id>).getRightOrThrow()
)
);
```
使用从第三方平台获取的社交访问令牌进行身份认证。
首先,使用此方式前需确定要接入的社交平台,并确认其受艾克索拉身份认证服务支持:所有支持的社交平台名称
- google
- facebook
- twitter
- linkedin
- naver
- baidu
- amazon
- apple
- battlenet
- discord
- github
- kakao
- mailru
- microsoft
- msn
- ok
- paypal
- psn
- qq
- reddit
- steam
- twitch
- vimeo
- vk
- wechat
- weibo
- yahoo
- yandex
- youtube
- xbox
- babka
- epicgames
`LoginUtils.SocialProvider` 预定义了一组常用的社交平台取值,便于直接调用。如需根据字符串获取对应实例,请调用 `LoginUtils.SocialProvider.parse("<social-provider-name>")`。
```java
final LoginUtils.SocialProvider socialProvider = LoginUtils.SocialProvider.EPICGAMES;
final String socialAccessToken = "<social-access-token>";
```
总体有两种实现方式:
- **使用 OAuth2(推荐)** ```java final Config.Integration configIntegration = Config.Integration.forXsolla( Config.Integration.Xsolla.Authentication.forSocial( ProjectId.parse(<your_project_id>).getRightOrThrow(), LoginUuid.parse(<your_login_id>).getRightOrThrow(), OAuth2ClientId.parse(<oauth2_client_id>).getRightOrThrow(), socialProvider, socialAccessToken ) ); ```
- **不使用 OAuth2** ```java final Config.Integration configIntegration = Config.Integration.forXsolla( Config.Integration.Xsolla.Authentication.forSocial( ProjectId.parse(<your_project_id>).getRightOrThrow(), LoginUuid.parse(<your_login_id>).getRightOrThrow(), socialProvider, socialAccessToken ) ); ```
关于如何获取**产品 ID** 和**登录管理器 ID**,请查看[**此处**](https://developers.xsolla.com/sdk/zh/publisher-account/getids/)。
您也可以通过[**自定义登录令牌**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/?auth-method=xsolla-jwt-custom#authentication)方式传入[**艾克索拉登录管理器 ↗**](https://xsolla.com/login) ([https://xsolla.com/login](https://xsolla.com/login)) 令牌。
### 已购内容恢复设置
已购内容恢复功能可找回玩家已完成的购买记录⸺例如在重装应用、更换新设备,或客户端未能确认原始交易后⸺从而避免玩家因同一商品被重复扣费。
SDK 从哪个后端进行恢复由两项设置共同决定⸺一处在发布商帐户中,另一处在下方 SDK 配置中。项目会一直从 Inventory API 恢复,直到这两处都切换为 Events API。关于具体组合、各后端记录的内容,以及已上线项目切换时涉及的事项,参见[**选择模式**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api/#selecting-a-mode)。 注意
**从 Inventory API 恢复不会提供真实的订单或发票标识符。**
物品库只保存玩家当前拥有的内容,并不记录背后的交易信息,因此 SDK 会在设备端临时生成这些标识符⸺它们不对应发布商帐户或订单查询中的任何实际记录。如果您的后端、支持工具或反欺诈校验需要将已恢复的购买内容与真实的艾克索拉订单匹配,就必须使用 Events API。各字段的具体差异见[**购买流程 — 恢复的购买内容**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/#restored-purchases)。
#### 每笔恢复购买对应的单位数量
一条物品库记录包含一个 SKU 和对应数量。默认情况下,SDK 会根据已拥有的单位数量,将这条记录拆分为多个数量为 1 的 `Purchase` 对象。如果商品目录将游戏内货币配置为按单位计算的虚拟物品,那么在一次恢复购买中,单个 SKU 可能会返回数十万个已拥有单位。此时,如果为每个单位都单独创建一个 `Purchase` 对象,就会造成明显的内存压力。
`withCollapseRestoredMultiUnitPurchases`(位于 `Config.Common`,见上文[**通用**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#common))会把该记录作为一个 `Purchase` 对象返回,并携带完整数量。默认值为 `false`:
```java
final Config.Common configCommon = Config.Common.getDefault()
.withCollapseRestoredMultiUnitPurchases(true);
```
| 配置 | 拥有量 | 结果 |
| --- | --- | --- |
| false | 少于 100 个单位 | 每个单位对应一个 Purchase 对象,每个对象的数量均为 1 |
| false | 100 个单位或更多 | 返回包含全部数量的一个 Purchase 对象 |
| true | 任意数量 | 始终返回包含全部数量的一个 Purchase 对象 |
该 `100` 单位阈值是防范上述情况的硬性上限。该阈值不可配置,即使关闭此开关也会生效⸺因此一旦拥有量超过该阈值,返回结构便会自动改变。若某个 SKU 的实际拥有量可能达到这一规模,请同时兼容两种结构。
核销合并后的 `Purchase` 会在单次 `consumeAsync()` 调用中耗尽其全部单位。除此之外,拆分仅用于方便展示:物品库按 SKU 汇总上报数量,因此生成的对象并不带有逐笔支付的标识⸺详见 [**Inventory API 与 Events API**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api/#no-anchor-data)。
### 艾克索拉 Events API
**艾克索拉 Events API** 可替代基于 Webhook 的集成,在后者中,大多数逻辑(购买校验、发放等)通常由集成方后端处理。该 API 不直接发送 Webhook,而是拦截它们并将其负载存储到由艾克索拉管理的远程队列中。对于缺乏后端能力或无需后端的项目,这种方式可以实现无服务器集成,同时仍可在应用内直接处理完整的交易流程。
提供 `Events` 配置也会将恢复切换为 Events API,因此恢复的购买会携带源自原始艾克索拉订单的真实订单 ID 与发票 ID⸺见上文[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android#purchase-restoration-settings)。
要启用该功能,请在*发布商帐户*中打开项目,前往**项目设置** > **集成设置**,选择**使用 API** 并点击**保存**。详情见[**发布商帐户中的 Events API**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。
启用***艾克索拉 Events API*** 将**禁用**项目的 **Webhook**⸺**二者不能同时使用**。
下面是启用 SDK 该功能所需的最小事件配置:
```java
final Config.Integration.Xsolla.Events configEvents =
Config.Integration.Events
.newBuilder()
.build()
```
如果您希望监听传入事件,可使用 `Events.Builder.withEventListener` 方法分配一个可选的自定义事件监听器:
```java
final Config.Integration.Xsolla.Events configEvents =
Config.Integration.Events
.newBuilder()
.withEventListener(event -> {
// Don't consume the event (mark as processed on the queue).
return false;
})
.build()
```
接下来,将该事件配置分配给集成配置:
```java
final Config.Integration configIntegration =
Config.Integration
.forXsolla(
// ...your authentication configuration
)
.withEvents(configEvents);
```
下表列出了与 Events API 相关的高级设置:
| 设置 | 值 | 默认值 | 说明 |
| --- | --- | --- | --- |
| withDefaultQueryPeriodMillis | Long | 5000 | 连续事件查询之间的时间间隔,单位为毫秒(设为 -1 表示禁用,设为 null 则使用默认值)。 |
| withQueryProfileIfExpectingPurchases | EventQueryProfile | null | 预期即将产生购买结果时应用的特定查询配置方案(例如刚完成购买流程正在等待确认,希望在限定时间内加快查询频率)。 |
| withExternalFreePurchaseHandlingEnabled | boolean | false | 是否处理由领取免费商品引发的外部购买事件? |
## 支付与收银台
调用 `Config.Payments.getDefault()` 获取默认配置。下面的示例会强制在**艾克索拉支付收银台**中显示关闭按钮:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withCloseButton(Config.Payments.CloseButton.show());
```
下表列出了 `Config.Payments` 支持的所有设置:
| 设置 | 值 | 默认值 | 说明 |
| --- | --- | --- | --- |
| withRedirectUrl | URL | null | 从艾克索拉支付收银台返回时要重定向到的 URL。 |
| withRedirectTimeoutSecs | Integer | null | 艾克索拉支付收银台自动关闭前的等待时间(为 null 则使用默认值)。 |
| withRedirectButtonText | String | null | 艾克索拉支付收银台中“返回”链接显示的文本。 |
| withRedirectCondition | Integer | null | 决定在何种条件下触发自动关闭(REDIRECT_CONDITION_DISABLED、REDIRECT_CONDITION_SUCCESS、REDIRECT_CONDITION_SUCCESS_OR_CANCELED、REDIRECT_CONDITION_ANY)。 |
| withTheme | Config.Payments.Theme | null | 定义艾克索拉支付收银台的视觉样式(Theme.Light、Theme.Dark、Theme.Custom)⸺未设置主题时,支付收银台会自动选择尺寸与样式。 |
| withCloseButton | Config.Payments.CloseButton | null | 定义艾克索拉支付收银台中关闭按钮的状态(请勿与“返回”链接混淆;CloseButton.Hide、CloseButton.Show)。 |
| withActivity | Config.Payments.Activity | null | 确定用于显示艾克索拉支付收银台的方式(Activity.System、Activity.WebView、Activity.CustomTabs、Activity.TrustedWebActivity⸺关于 TWA 详见此处)。 |
| withActivityOrientationLock | Integer | null | 指定显示艾克索拉支付收银台时要锁定的屏幕方向(可用性取决于所选的 Config.Payments.Activity;ACTIVITY_ORIENTATION_LOCK_PORTRAIT、ACTIVITY_ORIENTATION_LOCK_LANDSCAPE)。 |
| withBuyButtonSolutionEnabled | boolean | false | 启用或禁用购买按钮解决方案(更多信息见此处)。 |
| withEmailCollectionConsentOptInEnabled | boolean | false | 在支付流程中开启收集用户电子邮箱的授权选项(例如征求订阅资讯邮件的同意)。 |
| withInvokePurchasesUpdatedForMissingOrderId | boolean | false | 即使缺少订单 ID,也调用购买回调(适用于无订单 ID 的流程)。 |
| withShowLogoEnabled | Boolean | null | 控制支付收银台中艾克索拉 Logo 的可见性。传入 true 显示,false 隐藏,或传入 null 使用默认行为。 |
| withEventListeners | EventListeners | null | 为支付收银台的导航事件(页面打开、加载、关闭)注册监听器。使用 EventListeners 构建器配置回调。 |
| withDomainOverrideConfig | DomainOverrideConfig | null | 覆盖生产与沙盒环境下支付收银台的默认域名。使用 DomainOverrideConfig 构建器指定自定义域名。 |
| withCustomUserId | String | null | 要与支付收银台中的支付会话关联的自定义用户标识符(null 表示省略)。作为 custom_parameters.custom_user_id 发送,并会在购买相关 Webhook 中返回;不用于归因⸺见 withAttributionUserId。 |
| withAttributionUserId | String | null | 上报给归因平台(AppsFlyer、Adjust 等)的购买事件所关联的用户 ID,会作为 custom_parameters.custom_id 发送给支付收银台。该值必须等于归因 SDK 上报的客户用户 ID,否则购买事件无法与该用户匹配。为 null 时,事件将基于支付令牌中的用户 ID 匹配,默认即玩家的艾克索拉登录管理器用户 ID。1 |
| withInstallSource | String | null | 应用的分发渠道,会随订单以 user.mobile_app.install_source 发送,替代从操作系统安装程序检测到的渠道。适用于在应用商店外分发的版本包(例如从官网下载的 APK),此时操作系统会报告浏览器、系统软件包安装程序或无安装程序。该值会去除首尾空白后按原样发送;空白值视为未设置。为 null 时,发送检测到的值:google_play、aptoide、epic_games_store 或安装程序的包名⸺详见此处。 |
| withQueryCancellationReasonEnabled | boolean | false | 购买流程未完成即结束时,是否查询支付取消原因。 |
| withRedirectAppRelaunch | boolean | false | 当应用在外部浏览器支付流程中被系统终止时,允许通过支付收银台的“返回应用”按钮重新拉起应用,而非静默失败。 |
1 如果您的项目通过服务器端自定义 ID 登录或 PlayFab 进行玩家身份认证,或将用户 ID 映射到自定义 JWT 声明,支付令牌会携带该值而不是登录管理器用户 ID。请调用 `withAttributionUserId`,否则购买事件无法与归因平台匹配。
### Custom Tabs / Trusted Web Activity 提供程序控制
对于 Custom Tabs 和 Trusted Web Activity 流程,可控制允许的浏览器提供程序及其优先级:
```java
final Config.Payments configPayments = Config.Payments.getDefault()
.withActivity(Config.Payments.Activity.forCustomTabs())
.withEmailCollectionConsentOptInEnabled(true)
.withActivity(
Config.Payments.Activity.forCustomTabs()
.withBlacklistedProviders(Set.of("com.android.chrome"))
.withInternalProviderBlacklistEnabled(true)
.withBlacklistedTWAProviders(Set.of("com.vendor.browser"))
.withInternalTWAProviderBlacklistEnabled(true)
.withProviderWeights(Map.of("com.google.android.apps.chrome", 2.0f))
.withFallbackToFirstAvailableTWAProvider(true)
);
```
### 购买按钮解决方案
购买按钮解决方案能够以极少的集成工作量提供完整的原生支付体验,通过艾克索拉优化的 UI 组件在应用内处理整个支付流程。
**何时使用购买按钮解决方案**:
- 希望实现完全原生的集成
- 需要开箱即用的 1000+ 种支付方式
- 倾向于由艾克索拉托管支付 UI
- 希望自动满足各地区的合规要求
要启用购买按钮解决方案(仅适用于[**默认流程**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/?purchase-method=standard#starting-purchasing-flow)),请使用以下代码片段:
```java
final Config.Payments configPayments =
Config.Payments.getDefault()
.withBuyButtonSolutionEnabled(true);
```
### 事件监听器
`EventListeners` 是一个可选的不可变回调容器,无需创建子类或修改计费流程,即可接入**支付收银台**的 UI 生命周期事件。可通过 `.withEventListeners(...)` 将其挂载到支付配置中。
所有回调均在**主线程**分发⸺可直接安全地更新 UI。
| 接口 | 方法 | 触发时机 |
| --- | --- | --- |
| IOpenedListener | onOpened() | 支付收银台 Activity 已启动。 |
| ILoadedListener | onLoaded() | WebView 加载完成(无论加载成功、失败还是中止均会触发⸺SDK 在 EventListeners 层面不区分这些结果)。 |
| ICompletedListener | onCompleted() | 支付成功,且已传入 OK 和非空购买列表调用 onPurchasesUpdated。 |
| ICancelledListener | onCancelled() | 流程以 USER_CANCELED 响应码结束(在 onPurchasesUpdated(USER_CANCELED, null) 之外额外触发⸺不会替代原有回调)。 |
信息
对于基于 SKU 的流程,只有当购买列表非空时才会触发 `onCompleted`。在艾克索拉侧无有效订单 ID 的订单会被静默跳过。
使用写时复制构建器创建 `EventListeners` 实例⸺每次 `with*` 调用都会返回一个新实例。所有监听器均为可选;未设置的监听器不会被调用。向 `.withEventListeners(...)` 传入 `null` 会禁用所有监听器。
```java
final EventListeners listeners = EventListeners.getDefault()
.withOpenedListener(() -> { /* Pay Station opened */ })
.withLoadedListener(() -> { /* Pay Station loaded */ })
.withCompletedListener(() -> { /* payment completed */ })
.withCancelledListener(() -> { /* payment cancelled */ });
final Config.Payments configPayments = Config.Payments.getDefault()
.withEventListeners(listeners);
```
## 分析
通过分析配置,您可以向 SDK 传递元数据,供艾 克索拉用于内部分析与报表统计。该配置并非强制要求,但有助于更清晰地掌握应用性能、用户行为和交易流程⸺从而更高效地诊断或排查问题。
```java
final Config.Analytics configAnalytics =
Config.Analytics.getDefault()
.withGameEngine("<game-engine-identifier>")
.withGameEngineVersion("<game-engine-version>">);
```
下表列出了 `Config.Analytics` 支持的所有设置:
| 设置 | 值 | 默认值 | 说明 |
| --- | --- | --- | --- |
| withGameEngine | String | null | 自定义游戏引擎标识符;null 使用默认值。 |
| withGameEngineVersion | String | null | 自定义游戏引擎版本;null 使用默认值。 |
在 SDK 中配置分析前,请联系您的**集成经理**确认这是否适用于您的集成。
## 在沙盒模式下测试购买流程
关于如何启用沙盒模式以免在测试集成时产生真实扣款,详见[**此处**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/android/)。
配置 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios
本指南介绍如何为 iOS 配置**艾克索拉 Mobile SDK**,以在移动应用中启用支付处理。该 SDK 提供多种集成方式,从完全原生实现到基于 Web 的方案,您可以根据应用需求和开发周期选择最合适的方法。
## 基本 SDK 配置
艾克索拉 Mobile SDK 需要使用来自[**艾克索拉发布商帐户 ↗**](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/](https://publisher.xsolla.com/)) 的项目凭证进行配置。这些设置控制 SDK 如何连接到艾克索拉服务并处理支付流程。
### 必填配置参数
- **Project ID**:您的艾克索拉项目标识(数字)
- **Login Project ID**:您的艾克索拉登录管理器项目标识(UUID 字符串)
- **Platform**:指定目标平台(移动应用通常为 `.standalone`)
在初始开发和测试阶段,您可以使用以下示例凭证:
```objectivec
#import <XsollaMobileSDK/StoreKitWrapper.h>
// Initialize SDK settings with your project credentials
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: 301871
loginProjectId:@"dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a"
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
// Enable sandbox mode for testing (disable for production)
settings.useSandbox = YES;
// Enable the SDK functionality (set to NO to completely disable payments)
settings.enablePayments = YES;
// Configure external browser behavior (see compliance section below)
settings.openExternalBrowser = YES; // Set based on your compliance requirements
// Initialize the payment queue with your settings
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
[queue addTransactionObserver: self];
```
```swift
import XsollaMobileSDK
// Initialize SDK settings with your project credentials
let settings = SKPaymentSettings(projectId: 301871,
loginProjectId: "dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a",
platform: .standalone)
// Enable sandbox mode for testing (disable for production)
settings.useSandbox = true
// Enable the SDK functionality (set to false to completely disable payments)
settings.enablePayments = true
// Configure external browser behavior (see compliance section below)
settings.openExternalBrowser = true // Set based on your compliance requirements
// Initialize the payment queue with your settings
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
```
### 区域合规配置
`openExternalBrowser` 设置用于控制购买是在**外部网页支付页面** (`true`) 还是**应用内** (`false`) 完成。请根据目标市场进行设置⸺越来越多的司法辖区已要求 Apple 允许开发者将玩家引导至外部支付:
- **美国** — 允许使用外部购买链接(Epic 诉 Apple 案)→ `openExternalBrowser = true`
- **日本** — **《移动软件竞争法》(MSCA)** 允许外部支付与网页外链跳转 → `openExternalBrowser = true`
- **巴西** — Apple 与 **CADE** 达成的反垄断和解协议允许外部支付与外链跳转 → `openExternalBrowser = true`
- **欧盟** — 根据《**数字市场法案**》(DMA),两种方式均可:保留在应用内完成流程 → `openExternalBrowser = false`,或将玩家引导至网页 → `openExternalBrowser = true`。Apple 对两种方式收取不同的佣金,且自 **2026 年 10 月 1 日**起,选定的方案须锁定 12 个月不变,因此请先与业务团队敲定
```objectivec
settings.openExternalBrowser = YES; // External web payment — US, Japan, Brazil
settings.openExternalBrowser = NO; // In-app payment — EU
```
```swift
settings.openExternalBrowser = true // External web payment — US, Japan, Brazil
settings.openExternalBrowser = false // In-app payment — EU
```
备注
平台规则和佣金因市场而异且持续变化。正式上线前,请针对应用发行的每个地区确认 Apple 的现行要求。
对于更复杂的合规场景,您可以通过代码检测用户的地区与分发渠道,从而自动配置相应设置。了解如何[**检测 iOS 商店地区**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/)以在允许外部支付的地区启用该功能,或[**检测替代应用分发状态**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detectstore/)以根据应用的安装来源启用面向欧盟的合规流程。
### 关键配置说明
- **启用支付**:必须通过将 `enablePayments` 设为 `true` 来显式启用 SDK 支付。这样即使不移除 SDK 集成,也能在需要时彻底关闭支付功能。
- **沙盒模式**:`useSandbox` 默认值为 `true`,除非主动修改,否则 SDK 会在沙盒环境中运行。开发和测试阶段请保持为 `true` 以免产生真实交易,正式上线前请务必设为 `useSandbox = false`。
- **交易观察者**:请勿忘记将您的类注册为交易观察者 (Observer),以便接收支付完成回调。
### 默认支付方式
您可以为艾克索拉支付收银台设置默认支付方式。可在 `settings` 中全局配置(适用于所有购买),也可按单次购买配置。取值为支付收银台的支付方式 ID(例如 `3175` 表示 Apple Pay)。
```objectivec
// Global default (set before starting the SDK)
settings.paymentMethodId = [NSNumber numberWithInt:3175]; // 3175 = Apple Pay
// Per purchase override
SKMutablePayment *payment = [SKMutablePayment paymentWithProduct:product];
payment.paymentMethodId = [NSNumber numberWithInt:3175]; // 3175 = Apple Pay
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
```swift
// Global default (set before starting the SDK)
settings.paymentMethod = 3175 // 3175 = Apple Pay
// Per purchase override
let payment = SKPayment(product: product)
payment.paymentMethod = 3175 // 3175 = Apple Pay
SKPaymentQueue.default().add(payment)
```
备注
如果两者都设置,则该笔交易的单次购买取值会覆盖全局默认值。
### 已购内容恢复设置
默认情况下,SDK 会自动处理本地已购内容的恢复,以确保用户在重新安装应用,或支付过程中应用崩溃、内存不足时,仍能重新获得此前购买的商品。不过,您应根据后端集成架构调整该行为。
除非您在下方启用 Events API,否则恢复流程会读取玩家的艾克索拉物品库。关于两种方式各自返回与不返回的内容,请参阅[**恢复的购买内容**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/#restored-purchases)。 备注
**从 Apple StoreKit 迁移过来**?无需手动接入“恢复购买内容”调用⸺`restoreCompletedTransactions()` 在本 SDK 中为空操作。如上文 所述,恢复流程会通过本地恢复以及可选的艾克索拉 Events API 自动执行。消耗品余额需通过您的自有后端或艾克索拉物品库进行恢复,请在发放购买权益时将其持久化存储至相应位置。
此外,如果倾向于采用无需维护 Webhook 的无服务器方案,可启用**艾克索拉 Events API** 进行购买内容恢复(详见下文小节),同时保持本地购买内容恢复处于开启状态。
对于基于 Webhook 的集成(即由后端直接接收并处理艾克索拉发送的购买通知),请禁用本地恢复,以免与服务器侧交易管理产生冲突:
```objectivec
// Disable local purchase restoration for webhook-based integrations
settings.useLocalPurchaseRestoration = NO;
```
```swift
// Disable local purchase restoration for webhook-based integrations
settings.useLocalPurchaseRestoration = false
```
注意
**何时禁用本地购买恢复**:
- 后端使用 Webhook 接收艾克索拉发送的购买通知
- 在服务器上管理交易生命周期
- 需要避免本地系统与服务器侧系统重复处理购买
**重要限制**:
- 恢复的购买无法通过标准验证流程进行验证
- 除非通过 Events API 恢复,否则已恢复购买不包含原始艾克索拉订单的标识符
- 使用 Webhook 时,结束交易必须由您的后端处理
- 如果禁用了本地购买恢复,SDK 不会通过本地恢复或 Events API 执行任何恢复
- [**网充商店外链跳转**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios#web-shop-link-outs)模式会完全跳过恢复流程,不受这些设置影响
此设置会直接影响[**购买流程指南**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/)中描述的 `finishTransaction(_ transaction: SKPaymentTransaction)` 方法行为。禁用本地恢复后,您的后端需要通过 Webhook 通知来管理完整的交易生命周期。注意,在禁用本地恢复的情况下,未完成的交易在应用重新启动时不会重新出现,因此必须在后端正确处理。
#### 使用艾克索拉 Events API 进行恢复
艾克索拉 Events API 是基于 Webhook 集成的替代方案(在常规方案中通常由集成方的后端处理购买验证、权益发放等大部分逻辑)。该 API 不会直接发送 Webhook ,而是将其拦截并把负载存入由艾克索拉托管的远程队列。此方式使缺乏后端能力或无需搭建后端的项目也能实现无服务器集成,同时在应用内直接处理完整的交易流程。
通过 Events API 恢复还会使用玩家原始订单中的订单 ID 填充 `transactionIdentifier`、使用发票 ID 填充 `invoiceIdentifier`,便于您将恢复的购买内容与自身记录匹配。从物品库恢复时这两个属性均为 `nil`,因为物品库仅记录玩家当前拥有的商品⸺背后没有关联订单。
选用***艾克索拉 Events API*** 将**禁用**项目的 **Webhook**⸺**不能同时使用二者**。
要启用该功能,请在*发布商帐户*中打开项目,前往**项目设置** > **集成设置**,选择**使用 API** 并点击**保存**。详情见[**发布商帐户中的 Events API**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。
##### 在 iOS SDK 中启用 Events
在 SDK 配置中启用基于 Events 的购买恢复:
```objectivec
// Enable Events API for purchase restoration
settings.useEventsApiForPurchaseRestoration = YES;
```
```swift
// Enable Events API for purchase restoration
settings.useEventsApiForPurchaseRestoration = true
```
信息
如需了解更多信息,请参阅 [**Webhook 页面**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。 备注
基于 Events 的恢复需要 `settings.useLocalPurchaseRestoration = true`。如果禁用了本地购买恢复,SDK 将不会查询或使用 Events API 进行恢复。
### 归因用户 ID
如果您使用归因平台(AppsFlyer、Adjust 等),请设置 `attributionUserId`,以便通过**支付收银台**完成的购买能与应用中其他事件在同一用户名下上报到该平台。SDK 会将此值作为 `custom_parameters.custom_id` 发送给**支付收银台**,转发到归因平台的购买事件也以此为键。
该值必须等于您的归因 SDK 上报的客户用户 ID;否则购买事件无法与该用户匹配。如果留空,购买事件将根据支付令牌中的用户 ID 进行匹配。默认情况下,该值为玩家的**艾克索拉登录管理器**用户 ID。[1](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios#attribution-user-id-fallback)
1 如果您的项目通过服务器端自定义 ID 登录或 PlayFab 进行身份认证,或将用户 ID 映射到自定义 JWT 声明,则支付令牌会携带该值而非登录管理器的用户 ID。请显式设置 `attributionUserId`,否则购买事件将无法与您的归因平台匹配。
这与 `customUserId` 不同,后者以 `custom_parameters.custom_user_id` 发送,并会在购买 Webhook 中返回给您,但不用于归因。
```objectivec
// Must match the customer user ID reported by your attribution SDK
settings.attributionUserId = @"your-attribution-user-id";
```
```swift
// Must match the customer user ID reported by your attribution SDK
settings.attributionUserId = "your-attribution-user-id"
```
### 安装来源
设置 `installSource` 以上报应用的分发渠道,例如您的网站或启动器。SDK 会将其随订单一并发送为 `user.mobile_app.install_source`,并按原样发送,不会裁剪。
如果留空,SDK 会自行检测渠道,但仅适用于 iOS 17.4 及以上版本,可区分 App Store、Web 分发与替代市场。在更早的 iOS 版本上不会发送安装来源。
```objectivec
settings.installSource = @"website";
```
```swift
settings.installSource = "website"
```
## 使用艾克索拉登录管理器进行认证
如果您的应用使用艾克索拉登录管理器进行用户认证,您可以将登录令 牌提供给 SDK,使其与艾克索拉的支付服务配合工作。
### 设置登录令牌
在初始化您的设置之后、启动支付队列之前配置登录令牌:
```objectivec
// After initializing settings, set the Xsolla Login token
settings.customLoginToken = @"your_xsolla_login_token";
// Then start the SDK
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
// After initializing settings, set the Xsolla Login token
settings.customLoginToken = "your_xsolla_login_token"
// Then start the SDK
SKPaymentQueue.default().start(settings)
```
备注
艾克索拉登录管理器令牌应从您的[**艾克索拉登录管理器 ↗**](https://xsolla.com/login) ([https://xsolla.com/login](https://xsolla.com/login)) 集成中获取。请确保令牌有效,并在启动支付队列前完成设置,以启用已认证的支付流程。
## 在沙盒模式下测试
开发阶段请始终启用沙盒模式,以便在不处理真实交易或扣款的情况下测试您的支付集成。沙盒环境会使用测试数据模拟完整的支付流程。
### 启用沙盒模式
```objectivec
settings.useSandbox = YES; // Objective-C
settings.useSandbox = true // Swift
```
备注
`useSandbox` 默认值为 `true`,因此开箱即在沙盒环境中运行支付。正式上线前请设置 `useSandbox = false`,以便处理真实交易。 提示
有关完整的测试指引(包括测试银行卡卡号与支付场景),请参阅我们的 [**iOS 测试指南**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/ios/)。其中涵盖如何避免真实扣款、测试不同支付方式以及验证集成。
## 支付集成选项
艾克索拉 Mobile SDK 提供多种支付集成方式,适配不同的开发需求与周期。
### 购买按钮解决方案(推荐)
购买按钮解决方案能够以极少的集成工作量提供完整的原生支付体验,通过艾克索拉优化的 UI 组件在应用内处理整个支付流程。
如需了解更多详情(包括网充商店外链跳转与支付收银台的对比及平台注意事项),请参阅[**购买按钮 - iOS**](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/ios/)。
**何时使用购买按钮解决方案**:
- 希望快速完成原生支付集成
- 希望由艾克索拉负责支付 UI 与体验优化
- 需要开箱即用地支持多种支付方式
- 希望自动满足各地区的支付合规要求
```objectivec
// Enable Buy Button solution
settings.useBuyButtonSolution = YES;
```
```swift
// Enable Buy Button solution
settings.useBuyButtonSolution = true
```
### 网充商店外链跳转
网充商店方案会在浏览器中将用户重定向到您现有的艾克索拉网充商店,购买完成后再返回您的应用。该方式适合渐进式迁移,或希望与现有 Web 支付流程保持一致的场景。
**何时使用网充商店外链跳转**:
- 已拥有正在运营的艾克索拉网充商店
- 希望以最少的代码改动测试艾克索拉集成
- 需要在多平台间保持支付流程一致
- 正在实施从 Web 端向移动端支付的分阶段迁移
警告
在网充商店外链跳转模式下,SDK 不会执行原生的应用内支付流程,而是仅打开网充商店并立即取消所有 SDK 购买回调。该模式旨在尽量减少代码改动:请通过网充商店流程(例如 Webhook 或服务器端逻辑)处理商品发放与支付后状态更新,切勿依赖 SDK 购买回调。
#### 配置网充商店集成
使用辅助方法配置网充商店跳转流程:
```objectivec
[settings setupBuyButtonWebShopWithUrl:[NSURL URLWithString:@"https://yourwebshop.xsolla.site"]
userId:@"<USER_ID>"
returnUrl:@"yourgame://"
openExternally:YES];
```
```swift
settings.setupBuyButtonWebShop(url: URL(string: "https://yourwebshop.xsolla.site")!,
userId: "<USER_ID>",
returnUrl: "yourgame://",
openExternally: true)
```
**参数说明**:
- `url`:您的艾克索拉网充商店 URL,用户在此完成购买
- `userId`:您系统中的用户唯一标识,用于购买归因和用户跟踪
- `returnUrl`:在购买完成后将用户带回应用的深度链接 URL scheme
- `openExternally`:是否在外部浏览器中打开网充商店(推荐开启,便于满足合规要求并提供更佳用户体验)
#### 发起网充商店购买
完成配置后,调用购买方法并传入您的产品 SKU 发起购买:
```objectivec
// Attempt to purchase an item via Web Shop
BOOL handledExternally = [[SKPaymentQueue defaultQueue] purchaseWithSKU:@"money.100"];
if (handledExternally) {
// Web Shop opened successfully, update UI to reflect the redirect
NSLog(@"Purchase redirected to Web Shop");
// Optionally show a loading indicator or message to the user
}
```
```swift
// Attempt to purchase an item via Web Shop
let handledExternally: Bool = SKPaymentQueue.default().purchase(withSKU: "money.100")
if handledExternally {
// Web Shop opened successfully, update UI to reflect the redirect
print("Purchase redirected to Web Shop")
// Optionally show a loading indicator or message to the user
}
```
**后端集成**
使用网充商店方案时,您无需通过移动端 SDK 拉取商品目录(仅用于前端展示的场景除外)。订单履约应在后端沿用标准网充商店交易相同的 Webhook 与处理流程,确保整套支付基础设施保持一致。
## 深度链接配置
当用户被重定向到外部支付页面并需要返回应用时,深度链接对于完成支付流程至关重要。SDK 提供自动与手动两种深度链接处理选项。 提示
SDK 也支持 **Universal Links** (HTTPS),可替代自定义 URL Scheme(还能避免从外部浏览器返回应用时弹出“在 App Name 中打开?”的系统提示)。请参阅 [**iOS Universal Links**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-universal-links/)。
### 配置 URL Scheme
在配置深度链接处理之前,必须为应用设置自定义 URL Scheme。该 URL Scheme 允许外部来源(如支付页面)将用户重定向回应用。
**配置 URL Scheme**:
- 在 Xcode 项目导航器中选择您的项目
- 选择您的 App target
- 打开 **Info** 选项卡
- 下滑至 **URL Types** 并点击 ➕ 按钮
- 将 **URL Schemes** 字段设置为 `$(PRODUCT_BUNDLE_IDENTIFIER)`
![URL Scheme 配置] 提示
使用 `$(PRODUCT_BUNDLE_IDENTIFIER)` 可确保您的 URL Scheme 与应用的 Bundle Identifier 匹配,从而保证唯一性并避免与其他应用冲突。
### 自动深度链接处理(默认)
默认情况下,艾克索拉 Mobile SDK 通过方法交换 (Method Swizzling) 自动处理深度链接⸺这是一种在运行时拦截并修改 iOS 方法调用的技术。也就是说,SDK 会自动捕获传入的 URL 并完成处理,无需您编写任何额外代码。
**自动处理的优势**:
- 零额外代码
- 适配大多数应用架构
- 自动处理所有与艾克索拉相关的 URL
- 与现有 URL 处理保持兼容
一旦按上述方式配置了 URL Scheme,自动处理即可直接生效。
### 手动深度链接处理
在某些场景下,您可能需要禁用自动处理并实现手动深度链接处理。通常在以下情况下需要:
- 您的应用已有的自定义 URL 处理逻辑与方法交换存在冲突
- 您使用的框架(如 React Native 或 Unity)与方法交换配合不佳
- 您需要对深度链接处理方式拥有更多控制
- 在您的特定环境中遇到自动处理问题
- 您的应用架构需要显式的 URL 路由
#### 实现手动处理
**步骤 1:禁用自动处理**
在启动 SDK 之前,禁用自动 URL 处理:
```objectivec
// Disable automatic deep link handling before starting SDK
settings.swizzleUrlHandling = NO;
// Then start the SDK as usual
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
// Disable automatic deep link handling before starting SDK
settings.swizzleUrlHandling = false
// Then start the SDK as usual
SKPaymentQueue.default().start(settings)
```
**步骤 2:实现手动 URL 处理**
将 URL 处理添加到 `AppDelegate` 或 `SceneDelegate`。SDK 的 `openWithUrl:` 方法会返回一个布尔值,用于指示是否识别并处理了该 URL:
```objectivec
// In your AppDelegate.m
- (BOOL)application:(UIApplication *)app
openURL:(NSURL *)url
options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
// First, try to handle the URL with Xsolla SDK
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
if (handledBySDK) {
// URL was recognized and handled by Xsolla SDK
return YES;
}
// Handle other URLs specific to your app
// Add your custom URL handling logic here
return [self handleCustomURL:url];
}
// Alternative: In your SceneDelegate.m (for iOS 13+)
- (void)scene:(UIScene *)scene openURLContexts:(NSSet<UIOpenURLContext *> *)URLContexts {
for (UIOpenURLContext *context in URLContexts) {
NSURL *url = context.URL;
// Try to handle with Xsolla SDK first
BOOL handledBySDK = [[SKPaymentQueue defaultQueue] openWithUrl:url];
if (!handledBySDK) {
// Handle other URLs specific to your app
[self handleCustomURL:url];
}
}
}
```
```swift
// In your AppDelegate.swift
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
// First, try to handle the URL with Xsolla SDK
let handledBySDK = SKPaymentQueue.default().open(url: url)
if handledBySDK {
// URL was recognized and handled by Xsolla SDK
return true
}
// Handle other URLs specific to your app
return handleCustomURL(url)
}
// Alternative: In your SceneDelegate.swift (for iOS 13+)
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
for urlContext in URLContexts {
let url = urlContext.url
// Try to handle with Xsolla SDK first
let handledBySDK = SKPaymentQueue.default().open(url: url)
if !handledBySDK {
// Handle other URLs specific to your app
handleCustomURL(url)
}
}
}
```
**返回值用法**
当 URL 被识别为艾克索拉支付回调并由 SDK 处理时,`openWithUrl:` 将返回 `true`/`YES`。这使您可以为与艾克索拉支付无关的 URL 实现后备逻辑,确保应用能够正确处理所有类型的深度链接。
**步骤 3:处理支付收银台的屏幕方向(可选)**
如果您的应用支持的方向与希望用于支付收银台界面的方向不同,则需要额外实现方向处理。例如,若游戏仅支持横屏,但希望支付收银台以竖屏显示,请在 `AppDelegate` 中添加以下方法:
```objectivec
// In your AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application
supportedInterfaceOrientationsForWindow:(UIWindow *)window {
// Since the app may not support portrait, we must ensure that for the UIWindow
// that SDK creates it returns correct value for portrait support
UIInterfaceOrientationMask mask = [[SKPaymentQueue defaultQueue] supportedInterfaceOrientationsForWindow:window];
if (mask != 0) {
return mask;
}
// Fall back to default app orientation support
return [application supportedInterfaceOrientationsForWindow:window];
}
```
```swift
// In your AppDelegate.swift
func application(_ application: UIApplication,
supportedInterfaceOrientationsFor window: UIWindow?) -> UIInterfaceOrientationMask {
// Since the app may not support portrait, we must ensure that for the UIWindow
// that SDK creates it returns correct value for portrait support
let mask = SKPaymentQueue.default().supportedInterfaceOrientationsFor(window: window)
if !mask.isEmpty {
return mask
}
// Fall back to default app orientation support
return application.supportedInterfaceOrientations(for: window)
}
```
该方法允许 SDK 为其自身窗口(如支付收银台界面)指定方向要求,同时保持应用其他窗口的常规方向限制。若启用了自动深度链接处理,则会自动处理该问题。 **如何选择合适方式**
如果不确定是否需要手动深度链接处理,建议先使用默认的自动处理。它适用于大多数应用且无需额外代码。若后续遇到特定问题或需要更高的处理控制,再切换为手动处理。
## 后续步骤
完成 SDK 配置后,您即可进行初始化并开始处理支付。请继续阅读 [**iOS 初始化指南**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/ios/),了解如何在应用中设置交易观察者并处理交易事件。
初始化
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/ios/)
初始化 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/android
完成[配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/)后,需要初始化**艾克索拉 Mobile SDK** 并连接到艾克索拉服务。初始化分为 3 个步骤:
## 创建 BillingClient
使用 `Config` 和 `PurchasesUpdatedListener` 创建 `BillingClient`,并避免重复初始化:
```java
if (billingClient == null) {
billingClient = BillingClient.newBuilder(this)
.setConfig(config) // Config built in the previous step
.setListener((billingResult, purchases) -> {
// Invoked for every purchase flow outcome — success, cancel, or error.
// Handle consumption or entitlement grant here.
})
.build();
}
```
## 启动连接
调用 `startConnection()`。当 SDK 完成认证并就绪时,会触发 `onBillingSetupFinished()`:
```java
billingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (billingResult.isSuccess()) {
// Connected — safe to query products and launch purchases.
}
}
@Override
public void onBillingServiceDisconnected() {
// Connection dropped — release the client so it's recreated on next use.
billingClient.endConnection();
billingClient = null;
}
});
```
## 查询商品详情
在 `onBillingSetupFinished()` 内,为每个 SKU 获取 `ProductDetails`⸺此步骤是后续[购买流程](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/)所必需的:
```java
// Build the list of SKUs to fetch — add one Product entry per item in your catalog.
final QueryProductDetailsParams params = QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // SKU from your Xsolla Catalog
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build();
billingClient.queryProductDetailsAsync(params, (billingResult, productDetailsList) -> {
// Store productDetailsList — it's passed directly to the purchasing flow.
});
```
SDK 仅从您的艾克索拉商品目录中加载虚拟物品,不会返回虚拟货币、捆绑包及其他商品目录类型。
初始化 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/ios
完成[配置](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)后,需要初始化**艾克索拉 Mobile SDK** 并连接到**艾克索拉**服务。
使用上一步创建的设置完成初始化。请将此逻辑放在应用的初始化代码中,例如 AppDelegate 的 [didFinishLaunchingWithOptions ↗](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) ([https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions):)) 方法内。
```objectivec
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings]; // settings from the previous step
// conform your class to SKPaymentTransactionObserver and implement its method
@interface YourClass (SKPaymentTransactionObserver) <SKPaymentTransactionObserver>
@end
@implementation YourClass (SKPaymentTransactionObserver)
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStateFailed:
// purchase failed, present an error
break;
case SKPaymentTransactionStatePurchased:
// award the player with the purchased item (SKU: transaction.payment.productIdentifier)
break;
default: break;
}
}
}
@end
```
```swift
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
// conform your class to SKPaymentTransactionObserver and implement its method
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .failed:
// purchase failed, present an error
case .purchased:
// award the player with the purchased item (SKU: transaction.payment.productIdentifier)
default:
break
}
}
}
}
```
启动 `SKPaymentQueue` 并添加观察者后,应用可以请求 SKU 信息:
```objectivec
NSSet *skus = [NSSet setWithArray:@[@"money.100", @"ticket.10"]];
SKProductsRequest* req = [[SKProductsRequest alloc] initWithProductIdentifiers:skus];
req.delegate = self;
[req start];
// conform your class to SKProductsRequestDelegate and implement its method
@interface YourClass (SKProductsRequestDelegate) <SKProductsRequestDelegate>
@end
@implementation YourClass (SKProductsRequestDelegate)
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response {
// save loaded products somewhere
self.products = response.products
}
@end
```
```swift
let skus: Set<String> = ["money.100", "ticket.10"]
let req = SKProductsRequest(productIdentifiers: skus)
req.delegate = self
req.start()
// conform your class to SKProductsRequestDelegate and implement its method
extension YourClass: SKProductsRequestDelegate {
func productsRequest(_ request: SKProductsRequest, didReceive response: SKProductsResponse) {
// save loaded products somewhere
self.products = response.products
}
}
```
SDK 仅从您的艾克索拉商品目录中加载虚拟物品,不会返回虚拟货币、捆绑包及其他商品目录类型。
如需了解更多信息,请参阅 Apple [官方文档 ↗](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue) ([https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue)) 中的实现示例。
安装
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios/)
安装 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/android
### 先决条件
注意
- Android SDK >= **24**
- Java >= **11**
### 安装步骤
- 将仓库添加到项目的 Gradle 脚本(通常为 `settings.gradle`):
```kotlin
dependencyResolutionManagement {
repositories {
google()
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
}
```
即将推出。
- 在模块的 `build.gradle` 中为艾克索拉 Mobile SDK 添加新的依赖项:
```kotlin
dependencies {
def version_mobilesdk = '<version_code>' // e.g. '3.0.37'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
安装 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/installation/ios
## iOS 版本要求
艾克索拉 Mobile SDK 支持将 iOS 12.0 及更高版本作为最低部署版本。但请注意,依赖 Apple 外部购买 (External Purchases) 或替代应用分发 (Alternative App Distributions) 相关 API 的部分功能可能需要 iOS 17.5 或更高版本。
## 通过 Swift Package Manager 安装
### 使用 Xcode
- 在 Xcode 中,前往 **File → Add Package Dependencies…**。
- 输入仓库 URL: ```text https://github.com/xsolla/xsolla-sdk-ios ```
- 将依赖规则设为 **Up to Next Major Version**,并指定版本(例如,`3.8.0`)。
- 点击 **Add Package**。
- 在软件包产品对话框中,选择 **XsollaMobileSDK**,并将其添加到目标。
### 使用 Package.swift
在 `Package.swift` 文件中添加依赖:
```swift
dependencies: [
.package(url: "https://github.com/xsolla/xsolla-sdk-ios", from: "3.8.0")
]
```
然后将 `XsollaMobileSDK` 添加到目标的依赖项中:
```swift
.target(
name: "YourTarget",
dependencies: [
.product(name: "XsollaMobileSDK", package: "xsolla-sdk-ios"),
]
)
```
购买流程
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/)
购买流程 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android
购买流程是一个多阶段过程,包含[**收款**](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/android/#purchase-product)、购买[**验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)和[**核销**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android#consuming-purchased-goods)。玩家已完成的购买通过[**恢复**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android#restored-purchases)单独找回。
## 启动结算流程
您可以根据需求选择多种方式来启动购买流程。
要开始购买流程,请将之前[获取的](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/android/) `ProductDetails` 与一个 `BillingFlowParams` 一起传递给 `launchBillingFlow` 方法:
```java
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.build()
);
```
**高级设置**
`BillingFlowParams.Builder` 支持多个其他属性,可在使用 `BillingClient.launchBillingFlow()` 启动结算流程前进行设置:
| 设置 | 值 | 说明 |
| --- | --- | --- |
| setObfuscatedAccountId | string | 设置一个经过混淆处理的帐户 ID,可在购买流程完成后的回调或 Webhook 中使用。 |
| setObfuscatedProfileId | string | 设置一个经过混淆处理的帐户 ID,可在购买流程完成后的回调或 Webhook 中使用。 |
| setDeveloperPayload | string | 允许在购买流程中传递开发者自定义的元数据,可在购买流程完成后的回调或 Webhook 中使用。 |
| setExternalTransactionId | string | 允许设置与已启动的购买流程关联的自定义唯一交易 ID(请确保同时在发布商帐户中启用外部交易 ID,否则购买流程会失败)。 |
| setExternalTransactionToken | string | 将 Google Play 外部交易令牌(来自 enableUserChoiceBilling、createBillingProgramReportingDetailsAsync 或 createAlternativeBillingOnlyReportingDetailsAsync)附加到已启动的购买流程,从而传递到订单中。请参阅向 Google Play 报告外部交易。 |
| setTrackingId | string | 用于艾克索拉内部分析的跟踪 ID(请先与集成经理确认)。 |
| setForcePaymentMethodId | int | 强制为已启动的购买流程指定特定的支付方式(可在发布商帐户中查看对应 ID)。 |
| setCanceller | BillingFlowCanceller | 附加取消器,以便在启动后通过代码取消结算流程。 |
**取消结算流程**
创建 `BillingFlowCanceller` 并传入参数构建器,在需要时(例如超时或用户主动操作)调用 `cancel()`。SDK 会停止正在进行的重试并返回 `USER_CANCELED` 结果。
```java
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowParams
.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams
.newBuilder()
.setProductDetails(productDetails)
.build()
))
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
```
此方式支持使用外部生成的艾克索拉支付收银台支付令牌发起结算流程。
```java
// Parent activity to open the Xsolla Pay Station with.
final Activity activity = // ...
final String paymentToken = "<your-externally-generated-payment-token>";
final String developerPayload = null;
mBillingClient.launchBillingFlow(
activity, paymentToken, developerPayload
);
```
**高级设置**
如需更精细地控制基于令牌的结算流程,请 改用 `BillingFlowTokenParams` 构建器:
```java
final BillingFlowCanceller canceller = new BillingFlowCanceller();
mBillingClient.launchBillingFlow(activity, BillingFlowTokenParams
.newBuilder()
.setPaymentToken("<your-externally-generated-payment-token>")
.setDeveloperPayload(null)
.setCanceller(canceller)
.build()
);
// Cancel the flow at any point from any thread
canceller.cancel();
```
| 设置 | 值 | 说明 |
| --- | --- | --- |
| setPaymentToken | string | 外部生成的艾克索拉支付收银台支付令牌。 |
| setDeveloperPayload | string | 允许在购买流程中传递开发者自定义的元数据,可在购买流程完成后的回调或 Webhook 中使用。 |
| setCanceller | BillingFlowCanceller | 附加取消器,以便在启动后通过代码取消结算流程。 |
集成**购买按钮**有两种方式:将用户重定向至您的[**网充商店**](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/android/?purchase-method=webshop-linkouts),或使用应用内原生的[**购买按钮解决方案**](https://developers.xsolla.com/sdk/zh/mobilesdk/buy-button/android/?purchase-method=buy-button)。important
自 **Epic 诉 Google** 案裁决于 **2025 年 10 月 29 日**生效起,美国地区的 **Google Play** 应用可直接使用艾克索拉 SDK 购买流程,但必须先按[**此处**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/detect-gpb-storefront-android/)指南检测**商店地区的国家/地区代码**。
## 验证购买(推荐)
有关如何验证购买的说明,请参见[**购买验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)。注意
尽管验证**不是**必需步骤,但强烈建议进行,以尽量减少欺诈和其他恶意行为的风险。
## 核销已购商品
购买流程的最后一步是向用户发放已购商品并将其标记为已处理,这一过程称为**购买核销**。完成核销后,该商品将不再列为待处理购买,并且⸺视您的商品配置而定⸺用户可以再次购买。
如何执行核销取决于您的集成是在**客户端**处理,还是**通过 Webhook 在服务器端**处理。
### 基于客户端(无 Webhook)
在基于客户端的集成中,游戏客户端负责向用户发放商品,并通知艾克索拉该购买已处理。此操作在成功购买后(理想情况下在[**验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)之后)于 `PurchasesUpdatedListener.onPurchasesUpdated()` 回调中完成:
```java
final Purchase purchase = // ...
final ConsumeParams consumeParams = ConsumeParams
.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
// Notify Xsolla that the purchase has been processed and mark it as consumed.
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(
@NonNull final BillingResult billingResult, final String purchaseToken
) {
if (billingResult.isSuccess()) {
// Consumption succeeded — award the purchased goods to the user here.
} else {
// Consumption failed — do not grant entitlement.
}
}
});
```
important
强烈建议在核销已购商品之前,至少执行某种形式的[**验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)。
### 基于服务器 (Webhook)
在基于服务器的集成中,您的后端会在收到艾克索拉发送的 Webhook 后处理完整的购买生命周期⸺验证、发放和核销。购买完成后,客户端仍会触发 `PurchasesUpdatedListener.onPurchasesUpdated()` 回调,但在该流程中它不具备结果判定权,不得用于驱动任何购买逻辑。
**最简单的方法**是完全忽略该回调,让服务器确认结果。
**更完整的方法**是仅将其用于用户界面用途,例如:为已购买的商品展示“处理中”状态,并在服务器确认结果后清除该状态:
```java
final PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull final BillingResult billingResult, @Nullable final List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
// The purchase was initiated successfully.
// Your backend will handle validation, consumption, and entitlement via webhook.
// Optionally, show a pending/processing state in the UI here and
// update it once your server relays the confirmed result back to the client.
} else {
// The purchase did not complete (e.g. user cancelled or a connection error occurred).
// No action required — your backend will not receive a webhook for this purchase.
}
}
};
```
信息
有关基于 Webhook 的端到端流程(包括在后端执行的核销)详情,请参阅[**购买验证 — 服务器侧**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/#server-side-validation)。
## 恢复已购内容
恢复功能会返回玩家此前已完成的购买⸺例如重装应用后、更换新设备后,或客户端未能确认原始交易时。`BillingClient.queryPurchases()` 需手动调用,SDK 不会自动代为调用。
已恢复购买来自两个后端之一⸺默认的 Inventory API,或 Events API。关于项目如何选择后端,请参阅[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#purchase-restoration-settings);关于两者的底层机制对比,请参阅 [**Inventory API 与 Events API 对比**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api/)。
恢复最适用于确认应用预先已知 SKU 的**不可消耗型**商品的所有权。对于由您自己的服务器作为购买状态权威来源的可消耗商品,一般不需要执行恢复。
### 恢复的购买包含哪些内容
| 访问器 | Inventory API | Events API |
| --- | --- | --- |
| getOrigin() | INVENTORY_RESTORE | EVENTS_RESTORE |
| isRestored() | true | true |
| getPurchaseTime() | 始终为 0 | 原始支付时间 |
| getOrderId() — 发票 ID | 本地合成,跨查询稳定 | 来自原始订单的真实发票 ID |
| getOriginalOrderId() — 订单(购物车)ID | 与 getOrderId() 相同的合成值 | 来自原始订单的真实订单 ID |
| getQuantity() | 默认为 1⸺将持有量按每单位拆分为一条独立的 Purchase;启用折叠时返回完整数量 | 来自原始订单的数量 |
| isFree() | 始终为 false⸺物品库不区分付费商品与免费商品 | 若订单无发票则为 true |
尽管名称容易混淆,`getOrderId()` 返回的其实是艾克索拉**发 票** ID,而 `getOriginalOrderId()` 返回的才是艾克索拉**订单**(购物车)ID⸺这是因为 `Purchase` 类沿用了 Google Play Billing Library 的命名,其中 `getOrderId()` 代表支付完成后的标识符。如需将购买与您自己的订单记录进行匹配,请使用 `getOriginalOrderId()`。
`getPurchaseState()` 始终返回 `PURCHASED`,`isAcknowledged()` 始终为 `false`⸺两种后端均不支持确认机制,因此无需实现确认步骤。这两个字段均不表示是否为恢复记录;请改用 `getOrigin()` 或 `isRestored()` 判断。注意
**在 Inventory API 模式下,`getOrderId()` 和 `getOriginalOrderId()` 并非真实的订单标识符⸺切勿将它们当作真实订单 ID 发送至您的后端**。
这两个值是根据 SKU 及该单位在持有量中的位置于本地派生生成的,且两个字段写入的是同一个合成值,因此在该模式下二者相等。艾克索拉的任何系统⸺发布商帐户、订单查询、Webhook 负载等⸺均无法识别这些值。若将其当作真实订单号用于匹配订单、核查欺诈、查询退款或协助玩家处理客诉,将不会匹配到任何记录。
针对相同持有单位重复调用 `queryPurchasesAsync()` 时, 这些值会保持稳定;核销部分持有量也不会改变剩余单位的值⸺自 [**Android SDK 3.0.55 ↗**](https://github.com/xsolla/xsolla-sdk-android/releases/tag/3.0.55) 起便是如此。在此版本之前,每次查询都会随机生成这些值。
这是项目默认采用的恢复模式⸺请参阅[**选择模式**](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/inventory-vs-events-api/#selecting-a-mode)。
**iOS 在此处的行为不同**⸺对应的标识符会直接留空而非在本地合成,因为 iOS SDK 遵循 StoreKit 模型(其中该标识符为可选项),而 Android 遵循 Play Billing Library 模型(购买达到 `PURCHASED` 状态后即会填充该标识符)。两个平台均不会向对方的行为靠拢。
### 按商品类型可恢复的内容
Inventory API 恢复流程读取的是玩家的物品库清单,该清单仅返回虚拟商品和虚拟货币。在物品库中没有对应表示的商品类型会返回空结果:
| ProductType | Inventory API 下的恢复结果 |
| --- | --- |
| INAPP | ✔ 玩家持有的虚拟商品⸺不含限时商品(会被过滤掉) |
| VIRTUAL_CURRENCY | ✔ 每种货币返回一条 Purchase(来自余额接口) |
| BUNDLE | ✘ 无返回内容⸺包括虚拟货币套餐(商品目录将其归类为捆绑包) |
| SUBS, PLAY_PASS_SUBS | ✘ 无返回内容⸺不支持的商品类型 |
注意
**在 Inventory API 下,`BUNDLE` 查询不会恢复任何内容,而虚拟货币套餐属于捆绑包**⸺商品目录将其归类为捆绑包,而非虚拟货币。
套餐发放的虚拟货币仍可恢复:该虚拟货币已计入玩家余额,因此 `VIRTUAL_CURRENCY` 查询会将其返回。无法恢复的是**套餐购买记录本身**。在 Events API 下则可以恢复⸺但返回的是捆绑包内的**具体内容项**而非捆绑包 SKU,因此请按内容项(而非玩家付款购买的捆绑包 SKU)进行匹配。
`VIRTUAL_CURRENCY` 查询返回的 `getQuantity()` 设置为玩家的累计余额,而不是交易列表。由于余额是一个单值,无论是否启用 [`withCollapseRestoredMultiUnitPurchases`](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#units-per-restored-purchase),每种虚拟货币都会折叠为一个 `Purchase`。余额为 0 或负数的会被省略,超过 `Integer.MAX_VALUE` 的余额会被钳制为该上限。
商品类型仅作为 Inventory API 的筛选条件生效。在 Events API 下,无论传入何种类型,恢复查询都会返回**所有未核销的事件**,因此除应用内商品外,还会一并返回虚拟货币和捆绑包内容项。
### 核销已恢复的购买内容
已恢复的购买内容的核销方式与新购买内容完全一致⸺获取其 `getPurchaseToken()` 并传入 `consumeAsync()`,详见[**核销已购商品**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android#consuming-purchased-goods)。该令牌在两种模式下均用于标识购买,无需编写任何特定于模式的处理逻辑。
捆绑包的内容项会分别核销。SDK 会在本地跟踪部分核销,并在所有内容项都被核销后结算底层订单。
### 建议采用的实践
需要采用多少取决于您掌控的购买生命周期范围:
| 实践 | 忽略的影响 | 适用场景 |
| --- | --- | --- |
| 发放前先核对您自己的记录。恢复可能会返回玩家已领取过的购买,因此已处理过的购买不得重复发放。 | 严重 — 会向玩家重复发放同一笔购买 | 始终需要,包括纯客户端集成 |
| 将 getPurchaseTime() == 0 视为时间未知,而非某个具体时刻。每次通过 Inventory API 恢复都会返回 0,因此在混合列表中按时间排序会把它们全部归到纪元起点 (Epoch)。 | 低 — 购买历史记录排序错误 | 需要排序或展示购买历史记录时 |
| 优先检查 getOrigin(),切勿根据字段值猜测。isRestored() 仅表明这是找回的旧购买;getOrigin() 还会指明来源后端,而两种后端返回的数据有所不同。 | 中 — 旧购买会误触发首购 UI 与奖励 | 已恢复购买需走不同处理分支时(例如屏蔽“购买完成”弹窗) |
| 仅在订单 ID 具备实际意义时按其匹配购买。Events API 的 ID 真实且稳定,可在任意位置通用;Inventory API 的 ID 虽稳定但仅限当前设备本地有效,在您的后端或其他设备上均无法匹配。 | 高 — 后端去重校验会悄然失效 | 后端需校验购买是否已处理,或需跨设备核对时 |
| 切换后端前先比对自身已发放记录。项目一旦启用 Events API,无论 SDK 是否读取都会开始记录事件⸺切换后会一次性返回客户端从未见过的历史积压记录。 | 严重 — 历史积压记录一次性涌入,导致重复发放或漏发 | 仅限迁移已上线项目时 — 参阅迁移线上项目 |
购买流程 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios
购买流程包含多个阶段:完成[支付](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/ios/#purchase-product)、进行购买[验证](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios#validating-purchases-recommended)和[消耗](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios#consuming-purchased-goods)。玩家已完成的购买通过[恢复](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios#restored-purchases)单独找回。
### 启动购买流程
可以使用先前获取的 `SKProduct` 信息创建支付并发起购买:
```objectivec
SKProduct *product = ...; // previously fetched product
SKPayment *payment = [SKPayment paymentWithProduct:product];
[[SKPaymentQueue defaultQueue] addPayment:payment];
```
```swift
let product = ... // previously fetched product
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
```
### 验证购买(推荐)
注意
尽管验证**不是**必需步骤,但仍强烈建议进行验证,以尽量降低欺诈及其他恶意行为的风险。
有关如何验证购买的说明,请参阅[**购买验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/ios/)。
### 核销已购商品
购买流程的最后一步是将已购商品发放给用户,并将这些商品标记为“已发放”。这一过程也称为**购买核销**。
使用以下代码完成此操作:
购买结果会在 `paymentQueue:updatedTransactions:` 方法中得知:
```objectivec
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transactions {
for(SKPaymentTransaction *transaction in transactions) {
switch (transaction.transactionState) {
case SKPaymentTransactionStateFailed:
// Check if the user cancelled the purchase (don't treat as an error)
if (transaction.error.code == SKErrorPaymentCancelled) {
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
}
// Always acknowledge transaction and finish it
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
case SKPaymentTransactionStatePurchased:
// here you can save the purchase and award it to the user
// Always acknowledge transaction and finish it after it was saved
[[SKPaymentQueue defaultQueue] finishTransaction:transaction];
break;
default: break;
}
}
}
```
购买结果会在 `paymentQueue(_:updatedTransactions:)` 方法中得知:
```swift
func paymentQueue(_: SKPaymentQueue, updatedTransactions: [SKPaymentTransaction]) {
for transaction in updatedTransactions {
switch transaction.transactionState {
case .failed:
// Check if the user cancelled the purchase (don't treat as an error)
if (transaction.error as? SKXError)?.errorCode == .paymentCancelled {
SKPaymentQueue.default().finishTransaction(transaction)
break
}
// Always acknowledge transaction and finish it
SKPaymentQueue.default().finishTransaction(transaction)
case .purchased:
// here you can save the purchase and award it to the user
// Always acknowledge transaction and finish it after it was saved
SKPaymentQueue.default().finishTransaction(transaction)
default:
break
}
}
}
```
important
强烈建议在核销已购商品前,至少采用某种方式完成[**验证**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios#validating-purchases-recommended)。 备注
发放已购商品后,请务必调用 `finishTransaction(_:)`。如果启用了本地购买恢复(默认开启),未完成的交易会在下次启动时重新投递到 `paymentQueue(_:updatedTransactions:)`,直至完成⸺请参阅[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings)。
### 购买内容恢复
在重新安装应用、更换新设备,或购买完成前应用被关闭的情况下,恢复功能会返回玩家此前已完成的购买记录。该功能自动运行,无需手动调用任何方法。恢复 的数据来源在[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings)中配置⸺默认从玩家的艾克索拉物品库读取,也可改为使用艾克索拉 Events API。
在[**基于 Webhook 的集成**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/ios/#server-side-validation)中,上述两种方式均不使用:艾克索拉会将购买发送至您的后端,由后端决定回归玩家应获得的内容。请在应用中通过 `settings.useLocalPurchaseRestoration = false` 关闭恢复功能,并像服务器端验证流程一样仅使用交易回调来更新 UI。
恢复的购买记录会以 `.purchased`(而非 `.restored`)状态到达 `paymentQueue(_:updatedTransactions:)`,并像新购买一样履约。要区分二者,请检查 `original`:在恢复的购买上会被设置,而玩家刚完成的购买则为 `nil`。
恢复的交易包含哪些信息取决于后端:
| 属性 | 艾克索拉物品库(默认) | 艾克索拉 Events API |
| --- | --- | --- |
| transactionIdentifier | nil | 艾克索拉订单 ID |
| invoiceIdentifier | nil | 艾克索拉发票 ID |
| transactionDate | 恢复流程返回该记录的时间 | 恢复流程返回该记录的时间 |
| original.transactionDate | nil | 玩家支付的时间 |
| payment.quantity | 玩家拥有的数量 | 原始订单中的数量 |
与 StoreKit 一样,已恢复购买上的 `transactionDate` 表示 SDK 将购买记录返回给您的时间,而 `original.transactionDate` 表示玩家实际支付的时间。艾克索拉物品库不保存历史购买记录,因此从物品库恢复不会提供日期和订单 ID⸺仅表明玩家当前拥有该物品。
重装的玩家会取回其仍然拥有的所有内容,因此在发放恢复的购买前请先核对您的记录。否则可能会重复发放同一物品。
从艾克索拉物品库恢复仅返回**消耗型虚拟物品**。非消耗型物品、虚拟货币余额和捆绑包不会通过此方式返回⸺请从您自己的记录或直接从艾克索拉物品库获取这些数据。
只要还有任何未完成的购买,恢复就会被跳过,而且不会告知已被跳过。请完成您收到的每一笔交易,否则后续的恢复将不会执行。
测试与沙盒
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/ios/)
测试与沙盒 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/android
本节提供相关代码片段与示例,介绍如何配置沙盒环境以完成测试支付、输出更详细的日志等操作。
### 启用沙盒模式
```java
final var configCommon = Config.Common.getDefault()
// ...other settings
.withSandboxEnabled(true);
```
### 启用额外日志
```java
final var configCommon = Config.Common.getDefault()
// ...other settings
.withLogLevel(LogLevel.DEBUG)
// Forces even more internal data to be logged (e.g. profiling stats, etc).
.withDebugEnabled(true);
```
上线前,请将**沙盒模式**和**调试日志记录**关闭。
### 测试银行卡
如需查看沙盒模式下用于模拟支付的测试银行卡列表,请参见[此处 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards)。](https://developers.xsolla.com/doc/pay-station/testing/test-cards)%E3%80%82) important
测试银行卡无法在**沙盒模式**以外使用。
测试与沙盒 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/testing/ios
本节提供相关代码片段与示例,介绍如何配置沙盒环境以完成测试支付、输出更详细的日志等操作。
### 启用沙盒模式
```objectivec
SKPaymentSettings* settings = ...;
settings.useSandbox = YES;
```
```swift
let settings = SKPaymentSettings(...)
settings.useSandbox = true
```
备注
`useSandbox` 默认值为 `true`,因此在更改前,SDK 以沙盒模式运行。 注意
在**正式上线**前,请务必将**沙盒**模式**关闭** (`useSandbox = false`)。
### 启用额外日志
```objectivec
SKPaymentSettings* settings = ...;
settings.logLevel = SKLogLevelDebug;
```
```swift
let settings = SKPaymentSettings(...)
settings.logLevel = .debug
```
注意
在**正式上线**前,请确保已**关闭**调试**日志记录**。
### 测试银行卡
如需查看沙盒模式下用于模拟支付的测试银行卡列表,请参见[此处 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards)。](https://developers.xsolla.com/doc/pay-station/testing/test-cards)%E3%80%82) important
测试银行卡无法在**沙盒模式**以外使用。
故障排查
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/troubleshooting
选择平台:
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/troubleshooting/ios/)
故障排查 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/troubleshooting/ios
本文汇总常见的集成问题、原因及解决方法。如果您从 Apple StoreKit 迁移而来,部分机制存在差异⸺下文已逐一标出。
### 商品未显示或商品目录为空
`SKProductsRequest` 未返回任何商品(或返回数量少于预期),且通常不会报错。这几乎都是艾克索拉侧的配置问题,而非代码逻辑有误。请按以下顺序排查:
- **`projectId` 错误**。错误的 `projectId` 仍能成功建立 连接,但只会返回空的商品目录,且不会抛出错误。请在发布商帐户中核对该值。
- **商品未发布**。每件商品在发布商帐户中都必须处于**已发布 / 已启用**状态,草稿状态的商品不会返回。
- **SKU 不匹配**。您请求的 SKU 必须与发布商帐户中的 SKU **完全**一致,包括大小写和分隔符(例如点号与下划线)。
### 已购内容未恢复,或找不到可对接的“恢复购买”按钮
本 SDK 中的购买恢复**自动**执行,没有可供调用的手动恢复方法⸺`restoreCompletedTransactions()` 为空操作。请参阅[**已购内容恢复设置**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#purchase-restoration-settings),了解本地恢复与艾克索拉 Events API 的工作方式。消耗型物品余额需通过您的自有后端或艾克索拉物品库找回。
### "Application doesn't support login scheme" / "...payments redirect scheme"
SDK 通过 URL Scheme 将登录和支付收银台的回调重定向回应用;如果未注册该 Scheme,SDK 就会记录上述任一错误。由于 SDK 无法修改应用的 `Info.plist`,请手动注册一次该 Scheme:
- 添加一个与应用 Bundle Identifier 相同的 URL Scheme (`$(PRODUCT_BUNDLE_IDENTIFIER)`),详见 [**URL Scheme 配置**](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/ios/)。这一个基于 Bundle ID 的 Scheme **同时**覆盖登录与支付回调。
- 重定向 URL(`redirectUrl`、`paymentsRedirectUrl`)默认已采用基于 Bundle ID 的值,通常无需手动设置。
备注
**设备 ID 登录无需配置返回 URL**。设备 ID(匿名)登录直接在客户端完成标识符交换⸺不会触发浏览器重定向,也无需在发布商帐户中注册回调地址,只需为项目启用**设备 ID 登录**即可。重定向 URL 仅在使用基于浏览器的登录流程时才会用到。
### 发起购买时报错 "User is not logged in"
SDK 必须先建立已完成身份认证的会话才能创建订单;如果在身份认证完成前尝试购买,就会报错 `User is not logged in` 并失败。请确保在应用启动时、首次购买前完成身份认证:
- 如果您的游戏采用设备 ID 登录进行身份认证,请确认项目已启用**设备 ID 登录**。
- 如果您的游戏自行提供艾克索拉登录管理器令牌,请确认在启动支付队列**之前**已将 `settings.customLoginToken` 设置为有效且未过期的令牌⸺参阅[**设置登录令牌**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#setting-the-login-token)。
### 启动购买时出现 Main Thread Checker 警告
`SKPaymentQueue.default().add(_:)` 会触发 UIKit 界面展示,必须在主线程调用。如果您从异步 `Task` 或后台队列发起购买,Main Thread Checker 可能会标记警告。请切换到主线程再调用:
```objectivec
dispatch_async(dispatch_get_main_queue(), ^{
[[SKPaymentQueue defaultQueue] addPayment:payment];
});
```
```swift
await MainActor.run {
SKPaymentQueue.default().add(payment)
}
```
### SDK 连接的主机(防火墙 / 白名单)
如果您的网络工具或防火墙限制出站流量,请将 SDK 需要访问的艾克索拉主机加入白名单:
| 用途 | 主机 |
| --- | --- |
| 商店 API(商品目录、订单、物品库) | store.xsolla.com |
| 支付收银台(结算) | secure.xsolla.com — 当 useSandbox = true 时为 sandbox-secure.xsolla.com |
| 登录管理器 | login.xsolla.com |
### 可忽略的控制台警告
类似 `Couldn't read values in CFPrefsPlistSource... kCFPreferencesAnyUser...` 的控制台日志属于无害提示,可放心忽略⸺不会影响支付功能或 SDK 行为。
购买验证
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation
选择平台:
- [Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android/)
- [iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/ios/)
购买验证 - Android
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/android
向最终用户发放购买内容前,应对每笔购买交易进行验证。这有助于防范未授权购买,维护应用内经济系统的正常运行。购买验证是防范欺诈、保障收入并维护公平用户体验的关键安全措施。
目前主要提供两种不同的验证方式。
### 服务器侧验证
最安全可靠的验证方式是采用**服务器到服 务器** (**S2S**) 通信,使客户端完全不参与验证流程。这能最大限度降低安全风险,确保仅凭直接来自艾克索拉的已验证数据发放权益。
接入艾克索拉时,服务器侧验证通过**基于 Webhook 的模式**实现:
- 用户通过应用完成购买后,艾克索拉服务会自动向您的后端发送 [**Webhook 事件**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#user_validation)。
- 该 Webhook 包含所有必要的购买数据(包括艾克索拉 `order ID`),供您的服务器异步验证并处理该笔购买。
- 随后,您的后端即可根据这些数据更新用户的权益、余额、物品库等,无需客户端提供任何额外输入。
该流程确保客户端无法干预购买结果的判定⸺所有验证逻辑均在服务器端执行,且仅使用直接来自艾克索拉的可信数据。 提示
要了解 Webhook 的工作方式,请参见我们的 [**Webhook**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) 指南。 与 Google Play Billing 相比如何?
下表快速对比了**艾克索拉基于 Webhook 的服务器侧验证**与 **Google Play Billing 基于 API 的验证**。两者都用于确保购买真实合法,但底层基础设施和工作流截然不同。尤其需要注意:**艾克索拉不使用也不封装 Google Play Developer API**,而是通过 Webhook 提供独立的验证机制。
| 功能 | 艾克索拉 Mobile SDK | Google Play Billing |
| --- | --- | --- |
| 验证流程 | 基于 Webhook:购买完成后,艾克索拉服务会向您的后端发送通知。随后您的后端验证并处理订单。 | 基于 API:您的后端使用客户端返回的 purchaseToken 轮询或请求 Google Play Developer API 以验证购买真实性。 |
| 主要标识符 | 艾克索拉 order ID | Google Play purchaseToken |
| 验证方 | 艾克索拉的后端基础设施与您的服务器逻辑 | Google Play Developer API(purchases.products:get、purchases.subscriptionsv2:get 等) |
| 后端集成方式 | 响应式:基于 Webhook 的模型 会自动将购买数据推送到您的后端。 | 轮询或请求式:您的服务器在收到客户端的 purchaseToken 后,需要从 Google 的 API 拉取数据。 |
| 异步处理 | ✅ 支持。购买完成即触发 Webhook,可提前或在后台处理。 | ⚠️ 可行,但通常需要在查询 Google 之前进行轮询或经由客户端转发到服务器。 |
| 安全处理 | 更简单:艾克索拉会在向您的后端触发 Webhook 之前完成验证。您只需核验订单 ID 并据此履约发货。 | 更复杂:您的后端必须安全处理 API 令牌、校验签名,并正确响应不同的购买状态。 |
| 集成复杂度 | 较低 — 无需管理凭证权限范围或外部结算接口。艾克索拉负责管理购买流程并通知您的后端。 | 较高 — 需要配置 OAuth、服务帐户、令牌生命周期管理以及细致的错误处理。 |
### 客户端侧验证
客户端侧验证支持直接在用户设备上验证购买,无需搭建后端(服务器)。虽然比完全不验证更稳妥,但存在固有缺陷:任何在客户端运行的逻辑都可能遭到篡改或恶意利用。此方式仅提供基础级别的验证,由于存在固有的安全隐患,通常**不建议用于关键应用**。
在[初始化](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/initialization/android/) `BillingClient` 时,扩展 `PurchasesUpdatedListener` 的 `onPurchasesUpdated` 回调,并加入下面的代码,在客户端启用基础(不安全)的购买验证:
```java
final PurchasesUpdatedListener purchasesUpdatedListener = new PurchasesUpdatedListener() {
@Override
public void onPurchasesUpdated(
@NonNull final BillingResult billingResult, @Nullable final List<Purchase> purchases
) {
if (billingResult.isSuccess() && purchases != null) {
// Validate and consume purchases one by one.
for (int i = 0; i < purchases.size(); ++i) {
final ValidateParams validateParams = ValidateParams.newBuilder()
.setPurchaseToken(purchases.get(i).getPurchaseToken())
.build();
// This `validateAsync` method is part of the Xsolla Mobile SDK.
// It performs a client-side network call to Xsolla's services for validation.
// For developers coming from GPB, this serves a similar *purpose* to how you
// might send a `purchaseToken` from the client to your *own* backend for validation,
// but here, Xsolla's services act as that immediate validation point.
mBillingClient.validateAsync(validateParams, new ValidateResponseListener() {
@Override
public void onValidateResponse(
@NonNull final BillingResult billingResult, @Nullable final String purchaseToken
) {
// Make sure validation of the purchase was a success..
if (billingResult.isSuccess() && !TextUtils.isEmpty(purchaseToken)) {
// Prepare consumption parameters based on the purchase
// token received with the validation response.
final ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchaseToken)
.build();
// Notify Xsolla that the purchase has been processed and mark it as consumed.
mBillingClient.consumeAsync(consumeParams,
// TODO: Handle consumption success/failure.
// After successful consumption, grant entitlement to the user.
);
} else {
// Purchase validation has failed on the client-side.
// Handle error, do not grant entitlement.
}
}
});
}
} else {
// An error occurred, while trying to update the purchases.
// This could be due to BillingClient connection issues or a user cancellation.
// Handle error appropriately, do not grant entitlement.
}
}
}
```
与 Google Play Billing 相比如何?
艾克索拉 Mobile SDK 的结构与 Google Play Billing 相近,有助于简化开发,也便于熟悉 GPB 的人员采用。下表对比了两者在常见验证与履约流程中的做法:
| 功能 | 艾克索拉 Mobile SDK | Google Play Billing |
| --- | --- | --- |
| 验证 | validateAsync(...) – 将 purchaseToken 发送到艾克索拉服务进行基础验证 | 无内置验证;必须手动将 purchaseToken 发送到您的后端 |
| 核销与权益 | consumeAsync(...) – 验证后调用,用于标记购买并解锁内容 | consumeAsync(...) – 在自定义后端验证后调用以完成流程 |
## 结论与建议
艾克索拉 Mobile SDK 同时支持**客户端侧**和**服务器侧**的购买验证流程,适配多种应用需求和开发者工作流程。两种方法在安全性、复杂度和集成工作量上各有取舍。
在生产环境中,尤其是涉及真实付费交易或付费内容访问权限时,**强烈建议使用服务器侧验证**。这样可以确保所有权益都基于通过**艾克索拉的安全 Webhook 系统**直接收到的已验证购买数据授予,而不依赖客户端提供的数据。此举 可显著降低欺诈或篡改的风险。
客户端侧验证虽然实现更快,且适用于低风险场景,但应视为一种轻量方案。它从设备直接向艾克索拉服务发起验证请求,如果单独使用,可能被绕过。该方法更适合原型或提供非关键、低价值物品的应用。 信息
艾克索拉 Mobile SDK 提供灵活的验证选项,帮助开发者快速起步并在保障安全的同时扩展规模。为获得最佳效果,请采用**基于 Webhook 的服务器侧验证**,作为管理购买真实性与权益履约的主要机制。
购买验证 - iOS
https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/validation/ios
向最终用户发放购买内容前,应对每笔购买交易进行验证。这有助于防范未授权购买,维护应用内经济系统的正常运行。购买验证是防范欺诈、保障收入并维护公平用户体验的关键安全措施。
目前主要提供两种不同的验证方式。
### 服务器侧验证
最安全可靠的验证方式是采用**服务器到服务器** (**S2S**) 通信,使客户端完全不参与验证流程。这能最大限度降低安全风险,确保仅凭直接来自艾克索拉的已验证数据发放权益。
接入艾克索拉时,服务器侧验证通过**基于 Webhook 的模式**实现:
- 当用户在您的应用中完成购买后,艾克索拉服务会自动向您的后端发送 [**Webhook 事件**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#user_validation)。
- 该 Webhook 包含所有必要的购买数据(包括**艾克索拉** `order ID`),供您的服务器异步验证并处理该笔购买。
- 随后,您的后端即可根据这些数据更新用户的权益、余额、物品库等,无需客户端提供任何额外输入。
该流程确保客户端无法干预购买结果的判定⸺所有验证逻辑均在服务器端执行,且仅使用直接来自艾克索拉的可信数据。 提示
要了解 Webhook 的工作方式,请参见我们的 [**Webhook**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) 指南。 此流程中的交易回调仅用于界面展示
即使采用服务器侧验证,SDK 仍会照常触发客户端回调⸺`paymentQueue(_:updatedTransactions:)`,以及调用 `validateTransaction(_:)` 时返回的结果。在服务器侧 (Webhook) 流程中,这些回调**仅用于 UI/UX**:展示加载动画、确认画面或刷新商店界面。它们**不会**发放奖励,也绝不能用于发放奖励⸺相关权益已由您的后端根据可信 Webhook 独立于设备发放完毕。请将客户端回调仅视为界面显示信号,而非唯一可信数据源。
### 客户端侧验证
客户端侧验证支持直接在用户设备上验证购买,无需搭建后端(服务器)。虽然这比完全不验证更稳妥,但仍存在明显局限,即任何在客户端运行的逻辑都有可能遭到篡改或恶意利用。
在完成交易前,可以在客户端侧进行验证。应用关闭后恢复的未完成交易无法验证。
```objectivec
SKPaymentTransaction* transaction = ...;
[[SKPaymentQueue defaultQueue] validateTransaction:transaction completion:^(BOOL isValid, NSError * _Nullable error) {
// isValid will be YES for valid transactions
}];
```
```swift
let transaction: SKPaymentTransaction = ...
SKPaymentQueue.default().validateTransaction(transaction) { isValid, error in
// isValid will be true for valid transactions
}
```
## 与原生 StoreKit 验证对比
虽然艾克索拉提供了简化的验证方案,但了解其与 Apple 原生 StoreKit 验证[方法 ↗](https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique) ([https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique](https://developer.apple.com/documentation/storekit/choosing-a-receipt-validation-technique)) 的差异同样很有帮助。
### 服务器侧验证的差异
| 对比项 | 基于艾克索拉 Webhook | Apple 的 verifyReceipt API |
| --- | --- | --- |
| 实现 | 由艾克索拉自动触发 Webhook | 手动发起到 Apple 端点的服务器到服务器调用 |
| 安全性 | 高 - 不涉及客户端 | 高 - 与 Apple 直接校验 |
| 配置复杂度 | 低 - 配置 Webhook 端点 | 中 - 实现收据解析并发起 API 调用 |
| 数据格式 | JSON Webhook 负载 | Base64 编码的收据 → JSON 响 应 |
| 时机 | 异步,实时通知 | 同步,按需验证 |
| 交易历史 | 单笔购买事件 | 包含所有交易的完整收据 |
| 网络要求 | Webhook 端点可被艾克索拉访问 | 到 Apple 服务器的安全 HTTPS |
采用**艾克索拉基于 Webhook 的方式**时,艾克索拉会将已验证的购买数据推送至您的后端端点并自动完成验证,无需手动处理收据提取、解析或验证请求。
采用 **Apple 的原生方式**时,您的应用必须从应用包中提取收据数据,并由服务器向 Apple 端点(生产环境使用 `https://buy.itunes.apple.com/verifyReceipt` 或沙盒环境使用 `https://sandbox.itunes.apple.com/verifyReceipt`)发起验证请求,随后解析返回的 JSON 响应。
### 客户端侧验证的差异
| 对比项 | 艾克索拉 Mobile SDK | Apple 原生本地验证 |
| --- | --- | --- |
| 实现 | 简单的 SDK 方法调用 | 复杂的 PKCS #7 容器解码 |
| 代码复杂度 | 低 - 单个函数调用 | 高 - ASN.1 解析、密码学验证 |
| 验证步骤 | 由 SDK 内部处理 | 手动验证证书链、Bundle ID、版本、设备哈希 |
| 依赖 | 艾克索拉 Mobile SDK | Security 框架 |
| 维护 | 由艾克索拉维护 | 开发者维护密码学代码 |
| 安全级别 | 中 - 受限于客户端侧 | 中 - 受限于客户端侧 |
**艾克索拉的客户端侧验证**提供了简化的接口:
```swift
SKPaymentQueue.default().validateTransaction(transaction) { isValid, error in
// Simple validation result
}
```
**Apple 的原生本地验证**需要大量实现,包括将收据作为 PKCS #7 容器用 ASN.1 记法解码、验证证书链和签名有效性、计算用于设备标识的 SHA-1 哈希,并校验多个收据字段(Bundle ID、版本、设备哈希)。
任务邀请 (Offerwall) SDK
https://developers.xsolla.com/sdk/zh/offerwall
即将推出SDK 下载包 · API 参考 · 集成指南
**艾克索拉任务邀请 (Offerwall) SDK** 支持在游戏内直接嵌入任务邀请版块⸺原生展示广告主任务、发放虚拟奖励并跟踪任务完成情况,玩家全程无需离开应用。7x第 30 日留存率提升10–14x付费转化概率提升120%日活用户 LTV 增幅90%开发者收入分成
**有意接入?**SDK 下载包、API 参考及集成指南正在开发中⸺欢迎联系您的客户经理了解详情。
## 实现全量玩家群体变现
大多数游戏仅能通过 APP 内购从 2–5% 的玩家身上获得收入。**艾克索拉任务邀请 (Offerwall)** 是一套互动广告平台,无需玩家掏钱付费,即可将其余 95% 的玩家转化为收入来源。玩家通过完成广告主发布的任务赢取虚拟奖励(游戏内货币、道具及其他内容),形成多方共赢的价值闭环。
参与任务邀请的玩家第 30 日留存率高出 7 倍,转化为付费用户的概率高出 10–14 倍。在接入任务邀请的游戏中,日常活跃参与用户的 LTV 最高可提升 120%⸺使其兼具商业变现与留存促活双重价值。 **行业领先的收入分成**
艾克索拉为开发者提供高达 90% 的收入分成⸺远超行业普遍 30–60% 的水平。**反欺诈防护**
基于短信的用户验证可有效提升流量质量,杜绝虚假刷单行为,切实保障您的收入。**艾克索拉积分**
通用的跨游戏奖励货币,让玩家获得的价值不再局限于单一游戏,持续激发长期活跃。**全球覆盖**
面向全球玩家打造的任务与奖励体系,广告主预算需求广泛覆盖多个国家和地区及细分行业。
## 激励式参与模型
**艾克索拉任务邀请 (Offerwall)** 支持多种任务类型,助力充分提升玩家参与度与广告填充率: **按安装计费 (CPI)**
玩家通过安装并打开推广应用赢取奖励⸺这类高价值行为能直接为广告主带来有效安装量。**按互动计费 (CPE)**
玩家完成应用内阶段目标(如达到指定关卡、完成新手教程或达成特定目标)即可获得奖励。**按获客计费 (CPA)**
玩家完成注册、订阅或购买等操作⸺这些是广告主眼中最具高价值的深度转化事件。**按点击计费 (CPC)**
轻量级参与任务,玩家只需浏览内容、观看视频或参与推广素材互动即可完成。
**艾克索拉任务邀请 (Offerwall)** 也可作为零代码扩展模块接入您的[**艾克索拉网充商店** ↗](https://xsolla.com/mobile-web-shop) [(xsolla.com)](https://xsolla.com/mobile-web-shop)⸺只需在**发布商帐户**中启用,即可作为原生版块展示在商店页面中。如需了解更多信息,请访问[**任务邀请 (Offerwall)** ↗](https://xsolla.com/offerwall) [(xsolla.com)](https://xsolla.com/offerwall)。
发布商帐户
https://developers.xsolla.com/sdk/zh/publisher-account
**发布商帐户**是艾克索拉集成的核心控制面板⸺您可以在此创建项目、设置身份认证、管理商品目录并配置 Webhook。
## 创建项目
[推荐
应用已在 App Store 或 Google Play 上线
自动导入应用的商店信息。艾克索拉会将游戏数据(图片、游戏名称和品牌元素)预填到网充商店,并在数分钟内生成项目 ID。从现有商店页面设置 →](https://developers.xsolla.com/sdk/zh/publisher-account/new-project/setup-fasttrack/)[从头开始
创建新项目,配置艾克索拉登录管理器,并获取用于 SDK 集成的项目 ID 和登录管理器 ID。手动设置 →](https://developers.xsolla.com/sdk/zh/publisher-account/new-project/setup-manual/) **身份认证**
配置艾克索拉登录管理器使用设备 ID 进行无缝身份认证,或使用服务器侧登录以全面掌控后端。**商品目录**
使用多币种定价创建和管理虚拟物品 (SKU),或直接从 Google Play 或 App Store 导入。**Webhook 与事件**
配置支付 Webhook 以在后端处理交易,或使用艾克索拉事件API (Events API) 进行无服务器购买校验。**上线**
签署许可协议,并退出沙盒模式以启用真实付款。
查找项目 ID
https://developers.xsolla.com/sdk/zh/publisher-account/getids
在**发布商帐户**中查找**项目 ID** 和**登录管理器 ID**⸺初始化 SDK 时需要用到这两个 ID。
## 项目 ID
在**发布商帐户**中,**项目 ID** 显示在项目名称旁。 ![发布商帐户中的项目 ID 位置]
## 登录管理器 ID
要查找**登录管理器 ID**,请在**发布商帐户**中前往**登录管理器** > **运营看板**,复制登录管理器项目名称旁显示的 ID。 ![发布商帐户中的登录管理器 ID 位置]
## 在 SDK 中使用这些 ID
在项目中初始化 SDK 时使用这些 ID。
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(<Project ID>)
.SetLoginId(<Login ID>)
...
```
提示
有关如何配置 SDK 的更多信息,请访问[配置 SDK](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。
```java
final Config billingClientConfig = new Config(
Config.Common.getDefault(),
Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(<Project ID>).getRight(),
LoginUUID.parse(<Login ID>).getRight()
)
),
Config.Payments.getDefault()
);
```
提示
有关如何配置 SDK 的更多信息,请访问[配置 SDK](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/)。
```objectivec
SKPaymentSettings* settings = [[SKPaymentSettings alloc] initWithProjectId: <Project ID>
loginProjectId: <Login ID>
platform: SKPaymentPlatformStandalone
paystationUIThemeId: SKPaystationThemeDark
paystationUISize: SKPaystationSizeMedium];
SKPaymentQueue* queue = [SKPaymentQueue defaultQueue];
[queue startWithSettings: settings];
```
```swift
let settings = SKPaymentSettings(projectId: <Project ID>,
loginProjectId: <Login ID>,
platform: .standalone)
SKPaymentQueue.default().start(settings)
```
提示
有关如何配置 SDK 的更多信息,请访问[配置 SDK](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)。
上线流程
https://developers.xsolla.com/sdk/zh/publisher-account/gotolive
签署许可协议并从沙盒环境切换至生产环境⸺这是开始接收真实付款前的最后步骤。
## 签署许可协议
important
您必须在**发布商帐户**中为每个新项目分别签署协议。
请按以下步骤签署许可协议并启用真实付款:
- 打开您的**发布商帐户**。
- 在侧边栏中,前往**协议与税务** > **合同与协议**区域。
- 在**许可协议**选项卡中,点击**填写申请表**。
- 在相应字段中填写您的信息。
您的申请将在 **3 个工作日**内完成审核。如有疑问,艾克索拉会联系申请表中填写的联系人。审核通过后,协议状态将变为**已签署**。
在签署许可协议之前,您只能在**沙盒模式**下打开支付 UI。
## 切换到生产环境
- 确保您已与艾克索拉签署许可协议。
- 在 SDK 配置代码中,将 **sandbox** 设置为 **false**。
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSandbox(false)
.SetLogLevel(XsollaLogLevel.None)
// ...other settings
.Build();
```
```java
final Config billingClientConfig = new Config(
Config.Common.getDefault()
.withSandboxEnabled(false)
.withLogLevel(LogLevel.ERROR)
.withDebugEnabled(false),
// ...other settings
);
```
```objectivec
SKPaymentSettings* settings = ...;
settings.useSandbox = NO;
settings.logLevel = SKLogLevelError;
```
```swift
let settings = SKPaymentSettings(...)
settings.useSandbox = false
settings.logLevel = .error
```
## 测试银行卡与沙盒模式
注意
在完成第一次**真实付款**后,将启用**严格沙盒**支付政策。
沙盒模式下的支付功能仅向**发布商帐户**的**公司设置** > **用户**中所指定的用户开放。
设置身份认证
https://developers.xsolla.com/sdk/zh/publisher-account/login
为**艾克索拉登录管理器**项目配置身份认证方式,请选择与应用复杂度匹配的方案。
## 使用设备 ID 登录
important
如果您使用**艾克索拉 SDK**,且尚未集成艾克索拉登录管理器,则此方式为**必需**。
最适合不需要高级功能(如服务器验证、与艾克索拉的显式身份认证等)的休闲类应用。
### 在发布商帐户中启用使用设备 ID 登录
- 在**登录方式**区块中,选择任意选项并点击**配置**。
[![选择登录方式]](https://cdn.xsolla.net/developers/current/images/sdk/general/use-xsolla-servers/select-method.svg)
- 在顶部设置区块中,点击**登录管理器 API 集成**。
- 将**使用设备 ID 登录**开关设为 **ON**。
- 点击**保存更改**。
![设备 ID 登录设置]
更多信息,请参见[设备 ID 身份认证 ↗](https://developers.xsolla.com/doc/login/authentication-options/device-id) ([https://developers.xsolla.com/doc/login/authentication-options/device-id)。](https://developers.xsolla.com/doc/login/authentication-options/device-id)%E3%80%82)
## 在游戏服务器上登录
这是最进阶的方案⸺依赖项目后端对用户进行身份认证和校验,并广泛使用 Webhook 在后端与艾克索拉服务之间通信。更多信息,请参见 [**Auth by custom ID ↗**](https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id) ([https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id](https://developers.xsolla.com/api/login/server-custom-id/auth-by-custom-id)) API 参考。
从商店页面创建项目
https://developers.xsolla.com/sdk/zh/publisher-account/new-project/setup-fasttrack
关联您的 **Google Play** 或 **App Store** 商店页面⸺艾克索拉会自动拉取游戏的图片、名称、开发者信息和颜色方案,预先填充到您的**发布商帐户**项目和**网充商店**中。
- 注册或登录您的**发布商帐户**。 要注册,请访问 [publisher.xsolla.com ↗](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/)。](https://publisher.xsolla.com/)%E3%80%82)
- 在**发布商帐户**中创建一个项目(如果尚未创建)。
- 在项目中前往**商店入口** > **网站**板块。
- 点击**创建网站**按钮,并选择**网充商店**模板。
- 添加游戏已上架外部平台的链接(Google Play 商店或 Apple App Store)。 [![创建网站]](https://developers.xsolla.com/sdk/zh/assets/images/web-shop-create-site-1-55c3c75c111949355a8045234f0fc380.png)
- 点击**创建网充商店**。
艾克索拉会自动从商店获取应用信息,并将游戏数据填充到您的项目和**网充商店**中。
**网充商店**模板的样式会自动匹配您的游戏风格,并可直接与您的**艾克索拉 SDK** 集成配套使用。
## 设置身份认证
为项目启用**设备 ID** 登录⸺无需玩家凭证即可登录。接下来请前往[设置身份认证](https://developers.xsolla.com/sdk/zh/publisher-account/login/)。
手动创建项目
https://developers.xsolla.com/sdk/zh/publisher-account/new-project/setup-manual
从零开始创建**发布商帐户**项目并配置**艾克索拉登录管理器**,以获取 SDK 集成所需的项目 ID 和登录管理器 ID。
## 注册发布商帐户
发布商帐户是配置艾克索拉各项功能、查看分析数据及管理交易的核心工具。
如需注册,请访问[发布商帐户 ↗](https://publisher.xsolla.com/) ([https://publisher.xsolla.com/)。](https://publisher.xsolla.com/)%E3%80%82)
## 创建新项目
配置项目详情:
- 选择项目类型:**游戏**、**游戏平台**或**其他**。
- 使用英文输入项目名称。
- 选择发布平台。
- 选择变现方式。
- 选择开发阶段。
- 若项目为游戏:指定游戏类型与游戏引擎。
- 添加产品/游戏链接(可选)。
[![项目信息]](https://cdn.xsolla.net/developers/current/images/general/create-project/project-info.png)
- 点击**完成**以完成项目创建。
项目会显示在侧边栏。
![已创建的项目]
配置和集成 SDK 需要用到**项目 ID**。您可以在**发布商帐户**的项目名称旁找到该 ID⸺详情参见[**查找项目 ID**](https://developers.xsolla.com/sdk/zh/publisher-account/getids/#project-id)。
## 设置艾克索拉登录管理器
要设置艾克索拉登录管理器,请按照以下步骤操作:
- 在菜单中前往**玩家管理** > **登录管理器**。
- 点击**创建登录管理器项目**。
[![创建登录管理器项目]](https://cdn.xsolla.net/developers/current/images/sdk/general/use-xsolla-servers/create-login-project.svg)
- 选择**标准登录管理器项目**,然后点击**创建并设置**。
集成 SDK 需要用到项目的**登录管理器 ID**。您可以在登录管理器项目页面的项目名称旁找到该 ID⸺详情参见[**查找登录管理器 ID**](https://developers.xsolla.com/sdk/zh/publisher-account/getids/#login-id)。
## 设置身份认证
为您的**艾克索拉登录管理器**项目配置身份认证方式。接下来请前往[设置身份认证](https://developers.xsolla.com/sdk/zh/publisher-account/login/)。
配置艾克索拉商品目录
https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items
设置您的**虚拟物品** (IAP)⸺即**艾克索拉商品目录**中的可购商品,相当于 Google Play Billing 或 StoreKit 中的 APP 内购商品。 important
您的艾克索拉商品目录由[**虚拟物品 ↗**](https://developers.xsolla.com/doc/shop-builder/features/virtual-items) ([https://developers.xsolla.com/doc/shop-builder/features/virtual-items](https://developers.xsolla.com/doc/shop-builder/features/virtual-items)) 组成。每个虚拟物品均包含名称、描述、SKU(商品 ID)和价格。
请参照[**此指南 ↗**](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog) ([https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog),从](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_appstore_catalog)%EF%BC%8C%E4%BB%8E) App Store Connect 导入 APP 内购 (IAP),并将其同步为艾克索拉商品目录中的虚拟物品。注意
请在每次更新 App Store 的 APP 内购商品目录后执行此操作。
请参照[**此指 南 ↗**](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog) ([https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog),从](https://developers.xsolla.com/doc/shop-builder/how-to/import-catalog/?_xm=383621481969483790#shop_builder_how_to_import_google_catalog)%EF%BC%8C%E4%BB%8E) Google Play 导入应用内商品 (IAP),并将其同步为艾克索拉商品目录中的虚拟物品。注意
请在每次更新 Google Play 的商品目录后执行此操作。
使用此方法可通过发布商帐户界面手动管理艾克索拉商品目录 (IAP)。
### 向商品目录添加含基础设置的虚拟物品
- 在发布商帐户中打开项目,前往**商品管理** > **全部商品**区域。
- 点击**添加**,并在下拉列表中选择**虚拟物品**。
![创建虚拟物品]
- 配置基础设置,指定以下内容: - 图片(可选) - SKU - 一个或多个分组 - 商品名称 - 商品描述(可选) 将商品类型保留为默认值⸺**消耗品**(推荐)。
- 设置虚拟物品定价: - 如需创建免费虚拟物品,请在**付费或免费**字段中选择**免费商品**。 - 如需创建付费虚拟物品,请在**付费或免费**字段中选择**付费商品**,并以一种或多种货币填写价格。 备注 为保证获取商品目录的 API 调用正常执行,请确保所有商品的默认货币与已配置价格的货币列表保持一致。
- 将商品状态更改为**可用**。
![虚拟物品状态]
- 点击**创建商品**。
如需了解高级商品目录功能(虚拟货币、捆绑包、商品分组等),请参见[**商品目录创建指南 ↗**](https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa) ([https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa)。](https://developers.xsolla.com/doc/shop-builder/features/virtual-items/?_xm=383621481969483790#shop_builder_virtual_items_set_up_in_pa)%E3%80%82)注意
文件大小限制为 **7MB**(约 **1000** 条记录)。
目前暂无公开文档。请联系您的客户经理了解详情,或获取手动导入/同步支持。
您可以使用 REST API 在**发布商帐户**中管理虚拟物品 (IAP),从而在游戏服务器商品目录与艾克索拉商品目录之间实现物品库同步。
- #### 获取虚拟物品 ```text GET /v2/project/{project_id}/admin/items/virtual_items ``` 文档见[此处 ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/](https://developers.xsolla.com/api/igs-bb/operation/admin-get-virtual-items-list/))
- #### 创建虚拟物品 ```text POST /v2/project/{project_id}/admin/items/virtual_items ``` 文档见[此处 ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-create-virtual-item/))
- #### 更新虚拟物品 ```text PUT /v2/project/{project_id}/admin/items/virtual_items/sku/{item_sku} ``` 文档见[此处 ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-update-virtual-item/))
- #### 删除虚拟物品 ```text DELETE /v2/project/{project_id}/admin/items/virtual_items/sku/{item_sku} ``` 文档见[此处 ↗](https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/) ([https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/](https://developers.xsolla.com/api/igs-bb/operation/admin-delete-virtual-item/))
Webhook
https://developers.xsolla.com/sdk/zh/publisher-account/webhooks
当发生支付或用户验证时,艾克索拉会向您的后端发送包含事件数据的 HTTP 请求。
## Webhook 验证工作原理
服务器侧验证是指艾克索拉会就每笔购买、退款和拒付通知您的后端,由后端据此发放或撤销对应权益。游戏客户端不会参与权益发放或撤销的判定。
- 玩家通过 SDK 完成购买。
- 艾克索拉向您的后端发送 Webhook (HTTP POST)。
- 您的后端[验证签名](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#verifying-the-signature),然后处理事件。
- 您的后端发放权益,并向艾克索拉[返回成功状态码](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#responding-to-webhooks)(**`200`**/**`201`**/**`204`**)。
- 您的后端通过自有渠道通知游戏⸺此步骤不涉及 SDK。
关于此流程的客户端侧部分⸺发起购买并将 SDK 的购买完成回调作为 UI 反馈⸺请参见所用平台的购买指南:[Android](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/)、[iOS](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/)、[Unity](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)、[Windows](https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase/)。 启用 Webhook 时不要在客户端发放商品
SDK 不知道您在发布商帐户中的 Webhook 设置,因此购买完成后,客户端仍会触发购买完成回调。通过 Webhook 处理订单履约时,请将该回调仅视为 **UI 反馈**;如果也在客户端发放商品,会导致该笔购买被重复发放。客户端处理流程(购买回调 → 校验 → 消费)是另一种模式,仅在没有后端时使用。
不同 SDK 的购买完成回调不同。无论客户端使用哪一种,当由 Webhook 负责订单履约时,都应仅将其作为 UI 反馈:
| 平台 | 购买完成回调 | 客户端侧校验 → 消费(替代模型) |
| --- | --- | --- |
| Android | onPurchasesUpdated() | validateAsync() → consumeAsync() — 客户端侧校验 |
| iOS | paymentQueue(_:updatedTransactions:) (.purchased) | validateTransaction(_:completion:) → finishTransaction(_:) — 客户端侧校验 |
| Unity(含/不含 IAP) | ProcessPurchase(...) / PurchaseProduct(...) | ValidatePurchase(...) → ConsumeProduct(...) — 客户端侧校验 |
| Windows | PurchaseProduct(...) | ValidatePurchase(...) → ConsumeProduct(...) — 客户端侧校验 |
## 在发布商帐户中设置 Webhook
![发布商帐户中的 Webhook 设置]
### 启用 Webhook
- 在发布商帐户中打开您的项目。
- 在侧边栏中,前往**设置**并选择 **Webhook**。
- 在 **Webhook 服务器**字段中,填写要接收 Webhook 的服务器 URL(例如 `https://www.my-backend.com/webhooks`)。
- 系统会默认生成用于签名 Webhook 的密钥。要添加或轮换密钥: - 在**密钥**区域,点击**添加密钥**。 - 输入名称并点击**创建密钥**。 - 复制生成的值(仅显示一次)。 - 轮换时:在新密钥上点击** 设为有效**。每个项目最多可有 5 个密钥;确认签名校验通过后再删除旧密钥。
- 点击**启用Webhook**。
### 禁用 Webhook
- 在发布商帐户中打开您的项目。
- 在侧边栏中,前往**设置**并选择 **Webhook**。
- 点击**禁用 Webhook**。
## 接收的 Webhook 类型
项目会收到哪些 Webhook,取决于项目的注册时间。较新的项目采用合并的订单通知模式,旧项目则分别接收支付通知和退款通知。
| 项目注册时间 | 您将收到 | 说明 |
| --- | --- | --- |
| 2025 年 1 月 22 日之后 | order_paid、order_canceled(合并) | 不要处理 payment / refund。 |
| 2025 年 1 月 22 日之前 | payment、refund(单独)+ 带有商品数据的 order_paid / order_canceled | 旧分开模式。 |
如何检查自己使用哪种模型
在发布商帐户 → **项目设置** → **Webhook** 中,如果测试区域仅显示 `order_paid` 示例,说明您使用的是新的(合并)模型。
## 验证签名
每个 Webhook 都带有 `Authorization: Signature <value>` 请求头。处理任何事件前请先验证签名。
- 从 `Authorization` 请求头中读取签名(格式:`Signature <value>`)。
- 原样获取接收到的**原始请求体**。不要解析或重新序列化 JSON⸺重新编码会改变字节,导致签名不匹配。
- 拼接:`raw_body + secret_key`。
- 计算 **SHA-1**,取小写十六进制摘要。
- 使用**恒定时间**比较法与请求头中的签名值进行比对,防止时序攻击。
请使用原始请求体
签名校验必须基于艾克索拉发送的**原始字节**。请在任何 JSON 中间件解析之前捕获原始请求体⸺解析并重新序列化会改变字节,导致签名永远无法匹配。下方各框架示例展示了如何获取原始请求体。
```js
const crypto = require('crypto');
// Capture the RAW body, not parsed JSON:
// app.use('/webhooks', express.raw({ type: 'application/json' }));
function verifyXsollaSignature(rawBody, authHeader, secretKey) {
const provided = String(authHeader || '').replace(/^Signature\s+/i, '').trim();
const expected = crypto
.createHash('sha1')
.update(rawBody.toString('utf8') + secretKey)
.digest('hex');
const a = Buffer.from(provided);
const b = Buffer.from(expected);
return a.length === b.length && crypto.timingSafeEqual(a, b);
}
```
```php
function verifyXsollaSignature(string $rawBody, string $authHeader, string $secretKey): bool {
$provided = trim(preg_replace('/^Signature\s+/i', '', $authHeader));
$expected = sha1($rawBody . $secretKey);
return hash_equals($expected, $provided); // constant-time
}
```
```csharp
using System.Security.Cryptography;
using System.Text;
static bool VerifyXsollaSignature(string rawBody, string authHeader, string secretKey)
{
var provided = (authHeader ?? "").Replace("Signature ", "").Trim();
var hash = SHA1.HashData(Encoding.UTF8.GetBytes(rawBody + secretKey)); // .NET 5+
var expected = Convert.ToHexString(hash).ToLowerInvariant(); // .NET 5+
return CryptographicOperations.FixedTimeEquals(
Encoding.UTF8.GetBytes(provided),
Encoding.UTF8.GetBytes(expected));
}
```
对于 .NET Framework/.NET 5 之前的版本,将 `SHA1.HashData(...)` 替换为 `using var sha1 = SHA1.Create(); var hash = sha1.ComputeHash(...);`,并将 `Convert.ToHexString(hash)` 替换为 `BitConverter.ToString(hash).Replace("-", "").ToLowerInvariant()`。
```python
import hashlib
import hmac
def verify_xsolla_signature(raw_body: bytes, auth_header: str, secret_key: str) -> bool:
provided = auth_header.replace('Signature ', '').strip()
expected = hashlib.sha1((raw_body.decode('utf-8') + secret_key).encode('utf-8')).hexdigest()
return hmac.compare_digest(provided, expected)
```
```go
import (
"crypto/sha1"
"crypto/subtle"
"encoding/hex"
"strings"
)
func verifyXsollaSignature(rawBody []byte, authHeader, secretKey string) bool {
provided := strings.TrimSpace(strings.TrimPrefix(authHeader, "Signature "))
h := sha1.New()
h.Write(rawBody)
h.Write([]byte(secretKey))
expected := hex.EncodeToString(h.Sum(nil))
return subtle.ConstantTimeCompare([]byte(provided), []byte(expected)) == 1
}
```
```java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
static boolean verifyXsollaSignature(final byte[] rawBody, final String authHeader, final String secretKey)
throws NoSuchAlgorithmException {
final String provided = authHeader.replaceFirst("(?i)^Signature\\s+", "").trim();
final MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
sha1.update(rawBody);
sha1.update(secretKey.getBytes(StandardCharsets.UTF_8));
final byte[] hash = sha1.digest();
final StringBuilder hex = new StringBuilder(hash.length * 2);
for (final byte b : hash) {
hex.append(String.format("%02x", b));
}
// MessageDigest.isEqual is constant-time on modern JDKs.
return MessageDigest.isEqual(
provided.getBytes(StandardCharsets.UTF_8),
hex.toString().getBytes(StandardCharsets.UTF_8)
);
}
```
## 响应 Webhook
您的处理程序必须返回正确的 HTTP 代码。
| 响应 | 含义 |
| --- | --- |
| 200 / 201 / 204 | 成功⸺已接受 Webhook。 |
| 400(任意 4xx)+ 错误代码 | 请求存在问题。请在错误响应体中包含 code 与 message。常见错误代码:INVALID_SIGNATURE、INVALID_USER、INVALID_PARAMETER。 |
| 5xx | 己侧出现临时问题⸺艾克索拉会重试。 |
当您以 `4xx` 拒绝请求时,请在状态码之外一并返回错误响应体。其结构如下⸺请将 `code` 和 `message` 设置为符合此次拒绝原因的内容:
```json
{
"error": {
"code": "INVALID_SIGNATURE",
"message": "Signature mismatch"
}
}
```
针对 4xx 的退款
如果您的项目启用了自动退款,对 `order_paid` 返回 `4xx` 会触发向玩家的自动退款。仅在确实要拒绝此次购买时才返回 `4xx`⸺若是己侧出现临时问题,请返回 `5xx`,以便艾克索拉重试。
### 重试
- `order_paid` / `order_canceled`:如果您的 Webhook 接收端未返回成功响应,艾克索拉会按逐渐拉长的间隔进行重试:每 5 分钟重试 2 次、每 15 分钟重试 7 次,之后每 60 分钟重试 10 次。12 小时内最多投递 20 次,包括首次投递和后续重试。
- `payment` / `refund`(旧模式):同样会在 12 小时内按逐渐拉长的间隔重试。确切次数请参见 [Webhook 参考 ↗](https://developers.xsolla.com/webhooks/overview)。
- `user_validation` 是一次前置校验,而非重试机制:如果您返回 `400`/`5xx` 或未响应,该 Webhook **不会**重发,玩家会看到错误提示,且后续的 `payment`/`order_paid` Webhook 也**不会**发送。仅当该用户符合您的准入条件时,才返回成功响应。
## 使用 Webhook
每个 Webhook 都会要求您执行特定操作。请先验证每个请求的签名(参见[验证签名](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#verifying-the-signature)),然后根据 `notification_type` 处理。
### 用户验证 (user_validation)
在支付**之前**发送的前置校验请求,用于确认用户是否可以购买。返回 `204` 允许继续购买,或返回携带 `INVALID_USER` 的 `400` 予以拦截。该 Webhook [不重试](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#retries),且验证被拒绝后不会发送任何支付 Webhook⸺因此请仅对系统中确实存在的用户返回成功。
此处以及旧 [`payment`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#payment) Webhook 中的玩家 ID 位于 `user.id`。合并模式的 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_paid) Webhook 则通过 `user.external_id` 标识玩家⸺请按 Webhook 类型选用正确的字段。 示例
```json
{
"notification_type": "user_validation",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"user": {
"ip": "127.0.0.1",
"phone": "18777976552",
"email": "[email protected]",
"id": "1234567",
"name": "John Smith",
"country": "US"
}
}
```
完整字段列表请参见 [user_validation 参考 ↗](https://developers.xsolla.com/webhooks/operation/user-validation/)。
### 订单已支付 (order_paid)
这是用于触发订单履约处理的 Webhook,也是 2025 年 1 月 22 日之后注册的项目所使用的主要 Webhook。在合并订单通知模式中,它同时包含需要发放的商品以及支付数据。请读取 `items[]`(每项包含 `sku`、`type` 和 `quantity`),将其发放给 `user.external_id` 对应的用户,并返回 `204`。如果某个 `order.id`,已经处理过,请跳过该订单,以免 Webhook 重试时重复发放。测试订单会带有 `order.mode: "sandbox"`,对此类订单请不要执行真实的状态变更。
包含 Google 外部交易令牌的订单还会带有 `billing.ucb_report` 对象⸺即预构建的 Google `externalTransactions` 报告载荷。请参见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/#correlating-the-token-with-your-xsolla-order)。 示例
```json
{
"notification_type": "order_paid",
"items": [
{
"sku": "money.100",
"type": "virtual_good",
"quantity": 1,
"amount": "9.99",
"promotions": [
{
"amount_without_discount": "19.99",
"amount_with_discount": "9.99",
"sequence": 1
}
],
"is_pre_order": false,
"custom_attributes": {}
}
],
"order": {
"id": 123456789,
"mode": "default",
"currency_type": "real",
"currency": "USD",
"amount": "9.99",
"status": "paid",
"platform": "xsolla",
"invoice_id": "inv_12345",
"promotions": [],
"coupons": [],
"promocodes": []
},
"user": {
"external_id": "user_12345",
"email": "[email protected]",
"country": "US"
},
"billing": {
"notification_type": "payment",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"total": {
"currency": "USD",
"amount": 9.99
}
},
"transaction": {
"id": 555666777,
"external_id": "ext_trans_001",
"payment_date": "2025-01-15T14:22:10+00:00"
},
"payment_details": {
"payment": {
"currency": "USD",
"amount": 9.99
},
"vat": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"sales_tax": {
"currency": "USD",
"amount": 0.87,
"percent": 9.5
},
"payout": {
"currency": "USD",
"amount": 8.5
}
}
}
}
```
订阅与赠礼购买会包含额外的 `billing.purchase.subscription` / `billing.purchase.gift` 对象。完整字段列表请参见 [order_paid 参考 ↗](https://developers.xsolla.com/webhooks/operation/successful-order-payment/)。
### 订单已取消 (order_canceled)
这是用于触发撤销处理的 Webhook,适用于 2025 年 1 月 22 日之后注册的项目,并会在发生退款或拒付时发送。其结构与 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_paid) 相同:通过 `order.id` 查找原始发放记录,撤销或收回相应权益,并返回 `204`。它会按与 `order_paid` 相同的节奏[重试](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#retries),因此请基于 `order.id` 做去重处理,避免重复撤销。测试环境中的撤销通知会带有 `order.mode: "sandbox"`。
与 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_paid) 相同,当订单包含 Google 外部交易令牌时,也会携带 `billing.ucb_report` 对象⸺请参见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/#correlating-the-token-with-your-xsolla-order)。 示例
```json
{
"notification_type": "order_canceled",
"items": [
{
"sku": "money.100",
"type": "virtual_good",
"quantity": 1,
"amount": "9.99",
"is_pre_order": false,
"custom_attributes": {}
}
],
"order": {
"id": 123456789,
"mode": "default",
"currency_type": "real",
"currency": "USD",
"amount": "9.99",
"status": "canceled",
"platform": "xsolla",
"invoice_id": "inv_12345"
},
"user": {
"external_id": "user_12345",
"email": "[email protected]",
"country": "US"
},
"billing": {
"notification_type": "refund",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"transaction": {
"id": 555666777,
"external_id": "ext_trans_001"
}
}
}
```
完整载荷请参见 [order_canceled 参考 ↗](https://developers.xsolla.com/webhooks/operation/order-cancellation)。
### 支付 (payment)
此 Webhook 在旧模式(分开通知)中承载财务记录(含分项摘要)⸺适用于 2025 年 1 月 22 日之前注册的项目。独立的 [`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_paid) 则承载具权威性的商品发放数据。较新的项目完全不会收到 `payment`。如果某个 `transaction.id` 已经处理过,请跳过该交易。测试交易会带有 `transaction.dry_run: 1`。旧模式与之对应的撤销 Webhook 是 [`refund`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#refund)。
包含 Google 外部交易令牌的订单还会带有 `ucb_report` 对象⸺即预构建的 Google `externalTransactions` 报告载荷。请参见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/#correlating-the-token-with-your-xsolla-order)。 示例
```json
{
"notification_type": "payment",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"subscription": {
"plan_id": "b5dac9c8",
"subscription_id": "10",
"product_id": "Demo Product",
"date_create": "2014-09-22T19:25:25+04:00",
"date_next_charge": "2014-10-22T19:25:25+04:00",
"currency": "USD",
"amount": 9.99
},
"checkout": {
"currency": "USD",
"amount": 50
},
"total": {
"currency": "USD",
"amount": 200
},
"promotions": [
{
"technical_name": "Demo Promotion",
"id": 853
}
],
"coupon": {
"coupon_code": "ICvj45S4FUOyy",
"campaign_code": "1507"
},
"order": {
"id": 1234,
"lineitems": [
{
"sku": "ticket.10",
"quantity": 1,
"price": {
"currency": "EUR",
"amount": 6.5
}
}
]
}
},
"user": {
"ip": "127.0.0.1",
"phone": "18777976552",
"email": "[email protected]",
"id": "1234567",
"name": "John Smith",
"country": "US"
},
"transaction": {
"id": 1,
"external_id": 1,
"payment_date": "2014-09-24T20:38:16+04:00",
"payment_method": 1,
"payment_method_name": "PayPal",
"payment_method_order_id": 1234567890123456789,
"dry_run": 1,
"agreement": 1
},
"payment_details": {
"payment": {
"currency": "USD",
"amount": 230
},
"vat": {
"currency": "USD",
"amount": 0,
"percent": 20
},
"sales_tax": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"direct_wht": {
"currency": "USD",
"amount": 0,
"percent": 0
},
"payout_currency_rate": "1",
"payout": {
"currency": "USD",
"amount": 200
},
"xsolla_fee": {
"currency": "USD",
"amount": 10
},
"payment_method_fee": {
"currency": "USD",
"amount": 20
},
"repatriation_commission": {
"currency": "USD",
"amount": 10
}
},
"custom_parameters": {
"parameter1": "value1",
"parameter2": "value2"
}
}
```
完整字段列表请参见 [payment 参考 ↗](https://developers.xsolla.com/webhooks/operation/payment)。
### 退款 (refund)
旧模式(分开通知)中的撤销触发 Webhook,也是 [`payment`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#payment) 的对应撤销通知,在退款或拒付时发送。请通过 `transaction.id` 查找原始发放记录,撤销或收回相应权益,并返回 `204`。对已处理过的 `transaction.id` 要跳过,以免重试导致重复撤销。测试退款会带有 `transaction.dry_run: 1`。较新的项目会收到 [`order_canceled`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_canceled) 而不会再收到 `refund`。
与 [`payment`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#payment) 相同,当订单包含 Google 外部交易令牌时,也会携带 `ucb_report` 对象⸺请参见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/#correlating-the-token-with-your-xsolla-order)。 示例
```json
{
"notification_type": "refund",
"settings": {
"project_id": 18404,
"merchant_id": 2340
},
"purchase": {
"total": {
"currency": "USD",
"amount": 9.99
},
"order": {
"id": 1234,
"lineitems": [
{
"sku": "ticket.10",
"quantity": 1,
"price": {
"currency": "USD",
"amount": 9.99
}
}
]
}
},
"user": {
"id": "1234567",
"email": "[email protected]",
"country": "US"
},
"transaction": {
"id": 1,
"external_id": "ext_trans_001",
"payment_date": "2014-09-24T20:38:16+04:00",
"dry_run": 1
},
"refund_details": {
"code": 1,
"reason": "Test refund"
}
}
```
完整字段列表请参见 [refund 参考 ↗](https://developers.xsolla.com/webhooks/operation/refund)。
## 综合示例
下面是一个最小处理程序:验证签名、按 `notification_type` 路由,并返回正确的状态码。各语言选项卡复用[验证签名](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#verifying-the-signature)中的 `verifyXsollaSignature()` 函数: 示例无法内联展示的两点注意
- **选择正确的字段**。`user_validation` 以 `user.id` 标识玩家;`order_paid` / `order_canceled` 使用 `user.external_id`。用错字段是最常见的集成问题。
- **不要因临时故障返回 `4xx`**。如果启用了自动退款,针对 `order_paid` 的 `4xx` 可能触发退款。遇到己侧问题请返回 `5xx`,以便艾克索拉重试。
```js
const express = require('express');
const app = express();
// Raw body is required for signature verification.
app.use('/webhooks', express.raw({ type: 'application/json' }));
app.post('/webhooks', (req, res) => {
const secretKey = process.env.XSOLLA_WEBHOOK_SECRET;
if (!verifyXsollaSignature(req.body, req.get('authorization'), secretKey)) {
return res.status(400).json({
error: { code: 'INVALID_SIGNATURE', message: 'Signature mismatch' },
});
}
const event = JSON.parse(req.body.toString('utf8'));
switch (event.notification_type) {
case 'user_validation':
return userExists(event.user.id)
? res.sendStatus(204)
: res.status(400).json({
error: { code: 'INVALID_USER', message: 'User not found' },
});
case 'order_paid':
if (event.order.mode !== 'sandbox') {
enqueueFulfillment(event); // grant items async; dedupe on event.order.id
}
return res.sendStatus(204);
case 'order_canceled':
if (event.order.mode !== 'sandbox') {
enqueueRevocation(event); // revoke entitlement async; dedupe on event.order.id
}
return res.sendStatus(204);
default:
// Acknowledge unhandled types so Xsolla doesn't retry them.
return res.sendStatus(204);
}
});
```
```php
<?php
// Raw body is required for signature verification.
$rawBody = file_get_contents('php://input');
$authHeader = $_SERVER['HTTP_AUTHORIZATION'] ?? '';
$secretKey = getenv('XSOLLA_WEBHOOK_SECRET');
header('Content-Type: application/json');
if (!verifyXsollaSignature($rawBody, $authHeader, $secretKey)) {
http_response_code(400);
echo json_encode(['error' => ['code' => 'INVALID_SIGNATURE', 'message' => 'Signature mismatch']]);
exit;
}
$event = json_decode($rawBody, true);
switch ($event['notification_type']) {
case 'user_validation':
if (userExists($event['user']['id'])) {
http_response_code(204);
} else {
http_response_code(400);
echo json_encode(['error' => ['code' => 'INVALID_USER', 'message' => 'User not found']]);
}
break;
case 'order_paid':
if ($event['order']['mode'] !== 'sandbox') {
enqueueFulfillment($event); // grant items async; dedupe on order.id
}
http_response_code(204);
break;
case 'order_canceled':
if ($event['order']['mode'] !== 'sandbox') {
enqueueRevocation($event); // revoke entitlement async; dedupe on order.id
}
http_response_code(204);
break;
default:
http_response_code(204); // acknowledge unhandled types so Xsolla doesn't retry
break;
}
```
```csharp
app.MapPost("/webhooks", async (HttpRequest request) =>
{
var secretKey = Environment.GetEnvironmentVariable("XSOLLA_WEBHOOK_SECRET");
using var reader = new StreamReader(request.Body);
var rawBody = await reader.ReadToEndAsync();
var authHeader = request.Headers.Authorization.ToString();
if (!VerifyXsollaSignature(rawBody, authHeader, secretKey))
{
return Results.BadRequest(new { error = new { code = "INVALID_SIGNATURE", message = "Signature mismatch" } });
}
var evt = JsonSerializer.Deserialize<JsonElement>(rawBody);
switch (evt.GetProperty("notification_type").GetString())
{
case "user_validation":
return UserExists(evt.GetProperty("user").GetProperty("id").GetString())
? Results.StatusCode(204)
: Results.BadRequest(new { error = new { code = "INVALID_USER", message = "User not found" } });
case "order_paid":
if (evt.GetProperty("order").GetProperty("mode").GetString() != "sandbox")
EnqueueFulfillment(evt); // grant items async; dedupe on order.id
return Results.StatusCode(204);
case "order_canceled":
if (evt.GetProperty("order").GetProperty("mode").GetString() != "sandbox")
EnqueueRevocation(evt); // revoke entitlement async; dedupe on order.id
return Results.StatusCode(204);
default:
return Results.StatusCode(204); // acknowledge unhandled types
}
});
```
```python
import os
from flask import Flask, request, jsonify
app = Flask(__name__)
@app.post('/webhooks')
def webhooks():
secret_key = os.environ['XSOLLA_WEBHOOK_SECRET']
raw_body = request.get_data() # raw bytes, not parsed
auth_header = request.headers.get('Authorization', '')
if not verify_xsolla_signature(raw_body, auth_header, secret_key):
return jsonify(error={'code': 'INVALID_SIGNATURE', 'message': 'Signature mismatch'}), 400
event = request.get_json()
notification_type = event['notification_type']
if notification_type == 'user_validation':
if user_exists(event['user']['id']):
return '', 204
return jsonify(error={'code': 'INVALID_USER', 'message': 'User not found'}), 400
elif notification_type == 'order_paid':
if event['order']['mode'] != 'sandbox':
enqueue_fulfillment(event) # grant items async; dedupe on order.id
return '', 204
elif notification_type == 'order_canceled':
if event['order']['mode'] != 'sandbox':
enqueue_revocation(event) # revoke entitlement async; dedupe on order.id
return '', 204
else:
return '', 204 # acknowledge unhandled types so Xsolla doesn't retry
```
```go
func webhookHandler(w http.ResponseWriter, r *http.Request) {
secretKey := os.Getenv("XSOLLA_WEBHOOK_SECRET")
rawBody, _ := io.ReadAll(r.Body)
w.Header().Set("Content-Type", "application/json")
if !verifyXsollaSignature(rawBody, r.Header.Get("Authorization"), secretKey) {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{"code": "INVALID_SIGNATURE", "message": "Signature mismatch"},
})
return
}
var event struct {
NotificationType string `json:"notification_type"`
User struct{ ID string `json:"id"` } `json:"user"`
Order struct{ Mode string `json:"mode"` } `json:"order"`
}
json.Unmarshal(rawBody, &event)
switch event.NotificationType {
case "user_validation":
if userExists(event.User.ID) {
w.WriteHeader(http.StatusNoContent)
} else {
w.WriteHeader(http.StatusBadRequest)
json.NewEncoder(w).Encode(map[string]any{
"error": map[string]string{"code": "INVALID_USER", "message": "User not found"},
})
}
case "order_paid":
if event.Order.Mode != "sandbox" {
enqueueFulfillment(rawBody) // grant items async; dedupe on order.id
}
w.WriteHeader(http.StatusNoContent)
case "order_canceled":
if event.Order.Mode != "sandbox" {
enqueueRevocation(rawBody) // revoke entitlement async; dedupe on order.id
}
w.WriteHeader(http.StatusNoContent)
default:
w.WriteHeader(http.StatusNoContent) // acknowledge unhandled types
}
}
```
```java
@RestController
public class WebhookController {
@PostMapping("/webhooks")
public ResponseEntity<?> handle(
@RequestBody final byte[] rawBody,
@RequestHeader(value = "Authorization", required = false) final String authHeader)
throws Exception {
final String secretKey = System.getenv("XSOLLA_WEBHOOK_SECRET");
if (!verifyXsollaSignature(rawBody, authHeader, secretKey)) {
return ResponseEntity.badRequest().body(
Map.of("error", Map.of("code", "INVALID_SIGNATURE", "message", "Signature mismatch"))
);
}
final JsonNode event = new ObjectMapper().readTree(rawBody);
switch (event.get("notification_type").asText()) {
case "user_validation":
return userExists(event.get("user").get("id").asText())
? ResponseEntity.noContent().build()
: ResponseEntity.badRequest().body(
Map.of("error", Map.of("code", "INVALID_USER", "message", "User not found")));
case "order_paid":
if (!"sandbox".equals(event.get("order").get("mode").asText())) {
enqueueFulfillment(event); // grant items async; dedupe on order.id
}
return ResponseEntity.noContent().build();
case "order_canceled":
if (!"sandbox".equals(event.get("order").get("mode").asText())) {
enqueueRevocation(event); // revoke entitlement async; dedupe on order.id
}
return ResponseEntity.noContent().build();
default:
return ResponseEntity.noContent().build(); // acknowledge unhandled types
}
}
}
```
## 最佳实践与测试
- **在进行任何其他操作前先[验证签名](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#verifying-the-signature)**。对不匹配的签名以 **`400`** `INVALID_SIGNATURE` 拒绝。
- **快速响应,异步处理**。验证后立即返回 `204`,然后在后台队列中执行业务逻辑(发放商品、数据库写入)。艾克索拉建议处理程序在 1–3 秒内响应;失败时会在 12 小时内[重试](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#retries)最多 20 次。
- **预期同一个 Webhook 会收到两次**。例如发生超时后,艾克索拉可能多次投递。 请记录已处理的 `transaction.id` 或 `order.id` 并忽略重复请求,避免向玩家重复发放商品。
- **处理测试交易**。发布商帐户可发送真实 Webhook 进行测试⸺[`payment`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#payment) 以 `transaction.dry_run: 1` 标记,[`order_paid`](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks#order_paid) 以 `order.mode: "sandbox"` 标记。签名同样有效,但不会发生资金流转。对此请跳过状态变更(发放商品、数据库写入),或将其路由到沙盒路径。
- **结合源 IP 限制作为纵深防御**,与签名校验配合使用。艾克索拉从 `185.30.20.0/24`–`185.30.23.0/24` 以及一组 Google Cloud IP 发送 Webhook;在依赖该列表前,请参见[官方列表 ↗](https://developers.xsolla.com/webhooks/overview)以获取权威且最新的 IP 集合。
- **测试易错点**:如果使用 `webhook.site` 或类似请求查看工具,它会对所有请求返回 `200`⸺无法产生艾克索拉期望的签名错误响应 `400`。请使用真实处理程序测试签名拒绝逻辑。
## 替代方案:通过 Events API 实现无服务器
**艾克索拉 Events API** 是针对无后端项目的 Webhook 替代方案。艾克索拉不会向您的服务器 POST 事件,而是在其服务器侧存储事件载荷,由 SDK 直接在应用内拉取⸺因此整个交易流程可以在客户端侧完成。 事件API 与 Webhook 互斥
选择使用**艾克索拉事件API** 会**禁用**项目的 **Webhook**⸺两者不能同时使用。 ![发布商帐户中的 Events API 设置]
为项目启用 Events API:
- 在发布商帐户中打开您的项目。
- 在侧边栏,选择**项目设置**。
- 打开**集成设置**选项卡。
- 选择**使用 API** 并点击**保存**。
要以 Events API 模式初始化 SDK,请参见各平台指南:
- [**Android**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#xsolla-events-api)
- [**iOS**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/#using-xsolla-events-api-for-restoration)
- [**Unity**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#using-xsolla-events-api-for-restoration)
- [**Windows**](https://developers.xsolla.com/sdk/zh/windowstores/sdk/configuration/#events)
支持的 Webhook 类型完整列表,请参见[艾克索拉 Webhook 参考 ↗](https://developers.xsolla.com/webhooks/overview)。
各位开发者好,欢迎了解艾克索拉 SDK 3。
https://developers.xsolla.com/sdk/zh/technical-articles/intro-to-sdk3-integrations
![艾克索拉 SDK 3 横幅]
各位开发者好!我们是艾克索拉开发者关系团队。在这篇博文中,我们想向您介绍我们最新一代软件开发工具包⸺艾克索拉 SDK 3。只需一次简单集成,不到 15 分钟即可为您的移动端和 PC 游戏接入变现能力。
此前的艾克索拉 SDK 在每个集成目标平台上都重复实现了相同的逻辑。SDK 3 将这部分逻辑整合进单一原生核心,把各平台集成简化为构建于其上的轻量封装层⸺一次实现,多端绑定。结算流程也遵循同一原则:我们不再内置自有浏览器,而是直接调用操作系统原生提供的界面进行渲染,并将外链跳转作为核心主流程而非兜底方案。
借助 SDK 3,只需简单四步即可为游戏接入变现能力,开始售卖增益道具、皮肤、装备以及任何契合您游戏设计的商品:**身份认证**、**加载商品目录**、**发起购买**、**完成交易**。
## 集成指南
为便于您上手,我们准备了覆盖多种平台和引擎的材料,带您完成集成。
欢迎点击下方链接观看视频教程……
- [Unity 移动端版 SDK 3](https://youtu.be/wbfAUmP_v-s?si=DrNdxBc283VfMqwc)
- [Unity PC 版 SDK 3](https://youtu.be/hnOibNa6XOI?si=U2QEBzG7SqqR1Agq)
- [原生 iOS 版 SDK 3](https://youtu.be/L2C1zoAAjFY?si=zB23GdkzTubiGmzO)
- [原生 Android 版 SDK 3](https://youtu.be/-G0ly2yck-8?si=cFZndIE76iLsS-GK)
- [Unreal Engine (PC) 版 SDK 3](https://youtu.be/zbnJbwVVi9s)
……如果您更喜欢图文阅读,以下文章涵盖了与上述视频一致的内容:
- [Unity 移动端版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-mobile/)
- [Unity PC 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-unity-pc/)
- [Unity Web 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-web/)
- [原生 iOS 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-ios/)
- [原生 Android 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-native-android/)
- [Unreal Engine (PC) 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unreal-pc/)
## 平台合规
**iOS**:根据 2025 年 4 月 30 日美国法院的裁决,开发者可在 iOS 应用中加入外部支付链接。移动端专用艾克索拉 SDK 完全符合 Apple 修订后的 App Store 指南,既支持应用内支付收银台流程,也支持通过网充商店完成外链跳转支付。
**Android**:根据 2025 年 10 月 29 日 Epic 诉 Google 案禁令,美国区 Google Play 应用可使用官方支付体系之外的支付方案与外部支付链接,且不再受反引导限制约束。该 SDK 支持商店外 APK 分发、Google Play Billing 以及基于浏览器的结算流程⸺一次集成即可全部覆盖。
## SDK Explorer
想在一款真正可玩的完整游戏里直观体验 SDK 3 的实际运行效果吗?不妨试试 SDK Explorer,实时了解 SDK 3 的工作机制。您可以自由选择目标平台、编程语言或游戏引擎,一边试玩我们的 Pizza Shop 模拟游戏,一边直观查看底层实时发生的接口调用。
- [SDK Explorer 演示](https://developers.xsolla.com/sdk/demo/)
## 开始使用
准备就绪后,第一步是创建发布商帐户。(没错,发布商帐户同样面向开发者开放⸺毕竟现在人人都是发布商!)整个过程只需几秒钟。
- [创建发布商帐户](https://publisher.xsolla.com/)
## 繁杂事务交给我们
艾克索拉业务覆盖全球 200 多个国家和地区,支持 130 多种货币与 1000 多种支付方式。作为您的登记商户 (Merchant of Record),我们会为您处理税务、区域法律合规、反欺诈防护等各项事务。艾克索拉替您打理商业变现的繁琐环节,让您全身心投入最擅长的事:打造出色的好游戏。
## 敬请期待
感谢阅读至此。请持续关注艾克索拉 DevRel 团队发布的更多 SDK 3 内容,涵盖更多引擎与平台,以及其他帮助您构建游戏并拓展业务的产品与解决方案。
原生 Android — 艾克索拉 SDK 3 集成指南
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-3-native-android
![a65e3689-3367-4c52-9fc7-5ecadeb0880c.png]
## 在原生 Android 游戏中集成艾克索拉 SDK 3
接入流畅且安全的结算体验,完全不必打乱游戏的开发进度。本指南将为您详细拆解如何在原生 Android 游戏中集成艾克索拉 SDK,快速跑通游戏内变现流程。
完成本教程后,您将在 Android 上获得完整可用的艾克索拉支付流程。我们将介绍:
- **核心参考资料**:快速定位所需文档,告别盲目摸索,高效启动集成。
- **整体流程演练**:将 SDK 分步接入原生代码库的实操指南。
- **上线生产准备**:介绍配置艾克索拉发布商帐户以及将游戏从测试切换 到正式上线的关键步骤。
无论是想在游戏结束界面提供生命值恢复等即时购买选项,还是搭建完善的虚拟商店,本分步指南都能为您提供原生处理全球支付的基础方法。
## 先决条件
开始编码前,请确认开发环境满足基础要求。预先准备好这些要素可以让集成过程更顺畅。
### 开发要求
- **Android SDK**:最低 API 等级 24 (Android 7.0, Nougat) 或更高版本。
- **Java Development Kit (JDK)**:11 或更高版本。
- **Android Studio**:不仅提供强大的 IDE 功能,还包含完整的 Gradle 与 SDK 工具链。
- **现有游戏架构**:假设您已有可运行的原生 Android 项目,并备好可触发支付流程的特定 UI 元素(如商店菜单、游戏结束弹窗或结算按钮)。本文仅聚焦 SDK 接入实现,不涉及从零搭建游戏 UI。
### 艾克索拉基础设施
- **艾克索拉发布商帐户**:有效的帐户必不可少,尤其是在您准备将项目上线至生产环境时。如果尚未创建,请前往艾克索拉发布商帐户注册页面。
**沙盒环境**:无需今天填完完整的商户资料就能直接上手。为简化流程,本教程使用**艾克索拉沙盒环境**,无需提前配置正式生产帐户即可端到端测试完整的购买流程。如需查看发布商帐户完整管理的分步指南,请参阅艾克索拉官方配置文档。
## 我们要实现什么
为在真实场景中演示艾克索拉 SDK 3 的集成,本指南采用一个简洁直观的演示项目:完全使用原生 Java 编写的经典 Android 点击类游戏。保持核心玩法简单,便于我们将全部精力聚焦在底层变现代码上,而不必陷入复杂的游戏循环。
![c089ee5f-45c8-401d-a064-6e2416f7e61b.png]
Simple Clicker 游戏
### 演示游戏机制
示例应用的循环围绕以下基本交互展开:
- **核心动作**:玩家点击屏幕中央的大型金币图标,手动生成并积累虚拟货币。
- **渐进式升级**:玩家可使用积累的金币购买两类道具来加快进度: - **Click Multiplier**:提高每次点击的收益,提升手动收集效率。 - **Auto-Collector**:随时间自动收集金币,带来被动收益增长。
### SDK 集成触发点
盈利逻辑在付费商店按钮处触发。玩家点击购买按钮以获取付费物品或捆绑包时,应用会初始化艾克索拉支付流程。
应用无需将玩家跳转至外部网页浏览器,而是直接调用艾克索拉 SDK。不到一秒,安全的结算界面就会叠加显示在游戏画面上方,让玩家通过艾克索拉沙盒环境完成完整交易。
接下来的小节中,我们将打开代码库,逐一查看需要修改哪些文件和类,真正跑通这套原生结算体验。
## 参考资源
在编写代码前,建议先打开几页关键文档。将这些参考资料与 IDE 并排放置可以大幅节省时间,艾克索拉为原生 Android 环境提供了预构建的代码片段。
### 1. 中心入口:艾克索拉 SDK 站点
首选入口:[developers.xsolla.com/sdk](https://developers.xsolla.com/sdk)。该门户提供 SDK 核心能力、跨平台架构和关键集成用例的完整概览。
### 2. SDK Explorer 与 Integration Widget
最实用的辅助工具当属 [**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) 及其 Integration Widget。[Integration Widget](https://developers.xsolla.com/sdk/integration-widget) 既是艾克索拉 SDK 站点上的独立页面,也是 SDK Explorer 内置的选项卡,提供每个集成步骤完整可用的现成代码。在本指南中,我们会频繁借助该小组件获取整洁、可直接投入生产的 Java 代码块,直接复制粘贴到项目文件中。
### 3. Android 快速开始指南
要找到本教程使用的精确代码实现,请在侧边栏按以下路径导航:
[移动端 → 快速开始 → Android](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android)
该小节提供基础的原生代码块。我们将说明如何使用这些资源来实现两个主要目标:
- 在本地加载并渲染虚拟物品商品目录。
- 为玩家触发安全的原生沙盒结算流程。
**后续指引**:建议同时留意**发布商帐户**文档章节。虽然眼下的重点是通过沙盒先把本地 Android 代码跑通,但后续将游戏正式上线时,该章节会作为分步路线图,指导您在发布商帐户运营看板中初始化项目、配置商品并关联凭据。
## 第 0 步:设置艾克索拉 SDK 包
在实现支付功能之前,需要将艾克索拉 SDK 引入 Android 项目。跨平台工具(如 Unity)使用 Package Manager UI,原生 Android 则通过 Gradle 管理依赖。
我们将对项目的 Gradle 文件进行两处快速配置,然后在主 Activity 中添加一个关键的导入语句。
![de35ba8c-73fe-46c8-ae7b-44b342424f58.png]
设置开发工作区
### 1. 更新 settings.gradle
首先,确保项目能找到艾克索拉的包仓库。打开 `settings.gradle` 文件,确认在 repositories 区块中包含 `mavenCentral()`:
```java
// settings.gradle
repositories {
mavenCentral()
maven {
url = uri("https://raw.githubusercontent.com/xsolla/xsolla-sdk-android/main")
}
}
```
### 2. 配置 build.gradle(模块:app)
接着,打开模块级 `build.gradle` 文件,滚动到 `dependencies` 区块。在这里指定要使用的 SDK 版本并添加实现依赖行。
撰写本指南时使用的版本为 **3.0.37**。在 dependencies 中添加以下行:
```java
// build.gradle
dependencies {
def version_mobilesdk = '<version>' // '3.0.37'
implementation "com.xsolla.android:mobile:$version_mobilesdk"
}
```
将版本号定义为变量 (`def version_mobilesdk`) 可让构建文件更整洁,也便于后续升级 SDK。
### 3. 在主 Activity 中导入包
修改 Gradle 文件后,同步项目。为正式将 SDK 与游戏代码连接,打开主 Java Activity 文件(例如 `MainActivity.java`),在文件顶部添加艾克索拉包的核心导入语句:
```java
//MainActivity.java
import com.xsolla.android.mobile.*;
```
添加该行后,您的原生项目就已与艾克索拉 SDK 完整连接,可以开始编写初始化逻辑。
## 第 1 步:身份认证
安装好 SDK 包后,第一个正式集成里程碑是身份认证。艾克索拉 SDK 要求在应用启动时立即初始化有效配置。这一步会与艾克索拉服务建立安全连接,告知系统当前处于测试模式还是正式交易模式,并准备好结算客户端以响应用户交互。
### 设置代码上下文
在原生 Android 环境中,此初始化逻辑位于主 Activity 的生命周期中。打开主游戏 Activity 文件,定位到 `onCreate()` 方法。
前往艾克索拉 [**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget),切换到 **Authentication** 选项卡,复制现成可用的配置代码片段,直接粘贴到 `onCreate()` 方法中:
```java
import com.xsolla.android.mobile.*;
@Nullable
private BillingClient mBillingClient;
final Config.Common configCommon = Config.Common.getDefault()
.withDebugEnabled(true)
.withLogLevel(LogLevel.VERBOSE)
.withSandboxEnabled(true);
final Config.Integration configIntegration = Config.Integration.forXsolla(
Config.Integration.Xsolla.Authentication.forAutoJWT(
ProjectId.parse(301871).getRightOrThrow(), // Test project
LoginUuid.parse("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a").getRightOrThrow() // Test login ID
)
);
final Config config = new Config(
configCommon,
configIntegration,
Config.Payments.getDefault(),
Config.Analytics.getDefault()
);
// Inside onCreate(), after creating Config:
mBillingClient = BillingClient.newBuilder(this)
.setConfig(config)
.setListener((billingResult, purchases) -> {
// Handle purchase completion - see Finalize Purchase
})
.build();
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "Disconnected from Xsolla services.");
}
@Override
public void onBillingSetupFinished(@NonNull final BillingResult billingResult) {
if (!billingResult.isSuccessful()) {
Log.e(TAG, "Connection failed: " + billingResult.getResponseCode());
return;
}
}
});
```
**切换到生产环境**:在本次点击类游戏演示中,使用默认演示 ID 即可立即运行。但当您准备将游戏正式上线时,必须登录艾克索拉发布商帐户,查找专属的**项目 ID** 和**登录管理器 ID**,并替换到该配置块中。如需了解自定义身份提供商路由等进阶选项,请参阅艾克索拉官方配置文档。
## 第 2 步:加载商品目录
游戏成功连接艾克索拉服务后,下一步是拉取虚拟商店数据。艾克索拉 SDK 从云端动态管理商品目录,这意味着您在发布商帐户运营看板中对商品名称、图片或区域定价所做的任何修改,都会在游戏内自动更新,无需重新发版更新应用。
### 实现商品目录查询
要获取物品库详情,需针对待展示的特定商品 ID 构建查询请求。
```java
mBillingClient.queryProductDetailsAsync(
QueryProductDetailsParams.newBuilder()
.setProductList(Arrays.asList(
QueryProductDetailsParams.Product.newBuilder()
.setProductId("money.100") // Test product SKU
.setProductType(BillingClient.ProductType.INAPP)
.build()
))
.build(),
(billingResult, productDetailsList) -> {
// Launch purchase - see Purchase Product
}
);
```
## 第 3 步:购买商品
本地商品目录加载完成后,即可使用这些数据发起真实交易。当玩家在商店界面中点击某件商品时,艾克索拉 SDK 会接管后续复杂处理,拉起名为**艾克索拉支付收银台**的安全浮层界面,让用户直接在应用内原生使用超过 1000 种本地化支付方式。
### 启动结算流程
要启动结算流程,请将第 2 步商品目录查询返回的 `ProductDetails` 对象传入 SDK 的结算流程方法。
在 Integration Widget 的 **Purchase Product** 选项卡获取初始化片段,并把它绑定到商店按钮的点击监听器:
```java
// Inside productDetails callback (from Load Catalog):
if (billingResult.isSuccessful() &&
productDetailsList != null && !productDetailsList.isEmpty()) {
mBillingClient.launchBillingFlow(
activity, // Your Activity reference
BillingFlowParams.newBuilder()
.setProductDetailsParamsList(Arrays.asList(
BillingFlowParams.ProductDetailsParams.newBuilder()
.setProductDetails(productDetailsList.get(0))
.build()
))
.build()
);
} else {
Log.e(TAG, "No products available: " + billingResult.getResponseCode());
}
```
### 模拟完成一笔交易
由于我们在**第 1 步**启用了沙盒模式,您可以立即测试完整支付闭环,而无需担心信用卡被实际扣费。当支付收银台界面滑入屏幕时,选择 **Credit/Debit Card** 选项,并使用艾克索拉提供的官方模拟测试卡信息:
| 卡组织 | 测试卡号 | 有效期 | 安全码 (CVV) |
| --- | --- | --- | --- |
| Visa | 4111 1111 1111 1111 | 任意将来的日期 | 任意 3 位数字 |
| Mastercard | 5555 5555 5555 4444 | 任意将来的日期 | 任意 3 位数字 |
输入这些信息会模拟一次成功且已清算的授权流程,SDK 随后会向您的应用状态返回成功令牌。
## 第 4 步:完成购买
变现闭环的最后一环是监听交易结果,并将虚拟物品安全发放给玩家。拉起结算界面只是成功了一半;当玩家填完账单信息后,游戏还必须监听艾克索拉服务器返回的回调。
购买成功完成后,核销该交易令牌并向用户发放商品。
```java
// Inside onPurchasesUpdated callback:
if (billingResult.isSuccessful() && purchases != null) {
for (Purchase purchase : purchases) {
mBillingClient.consumeAsync(
ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build(),
(billingResult, purchaseToken) -> {
if (billingResult.isSuccessful()) {
Log.d(TAG, "Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
} else {
Log.e(TAG, "Consumption failed: " + billingResult.getResponseCode());
}
}
);
}
} else {
Log.e(TAG, "Purchase failed or cancelled: " + billingResult.getResponseCode());
}
```
![a9148935-8a90-4a4e-a5da-17c6a187ed22.png]
艾克索拉支付收银台
### 验证并核销
该步骤会完成交易核销,随后即可安全地向玩家发放虚拟物品。如需排查异常场景或探索进阶实现方式,请参阅官方[购买流程文档](https://developers.xsolla.com/sdk/mobilesdk/sdk/purchase/android)。
## 下一步
恭喜!您已经掌握了原生 Android 游戏集成艾克索拉 SDK 的完整实现方案。虽然点击类示例游戏展示了核心闭环,但要将本地沙盒原型真正推向全球商业化市场,还需要完成几项关键升级。
以下是将实现提升到新层级的路线图:
### 1. 动手练习:扩展示例
如果您想研究一份完整的独立实现,请返回 [Android 快速开始指南](https://developers.xsolla.com/sdk/mobilesdk/quick-start/android),滚动到页面底部查看[**扩展示例**](https://developers.xsolla.com/sdk/mobilesdk/quick-start/extended-examples/android-example)。
- **关键区别**:应用启动后会立即弹出支付收银台覆盖层。它是一个极佳的独立沙盒,可用于复制、粘贴并测试您的环境变量,不受外部代码干扰。
### 2. 使用服务端 Webhook 保障经济体系安 全
虽然本地客户端侧确认适用于初期原型,但生产版本绝不应完全依赖设备来校验支付。
- **升级建议**:为降低欺诈风险,建议将后端架构升级为使用[**艾克索拉 Events API**](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api) 或基于 Webhook 的服务端验证,确保在发放物品前通过服务器到服务器方式安全核验每笔交易。
- 注:如需针对您的业务架构正确配置 Webhook 或 Events API,可直接在发布商帐户运营看板中完成设置,或发送邮件联系客户团队:[[email protected]](mailto:[email protected])。
### 3. SDK Explorer
为充分发挥本指南的作用,建议将[艾克索拉 SDK Explorer](https://developers.xsolla.com/sdk/demo/) 及其 [Integration Widget](https://developers.xsolla.com/sdk/integration-widget) 与 IDE 并排打开。该小组件可作为代码底座,提供每个里程碑所需的完整 Java 代码片段。在将代码直接复制粘贴进游戏文件的同时,我们还可以借助功能更全面的 SDK Explorer 配置凭据,并随时查看事件响应行为。
![db34d3d6-4715-424d-b60d-f0303c8a9095.png]
SDK Explorer - Integration Widget 视图(大图)
### 4. 注册成为发布商
最关键的下一步是走出代码编辑器,确立您的线上阵地。前往发布商帐户页面,注册您的官方[**发布商帐户**](https://publisher.xsolla.com/)。
在发布商帐户看板中,按照简单向导完成以下事项:
- 生成永久可用的正式环境**项目 ID** 和**登录管理器 ID**。
- 搭建真实的虚拟商店商品目录,将通用测试键值替换为实际的付费物品、美术素材和商品描述。
- 定制**支付收银台**界面外观,使其契合游戏的品牌视觉风格。
官方文档对发布商帐户看板中的每个功能开关都提供了分步指南。请花时间探索这些工具;如果遇到问题,可依靠活跃的开发者社区。祝您在全球市场成功发布游戏!
原生 iOS — 艾克索拉 SDK 3 集成指南
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-3-native-ios
**将艾克索拉 SDK 3 集成到您的原生 iOS 游戏中**
面向 Swift 开发者的分步指南:身份认证、加载商品目录、购买商品与购买验证。
## 简介
艾克索拉 SDK 3 让原生 iOS 游戏能够直接接入艾克索拉支付基础设施⸺无需弃用现有的 StoreKit。如果您已有基于 StoreKit 的项目,该 SDK 会以轻量封装层的形式接入熟悉的 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) API,在您已掌握的流程之上无缝叠加身份认证、支付收银台与购买验证能力。
本指南分四个独立步骤完整演示整个集成流程:身份认证、加载商品目录、购买商品与完成交易。每一步都会同时讲清“怎么做”和“为什么这样做”,帮助您真正吃透整套集成逻辑⸺而非只是机械地复制粘贴代码。 **[SDK Explorer](http://developers.xsolla.com/sdk/demo)**
艾克索拉提供了一 个基于浏览器的实时交互演示,完整还原 iOS 端的实际集成流程。
如需按本文场景配置该演示,请点击屏幕顶部中央的设置按钮,并选择以下配置:
**平台** — iOS **国家/地区** — 美国
- **平台** — iOS
- **国家/地区** — 美国
- **商店** — App Store
- **引擎** — 无
- 关闭**使用服务器登录**
- **Webhook 模式** — 关闭
- **购买按钮** — 关闭
- **浏览器模式** — 外部
然后点击**应用更改**。
![6520bb66-2475-436b-8372-4b5e9fe9ceb9.png]
![0b3bd016-af0e-4c61-bc0d-b3905b4666be.png]
## 先决条件
开始前,请确认:
- **Xcode** — 当前稳定版本。艾克索拉 Mobile SDK 支持 iOS 12.0+,但部分 Apple 外部购买 (External Purchase) 功能需要 iOS 17.5+。
- **Swift 或 SwiftUI iOS 项目** — 面向 iPhone 和 iPad,已正确配置 StoreKit,且已在 [App Store Connect](https://appstoreconnect.apple.com/) 中注册产品标识符。
- **艾克索拉发布商帐户** — 用于创建商品目录,并获取项目 ID 与登录管理器项目 ID。可在 [publisher.xsolla.com](https://publisher.xsolla.com/) 注册。
- **备妥各项 ID** — 项目 ID(纯数字)与登录管理器项目 ID (UUID)。可在[发布商帐户](https://developers.xsolla.com/sdk/publisher-account/getids)中查看:项目 ID 显示在项目名称旁;登录管理器项目 ID 位于**玩家管理 → 登录管理器 → 运营看板**下。
**注意 ID 的准确性**:填错项目 ID 或登录管理器项目 ID 时连接仍会显示成功⸺但 SDK 会返回空结果。排查其他问题前,请务必先核对这两个 ID。
## 安装
通过 [Swift Package Manager](https://www.swift.org/documentation/package-manager/) 添加[艾克索拉 Mobile SDK](https://github.com/xsolla/xsolla-sdk-ios):
##### 1. 在 Xcode 中,依次选择 File → Add Package Dependencies…
![caeb2128-feed-4a29-8c6f-72456b46f2e3.png]
##### 2. 搜索以下仓库 URL:
`https://github.com/xsolla/xsolla-sdk-ios`
![e4fd1a85-ca1a-43c3-9b51-f340e340f870.png]
##### 3. 将依赖规则设置为 Up to Next Major Version(如 3.8.0),然后点击 Add Package。
##### 4. 在软件包产品对话框中选择 XsollaMobileSDK,并将其添加到目标 Target。
![2ef2a327-67ce-4bee-8c65-c69a11e32b05.png]
如果您改为通过 Package.swift 管理依赖:
```swift
// Package.swift
dependencies: [
.package(url: "https://github.com/xsolla/xsolla-sdk-ios", from: "3.9.2")
],
targets: [
.target(
name: "YourTarget",
dependencies: [
.product(name: "XsollaMobileSDK", package: "xsolla-sdk-ios")
]
)
]
```
## 第 1 步:身份认证
在 SDK 3 中,身份认证通过传入 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) 的设置对象完成。该对象在单次初始化调用中桥接了艾克索拉的身份认证层与 StoreKit⸺并非替换 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue),而是在其基础上进行扩展。
### 创建 SKPaymentSettings 对象
导入 XsollaMobileSDK,并使用项目 ID、登录管理器项目 ID 及目标平台构建 [SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) 对象。请将其放在应用的初始化路径中⸺[AppDelegate.application(_:didFinishLaunchingWithOptions:)](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) 是最理想的位置。
```swift
import XsollaMobileSDK
let settings = SKPaymentSettings(
projectId: YOUR_PROJECT_ID, // Numeric, from Publisher Account
loginProjectId: "YOUR-LOGIN-UUID", // UUID string, from Login → Dashboard
platform: .standalone // Use .standalone for mobile
)
// Required: enable payments (false = silent no-op on purchase attempts)
settings.enablePayments = true
// Required for U.S. storefronts: opens Pay Station in external Safari
settings.openExternalBrowser = true
// Enable during development and testing only
settings.useSandbox = true
// Pass into SKPaymentQueue on start and connect SKPaymentTransactionObserver
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
```
**`.enablePayments = false` 会导致静默失败**:如果 enablePayments 为 false,购买调用看似成功,但实际上不会执行任何操作⸺无报错、无回调、无日志。由于该属性默认值为 false,请务必显式设为 true。 **💡 最佳实践:按构建配置切换设置**
相较于硬编码 `false` 或 `true`,建议基于 Development 与 Release 构建配置的环境属性进行切换。
```text
useSandbox = ProcessInfo.processInfo.environment["XSOLLA_SANDBOX"] == "1"
```
**外部浏览器与美国区合规**:自 2025 年 4 月 30 日起,在美国 区 App Store 分发的应用必须在 Safari 中打开外部支付链接(而非应用内 Web 视图)。请设置 `.openExternalBrowser = true` 以满足合规要求。在欧盟地区,两种方式均受支持:设为 `false` 可将支付收银台保留在应用内,设为 `true` 则跳转至外部网页。Apple 对这两种方式收取的佣金费率不同,详见 [Payment options on the App Store in the EU](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu/)。如需按地区动态配置,请参阅[商店地区检测文档](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront)。
### 客户端侧匿名身份认证
对于无需帐户系统的游戏,SDK 3 支持通过自定义用户 ID 实现基于设备的匿名身份认证。该 ID 可以是任意稳定且唯一的字符串⸺例如设备标识符、首次启动时生成的 UUID 或玩家代号。
关键要求是持久化:该 ID 必须在应用重启后仍然可用,以便艾克索拉在多个会话之间识别同一用户。[UserDefaults](https://developer.apple.com/documentation/foundation/userdefaults) 适合承载该值:
```swift
// Generate Player ID once and persist to UserDefaults
func resolvedPlayerID() -> String {
let key = "xsolla_player_id"
if let existing = UserDefaults.standard.string(forKey: key) {
return existing
}
let newID = UUID().uuidString
UserDefaults.standard.set(newID, forKey: key)
return newID
}
settings.customUserId = resolvedPlayerID()
```
如果您的游戏已接入艾克索拉登录管理器,也可以直接提供登录 JWT:
```swift
// When using Xsolla Login for account management
settings.customLoginToken = yourXsollaLoginJWT
```
**💡 最佳实践:用 Provider 类封装设置**
与其将 SDK 初始化逻辑分散在代码 库各处,不如将其封装到专门的商店管理类中。这样更便于测试、Mock 与后续扩展⸺当您需要通过编译标志同时支持沙盒模式与正式模式时尤为实用:
```swift
class XsollaStoreProvider {
init(projectId: Int, loginProjectId: String, sandbox: Bool) {
// Create SKPaymentSettings object
let settings = SKPaymentSettings(
projectId: projectId,
loginProjectId: loginProjectId,
platform: .standalone
)
// Configure settings
settings.enablePayments = true
settings.openExternalBrowser = true
settings.useSandbox = sandbox
settings.customUserId = resolvedPlayerID()
// Start SKPaymentQueue and connect observer
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(transactionObserver)
}
}
```
### 配置 URL Scheme 与重定向处理
支付收银台与艾克索拉登录管理器会在支付和身份认证流程完成后,通过深度链接将用户带回应用。您必须注册一个 URL Scheme,并在设置对象中完成绑定。
在 Xcode 中,选择目标 → Info 选项卡 → URL Types 区域。新增一条记录,并将 URL Scheme 设为您的 Bundle ID(如 com.yourcompany.yourgame)。也可以使用变量 $(PRODUCT_BUNDLE_IDENTIFIER),以自动跟随目标的标识符。
![ea960ecd-33e1-4c32-b6ee-ce71ecb42537.png]
然后在设置对象中接入这些重定向:
```swift
let bundleID = Bundle.main.bundleIdentifier ?? "com.yourcompany.yourgame"
// Pay Station returns here after a completed purchase
settings.payments.redirectUrl = "\(bundleID)://xsolla_confirm/payment"
// Xsolla Login returns here after authentication callbacks
settings.redirectUrl = "\(bundleID)://auth/callback"
```
最后,在您的 [app delegate](https://developer.apple.com/documentation/uikit/uiapplicationdelegate/application(_:didfinishlaunchingwithoptions:)) 或 scene delegate 中将传入的 URL 转发给支付队列:
```swift
// For AppDelegate
func application(_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
SKPaymentQueue.default().open(url)
return true
}
// For SwiftUI scene lifecycle
// Add .onOpenURL { url in SKPaymentQueue.default().open(url) }
// to your root view
```
**💡 最佳实践:预热支付收银台连接**
首次购买时冷启动支付收银台可能需要数秒。DNS 解析、TLS 握手以及启动 [SFSafariViewController](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller) 都会叠加延迟。在较慢网络下,这个延迟足以让玩家质疑是否已点击成功。
预热连接可以消除绝大部分延迟。核心思路是在应用启动时⸺即玩家打开商店之前⸺提前预热网络栈并完成艾克索拉身份 认证握手。[SFSafariViewController.prewarmConnections(to:)](https://developer.apple.com/documentation/safariservices/sfsafariviewcontroller/prewarmconnections(to:)) 自 iOS 15 起可用:
```swift
import SafariServices
class XsollaStoreProvider {
private var prewarmSessions: [URLSessionDataTask] = []
func prewarm() {
// 1. Pre-warm Safari's network connections to Xsolla endpoints
let endpoints = [
"https://secure.xsolla.com",
"https://sandbox-secure.xsolla.com" // include in debug builds
]
let urls = endpoints.compactMap { URL(string: $0) }
prewarmSessions = SFSafariViewController.prewarmConnections(to: urls)
// 2. Trigger catalog load early to warm the auth handshake
loadProducts()
}
}
```
在应用初始化期间调用 `prewarm()`,而不是在打开商店 UI 时调用。目标是在玩家点击购买按钮前,连接已处于预热状态。
## 第 2 步:加载商品目录
在展示价格或发起购买前,应用需要先从 Apple 获取对应的 [SKProduct](https://developer.apple.com/documentation/storekit/skproductsrequest) 对象。SDK 3 并未新增独立的商品目录 API⸺您依然使用标准的 [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest)。SDK 在此环节的作用,是确保应用中的产品标识符与艾克索拉发布商帐户中注册的商品保持一致。
### 在发布商帐户中创建商品
登录[发布商帐户](https://publisher.xsolla.com/),选择您的项目并前往商品管理页面。
![342d483c-3495-4eae-b4fd-79ec1ce3d25d.png]
在 SDK 3 原生集成中,必须使用**虚拟物品**类型⸺其他商品类型(如**虚拟货币套餐**)不会通过 SDK 的 StoreKit 路径返回。
![d8093b98-f877-459e-9aa0-18bbf485991c.png]
每个商品需要提供:
- 与 `.storekit` 配置中某个条目匹配的 SKU
- 名称、描述,以及可选的图片
- 默认价格(例如入门套餐 0.99 美元)
![751b1805-3309-40e7-b130-1618c76cb5bd.png]
您可以手动配置商品目录、通过 JSON 导入,或直接从 [App Store Connect](https://appstoreconnect.apple.com/) 或 Google Play 迁移导入。商品目录配置完成后,请在测试前将所有商品状态切换为“可用”。
状态必须设置为**可用**⸺不可用的商品会被静默排除在查询结果之外。
![a49732cc-cce2-492f-a8a4-b3dcc51c830d.png]
### 通过 SKProductsRequest 请求商品
完成身份认证初始化后,使用待加载的一组 SKU 创建 [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest)。产品标识符区分大小写⸺必须与 [App Store Connect](https://appstoreconnect.apple.com/) 及发布商帐户商品目录中的配置完全一致。
**在开发阶段记录 `.invalidProductIdentifiers`**:SKProductsResponse 包含 `invalidProductIdentifiers` 数组,其中列出了 Apple 无法解析的 SKU。在生产环境中该数组不会显式报错⸺既不返回结果,也不会触发失败。请在开发阶段打印该数组;一旦数组非空,几乎都意味着应用、[App Store Connect](https://appstoreconnect.apple.com/) 与发布商帐户之间存在 SKU 不匹配。
```swift
import StoreKit
class ProductLoader: NSObject, SKProductsRequestDelegate {
var loadedProducts: [SKProduct] = []
func loadProducts(skus: [String]) {
let identifiers = Set(skus)
let request = SKProductsRequest(productIdentifiers: identifiers)
request.delegate = self
request.start()
}
// SKProductsRequestDelegate
func productsRequest(_ request: SKProductsRequest,
didReceive response: SKProductsResponse) {
loadedProducts = response.products
if !response.invalidProductIdentifiers.isEmpty {
print("[Xsolla] Invalid SKUs: \(response.invalidProductIdentifiers)")
}
}
}
```
**💡 最佳实践:面向真实网络环境的请求加固**
在生产环境中,[SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest) 可能因网络较差或会话中途网络切换而静默失败。最小加固策略是在初始化后增加短暂延迟,并用可重试的错误处理封装请求:
```swift
func loadProductsWithRetry(skus: [String], attempt: Int = 0) {
// Brief delay on first load to let SDK initialization settle
let delay: TimeInterval = attempt == 0 ? 0.5 : 2.0
DispatchQueue.main.asyncAfter(deadline: .now() + delay) {
let request = SKProductsRequest(productIdentifiers: Set(skus))
self.activeRequest = request
request.delegate = self
request.start()
}
}
func request(_ request: SKRequest, didFailWithError error: Error) {
print("[Xsolla] Product request failed: \(error.localizedDescription)")
// Retry up to 3 times with exponential backoff
if currentAttempt < 3 {
loadProductsWithRetry(skus: pendingSKUs, attempt: currentAttempt + 1)
}
}
```
![7711f5a1-155b-490e-a8a4-1c6ab0840a50.png]
游戏内加载的商品目录
### 商品目录故障排查清单
![82fe8dee-248a-4262-a4e7-1a18ab027874.png]
如果商品目录加载完成却未返回任何商品,深入排查代码前请先按以下清单逐项核对:
- **商品上架状态** — 发布商帐户中的每件商品都必须显式设为“可用”。处于草稿或不可用状态的商品不会出现在查询结果中。
- **商品类型** — 只有虚拟物品会通过 SKProductsRequest 路径返回,虚拟货币套餐与捆绑包类型不会显示。
- **项目 ID 与登录管理器 ID** — 请对照[发布商帐户](https://developers.xsolla.com/sdk/publisher-account/getids)核对这两个值。ID 填错时连接仍会成功,但会返回空结果。
- **SKU 区分大小写** — `com.yourcompany.stardust_pack` 与 `com.yourcompany.Stardust_Pack` 属于不同的标识符,请逐字符严格匹配。 - **App Store Connect 同步** — 确认相同的产品标识符已存在于 [App Store Connect](https://appstoreconnect.apple.com/) 中,且处于 Ready to Submit 或 Approved 状态。
# 第 3 步:购买商品
商品加载完成后,发起购买只需一行代码。SDK 封装了熟悉的 [SKPayment](https://developer.apple.com/documentation/storekit/skpayment) API,并在开始处理支付时将请求路由至支付收银台。主线程调用要求与观察者模式均与原生 StoreKit 完全一致。
### 发起购买
将所选商品的 [SKProduct](https://developer.apple.com/documentation/storekit/skproduct) 传入 [SKPayment](https://developer.apple.com/documentation/storekit/skpayment) 并加入队列。关键约束是 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) 会与 UIKit 交互,必须始终在主线程调用:
```swift
func purchase(_ product: SKProduct) {
// SKPaymentQueue calls UIKit-always dispatch to main thread
DispatchQueue.main.async {
// Set the root view controller so Pay Station has a presentation anchor
if let windowScene = UIApplication.shared.connectedScenes
.compactMap({ $0 as? UIWindowScene })
.first,
let root = windowScene.windows.first?.rootViewController {
SKPaymentQueue.default().rootViewController = root
}
// Kick off payment, passing in the product to be purchased
let payment = SKPayment(product: product)
SKPaymentQueue.default().add(payment)
}
}
```
**在加入队列前务必设置 rootViewController**:支付收银台会以 Safari 视图形式叠加展示在应用窗口之上。如果未在 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue) 上设置 `rootViewController`,支付界面将缺少呈现锚点,导致购买失败或出现异常表现。请在调用 `add()` 前立即完成设置。
### 在观察者中处理交易
通过 [SKPaymentQueue.default().add(self)](https://developer.apple.com/documentation/storekit/setting-up-the-transaction-observer-for-the-payment-queue) 注册的类会接收每一次交易状态变化。核心 规则:对所有状态(purchased、failed、restored),都要调用 [SKPaymentQueue.default().finishTransaction(_:)](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver)。
未完成的交易会持久保留,并在每次应用启动时重新返回给观察者处理,直至完成核销。漏调 finishTransaction 是引发重复发放道具 Bug 的常见原因⸺这类问题在测试阶段极难复现,但在玩家侧却非常明显。
```swift
extension YourClass: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue, updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
let sku = transaction.payment.productIdentifier
switch transaction.transactionState {
case .purchased:
// Grant items and call finishTransaction to consume
grantItem(sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
case .failed:
// Surface genuine errors; ignore user cancellations
if let error = transaction.error as? SKError,
error.code != .paymentCancelled {
handlePurchaseError(error, sku: sku)
}
// Always finish-even on failure
SKPaymentQueue.default().finishTransaction(transaction)
@unknown default:
break
}
}
}
}
```
**区分 .failed 与 .cancelled**:[SKError.paymentCancelled](https://developer.apple.com/documentation/storekit/skerror) 是玩家主动关闭购买页面时的正常返回码,并不代表发生故障,不应向玩家弹出错误提示。其余 [SKError](https://developer.apple.com/documentation/storekit/skerror) 错误码才属于需要提示或记录日志的真实异常。 **💡 最佳实践:自定义支付收银台主题**
[SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios) 暴露了支付收银台的 UI 参数。虽然可选,但让支付收银台外观与游戏视觉风格一致,可以带来更连贯的体验,并向玩家传达他们仍处于您的产品之中:
```swift
// Constructor parameters for Pay Station visual customization
let settings = SKPaymentSettings(
...
payStationUIThemeId: .dark, // or .light
payStationUISize: .medium // or .small, .large
...
)
```
![b8202083-c162-4425-9fbb-a1a5d16c36cc.png]
设备上的支付收银台
## 第 4 步:完成购买
完成购买包含两个环节:调用 [finishTransaction](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver)(必需,见第 3 步),以及在发放道具前调用 [validateTransaction](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios)(强烈建议)。验证步骤会向艾克索拉服务器确认该笔支付已成功处理⸺这是防范收据重放或篡改的关键防线。
### 客户端侧验证
在客户端侧验证中,在支付队列上调用 [validateTransaction](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios),并将发放道具的逻辑包裹在其完成回调中。这样可确保仅在艾克索拉确认交易后才发放:
```swift
func validateAndGrant(transaction: SKPaymentTransaction, sku: String) {
// Call .validateTransaction and handle appropriately
SKPaymentQueue.default().validateTransaction(transaction) { result in
switch result {
case .success:
// Safe to grant the item
self.grantItem(sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
case .failure(let error):
// Validation failed-do not grant the item
// Log for investigation; optionally surface a support prompt
print("[Xsolla] Validation failed for \(sku): \(error)")
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
// Replace non-validated pass in case .purchased with validation helper
func paymentQueue(_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction]) {
...
case .purchased:
// Validate before granting
validateAndGrant(transaction: transaction, sku: sku)
case .failure:
...
...
}
```
**务必在验证回调中调用 finishTransaction**:请注意,验证回调的成功分支与失败分支中都调用了 `finishTransaction`。这一点非常关键:避免未通过验证的交易陷入死循环。如果验证失败,请先结束该笔交易并记录日志,再交由支持团队通过[发布商帐户](https://publisher.xsolla.com/)中的交易日志进行排查。
**生产环境中的服务端验证**:客户端侧验证是不错的起点,也适用于许多游戏。但对于应用内经济价值较高,或竞技属性较强的游戏,如果玩家非法获取道具会造成明显影响,建议迁移到基于[艾克索拉 Webhook 系统](https://developers.xsolla.com/sdk/publisher-account/webhooks)的服务端验证。服务端验证更难被拦截或篡改,因为收据不会经过您无法完全控制的客户端代码。
## 整合示例
下面是完整的初始化流程,精简展示四个步骤如何串联:
```swift
import XsollaMobileSDK
import StoreKit
import SafariServices
class XsollaStoreManager: NSObject {
static let shared = XsollaStoreManager()
var products: [SKProduct] = []
func configure() {
// Step 1: Authentication
let settings = SKPaymentSettings(
projectId: YOUR_PROJECT_ID,
loginProjectId: "YOUR-LOGIN-UUID",
platform: .standalone
)
settings.enablePayments = true
settings.openExternalBrowser = true
settings.useSandbox = ProcessInfo.processInfo.environment["XSOLLA_SANDBOX"] == "1"
settings.customUserId = resolvedPlayerID()
SKPaymentQueue.default().start(settings)
SKPaymentQueue.default().add(self)
// Best practice: pre-warm before the player opens the store
prewarm()
// Step 2: Load Catalog
loadProducts(["com.yourcompany.item1", "com.yourcompany.item2", ...])
}
// Retrieve persisted player ID, create on first launch
private func resolvedPlayerID() -> String {
let key = "xsolla_player_id"
if let existing = UserDefaults.standard.string(forKey: key) { return existing }
let newID = UUID().uuidString
UserDefaults.standard.set(newID, forKey: key)
return newID
}
// Prewarm connections
private func prewarm() {
// 1. Pre-warm Safari's network connections to Xsolla endpoints
let endpoints = [
"https://secure.xsolla.com",
"https://sandbox-secure.xsolla.com" // include in debug builds
]
let urls = endpoints.compactMap { URL(string: $0) }
SFSafariViewController.prewarmConnections(to: urls)
}
private func loadProducts(_ skus: [String]) {
let request = SKProductsRequest(productIdentifiers: Set(skus))
request.delegate = self
request.start()
}
}
// Step 3: Process Purchase Events
extension XsollaStoreManager: SKPaymentTransactionObserver {
func paymentQueue(_ queue: SKPaymentQueue,
updatedTransactions transactions: [SKPaymentTransaction]) {
for transaction in transactions {
let sku = transaction.payment.productIdentifier
switch transaction.transactionState {
case .purchased: validateAndGrant(transaction: transaction, sku: sku)
case .failed:
handleError(transaction.error, sku: sku)
SKPaymentQueue.default().finishTransaction(transaction)
@unknown default: break
}
}
}
// Step 4: Validation
func validateAndGrant(transaction: SKPaymentTransaction, sku: String) {
SKPaymentQueue.default().validateTransaction(transaction) { result in
if case .success = result { self.grantItem(sku: sku) }
SKPaymentQueue.default().finishTransaction(transaction)
}
}
}
extension XsollaStoreManager: SKProductsRequestDelegate {
func productsRequest(_ r: SKProductsRequest,
didReceive response: SKProductsResponse) {
products = response.products
if !response.invalidProductIdentifiers.isEmpty {
print("[Xsolla] Invalid SKUs: \(response.invalidProductIdentifiers)")
}
}
}
```
## 总结
艾克索拉 SDK 3 通过以下四个步骤接入原生 iOS 游戏,每一步都直接建立在您熟悉的 StoreKit 原生机制之上:
- **身份认证** — 使用项目 ID 与登录管理器项目 ID 创建 [SKPaymentSettings](https://developers.xsolla.com/sdk/mobilesdk/sdk/configuration/ios),设置 `enablePayments = true` 并开启 `openExternalBrowser = true`(满足美国区合规要求),配置稳定的自定义用户 ID 用于匿名身份认证,并注册 URL Scheme 以接收支付收银台回调。
- **加载商品目录** — 使用 [SKProductsRequest](https://developer.apple.com/documentation/storekit/skproductsrequest) 拉取商品,确保[发布商帐户](https://publisher.xsolla.com/)中的每件虚拟物品均已设为“可用”。在开发阶段记录 `invalidProductIdentifiers`,以便及早发现 SKU 不匹配问题。
- **购买商品** — 调用 [SKPaymentQueue](https://developer.apple.com/documentation/storekit/skpaymentqueue).add() 前先切换到主线程,在队列上设置 `rootViewController` 作为呈现锚点,并在观察者中妥善处理全部交易状态(包括挂起与失败状态)。
- **完成购买** — 将道具发放逻辑包裹在 `validateTransaction` 回调内,待服务器确认支付成功后再发放道具。务必在验证回调的每一个分支中调用 [finishTransaction](https://developer.apple.com/documentation/storekit/skpaymenttransactionobserver)。
完整的 SDK 文档(包括[商店地区检测](https://developers.xsolla.com/sdk/mobilesdk/sdk/advanced/ios-storefront)与服务端 Webhook 等进阶主题)请参见 [developers.xsolla.com/sdk/mobilesdk](https://developers.xsolla.com/sdk/mobilesdk/)。每当新增商品类型或调整支付配置时,不妨重新打开 [SDK Explorer](https://developers.xsolla.com/sdk/demo/) 查看⸺它提供的实时事件日志能直观呈现 SDK 的底层运行状态,远比单纯查看调试器日志清晰。
## 下一步
接下来可考虑:
- **迁移至[服务端验证](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation)或 [Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api)** - 说明:目前需联系您的客户经理,或发送邮件至 [[email protected]](mailto:[email protected]) 为项目开通配置 Events API
- **探索其他[身份认证与登录方式](https://developers.xsolla.com/api/login/getting-user-token)**
- **[配置支付收银台](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works)**
## 资源
| | |
| --- | --- |
| 艾克索拉 Mobile SDK 文档 | 安装、配置与高级集成选项 |
| SDK Explorer | 可配置的交互式演示,带实时事件日志,直观展示完整支付流程,并提供各步骤速查 |
| iOS 快速入门指南 | 最简集成方案,助您跑通首笔测试支付 |
| iOS 安装详情 | SPM 安装步骤(含 Package.swift 配置说明) |
| iOS 配置参考 | 全部 SKPaymentSettings 属性与支付集成选项 |
| 查找项目 ID | 在发布商帐户中查找项目 ID 与登录管理器项目 ID |
| 支付收银台测试银行卡 | 可用于沙盒测试的银行卡号 |
| 设置交易观察者 | Apple 关于 SKPaymentTransactionObserver 的参考 |
| SFSafariViewController.prewarmConnections | 预热网络连接,加速支付收银台启动 |
| SKError - Apple | 含 paymentCancelled 在内的 StoreKit 错误代码完整列表 |
Unity 移动端 — 艾克索拉 SDK 3 集成指南
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-3-unity-mobile
## 我们要实现什么
完成本教程后,您将在 Unity iOS 项目中集成并跑通完整的艾克索拉支付流程⸺从安装 SDK 包一直到完成一笔测试交易。
我们使用 [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098?srsltid=AfmBOoortrFfstSIcxJ_7cOY0gSeNUuf16wGDlP9GXWiqEabgiRvXEDI) 作为演示项目。设计的场景非常简单:玩家阵亡后弹出提示窗口,提供两个选项⸺重新开始并丢失进度,或购买满血状态并从最近的检查点复活。这是典型的“即时冲动消费”时刻,非常适合接入支付收银台。
以下是本教程使用的关键配置摘要:
- **Unity 版本**:6.3.5
- **演示项目**:Unity 2D Game Kit
- **艾克索拉 SDK** - **身份认证方式**:客户端侧设备 ID(无需登录) - **支付界面**:在外部浏览器 (Safari) 中打开艾克索拉支付收银台,这是目前美国区 iOS 应用的合规方案 - **购买验证**:仅客户端侧
**iOS**:根据 2025 年 4 月 30 日美国法院的裁决,开发者可在 iOS 应用中加入外部支付链接。移动端专用艾克索拉 SDK 完全符合 Apple 修订后的 App Store 指南,既支持应用内支付收银台流程,也支持通过网充商店完成外链跳转支付。
**Android**:根据 2025 年 10 月 29 日 Epic 诉 Google 案禁令,美国区 Google Play 应用可使用官方支付体系之外的支付方案与外部支付链接,且不再受反引导限制约束。该 SDK 支持商店外 APK 分发、Google Play Billing 以及基于浏览器的结算流程⸺一次集成即可全部覆盖。
## 先决条件
开始之前,请先准备好以下内容:
- 一个 Unity 项目,最好已预留好触发支付的入口。本文不涉及搭建游戏 UI,默认您已确定支付流程在项目中的挂载位置(例如弹窗、商店菜单、按钮等)。
- 已安装 Unity IAP 包。艾克索拉 SDK 构建在 Unity 的内购框架之上,因此交互方式非常熟悉,但也意味着继续操作前需要先在项目中安装好 Unity IAP 包。
- 一个已激活的艾克索拉发布商帐户。本文将逐步演示需要在发布商帐户内完成的所有配置,但不包含注册和激活帐户本身的流程。如果您尚未注册,请先前往艾克索拉[发布商帐户注册页面](https://publisher.xsolla.com)完成设置。
## 参考资源
跟练本教程时,建议同时打开 SDK Explorer 及其集成小组件 (Integration Widget)。[集成小组件](https://developers.xsolla.com/sdk/integration-widget)既是艾克索拉 SDK 网站上的独立页面,也是 [SDK Explorer](https://developers.xsolla.com/sdk/demo/) 内的一个选项卡,按步骤提供完整可用的现成代码⸺本文会直接将这些代码复制粘贴到项目中。此外,过程中我们也会不时结合 SDK Explorer 查看配置与背景说明。
![8b45e7a1-da58-4f13-a4b5-98f15c21348b.png]
SDK Explorer - Integration Widget 视图(大图)
## 集成的四个阶段
在开始之前,先了解一下我们使用的集成框架。艾克索拉 SDK 与 SDK Explorer 将完整的支付集成划分为四个阶段:
- Authenticate -> 确认玩家身份。发起任何交易前,SDK 都需要有效的用户身份。本示例通过设备 ID 静默完成身份认证,因此玩家不会看到登录界面。
- Load Catalog -> 拉取商品。SDK 从艾克索拉后端获取商品目录,并将这些商品注册到 Unity 的 IAP 层,使其在运行时可供购买。
- Purchase Product -> 发起交易。 玩家点击购买的瞬间,SDK 会将流程交由艾克索拉支付收银台接管,由其展示支付界面、处理交易,并返回成功或失败结果及购买收据。
- Finalize Purchase -> 根据结果执行后续逻辑。游戏在此阶段响应已完成的交易:验证购买、发放物品(并执行相关的游戏逻辑代码)、更新游戏状态,最后妥善结束交易。
本文的四个集成步骤与上述四个阶段一一对应。SDK Explorer 与集成小组件也按同样的框架组织,便于查找各阶段对应的代码。
## 第 0 步:安装艾克索拉 SDK 包
在接入艾克索拉开启变现、执行上述 4 个集成步骤之前,需要先在 Unity 项目中安装艾克索拉 SDK 包。
集成小组件与 SDK Explorer 会提供准确的 Git URL。您可以从那里获取,或直接在 [GitHub 仓库安装说明](https://github.com/xsolla/xsolla-sdk-unity#installation) 中复制,然后在 Unity 中:
- 前往 **Window** > **Package Management** > **Package Manager**。
- 点击 **+** 图标。
- 选择 **Install package from Git URL**。
- 粘贴该 URL,然后点击 **Install**。 - 本文撰写时的 Git URL: ```text https://github.com/xsolla/xsolla-sdk-unity.git ```
现在您应该能在 Package Manager 中看到艾克索拉 SDK。
![a39a23ac-02a0-4be0-b0af-24473f42b4b6.png]
Unity Package Manager 显示已安装艾克索拉 SDK
## 第 1 步:身份认证
### 设置脚本
在场景中创建一个空的 GameObject⸺本示例将其命名为 **XsollaPay Station**。将其放到层级视图中的合适位置,然后挂载一个同名的 C# 脚本组件。
![a9076865-9bb9-41d1-bea5-ba0764301aef.png]
在项目层级视图中添加空游戏对象
![4570c4b6-d845-4433-9c28-07902a354821.png]
将脚本挂载到游戏对象上
清空 Unity 脚本自带的默认模板代码,先打开 SDK Explorer 了解身份认证所需的配置项。准备开始编写 代码时,切换到集成小组件,选择 **Authentication** 选项卡并复制其提供的完整类代码⸺这是包含完整上下文的代码,而不仅是零散片段。
![99bd602a-076e-4efb-bc80-368e633b5abd.png]
集成小组件中第 1 步 (Authenticate) 对应的代码
将代码粘贴到脚本文件中,然后把类名改为与文件名一致,因为在粘贴小组件代码时它会被覆盖。
### 此阶段的错误提示
您很可能会立刻看到一些编译错误。别担心,这是预期现象。Unity IAP 框架要求存在特定的方法签名(此处是 `ProcessPurchase` 与 `OnPurchaseFailed`),即使这些方法尚未实现。SDK Explorer 与集成小组件会按步骤逐步完善代码,因此一些函数要到后续步骤才会被引入与解释。不幸的是,Unity 现在就需要这些方法的“空壳”来顺利编译。如果您希望在尚未完成全部 4 个步骤前就构建并运行项目,则需要现在先补上这些必需的方法签名。
![3cba3cb4-38a6-463d-ab85-6dbf960016be.png]
抛出的编译错误
解决方法是先暂时跳到 SDK Explorer 的 **Purchase Product** 与 **Finalize Purchase** 步骤,从集成小组件中复制 `ProcessPurchase` 和两个 `onPurchaseFailed` (x2) 的空壳方法 ,粘贴到您的类中并将方法体注释掉。只要 Unity 识别到正确的方法签名,编译错误就会消除。
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
// Logic to be added here in Step 4
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here (Reviewed in Step3/4)
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here (Reviewed in Step3/4)
return;
}
}
```
我们会在步骤 3 与步骤 4 中回到这些方法并完成实现。
**提示**:按集成小组件分步操作时,这是一个已知的小卡点。并不是您的操作有问题⸺Unity IAP 框架本身的机制就是如此。提前把空壳方法加上,就能在每个阶段边做边测。
### 配置项目 ID 和登录管理器 ID
在复制过来的代码中,您会看到带有默认占位值的 `SetProjectId` 与 `SetLoginId` 调用。这些值指向通用的艾克索拉演示帐户及其示例商品目录⸺适合快速自检,但后续需要替换为您自己的凭据与商品。为此,请先在[发布商帐户](https://publisher.xsolla.com)中完成项目设置。
#### 在发布商帐户中创建新项目
设置项目可将您的游戏关联到目标艾克索拉商店配置,以便销售和管理自有商品目录,同时配置支付与变现选项。创建步骤如下:
##### 1. 登录发布商帐户并点击创建项目
![77c304c5-ce02-4dcc-b87e-ea051e921cb9.png]
进入发布商帐户的项目区域创建新项目
##### 2. 填写基本信息
示例配置:
- 项目类型:游戏
- 发布平台:移动端
- 盈利方式:游戏内交易
- 开发阶段:制作中
- 类型:动作
- 游戏引擎:Unity
![7a63311f-b6a8-4f73-8e7a-fe10e39e67c2.png]
项目详情填写示例
##### 3. 创建项目并记下新的项目 ID
#### 设置登录管理器项目
登录管理器项目用于告知 SDK 您的应用要采用哪种认证设置。它可按认证方式与平台进行配置,有助于组织与管理不同的玩家群体。创建步骤如下:
##### 1. 前往玩家管理区域并点击登录管理器
在发布商帐户的项目中,前往左侧边栏的**玩家管理**区域并点击**登录管理器**。
![652b6676-6212-4285-a40d-a811f60ceb9d.png]
在发布商帐户中进入登录管理器项目运营看板
##### 2. 创建新的登录管理器项目
为其起一个便于记忆、能反映用途的名称(我们使用了“client-auth”)。
![b5aea25c-e995-4388-a1ec-7ea5e87e3488.png]
创建新的登录管理器项目
##### 3. 选择经典登录作为基础方式
我们很快会覆盖该设置。
![2e8dca45-c0fb-4dad-8eb7-014b8172dab6.png]
将登录管理器项目配置为经典登录⸺稍后会被设备 ID 身份认证取代,但系统要求先指定一种默认方式
##### 4. 启用登录管理器 API 集成
这是启用设备 ID(客户端侧)身份认证并跳过标准登录流程的关键开关。
![43b40fea-3dde-4f94-9031-92d6335b49d9.png]
![35b608ee-1bc1-4991-9f0e-06117a7192b7.png]
开启 API 集成开关以启用设备 ID 身份认证
保存设置并返回发布商帐户运营看板。现在即可看到**项目 ID** 与**登录管理器 ID**。
回到 VS Code,将占位值替换为您的实际值:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(XXXXXX)
.SetLoginId("XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX")
.Build();
```
### 将 Sandbox 设为 true
在代码中,确保如下设置:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
....
.SetSandbox(true)
.Build();
```
沙盒模式允许您在不使用真实货币的情况下进行测试交易。上线前请务必关闭。
**警告**:如果在生产环境中保留 `IsSandbox = true`,真实购买将无法正常处理。请务必提醒自己在发版时将其关闭。
### 验证身份认证是否正常工作
运行游戏并查看 Unity Console。重点留意两条日志:确认商店已就绪的 **Initialize finished**,以及确认身份认证已完成的 **Authenticate By Saved Token onSuccess**。认证过 程中可能还会输出几条中间日志⸺这些都是正常的。最后需要确认看到 **IsBasedOnDeviceId: True**,表明设备 ID 身份认证运行正常。
您还会看到一条类似“no products were returned from the store”的报错⸺在当前阶段完全正常,因为我们还没有配置商品目录。接下来第 2 步就会处理它。
![bc0104cb-59c8-4670-b147-13e456c2167f.png]
未收到商品的报错提示
## 第 2 步:加载商品目录
### 在发布商帐户中创建商品
在发布商帐户中打开项目,在左侧边栏前往**商品管理** > **全部商品**。
![005f85e4-4301-4d30-8a26-3a9e86496909.png]
在发布商帐户运营看板中进入商品管理页面
如需创建新商品,请点击**创建商品** > **虚拟物品**,并填写以下信息:
![a82de719-ed8f-47d8-9b0d-62d63fc535b1.png]
创建新的虚拟物品
- **商品名称**:玩家在购买流程中看到的名称
- **SKU**:在代码中引用该商品时使用的 ID
- **商品描述**:选填,但建议填写
- **价格**:使用真实货币设置(本示例设为 1.99 美元)
- 其余选项暂时保持默认
**重要**:保存前,请务必在页面顶部将该商品标记为**可用**。否则,即使 SKU 正确,游戏内也无法获取该商品。如果后续明明已创建商品却看到“no products found”报错,这也是首要排查项。
![0d26341a-8583-481c-80b0-3865064b90ea.png]
配置新虚拟物品的属性并将其设为可用
### 将商品目录接入游戏
返回集成小组件并选择 **Load Catalog** 步骤。本节会向您的类中新增两段代码。
在 `Start` 函数中,将商品注册到 Unity 的 IAP 层:
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("product-sku", ProductType.Consumable);
```
简单说明一下这里的原理:艾克索拉后端负责托管商品目录,但 Unity 的 IAP 层在运行时也需要知道应初始化并拉取哪些商品,`AddProduct` 就是用来告知 Unity IAP 层的。`ProductType.Consumable` 标记表示该物品可重复购买⸺对于生命值补充这类玩家可能多次购买的道具非常关键。
在 `OnInitialized` 回调中,您也可以按需遍历返回的商品数据做进一步处理⸺例如在加载完成后用实时价格和描述填充商店 界面。我们将在第 3 步采用另一种方式来驱动动态价格按钮,因此本示例不使用这段代码,仅贴出供参考。
```csharp
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
...
// Products available via _storeController.products.all
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
// Display product to user
}
}
```
### 验证商品目录是否已加载
运行游戏并查看 Console。寻找包含 **retrieved products finished successfully** 的日志,确认拉取到的商品数量显示为 1(或您实际添加的商品数量),同时第 1 步中的“未收到商品”报错应已消失。此时它通常会出现在日志末尾。
![9906f29f-0661-42e5-a9b1-deb87f8426b6.png]
Unity 日志确认商品请求与拉取成功
## 第 3 步:发起购买
### 添加购买代码
返回集成小组件,选择 **Purchase Product** 步骤。这里新增的核心代码是 `InitiatePurchase` 调用。
```csharp
public void PurchaseSku(string productID)
{
_storeController.InitiatePurchase(productID);
}
```
仅这一行代码即可启动完整的艾克索拉购买流程。调用后,控制权会移交给艾克索拉后端:拉起支付收银台并传入所需的商品信息,完成交易与用户交互,最后在结束时触发 `ProcessPurchase` 或 `OnPurchaseFailed`。这行调用本身非常轻量⸺真正的业务逻辑都集中在您的回调与后端中。
**提示**:外部浏览器(iOS 上的 Safari)行为可在 SDK Explorer 中 Purchase Product 步骤下的 *Configuration* 选项卡里配置。默认设为 *External Browser*,这是当前美国区 iOS 应用的合规选项。如有需要,也可改用应用内原生界面或购买按钮方案。
### 接入您的游戏逻辑
SDK Explorer 的代码能让购买触发器工作,但仍需将其接入您的实际游戏。我们的演示进行了如下调整:
- **改为动态发起购买** — 不在 `InitiatePurchase` 中硬编码商品 ID,而是将其作为参数传入: ```csharp public void PurchaseSku(string productID) { _storeController.InitiatePurchase(productID); } ```
- **新增 `GetProductPrice` 函数** — 从已初始化的商品数据中读取指定 SKU 的实时价格,并以格式化字符串的形式返回: ```csharp public string GetProductPrice(string productId) { if (_storeController == null) return "..."; var product = _storeController.products.WithID(productId); return product != null ? product.metadata.localizedPriceString : "..."; } ```
- **将该类改为单例模式** — 由于项目包含多个场景,需要支持从其他脚本全局访问 `XsollaPayStation` 类: ```csharp public class XsollaPayStation : MonoBehaviour, IDetailedStoreListener { public static XsollaPayStation Instance { get; private set; } ... void Awake() { if (Instance != null && Instance != this) { Destroy(gameObject); return; } Instance = this; DontDestroyOnLoad(gameObject); } } ```
- **UI 弹窗** — 在另一个类中搭建 UI 弹窗,展示 `GetProductPrice` 返回的价格;点击购买选项会触发 `InitiatePurchase` 调用,选择重新开始则会彻底重置并清空所有进度。
![9207c81d-9382-4ec0-9734-3bad0549579d.jpg]
游戏内用于购买生命值并触发购买流程的 UI 弹窗截图
### 测试购买流程
运行游戏并触发购买。您应会看到在外部浏览器窗口中 打开支付收银台,显示:
![3221c7f3-efdb-4148-acad-daea6c56c450.png]
在外部浏览器中打开的艾克索拉支付收银台
- 您的商品图片
- 您的游戏名称
- 目录中的商品名称与含税价格
- 可用支付方式
进行沙盒测试时,支付收银台界面内直接提供了[测试银行卡信息](https://developers.xsolla.com/dev-resources/testing/test-cards/)链接⸺开发阶段请使用这些测试卡号,切勿填写您个人的真实银行卡信息。
完成购买后查看 Unity Console,应能看到完整的购买流程记录:发起购买、艾克索拉后端确认订单,以及 Unity IAP 结束交易 (FinishTransaction)。此时游戏画面还不会产生变化,因为 `ProcessPurchase` 要到第 4 步才会实现。
## 第 4 步:完成购买
### 了解返回值
看代码之前先提醒一点:`ProcessPurchase` 的返回值取决于您采用的购买验证方式。由于本示例采用客户端侧验证,会直接返回 `PurchaseProcessingResult.Complete`⸺无需等待外部系统响应,当场确认并关闭交易即可。如果采用服务端验证,则应返回 `Pending`,在收到后端确认前先将交易保持挂起状态。
**注意**:SDK Explorer 默认展示 Events API / 服务端验证代码。请务必在 Finalize Purchase 步骤中检查 Configuration 选项卡并选择 Client-Side Only,以查看与本文方案一致的代码。
### 实现 ProcessPurchase
以下为仅客户端校验场景下的 `ProcessPurchase` 实现:
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (success)
{
// Purchase is valid - grant the item to the player, then confirm:
}
else
{
// Purchase validation failed - do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Complete;
}
```
**提示**:请注意,这段代码仅对应客户端侧购买验证。若采用服务端验证或基于 Events API 的验证,还需补充额外代码。
**注意:生产环境的服务端校验** — 客户端侧校验是不错的起点,且适用于许多游戏。但对于应用内经济价值较高,或竞技属性较强的游戏,如果玩家非法获取道具会造成明显影响,建议迁移到基于[艾克索拉 Webhook 系统](https://developers.xsolla.com/sdk/publisher-account/webhooks)的服务端校验。服务端校验更难被拦截或篡改,因为收据不会经过您无法控制的客户端代码。
### 关于 OnPurchaseFailed 的说明
您会注意到 `OnPurchaseFailed` 有两个版本。这是因为 Unity IAP 存在两个 不同的监听接口,分别触发略有差异的方法版本。保留这两个版本即可覆盖不同接口场景。对本项目与客户端侧校验而言,此时两者都无需额外逻辑,可沿用集成小组件的默认实现。
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
### 添加您的游戏逻辑
搭好艾克索拉的底层流程后,即可在 `ProcessPurchase` 代码块内补充购买成功后游戏需要执行的业务逻辑。在本演示项目中,就是关闭弹窗并调用复活函数,让玩家在最近的检查点满血复活。具体实现完全取决于您的游戏设计⸺关键在于这段逻辑应当写在 `ProcessPurchase` 中。
### 验证完整流程
端到端完整跑一遍游戏:触发购买流程,在支付收银台完成交易,这一次就能看到游戏内产生实际响应⸺在本示例中,玩家会在检查点满血复活。
在 Console 中查看最终购买确认日志。应能看到完整的收尾序列:校验被触发(确认 `ProcessPurchase` 正确走了客户端校验路径)、Unity IAP 以 FinishTransaction 关闭交易,以及您自定义的“购买成功”日志(如有)。
![f62d93da-2076-4f6b-8168-37aea9ef3b7f.gif]
展示最终跑通集成的关键功能与完整流程的 GIF 动图
## 全部完成
至此,您已在面向 iOS 的 Unity 项目中完成了整套艾克索拉支付集成⸺涵盖设备 ID 身份认证、动态商品目录、通过外部浏览器拉起支付收银台,以及客户端侧购买验证。
最终的类结构应包含:
- 使用项目 ID 与登录管理器 ID 配置好的**初始化与身份认证**
- 向 Unity IAP 声明商品 SKU 的**商品目录注册**
- 与游戏 UI 触发入口绑定的 `InitiatePurchase`
- 立即返回 `Complete` 并触发购买后游戏逻辑的 `ProcessPurchase`
- 妥善处理失败情况的两个 `OnPurchaseFailed` 重载版本
## 下一步
从这里出发的几个自然方向:
- **添加更多商品** — 扩展 `AddProduct` 与商店界面,以支持完整的商品目录
- **迁移至[服务端验证](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation)或 [Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api)** — 如果安全性是优先考量(涉及真实货币交易时通常如此),升级路径是采用艾克索拉 Events API 或基于 Webhook 的服务端验证。借助 SDK Explorer 可以直观看到具体需要改动的代码 - 注意:目前需联系您的客户经理,或发送邮件至 [[email protected]](mailto:[email protected]) 为项目开通配置 Events API
- **探索其他[身份认证与登录方式](https://developers.xsolla.com/api/login/getting-user-token)** — 设备 ID 上手快捷,但无法跨设备保留身份。艾克索拉支持丰富的登录方式,包括邮箱、社交帐号及平台原生身份认证
- **[配置支付收银台](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works)** — 在发布商帐户中可自由管理支付方式、自定义界面主题及配置区域选项
- **参考资源** — [艾克索拉 SDK 网站](https://developers.xsolla.com/sdk/)针对本文介绍的各项功能及更多进阶主题提供了详尽的图文教程、快速指南和视频。跑通基础集成后,不妨多花些时间体验 [SDK Explorer](https://developers.xsolla.com/sdk/)⸺按阶段筛选并实时观察日志更新,能帮助您更深入地理解 SDK 的底层运行机制。
祝您顺利。如遇问题,艾克索拉开发者社区与支持团队随时为您提供帮助。
Unity Web — 艾克索拉 SDK 3 集成指南
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-3-unity-web
![演示游戏⸺玩家失去最后一条生命后弹出“购买复活”窗口,触发即时购买契机]
演示游戏⸺玩家失去最后一条生命后弹出“购买复活”窗口,触发即时购买契机
## 我们要实现什么
读完本文后,您将在 Unity Web 项目中集成并跑通完整的艾克索拉支付流程⸺从安装 SDK 包一直到完成一笔测试交易。
本文全程以 [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098) 作为参考项目。设计的场景非常简单:玩家失去最后一条生命时弹出提示窗口,提供两个选项⸺购买恢复满血状态并从刚才中断的位置继续,或重新开始并丢失游戏进度。这是典型的即时购买契机,非常适合集成支付收银台。
点击购买按钮后,游戏内会原生 打开艾克索拉支付收银台。对于 Web 游戏,这是推荐方案;如有需要,您也可以配置为其他打开方式。购买完成后,玩家会在最近的检查点满血复活。
![支付收银台]
支付收银台
以下是本次集成的具体要点摘要:
- **身份认证方式**:服务端,通过自定义 ID (Custom ID) 完成(玩家无需登录或注册)
- **商品目录管理**:手动
- **购买验证方式**:仅客户端侧
> **提示**:更喜欢看视频教程?点击观看本次集成的视频演示:[Unity Web 版艾克索拉 SDK 3](https://www.youtube.com/watch?v=RDa6b4O98L8)
## 先决条件
开始前,请确认:
- **Unity** — 本文使用的参考项目基于 Unity 游戏引擎 6.3.5 版本。
- **一个可接入支付流程的游戏项目**。默认您已经确定在项目何处接入艾克索拉支付流程。本演示是在玩家阵亡时触发游戏事件⸺您的游戏也应选定类似的时机,在合适的位置向玩家展示购买入口。
- **已安装 Unity IAP 包**。艾克索拉 SDK 直接构建在 Unity 的 In-App Purchasing 框架之上。如果尚未安装,安装艾克索拉包时会自动一并处理。撰写本文时暂不支持 Unity IAP 5⸺如果单独安装,请留意核对所用版本。
- **一个已激活的艾克索拉发布商帐户**。本文将逐步演示需要在帐户内完成的所有配置,但不涵盖注册帐户本身的步骤。如果尚未注册,请先前往[艾克索拉发布商帐户注册页面](https://publisher.xsolla.com/signup?integration_type=SDK)完成设置。
- **一台服务器**。Web 端的 Custom ID 身份认证需要通过后端向艾克索拉请求令牌。如何从零搭建服务器不在本文范围内⸺这里仅从整体层面介绍服务端需要完成的工作。
## 参考资源
在操作过程中建议同时打开以下三个资源,后续也可作为参考:
- [**艾克索拉 SDK 文档**](https://developers.xsolla.com/sdk/) — 全面涵盖理解 SDK 3 所需的全部资料,包含各平台文档与核心概念说明。
- [**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) — 可将其视为交互式文档。左侧是可实时试玩的游戏;右侧默认展示支付流程的实时日志输出,每条日志均可展开查看详情;底部设有四个选项卡,分别对应支付流程的四个步骤⸺每个选项卡都会给出对应步骤的文档与代码,您还可以按自己的实现方案调整配置,代码和文档会随之实时同步更新。
- [**发布商帐户**](https://publisher.xsolla.com) — 集中管理艾克索拉生态中的各项配置,例如身份认证体系、商品目录和支付偏好设置。
![SDK Explorer - 默认视图]
SDK Explorer - 默认视图
在 SDK 文档和 SDK Explorer 中还有一个非常实用的资源:[**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget)。如果您想走最省事的实现路径,它会为支付流程的四个步骤分别提供即拿即用的完整代码,只需点几下鼠标就能搭起一套可运行的支付流程。
(之所以能做到这一点,是因为它默认绑定了模板项目凭据和模板商品目录,因此正式上线前请务必替换为自己的登录管理器 ID 和项目 ID。)
本指南仅使用 Integration Widget 提供的**代码结构**,随后会将其更新为我们自己的项目、商品目录和配置。
![SDK Explorer 中的 Integration Widget 窗口]
SDK Explorer 中的 Integration Widget 窗口
## 集成的四个阶段
艾克索拉 SDK 和 SDK Explorer 将完整的支付集成划分为四个阶段,本指南的每一步都与其中一个阶段一一对应:
- **Authenticate** -> 确认玩家身份。本项目在后台使用 Custom ID 与服务器签发的访问令牌完成,玩家不会看到登录界面。
- **Load Catalog** -> 将产品注册到 Unity 的 IAP 层,使其在运行时可购买。
- **Purchase Product** -> 发起交易。SDK 交由支付收银台处理支付 UI 与状态,并返回成功或失败。
- **Finalize Purchase** -> 根据结果执行操作,验证购买并向玩家发放物品。
## 第 0 步:安装艾克索拉 SDK 包
开始四个步骤前,先把艾克索拉 SDK 包加入您的 Unity 项目。
要检查是否已安装,打开 **Window > Package Management > Package Manager**,搜索“Xsolla”。
![Unity Package Manager 中显示已安装艾克索拉 SDK]
Unity Package Manager 中显示已安装艾克索拉 SDK
如果尚未安装,在 SDK Explorer 中打开 Integration Widget,并从 Install 侧边栏面板复制 Git URL 命令。然后在 Package Manager 中:
- 点击 **+** 图标。
- 选择 **Install package from Git URL**。
- 粘贴 URL*,然后点击 **Install**。
```text
https://github.com/xsolla/xsolla-sdk-unity.git
```
*撰写本文时该地址有效⸺请始终从 Integration Widget 或 [GitHub 仓库安装说明](https://github.com/xsolla/xsolla-sdk-unity#installation)获取最新 URL。
![Integration Widget 显示 Git 安装命令]
Integration Widget 显示 Git 安装命令
## 第 1 步:身份认证
### 设置脚本
在场景中创建一个空的 GameObject⸺本示例将其命名为 **XsollaPayStation**。为其挂载一个新的 C# 脚本组件,然后打开脚本并删掉默认模板代码。
![层级中包含 XsollaPayStation GameObject,Inspector 中显示其脚本组件]
层级中包含 XsollaPayStation GameObject,Inspector 中显示其脚本组件
前往 SDK Explorer,打开 Integration Widget,并将 **Authenticate** 选项卡中的**全部**内容复制到您的类中。这样即可得到初始代码结构。
### 此阶段的错误提示
您会立刻看到一个编译错误。这是正常现象⸺我们基于 Unity IAP 构建,而该框架要求实现几个将在后续步骤才会讲到的函数。将鼠标悬停在报错位置即可看到具体缺失的函数:`OnPurchaseFailed` 和 `ProcessPurchase`。
![VS Code 悬浮提示列出 IDetailedStoreListener 缺失的接口成员]
VS Code 悬浮提示列出 IDetailedStoreListener 缺失的接口成员
在复制的代码底部有一条说明,指出这些函数来自 Purchase Product 和 Finalize Purchase 步骤。因此:
- 在 Integration Widget 中,打开 **Purchase Product**,并将其中的三个函数都复制到您的类中(`PurchaseSku` 和两个 `OnPurchaseFailed` 版本)。 - 就 Unity IAP 而言,`PurchaseSku` 并不是缺失函数,但我们需要它来打通支付流程,干脆现在一并加入。
- 打开 **Finalize Purchase**,复制 `ProcessPurchase` 函数。
至此,错误消除,您已经拥有完整支付流程的基础结构。我们会在第 3 和第 4 步中进行正确配置。
> **提示**:不妨趁现在把类名改为与脚本组件名一致(本示例为 `XsollaPayStation`)⸺粘贴进来的小组件代码默认使用的是 `YourSDKIntegrationBehaviour`。
### 切换为服务端身份认证
Integration Widget 默认采用最简集成路径,在大多数平台上是通过设备 ID 完成客户端侧身份认证。**但 Web 平台不支持设备 ID**,因此我们需要改用 Web 端的对应方案:基于自定义 ID (Custom ID) 的身份认证,这需要配合一台服务器使用。该方式对玩家的打扰最少,也是 Web 端最省事的接入路径,因为全程静默在后台完成,无需弹出任何登录或注册界面。
要查看具体设置方式,回到 SDK Explorer,确保位于 **Authenticate** 步骤,打开 **Configure** 选项卡并设置为 **Server-Side Auth**。
![SDK Explorer,Authenticate 步骤 > Configure 选择了 Server-Side Auth]
SDK Explorer,Authenticate 步骤 > Configure 选择了 Server-Side Auth
向下滚动到代码,有两点需要注意:
```csharp
var settings = XsollaClientSettings.Builder.Create()
.SetProjectId(<project-id>)
.Build();
var configuration = XsollaClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("<server-token>")
.SetSandbox(true)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
UnityPurchasing.Initialize(this, builder);
```
- `SetSandbox(true)` — 允许使用测试交易和测试银行卡运行支付流程,无需动用真实资金即可快速测试。正式上线或打包任何生产版本包前请务必移除。
- `SetAccessToken` — 由您的服务器返回访问令牌后,在此处将其传入配置以完成用户身份认证。
### 延迟设置访问令牌
在 SDK Explorer 中点击 `SetAccessToken` 链接跳转到**配置** (Configuration) 文档页,并定位到**为配置分配艾克索拉访问令牌** (Assign Xsolla access token to the configuration) 小节。
**Default** 方式会直接传入令牌⸺但前提是在 SDK 初始化之前就已经拿到有效令牌。如果在玩家进入游戏前已有前置登录流程,这种方式完全可行;但采用 Custom ID 身份认证时并没有前置登录环节,因此需要在初始化完成之后再传入令牌。为此,请切换到 **Delayed (deferred)** 选项卡。
![文档⸺“Assign Xsolla access token to the configuration”,已选中 Delayed (deferred) 选项卡]
文档⸺“Assign Xsolla access token to the configuration”,已选中 Delayed (deferred) 选项卡
其思想是先构建配置,然后在令牌可用时以异步方式添加访问令牌。为此,原始配置会设置一个延迟配置任务,用于调用 `DelayedTask` 函数,该函数等待服务器返回令牌后再更新配置:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetDelayedConfigurationTask( DelayedTask() )
.Build();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
var result = await Server.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetSettings(
XsollaStoreClientSettings.Builder.Update(configuration.settings)
.SetProjectId(result.projectId)
.Build()
)
.SetAccessToken(result.accessToken)
.Build();
}
```
设置好延迟配置任务后,还需要两样东西才能让流程工作:一台服务器,以及客户端中用于向服务器请求令牌的逻辑。
### 服务器(整体概览)
如果还没有现成的服务器,需要先搭建一台。基础服务跑起来后,回到 SDK Explorer,确认仍处于 **Authenticate** 步骤,即可看到 **Overview**、**Server Token**、**Custom ID** 和 **User Token** 四个选项卡。它们完整涵盖了服务器需要执行的逻辑,并提供跑通艾克索拉支付流程所需的服务端代码。
![SDK Explorer Authenticate > Server Token 选项卡与实现代码]
SDK Explorer Authenticate > Server Token 选项卡与实现代码
简而言之,服务器需要完成的关键事项:
- 使用 OAuth 客户端凭证向艾克索拉请求访问令牌。
- 使用 该授权为玩家的 Custom ID 创建**用户**访问令牌。
- 将令牌返回给游戏客户端。
艾克索拉返回的响应中包含访问令牌、刷新令牌及过期时间。本演示仅将访问令牌转发给客户端,但在生产环境中,服务器应妥善保存并配合使用这几项信息,以免超时导致会话中断。
最后,服务器要连接艾克索拉服务,还需要用到您的**客户端凭据**⸺这意味着需要先在发布商帐户中完成项目设置。
### 在发布商帐户中设置项目
**创建项目**。在发布商帐户中创建一个新项目并填写基础信息。本演示项目的配置如下:
- **变现方式**:游戏内交易
- **开发阶段**:制作中
- **游戏类型**:动作
- **游戏引擎**:Unity
- 然后点击**创建**
![发布商帐户⸺新建项目详情表单]
发布商帐户⸺新建项目详情表单
接着,**创建登录管理器项目**。前往**玩家管理**区域并创建一个登录管理器项目⸺该系统负责管理经过验证的玩家身份。
- 对于本演示,选择**独立**项目即可。请重命名以体现用途(本示例命名为“AuthViaCustomID”)。
- 选择**经典登录**⸺后续通过 Custom ID 进行的授权会覆盖该基础配置,因此这里不再展开经典登录的常规机制。
- 前往**安全性**区域,新建一个 **OAuth 2.0 客户端**。 - 确保启用**服务器到服务器连接**。
- 创建完成后复制**客户端 ID** 和**密钥**,填入此前从 SDK Explorer 获取的服务端代码对应位置。
![登录管理器项目的“安全性 > OAuth 2.0 客户端”区域]
登录管理器项目的“安全性 > OAuth 2.0 客户端”区域
> **警告**:客户端密钥只能保存在您的服务器上⸺切勿将其写入 Unity 客户端代码中。
返回登录管理器运营看板,现在即可看到**登录管理器 ID** 和**项目 ID**。请将这两个 ID **同时**填入服务器代码和 `XsollaPayStation` 类中(`SetProjectId` / `SetLoginId`*)。
*严格来说,只有服务器端需要用到登录管理器 ID;不过将其一并填入客户端代码中也完全无妨。
![登录管理器运营看板中显示的登录管理器 ID 和项目 ID]
登录管理器运营看板中显示的登录管理器 ID 和项目 ID
至此,所有内容都已指向您的自有游戏项目,而非艾克索拉的模板项目。
### 在客户端请求令牌
此流程的最后一步是客户端侧:告诉服务器该玩家需要新的访问令牌。在 SDK Explorer 的代码中,这由 `DelayedTask` 函数内的 `Server.GetXsollaTokenAsync()` 调用完成。它做两件关键事情:
- **生成或读取玩家 ID** — 在本项目中,通过 `GetOrCreatePlayerId` 函数在 `PlayerPrefs` 中读写 GUID 来实现。
- **将该 ID 发送给服务器并等待返回令牌** — 拿到令牌后传回 `XsollaPayStation`,写入配置以完成用户身份认证。
以下是本演示项目中的实现类,仅供参考⸺实际代码很可能因您的架构而异。其中的请求与响应数据结构(入参 `gameId`、出参 `token`)以及 `_localServerUrl` 均对应**本示例**的演示服务器⸺请替换为您自有服务器所需的格式:
```csharp
using System;
using System.Text;
using System.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
public class <your-classname>
{
// Your server's token endpoint
private readonly string _localServerUrl = "<your-server-token-endpoint>";
[Serializable]
private class LoginRequest { public string gameId; }
[Serializable]
private class LoginResponse { public string token; }
public async Task<string> GetXsollaTokenAsync()
{
string gameId = GetOrCreatePlayerId();
var requestBody = new LoginRequest { gameId = gameId };
byte[] bodyRaw = Encoding.UTF8.GetBytes(JsonUtility.ToJson(requestBody));
using (var request = new UnityWebRequest(_localServerUrl, "POST"))
{
request.uploadHandler = new UploadHandlerRaw(bodyRaw);
request.downloadHandler = new DownloadHandlerBuffer();
request.SetRequestHeader("Content-Type", "application/json");
await request.SendWebRequest();
if (request.result != UnityWebRequest.Result.Success)
throw new Exception($"Custom ID login failed: {request.error}\n{request.downloadHandler.text}");
var response = JsonUtility.FromJson<LoginResponse>(request.downloadHandler.text);
if (string.IsNullOrEmpty(response.token))
throw new Exception("Login response did not contain a token.");
return response.token;
}
}
public string GetOrCreatePlayerId()
{
const string key = "xsolla_game_id";
if (!PlayerPrefs.HasKey(key))
PlayerPrefs.SetString(key, Guid.NewGuid().ToString());
return PlayerPrefs.GetString(key);
}
}
```
接着让 `DelayedTask` 调用这个类。官方文档示例中服务器会同时返回访问令牌和项目 ID,因此示例代码写的是 `result.accessToken` 和 `result.projectId`。而在本示例中,服务器仅返回访问令牌,因此该类直接返回纯字符串⸺可直接传入 `SetAccessToken`。由于项目 ID 已在初始配置中通过 `SetProjectId` 指定,文档示例中的 `SetSettings` 代码块无需添加。
`GetXsollaTokenAsync` 是实例方法,所以请在 `XsollaPayStation` 中创建该类的实例并从那里调用:
```csharp
private readonly <your-classname> _authenticator = new <your-classname>();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
string token = await _authenticator.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetAccessToken(token)
.Build();
}
```
这只是实现方式之一⸺具体细节取决于您的服务器架构,把握好上述两个核心要点即可。
### 验证身份认证是否正常工作
至此循环已完整,访问令牌已异步注入 SDK。此时打包运行不会有太多可见效果,但您可以构建 WebGL,在浏览器中打开,并在开发者控制台中按“Xsolla”过滤,查找类似如下的日志:
- `XsollaToken created (access only); IsBasedOnDeviceId: False` — 已收到服务器返回的令牌(`False` 确认当前未采用设备 ID,因为设备 ID 不适用于 Web 版本包,这与 Custom ID 是两个独立概念)。
- `Authenticate By Saved Token onSuccess` — 身份认证已完成。
- `[XsollaPurchasingStore]: Initialize finished` — SDK 已准备就绪。
这些是调试级别日志,请确保保留来自 Integration Widget 代码的 `.SetLogLevel(XsollaLogLevel.Debug)` 配置。
您还会看到一个错误,高亮提示当前**没有可用产品**。这是预期现象,因为我们已经从小组件的测试凭证/项目切换到自己的项目,但尚未创建任何商品。我们将在下一步修复,暂时可以忽略此错误(如“no products are currently available”)。
## 第 2 步:加载商品目录
### 配置本步骤
在 SDK Explorer 中进入 **Load Catalog** 步骤,打开 **Configure** 并选择 **Manual entry**⸺本演示既不从现有平台商店同步商品,也不通过代码动态修改商品目录,因此手动录入是最快捷的上手方式。
![SDK Explorer Load Catalog > Configurator 选择了 Manual entry]
SDK Explorer Load Catalog > Configurator 选择了 Manual entry
切回 **How to** 选项卡,核心相关代码实际上只有一行⸺`AddProduct`:
```csharp
var builder = ConfigurationBuilder.Instance(module);
builder.AddProduct("product_sku1", ProductType.Consumable);
builder.AddProduct("product_sku2", ProductType.Consumable);
builder.AddProduct("product_sku3", ProductType.Consumable);
// ...
UnityPurchasing.Initialize(this, builder);
```
它告诉 Unity IAP 要包含哪些产品,并让它们在游戏中可访问。您先前从 Integration Widget 复制的代码已经包含了该调用,但加入了多个模板产品(如 `ticket.10`)。请按需要添加或删除多余的行。
Integration Widget 的 Load Catalog 步骤还会在 `OnInitialized` 中添加一段循环,将商品信息保存下来供代码动态调用(例如填充商店界面)。本示例不需要这部分逻辑,直接忽略即可。
接下来需要在商品目录中创建我们自己的商品供代码调用。
### 在发布商帐户中创建商品
在发布商帐户项目中,前往**商品管理** > **全部商品**,并选择**手动创建**。
![创建新商品并选中“虚拟物品”]
创建新商品并选中“虚拟物品”
本示例的回血包属于**虚拟物品**,请选中该项并点击**继续**,然后按页面提示填写:
- 上传图片。
- 添加名称、SKU、描述等。 - SKU 是您在游戏中调用该产品时使用的产品 ID。
- 将其设为**付费**商品,使用**真实货币**定价,并设置所需价格。
其余选项全部保持默认,点击**创建**。
![新建虚拟物品表单,已填写 SKU、名称与图片]
新建虚拟物品表单,已填写 SKU、名称与图片
> **重要**:新建商品默认处于**不可用**状态⸺即使在代码中查询了正确的 SKU,游戏内也不会显示该商品。请在创建时将商品状态设为**可用**。如果在创建流程中漏掉了这一步,或后续需要调整,也不必担心⸺创建完成后随时可在商品目录中修改。后续若遇到“no products”报错,这也是首要排查项。
![选择商品状态对话框,已选中“可用”]
选择商品状态对话框,已选中“可用”
### 将商品接入您的游戏
把新建的 SKU 填入您的 `AddProduct` 调用行中:
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("buy-full-health", ProductType.Consumable);
```
### 验证商品目录是否已加载
如果现在再次构建,第一步中的“no products”错误应已消失,您会看到类似如下的日志:
- `ProductsRequest: products=["product-sku"]` — 正在请求的商品。
- `RetrieveProducts finished successfully. Restored: 0, Retrieved: n` — 随后会输出刚刚添加的商品数据(SKU、名称、价格)。
![控制台显示 RetrieveProducts 成功完成,并列出 buy-full-health 的产品数据]
控制台显示 RetrieveProducts 成功完成,并列出 buy-full-health 的商品数据
## 第 3 步:购买商品
### 配置本步骤
在 SDK Explorer 中打开 **Purchase Product** 步骤,这里的配置决定了支付收银台向玩家展示的方式。本示例选用 **Native in-app UI**,即直接在游戏内打开支付收银台⸺这是 Web 项目的默认推荐方案,能为玩家带来更连贯顺畅的体验。
如果您更倾向于使用外部浏览器,或通过购买按钮跳转至网充商店,可切换对应选项查看代码需要做哪些调整。
![SDK Explorer Purchase Product > Configurator 选择了 Native in-app UI]
SDK Explorer Purchase Product > Configurator 选择了 Native in-app UI
**How to** 选项卡将所需代码拆分为三个函数:
- **发起购买** — 用于启动支付流程,即游戏内购买触发入口需要调用的逻辑。 - 在本演示中,该操作绑定在购买按钮的点击监听器上。
- `ProcessPurchase` — 购买完成后执行的逻辑,主要在第 4 步实现。 - 在本演示 中,这里会触发玩家复活并恢复满血。
- `OnPurchaseFailed` — 购买失败处理分支。
这些函数您已在第 1 步从 Integration Widget 复制。您会注意到存在**两个** `OnPurchaseFailed`,因为 Unity IAP 有两个回调签名:一个带原因、一个带描述。
### 更新购买代码
回到代码,将您的新商品 SKU 填入 `PurchaseSku` 函数。
```csharp
public void PurchaseSku()
{
_storeController.InitiatePurchase("<your-product-sku>");
}
```
在两个 `OnPurchaseFailed` 函数中,加入处理失败路径所需的逻辑。
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
Debug.Log("Purchase Process has been cancelled by the user");
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
Debug.Log("Purchase Process has been cancelled by the user");
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
### 动态显示价格
在本演示中,我们直接从商品目录中的对应商品读取按钮上显示的价格。为此,我们在 `XsollaPayStation` 中新增了 `GetProductPrice` 函数:
```csharp
public string GetProductPrice(string productId)
{
if (_storeController == null) return "...";
var product = _storeController.products.WithID(productId);
return product != null ? product.metadata.localizedPriceString : "...";
}
```
弹窗 UI 类会调用该函数设置按钮价格,并在按钮的点击监听器中调用 `PurchaseSku`。其余逻辑与具体项目强相关,本文不再展开。
到这一步,玩家已通过服务端 Custom ID 完成身份认证,自定义商品目录也已从发布商帐户项目中加载完毕,玩家即可发起购买。触发后会自动拉起支付收银台并顺利完成支付*⸺接下来只剩最后一步。
(*如果此时就打包测试,请注意:在沙盒模式下,支付收银台界面内自带测试银行卡链接,可直接用来验证支付流程⸺详见下文“构建与测试”小节。)
## 第 4 步:完成购买
### 配置本步骤
在 SDK Explorer 中打开 **Finalize Purchase** 步骤并进入 **Configure**。为了采用最简单路径,选择 **Client-side validation**,表示我们不借助服务器或事件系统来处理验证。
![SDK Explorer Finalize Purchase > Configurator 选择了 Client-side validation]
SDK Explorer Finalize Purchase > Configurator 选择了 Client-side validation
由于我们之前已从 Integration Widget 复制过代码,这里唯一相关的就是 `ProcessPurchase`。该函数会调用 `Validate`,使用支付收银台回执验证购买。若验证成功,接下来就由您的游戏逻辑发放物品。
Integration Widget 代码使用 Unity IAP 的标准延迟确认机制:`ProcessPurchase` 会立即返回 `PurchaseProcessingResult.Pending`,只有在验证成功后才调用 `ConfirmPendingPurchase`:
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
// Validate the receipt before granting items
validator.Validate(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is valid - grant the item to the player, then confirm (unconfirmed
// transactions persist and are redelivered on each app launch).
_storeController.ConfirmPendingPurchase(product);
Debug.Log($"Purchase Validation successful");
}
else
{
// Purchase validation failed - do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
// Returned immediately while the async validation callback is pending
return PurchaseProcessingResult.Pending;
}
```
### 为什么返回 Pending
由于验证是异步执行的,`ProcessPurchase` 会在 `Validate` 回调触发之前先行返回。返回 `Pending` 会告知 Unity IAP 暂勿结束该笔交易。一旦验证失败,或玩家在验证完成前关闭了游戏,这笔购买记录就会保持未确认状态,并在下次启动游戏时重新传回客户端处理,而不会丢失。
请保留现有代码不变⸺切勿改为 `PurchaseProcessingResult.Complete`,否则会在游戏完成验证并发放物品之前,提前将这笔购买核销掉。
> **说明(生产环境的服务端验证)**:客户端侧验证是不错的起点,但对于应用内经济价值较高,或竞技属性较强的游戏,建议迁移到服务端验证,或通过 Events API 在客户端侧完成验证。
### 添加您的游戏逻辑
最后一步是让游戏在购买完成时做出响应。这部分逻辑取决于您的具体游戏设计⸺在本演示中,验证通过后我们会关闭弹窗,并让玩家在最近的检查点满血复活。核心要点是:这段逻辑必须放在 `ProcessPurchase` 函数的 `success` 分支内,且位于 `ConfirmPendingPurchase` 调用之前。
## 构建与测试
回到 Unity,创建一次干净的构建,确保所有更改已保存。然后:
- 启动您的服务器。
- 打开浏览器及开发者控制台,并按“Xsolla”过滤。
- 访问本地服务端口。
您应立刻看到控制台日志出现:初始化、获取令牌、身份验证以及初始化完成。再往下能看到发出的产品请求和成功获取的产品。
![浏览器运行构建,开发者控制台按“Xsolla”过滤,显示初始化/验证/产品日志]
浏览器运行构建包,开发者控制台按“Xsolla”过滤并显示初始化/认证/商品日志
试玩游戏直至触发点并启动购买流程。确认日志显示已发起购买,随后在游戏内弹出支付收银台(或按您配置的其他方式展示)。此时应能看到商品目录中的商品信息(图片、价格等)与支付详情表单并列显示。
![游戏内打开支付收银台,显示商品图片、价格和支付表单]
游戏内打开支付收银台,显示商品图片、价格和支付表单
由于处于沙盒模式,支付收银台窗口中会直接提供一个[**测试银行卡**](https://developers.xsolla.com/dev-resources/testing/test-cards/)链接。可使用页面上的测试银行卡信息快速验证支付流程,无需担心真实卡信息和真实货币。
![艾克索拉文档页面,显示测试银行卡信息]
艾克索拉文档页面,显示测试银行卡信息
切回支付收银台窗口,填入测试银行卡信息并完成购买,观察游戏画面是否按预期响应,直观确认购买流程已跑通。在本演示中,玩家会在最近的检查点满血复活。再回到控制台,即可核对确认购买收尾流程已执行完毕的日志:
- `[XsollaPurchasingStore]: Purchase finished`
- `[XsollaPurchasingStoreValidator]: Validate`
- `FinishTransaction: consuming sku=buy-full-health`
- `Consume finished: sku=buy-full-health quantity=1 consumed.`
- `FinishTransaction finished: sku=buy-full-health consumed 1 unit(s)`
![玩家满血复活,控制台显示交易完成与商品已核销的日志]
玩家满血复活,控制台显示交易完成与商品已核销的日志
## 集成完成
至此,您已在 Unity Web 项目中完成了整套艾克索拉支付集成⸺涵盖服务端 Custom ID 身份认证、自定义商品目录、游戏内原生打开的支付收银台,以及客户端侧购买验证。
最终的类结构应包含:
- 使用您的项目 ID 与登录管理器 ID 配置初始化,并包含从服务器异步获取并写入访问令牌的延迟配置任务。
- 在 Unity IAP 中完成商品目录注册,声明您的商品 SKU。
- 将 `PurchaseSku` 绑定到游戏内的 UI 触发入口。
- `ProcessPurchase` 先返回 `Pending`,在验证通过后触发购买后的游戏逻辑并调用 `ConfirmPendingPurchase`。
- 同时保留两个版本的 `OnPurchaseFailed` 回调。
Hello Money:使用 Unreal SDK 3 完成首次集成
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-3-unreal-pc
艾克索拉 SDK 3 将任意平台上的每笔购买都浓缩为相同的四个步骤:完成玩家身份认证、加载商品目录、发起购买以及完成购买。本文由演讲《Hello Money: Your First Integration with Unreal SDK 3》整理成文,按步骤逐一拆解;如果您更希望观看视频而不是阅读文章,[可点击此处查看录像](https://youtu.be/zbnJbwVVi9s)。Unreal Engine 是这一产品阵容的最新成员,目前处于试点发布阶段,本文将专门演示这四个步骤在其中的具体实现。我们将从零搭建一个完整示例:真实的艾克索拉发布商帐户、真实的商品目录物品,以及一次通过支付收银台完成的真实购买,并将其接入 Epic Games 官方示例项目 Crop Out。
最终效果是在正在运行的游戏内完成一次真实购买并得到确认,且项目从一个完全空的发布商帐户起步。整个演示全程基于蓝图实现,同时每一步都提供等价的 C++ 写法。SDK 同时支持两者,大多数团队在真实项目的不同阶段都会同时用到二者。
**演示环境与配置**
| | |
| --- | --- |
| 引擎版本 | Unreal Engine 5.8 |
| 示例项目 | Crop Out,Epic Games 提供的免费官方示例项目 |
| 身份认证 | 设备 ID 静默登录(玩家自动登录,无需填写登录表单) |
| 支付 UI | 艾克索拉支付收银台,在系统默认浏览器中打开 |
| 购买验证 | 客户端侧验证,订单完成后通过 Get Inventory Items 确认 |
> **开始之前**。本演示全程使用蓝图实现,仅凭蓝图即可从头跟到尾。每个步骤旁也附上了等价的 C++ 代码⸺并不是要求两者并用,而是考虑到不少开发者更习惯阅读代码而非节点图。不妨把每段 C++ 代码看作理解同一思路的另一种视角:如果您偏好写代码,值得一看;如果不打算用 C++,直接跳过也完全没问题。C++ 代码本身同样只是合理写法之一,并非唯一标准答案。您完全可以换一种方式组织类结构、采用不同的命名,或者把访问令牌存放在其他位置⸺只要这几个核心 SDK 调用大致按相同顺序执行,就能正常工作。
## 我们要实现什么
我们将基于 [Crop Out](https://www.unrealengine.com/blog/cropout-casual-rts-game-sample-project) 构建,这是 Epic Games 的官方示例项目之一,可在 Epic Games Launcher 的 Samples 区域或 Fab 免费获取。它模拟了一个小型村落经济:村民需要食物才能持续工作,工作越多,村落建造进度越快,存够食物后最终完成一座纪念碑。这一循环天然适合接入真实购买,因为玩家在支付后可以立即看到食物增长。
目前游戏里已经有一个 **Buy Food** 按钮,但它只会触发普通玩法逻辑。学完本指南后,点击该按钮将拉起真实的艾克索拉结算流程,购买完成后会把食物直接注入村落经济体系,效果与其他游戏内奖励完全一致。
![Crop Out 中的 Buy Food 按钮,目前仅触发普通玩法逻辑。]
Crop Out 中的 Buy Food 按钮,目前仅触发普通玩法逻辑。
## 先决条件
开始前请准备:
- Unreal Engine 5.8。
- 在 Windows 上,安装 Visual Studio 2022 并勾选 **Game Development with C++** 工作负载。在 Linux 上,标准 clang 工具链即可。艾克索拉 SDK 3 以源代码形式提供,而非预编译的二进制文件,因此插件会在您首次打开项目时随项目一起编译,即使您的游戏逻辑完全使用蓝图实现也不例外。
- 一个已激活的艾克索拉发布商帐户。如果还没有,下一节将带您完成创建。
> **注意**。该工具链仅用于编译插件本身。即使项目完全采用蓝图构建也依然需要它,因为无论哪种开发方式,SDK 都会统一从源码编译。这与您是否查看下文附带的 C++ 代码无关。
## 集成的四个阶段
无论游戏经济多复杂,基于艾克索拉 SDK 3 的每次购买都可拆解为相同的四个步骤。接下来本指南将按此顺序进行。
> **身份认证 (Authenticate)**
>
> 确认玩家身份。本示例通过设备 ID 静默完成,玩家不会看到登录界面。
> **加载商品目录 (Load Catalog)**
>
> 拉取商品列表。商品目录由艾克索拉后端提供,玩家准备购买时可直接调用。
> **购买商品 (Purchase Product)**
>
> 发起交易。从此处起由支付收银台接管,负责展示支付 UI 并返回支付令牌与订单 ID。
> **完成购买 (Finalize Purchase)**
>
> 根据结果执行后续逻辑。确认订单最终状态,核实玩家确已拥有该物品,然后在游戏内发放奖励。
这四个步骤构成了能够跑通真实交易的最小完整闭环。一旦端到端跑通,您就掌握了整套集成的核心脉络,其余进阶能力⸺更多登录方式、虚拟货币、捆绑包、优惠券以及更深入的物品库工具⸺全都建立在同一基础之上。GitHub 试点仓库中的 SDK 文档对这些功能有更详尽的说明;[加入 Unreal Engine 试点计划](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program)即可获取访问权限。
![Unreal SDK GitHub 页面]
Unreal SDK GitHub 页面
## 设置艾克索拉发布商帐户
无论使用哪款引擎,所有艾克索拉集成都从同一个地方起步:艾克索拉发布商帐户。它是支撑整套商业化配置的后台中枢⸺您的商品目录在这里维护,定价也在这里管理,无论游戏基于 Unreal、Unity 还是其他引擎发行,后台界面都完全一致。在打开 Unreal 之前,我们需要先从这里获取三个 ID,下文将逐步演示。
### 创建项目
项目用于将您的游戏与专属的商店配置绑定:拥有独立的商品目录与定价体系,与帐户下的其他项目互不干扰。
- 登录发布商帐户。您将进入以下运营看板。 ![登录后看到的发布商帐户运营看板。] 登录后看到的发布商帐户运营看板。
- 点击**创建项目**,并填写基础信息:项目名称、变现方式(本演示选择游戏内购买)、游戏类型与游戏引擎。这些选项后续随时可以修改,无需过度纠结。 ![填写项目基础信息。] 填写项目基础信息。
- 创建项目,并记下新生成的**项目 ID**,稍后在 Unreal 中会用到。 ![项目 ID] 项目 ID
### 创建登录管理器项目
项目负责管理“卖什么”,而独立的登录管理器项目负责管理“玩家是谁”。之所以刻意将两者解耦,是因为同一款游戏日后可能会接入多种登录方式,而完全不必改动商品目录。初次接触时这一步最容易让人踩坑,主要就是因为这种分离设计乍看之下不够直观。
- 在侧边栏依次进入**玩家管理** > **登录管理器**,首次打开时会看到一个简短的欢迎页面。 ![首次打开登录管理器时的欢迎页面。] 首次打开登录管理器时的欢迎页面。
- 创建一个新的登录管理器项目。在本演示中,玩家使用**设备 ID** 登录,即游戏一启动便自动完成身份认证,无需输入任何信息或填写表单。选择**标准登录管理器项目**即可满足需求。 ![标准登录管理器项目⸺适用于设备 ID 登录的正确选项。] 标准登录管理器项目⸺适用于设备 ID 登录的正确选项。
- 进入新建的登录管理器项目,找到**登录管理器 API 集成**,该开关默认处于关闭状态。 ![位于登录管 理器项目看板中的“登录管理器 API 集成”开关,当前仍处于关闭状态。] 位于登录管理器项目看板中的“登录管理器 API 集成”开关,当前仍处于关闭状态。
- 开启**使用设备 ID 登录**开关并保存。 ![开关已开启,此设置用于启用设备 ID 登录。] 开关已开启,此设置用于启用设备 ID 登录。
> **特别留意**。如果保持该开关关闭,登录将会失败,且不会有明显报错提示问题出在这里。开启该开关后还会生成您的**登录管理器 ID**⸺它是一串 UUID 而非简短数字,请勿将其与上一节的项目 ID 混淆。
### 获取 OAuth 客户端 ID
- 仍在登录管理器项目内,打开**安全性**,再进入 **OAuth 2.0**,记下页面显示的客户端 ID。
> **不同于登录管理器 ID**。这个值很容易被忽略,而且它与登录管理器 ID 并非同一概念:登录管理器 ID 是 UUID,而 OAuth 客户端 ID 是 OAuth2 端点所需的独立数字标识符。如果把两者混为一谈,简单测试时或许看似正常,但一旦真实流量进入游戏就会悄然失败⸺若未在此处区分清楚,后续排查起来会非常棘手。
### 创建虚拟物品
终于可以上架一个真实可售的内容了。
- 在商品管理中创建一个新的虚拟物品。本演示使用 **Golden Crop**,并设置简洁规范的 SKU(例如 `golden_crop`),避免包含空格或特殊字符,以免后续在代码中引用时出错。 ![在商品管理中创建 Golden Crop。] 在商品管理中创建 Golden Crop。
- 设置一个大于零的真实价格。免费物品会直接跳过结算界面,如果价格设为 0,后续演示中就无法看到支付收银台的实际效果。 ![为 Golden Crop 设置定价,并实时预览商店页面卡片效果。] 为 Golden Crop 设置定价,并实时预览商店页面卡片效果。
- 保存前将商品状态标记为**可用**⸺这是最容易遗漏的一项设置。 ![将商品标记为可用。] 将商品标记为可用。
> 🚫 **值得再次确认**。如果漏设**可用**状态,后续无论 SKU 写得多准确,该商品都不会返回,而且系统不会给出任何报错提示您回到这里排查 。
至此,发布商帐户针对新项目展示的设置引导已基本完成:一个项目、一个已启用设备 ID 登录的登录管理器项目,以及一件可售商品。
![项目的设置检查清单,供参考。]
项目的设置检查清单,供参考。
至此已集齐三个 ID(项目 ID、登录管理器 ID 与 OAuth 客户端 ID),并备好一件可售商品⸺全程均在浏览器中完成,尚未打开 Unreal。
> 💡 **提示**。发布商帐户的界面会不定期更新;如果您实际操作时某些字段的位置或名称略有变化,请以官方发布商帐户文档中的最新界面说明为准。
## 安装并配置插件
三项 ID 就绪后,将插件引入项目。
![Windows 资源管理器中的 Crop Out 项目文件夹,包含 Plugins 文件夹与 XsollaCropoutSample.uproject]
> **关于“以源码形式提供”**。艾克索拉 SDK 3 以源代码形式分发,而非预编译二进制文件,因此没有现成的编译后插件文件可供直接放入。项目会在首次打开时通过自身构建流程编译该插件⸺正因如此,前文提到的 Visual Studio 或 clang 工具链仅在这一环节必需,与项目其余部分无关。
- 在项目的 `Plugins` 文件夹内为插件创建一个新文件夹。本演示使用 `Plugins/XsollaSDK`。
- 从 SDK 的 GitHub Releases 页面下载仅包含源码的发行包,并解压到该文件夹。该仓库仅向试点参与者开放;请[加入 Unreal Engine 试点计划](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program)以获取访问权限。 ![Unreal SDK GitHub 页面] Unreal SDK GitHub 页面
- 在项目的 `.uproject` 文件中添加插件。这一行用于告知 Unreal 需要加载该插件。
- 打开项目。首次打开时 Unreal 会提示编译插件;点击确认并等待编译完成。 ![Unreal 弹窗提示缺少艾克索拉模块并询问是否重新编译]
- 依次打开 **Edit** > **Plugins**,确认 **XsollaSDK** 显示为 **Enabled**。
![Unreal Editor 的 Edit 菜单,突出显示 Plugins]
![Plugins 窗口中显示艾克索拉 SDK 3 插件已启用]
接下来配置凭证。打开项目 `Config` 文件夹下的 `DefaultGame.ini`,添加 `[/Script/XsollaSettings.XsollaSDKSettings]` 节。相同字段也可在编辑器内通过 **Project Settings** > **Plugins** > **Xsolla SDK** 进行设置,编辑器会自动写入同一文件。无论采用哪种方式,都需要在这里填入发布商帐户中的三个 ID:`ProjectId`、`LoginId` 与 `OauthClientId`,以及将 `Environment` 设为 `Sandbox`,把所有调用路由到艾克索拉的 Sandbox 端点而非生产环境,避免测试时产生真实花费。
![DefaultGame.ini,其中包含 ProjectId、LoginId、OauthClientId 与 Environment。]
DefaultGame.ini,其中包含 ProjectId、LoginId、OauthClientId 与 Environment。
```ini
[/Script/XsollaSettings.XsollaSDKSettings]
ProjectId=<your Project ID>
LoginId=<your Login project UUID>
OauthClientId=<your OAuth2 client_id, an integer>
Environment=Sandbox
```
> **可能会看到 bSandbox 字段** 。一旦编辑器向该文件写入内容,您可能会注意到同一配置块中多出了一行 `bSandbox`。该字段属于已弃用的历史遗留项,保留它只是为了兼容直接读取该字段的旧代码,Unreal 会自动将其与 `Environment` 保持同步,无需手动修改。真正控制 SDK 访问哪套端点的配置项是 `Environment`。
> **上线前**。正式发布前,请务必将 `Environment` 切换为 `Production`。如果正式上线的版本包中仍保留 `Sandbox`,真实购买将始终无法完成处理。
## 演示的构建方式
在进入四个步骤之前,值得先说明此演示的结构,以及哪些是仅为演示而非最佳实践。
本演示中的所有艾克索拉调用都放在同一个 Actor 组件内,并统一从 **Event Begin Play** 启动。并不是因为这样“更好”或“正确”,而是它最便于在一个地方观察四步依次发生并理解其作用。SDK 并不关心调用来自哪里。真实项目中,这些调用往往分散在 Widget、Game Mode、自定义子系统或其他更契合项目结构的地方。下面内容请作为观察整套流程的方式,而不是可直接照搬到生产环境的范式。
无论结构如何,值得保留的一点是 Login 与 Store 的暴露方式:两者都是 **Game Instance Subsystems**。
![蓝图图表中的 Xsolla Login Subsystem 节点]
Unreal 在游戏启动时会自动创建且仅创建一个该子系统实例,并在整个会话期间保持存活,因此无需手动生成。无论项目从哪里调用它们,访问方式都相同:调用 **Get Game Instance Subsystem**,并选择对应类。
![BAC_XsollaPurchaseFlow:一个 Actor 组件串起四个步骤,为了演示简化而非推荐结构。]
BAC_XsollaPurchaseFlow:一个 Actor 组件串起四个步骤,为了演示简化而非推荐结构。
这个 Actor 组件会在启动时一次性解析两个子系统,记录访问令牌、已加载的商品目录物品与当前订单 ID,并通过 **On Progress Updated** 和 **On Flow Failed** 两个事件对外汇报进度。任何 HUD 或 UI 只需监听这两个事件即可响应流程变化,无需关心艾克索拉的底层运作细节⸺无论在您的实际项目中最终由哪个模块发起调用皆是如此。
> 💡 **提示**。子系统是 Unreal Engine 的通用架构概念,建议在本文之外做进一步了解。引擎官方文档对这一设计模式有更深入的介绍,包括在项目各处组织子系统访问的其他方式。
**第 1 步(共 4 步)**
## 身份认证
在 **Event Begin Play** 上,获取 Login 子系统并调用 **Login With Current Device**:即前文所述的 Device ID 路径,无需表单与输入,玩家会被直接登录。给该调用打断点能精确标记从蓝图移交至 艾克索拉的时刻。其后的一切都需要等待真实的服务往返,而不是即时返回。
![先调用 Login With Current Device,随后 OnLoginCompleted,并将访问令牌保存以供后续步骤使用。]
先调用 Login With Current Device,随后 OnLoginCompleted,并将访问令牌保存以供后续步骤使用。
> **Login With Current Device 与 Login With Device ID**。Login With Current Device 是一个封装好的便捷节点,会自动读取当前设备标识并传给底层的 Login With Device ID 调用,非常适合本文这类演示场景。在实际项目中,直接调用 Login With Device ID 可以让您的代码自主决定具体上报哪些设备信息。
**On Login Completed** 会在往返完成后触发,返回令牌与错误。成功时,拆解返回对象,保存访问令牌到变量(后续各步都需要),并通过 **On Progress Updated** 报告成功;失败时,转到 **On Flow Failed**,并携带错误消息。
如果只接好这一步就运行游戏,登录成功后流程便会停下,因为此时尚未加载商品目录。这是符合预期的正常现象。
![先调用 Login With Current Device,随后 OnLoginCompleted,并将访问令牌保存以供后续步骤使用。]
先调用 Login With Current Device,随后 OnLoginCompleted,并将访问令牌保存以供后续步骤使用。
#### C++ 等价实现
这是本文的第一段 C++ 代码,先简单说明阅读方式:它并不是供您二选一的另一套独立方案,而是将上文的身份认证步骤改用代码而非蓝图节点表达出来,方便习惯看代码的开发者对照参考。在实际项目中合理的组织方式不止一种,核心在于解析 Login 子系统并调用 `LoginWithCurrentDevice`,作用与蓝图中的 Get Login Subsystem 节点一致。本示例通过 `GetWorld()` 而非直接调用 `GetGameInstance()` 来获取子系统,是因为这段代码位于 Actor 组件而非 Actor 本身之中,只有 Actor 才直接提供该快捷方法。
```cpp
UXsollaLoginSubsystem* LoginSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaLoginSubsystem>();
FOnLoginCompleted OnCompleted;
OnCompleted.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnLoginCompleted);
LoginSubsystem->LoginWithCurrentDevice(OnCompleted);
```
此处的 `OnCompleted` 是一个动态委托 (dynamic delegate),也是 Unreal 为异步操作提供回调的标准机制,同时支持在蓝图中进行绑定。使用 `BindDynamic` 进行编译期绑定(而非在运行时按函数名查找),可以让编译器直接校验 `OnLoginCompleted` 是否匹配委托预期的函数签名,在编译阶段立即捕获签名不匹配问题,避免留到运行时才报错。
在 `OnLoginCompleted` 中,先进行错误检查。若无错误,则保存访问令牌,供后续每一步使用。
```cpp
void UBAC_XsollaPurchaseFlow::OnLoginCompleted(const FXsollaAuthToken& Token, const FXsollaError& Error)
{
if (Error.IsError())
{
return;
}
AccessToken = Token.AccessToken;
}
```
**第 2 步(共 4 步)**
## 加载商品目录
对于本文这样简单的场景(一个按钮对应一件已知商品),其实并不一定要拉取整份商品目录,直接按 SKU 引用即可。但为了完整展示标准集成模式,这里依然保留了加载商品目录的步骤,方便您先直观验证它能跑通,后续再放心应用到其他场景中。
![Get Virtual Items 节点]
Get Virtual Items 节点
获取 Store 子系统并调用 **Get Virtual Items**。这里的运行逻辑与第 1 步相同:同样是一次跨网络边界调用,蓝图将控制权交给艾克索拉并等待响应。不同之处在于,由于沙盒商品目录支持匿名读取,本次调用无需传入访问令牌;不过正式生产环境下的项目是否需要传入令牌,取决于具体配置。
调用成功后,返回的商品列表会存入 Items 变量。前文提到的**可用**开关正是在这里发挥关键作用:如果忘了将商品设为可用状态,此处返回的列表就会为空,且不会有任何其他报错提示⸺因此日后若遇到商品目录意外为空的情况,建议首先排查这一项。
![断点分别落在 Authenticate 与 Load Catalog,均为到艾克索拉的真实往返。]
断点分别落在 Authenticate 与 Load Catalog,均为到艾克索拉的真实往返。
#### C++ 等价实现
这里同样再提醒一句:以下代码只是 C++ 的一种实现写法,无需一字不差地照搬。它通过 Game Instance 解析 Store 子系统(作用等同于上方的 Get Store Subsystem 节点),并调用 `GetVirtualItems` 拉取商品目录。本示例中负责处理返回结果的函数命名为 `OnCatalogLoaded`⸺函数名叫什么并不重要,核心在于发起这次调用本身。
```cpp
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnStoreItemsUpdate OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnCatalogLoaded);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->GetVirtualItems(OnSuccess, OnError);
```
调用完成后,`OnCatalogLoaded` 会收到完整的物品列表,此处仅需将其保存到 `CachedItems`,以便玩家想购买时立即检索。
```cpp
void UBAC_XsollaPurchaseFlow::OnCatalogLoaded(const FXsollaStoreItems& Items)
{
CachedItems = Items;
}
```
**第 3 步(共 4 步)**
## 购买商品
这是玩家真正进行操作的步骤。Buy Food 按钮绑定到一个名为 **Purchase Product** 的自定义事件,按下后触发如下流程。
首先从商品目录中取出 Golden Crop,并在执行后续操作前先检查其 SKU 和“是否免费”标记。这一步检查很关键:免费商品同样会返回完全合法的响应,只不过其中的支付令牌为空⸺如果跳过这项检查,就可能试图为一件根本不会生成支付会话的商品强行打开结算界面。
![Create Payment Token 节点。]
Create Payment Token 节点。
在本演示中,Golden Crop 不是免费物品,因此接下来调用 **Create Payment Token**,使用其 SKU 与访问令牌,在艾克索拉侧创建实际订单。在此处打断点可标记控制权的交接。
#### C++ 等价实现:Create Payment Token
与前文相同:这是一种写法,不是唯一正确解法。它会在 `CachedItems` 中查找 SKU 为 Golden Crop 的条目,并检查 `bIsFree`,与蓝图中的前置检查一致。若该物品不是免费品,则在 Store 子系统上使用 SKU 与访问令牌调用 `CreatePaymentToken`,由 `OnPaymentTokenReady` 处理结果。
```cpp
const FXsollaStoreItem* GoldenCrop = CachedItems.Items.FindByPredicate(
[](const FXsollaStoreItem& Item) { return Item.Sku == TEXT("golden_crop"); });
if (!GoldenCrop || GoldenCrop->bIsFree)
{
return;
}
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnPaymentTokenSuccess OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnPaymentTokenReady);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->CreatePaymentToken(GoldenCrop->Sku, OnSuccess, OnError, AccessToken, GoldenCrop->bIsFree);
```
> **如果您在游戏其他位置也售卖免费物品**。本演示特意为 Golden Crop 设置了价格,因此上方的提前返回分支只会在查找不到对应 SKU 时触发。如果您的商品目录中确实包含免费物品,依然建议走这套流程,只需将分支判断后移一步:`CreatePaymentToken` 会为免费物品返回有效订单与空的支付令牌,此时正确的处理方式是直接跳过 Open Purchase UI 并调用 `AwaitOrderFinalization`,因为免费物品无需打开支付收银台会话。
调用成功后会同时返回支付令牌与订单 ID。先将订单 ID 保存下来供第 4 步使用,再将支付令牌传入 **Open Purchase UI**,正式打开支付收银台。
![Open Purchase UI 节点]
Open Purchase UI 节点
#### C++ 等价实现:支付令牌回调与 Open Purchase UI
容我们再提醒一次(毕竟读到这里篇幅已经不短):以下代码只是示例写法,并非硬性规定。该回调会在 `CreatePaymentToken` 成功后触发,执行与蓝图完全一致的后续动作:保存订单 ID 留待第 4 步使用,然后将支付令牌传入 `OpenPurchaseUI` 以打开支付收银台。
```cpp
void UBAC_XsollaPurchaseFlow::OnPaymentTokenReady(const FXsollaPaymentToken& Token)
{
CurrentOrderId = Token.OrderId;
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
StoreSubsystem->OpenPurchaseUI(Token.Token);
}
```
在桌面端,这一调 用会在系统默认浏览器中打开支付收银台(其他平台在支持外部浏览器时也会采用同样的回退机制)。该调用本身不会冻结游戏画面,只有打上断点时才会暂停执行。正常运行时,玩家在浏览器结算页面操作期间游戏会继续流畅运行,Unreal 只是在后台静候结果信号返回。Golden Crop 当前处于沙盒定价模式,可直接使用测试银行卡完成支付,沙盒环境下不会产生任何真实扣款。
![浏览器中的 Golden Crop 支付收银台结算页面]
**第 4 步(共 4 步)**
## 完成购买
最后一步背后的设计取舍值得专门说明一下,因为单看蓝图节点并不容易一眼看透。Unreal 的独立运行版本包 (standalone) 无法监听外部浏览器窗口的关闭事件,因此没有现成的“窗口关闭”信号可供等待。取而代之的方案是:由游戏主动发起查询。
调用 **Await Order Finalization** 并传入访问令牌与订单 ID,同时在发起调用前先绑定好 **On Order Finalized** 事件。在底层,该节点会每隔约两秒查询一次订单状态,直至订单进入最终状态(已支付、已完成或已取消),随后触发一次回调。
![Await Order Finalization 节点]
Await Order Finalization 节点
> **简述轮询与 Webhook**。 在继续之前先简要界定这两个概念,因为下文会直接用到。轮询 (Polling) 是指游戏客户端按照定时器间隔反复向艾克索拉发起询问,确认订单是否已经完成;Webhook 则恰恰相反:由您自己掌控的服务器保持监听,一旦订单完成,艾克索拉会立即主动向服务器推送消息,无需客户端反复查询。深入展开这两种机制超出了本指南的篇幅范围,建议直接参阅艾克索拉关于 [Webhook 与 Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks) 的官方文档。
> 💡 **本例中的轮询与 Webhook**。这里的轮询由 SDK 自动执行,无需任何额外配置,因此 Await Order Finalization 非常适合本文这样的首次集成演示。如果您的项目已经具备自有后端,也可以换用服务端方式监听订单完成事件:通过 `DefaultEngine.ini` 中的 `WebhooksMode` 配置项接入真实的艾克索拉 Webhook 或 Events API(该配置之所以放在该文件而非 `DefaultGame.ini` 中,是因为它属于服务端部署架构选项,而非发布商帐户身份凭证)。一旦具备可接收通知的后端服务,就值得切换到这一方案;在此之前,客户端轮询更加简单省心,也是完全可行的做法。
![在 Await Order Finalization 处触发的断点,等待订单最终状态]
在 Await Order Finalization 处触发的断点,等待订单最终状态
获得最终状态后,调用 **Get Inventory Items** 确认该物品已在“已拥有”列表中:这是真正证明购买已完成的依据,而不只是一个“成功状态”。
![Get Inventory Items 节点]
Get Inventory Items 节点
#### C++ 等价实现
最后再强调一次:下面的代码同样并非唯一标准写法。等待订单完成的逻辑转换为 C++ 非常直观:先使用 `AddDynamic`(而非 `BindDynamic`,因为 `OnOrderFinalized` 是支持通知多个监听者的多播委托)将 `HandleOrderFinalized` 绑定到 `OnOrderFinalized`,随后传入访问令牌与订单 ID 调用 `AwaitOrderFinalization`,即可实现与上方蓝图节点完全一致的效果。
```cpp
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
StoreSubsystem->OnOrderFinalized.AddDynamic(this, &UBAC_XsollaPurchaseFlow::HandleOrderFinalized);
StoreSubsystem->AwaitOrderFinalization(AccessToken, CurrentOrderId);
```
`HandleOrderFinalized` 触发后,调用 `GetInventoryItems` 并传入访问令牌,对应蓝图节点 Get Inventory Items。在 `OnInventoryLoaded` 中实际确认该物品是否存在,即检查返回列表中是否包含先前购买的同一 SKU,仅在检查通过后才在游戏内发放奖励。
```cpp
void UBAC_XsollaPurchaseFlow::HandleOrderFinalized(int32 OrderId, EXsollaOrderTerminalStatus TerminalStatus)
{
UXsollaStoreSubsystem* StoreSubsystem =
GetWorld()->GetGameInstance()->GetSubsystem<UXsollaStoreSubsystem>();
FOnInventoryItemsLoaded OnSuccess;
OnSuccess.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnInventoryLoaded);
FOnStoreError OnError;
OnError.BindDynamic(this, &UBAC_XsollaPurchaseFlow::OnStoreError);
StoreSubsystem->GetInventoryItems(AccessToken, OnSuccess, OnError);
}
void UBAC_XsollaPurchaseFlow::OnInventoryLoaded(const FXsollaInventoryItems& Items)
{
const bool bOwnsGoldenCrop = Items.Items.ContainsByPredicate(
[](const FXsollaInventoryItem& Item) { return Item.SKU == TEXT("golden_crop"); });
if (bOwnsGoldenCrop)
{
// Confirmed: credit the reward here, the equivalent of Add Resource in Blueprint.
}
}
```
随后通过 **Get Game Mode** 进入 **Add Resource**,资源类型设为 Food。
![Add Resource 节点]
Add Resource 节点
> **此处开始交由您的业务逻辑接管**。Add Resource 是 Crop Out 示例项目中原本就存在的测试指令(最初供官方示例自测使用),这里借用它来代替真实的奖励发放逻辑。在此节点之前的所有步骤均可直接移植到任何 Unreal 项目中;而从这一节点开始,真实项目就可以接入自身的物品库或货币发放系统。如果物品库校验未通过,流程同样会路由至 On Flow Failed,与前文各步骤的错误处理保持一致。
## 查看运行效果
在完整跑通端到端流程前,请先清除全部四个断点,否则游戏一启动就会频繁中断暂停。现在,玩家已完成身份认证、真实商品目录已加载就绪、真实购买逻辑已绑定至游戏按钮,且奖励发放前会先完成到账确认。整套闭环至此全部打通:四个步骤依次衔接执行,没有任何环节缺失。
当最后一个节点返回时,食物数量会立即增加,村民继续工作,并因库存已足够而完成纪念碑建设。这正是一次真实购买应有的体验:把支付即时转化为玩家可见且可享受的内容。
![闭环:购买已完成,立即反映在村落的食物数量中。]
闭环:购买已完成,立即反映在村落的食物数量中。
## 您已经构建了什么
这就是在 Unreal Engine 中完成的整套艾克索拉 SDK 3 集成:从零配置一个全新的发布商帐户起步,直到跑通一笔真实可用的游戏内购买⸺无论实际项目中各个调用最终拆分在哪些模块里,核心始终遵循这四个步骤。
- 使用真实的项目 ID、登录管理器 ID 与设备 ID 登录完成身份认证配置
- 从发布商帐户加载真实商品目录,并通过“可用”开关控制上架状态
- 将真实购买流程接入游戏自身 UI,并在发放任何奖励前通过 Get Inventory Items 完成确认
- 为每一步提供等价的 C++ 实现,兼顾纯 C++ 项目及蓝图与 C++ 混用的项目
## 下一步
- **添加更多商品**。参照第 2 步已跑通的方式,从单个 SKU 拓展至完整的商品目录。
- **迁移至服务端验证**。一旦具备可接收通知的后端服务,通过在 `DefaultEngine.ini` 中配置 `WebhooksMode` 切换至真实的艾克索拉 Webhook 或 Events API,对于涉及真实货币交易的游戏经济体系而言通常比客户端轮询更加稳妥。
- **探索其他登录方式**。设备 ID 接入快捷,但无法在玩家更换设备时保留身份。艾克索拉支持丰富的其他登 录选项,包括邮箱、社交帐号及平台原生身份认证。
- **配置支付收银台界面**。发布商帐户还支持统一配置支付方式、界面主题以及面向玩家展示的结算页面地区设置。
- **阅读插件源码**。完整插件源码及配套文档(涵盖本文涉及的所有子系统 API 参考)已在 GitHub 向试点参与者开放,[加入 Unreal Engine 试点计划](https://developers.xsolla.com/sdk/unreal-pilot/#join-the-pilot-program)即可获取访问权限。
- **改用 Unity 开发**?我们同样准备了涵盖相同四个步骤的配套教程:[Unity 移动端版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-3-unity-mobile/) 与 [Unity PC 版 SDK 3](https://developers.xsolla.com/sdk/technical-articles/xsolla-sdk-unity-pc/)。
祝您顺利。如果遇到与本文描述不一致的情况,欢迎联系艾克索拉开发者社区与支持团队。
Unity PC — 艾克索拉 SDK 3 集成指南
https://developers.xsolla.com/sdk/zh/technical-articles/xsolla-sdk-unity-pc
艾克索拉购买流程演示
本指南主要面向计划进行平台外 PC 游戏分发,或在 Epic Games Store 中采用双渠道结算的开发者。在正式测试与上线发布阶段,您通常需要通过发布商帐户配置网充商店或艾克索拉游戏启动器;不过在跟练本指南时,暂不配置这两项也可以直接跑通流程。
## 我们要实现什么
本指南使用 [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098) 作为演示项目。设计的场景非常简单:玩家阵亡后弹出提示窗口,提供两个选项⸺重新开始并丢失当前进度,或者购买满血恢复并从最近一个检查点复活。这是典型的即时购买契机,非常适合接入支付收银台。
本指 南涵盖完整的四个集成阶段:身份认证 (Authenticate)、加载商品目录 (Load Catalog)、购买商品 (Purchase Product) 和完成购买 (Finalize Purchase)。您可以从头到尾跟着搭建整套流程,也可以直接跳到所需的具体步骤。无论哪种方式,本文内容都与 SDK Explorer 及 Integration Widget 一一对应,方便您随时查阅更详尽的参考信息。
本指南使用以下环境:
- **Unity 版本**:6.3.5
- **演示项目**:Unity 2D Game Kit
- **艾克索拉 SDK**
- **身份认证方式**:设备 ID(无需登录)
- **支付 UI**:在用户的默认浏览器中打开艾克索拉支付收银台(桌面端默认)
- **购买验证**:仅客户端侧验证
## 先决条件
开始前,请确认已完成:
- **已安装 Unity**。本指南使用 Unity 6.3.5,支持 IAP 的 Unity 2022.3+ 版本均可正常运行。
- **一个可操作的 Unity 项目**。如果手头没有现成项目,可以直接使用本文全程采用的 [Unity 2D Game Kit](https://assetstore.unity.com/packages/templates/tutorials/2d-game-kit-107098) 跟练。
- **已安装 Unity IAP 包**。艾克索拉 SDK 与 Unity 的 In-App Purchasing 框架深度集成,需要将该 IAP 包作为前置依赖项。
- 一个**已激活的艾克索拉发布商帐户**。本指南会逐步演示需要在发布商帐户内完 成的所有配置,但不涵盖注册帐户本身的流程。如果尚未注册,请先前往[艾克索拉发布商帐户注册页面](https://publisher.xsolla.com)完成创建。
## 参考资源
无论是按本文一步步操作,还是之后深入学习,建议先了解以下三个入口。
[**艾克索拉 SDK 文档**](https://developers.xsolla.com/sdk)是您的核心参考资料,从中可以查阅创建发布商帐户的指南、其他集成方案,以及下方两款工具的入口链接。
[**SDK Explorer**](https://developers.xsolla.com/sdk/demo/) 是可交互的 SDK 演示。您可以在游戏中测试购买,并实时查看日志,走完四个变现步骤。
[**Integration Widget**](https://developers.xsolla.com/sdk/integration-widget) 是位于 SDK 文档侧边栏的交互式代码参考工具,可按集成阶段逐步浏览每一步新增的具体代码。本指南后续将全程从该小组件中复制代码。
![fe51f1dc-037a-4b4b-ad6e-8da36ce1f13e.png]
SDK Explorer - Integration Widget 视图(大图)
简而言之,SDK Explorer 是可交互演示,而 Integration Widget 是代码参考。两者都覆盖相同的四个步骤,但用途不同。
## 集成的四个阶段
艾克索拉 SDK 将完整支付集成划分为四个阶段:
- **身份认证 (Authenticate)**:确认玩家身份。在发起任何交易之前,SDK 需要先获取有效的用户身份标识。
- **加载商品目录 (Load Catalog)**:获取商品列表。SDK 会从艾克索拉后端拉取您的商品目录,并将这些商品注册到 Unity 的 IAP 层,供运行时发起购买。
- **购买商品 (Purchase Product)**:发起交易。玩家点击购买按钮的瞬间,SDK 会将流程交由支付收银台接管,负责展示支付 UI、处理交易,并连同购买凭据一并返回成功或失败信号。
- **完成购买 (Finalize Purchase)**:根据交易结果执行后续逻辑。游戏在收到交易完成通知后执行验证、发放道具、更新游戏状态,并妥善关闭该笔交易。
熟记这四个阶段后,您就能随时明确当前所处的集成进度,也能清楚该在 SDK Explorer 或 Integration Widget 的对应阶段查阅参考内容。
## 第 0 步:安装艾克索拉 SDK 包
Integration Widget 会提供所需的准确 Git URL。您可以直接从该小组件中复制,或在 [GitHub 仓库](https://github.com/xsolla/xsolla-sdk-unity#installation)中获取:
```text
https://github.com/xsolla/xsolla-sdk-unity.git
```
然后在 Unity 中:
- 前往 **Window > Package Manager**
- 点击左上角的 **+** 图标
- 选择 **Install package from Git URL**
- 粘贴 URL 并点击 **Install**
现在您应该能在 Package Manager 中看到艾克索拉 SDK。
![51c47e41-8da6-4897-af39-1f8c66a51414.png]
通过 GitHub URL 添加 SDK
![591ca407-bf4e-43d5-b25e-060617cc184b.png]
通过 Package Manager 安装完成的艾克索拉 SDK
## 第 1 步:身份认证
### 设置脚本
在场景层级中新建一个空的 GameObject(我们将其放在“System”标签下), 并添加一个新的 C# 脚本作为组件。我们将其命名为 `XsollaPayStation`。
![cc9e346f-8426-4bcf-856f-75f83c50066f.png]
创建空对象
![5edab766-969c-455f-90c9-ebffdc6fbd88.png]
将 XsollaPayStation.cs 挂载到对象上
前往 Integration Widget,选择 **Authenticate** 选项卡。此步骤提供完整类定义。复制其内容覆盖您的脚本文件,然后将类名改为与文件名一致。后续步骤会提供需要添加到该类的代码片段。
```csharp
using System;
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using Xsolla.SDK.Store;
using Xsolla.SDK.Common;
using Xsolla.SDK.UnityPurchasing;
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
IStoreController _storeController;
IExtensionProvider _storeExtensions;
void Start()
{
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder.Instance(module)
// ... product registration (see "Load Catalog" step)
;
UnityPurchasing.Initialize(this, configurationBuilder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_storeExtensions = extensions;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
Debug.LogError($"Initialization failed: {error}");
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
Debug.LogError($"Initialization failed: {error}. Details: {message}");
}
// ... ProcessPurchase, OnPurchaseFailed (see "Purchase Product" and "Finalize Purchase" steps)
}
```
![338f6d3f-ef47-420f-8ae6-a91ac0d806dd.png]
第 1 步:身份认证
**此处出现编译报错属正常现象**:Authenticate 步骤提供的代码尚未满足完整的 Unity IAP 接口契约,因此您会看到提示 `PurchaseProcessingResult` 和 `OnPurchaseFailed` 尚未实现的编译错误。请先添加下方的占位方法以消除报错;我们会在“第 3 步:购买商品”中补全 `OnPurchaseFailed` 的正式实现,并在“第 4 步:完成购买”中实现 `PurchaseProcessingResult`。
**用于解决编译错误的占位方法**
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
throw new NotImplementedException();
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
throw new NotImplementedException();
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
throw new NotImplementedException();
}
```
按 Integration Widget 分步操作时,这是一个已知的小卡点。由于小组件会将这些方法拆分在多个步骤中逐步完善,部分接口要求要到后续步骤才会补齐。
### 配置项目 ID 和登录管理器 ID
在复制过来的代码中,您会看到带有默认占位值的 `SetProjectId` 和 `SetLoginId` 调用,它们指向一个通用的艾克索拉演示项目。仅做快速连通性验证时可以直接使用,但若要接入自己的商品目录,则需要替换为您的专属项目凭证。为此,请先在[发布商帐户](https://publisher.xsolla.com)中完成项目设置。
#### 在发布商帐户中创建新项目
- 登录发布商帐户,在侧边栏点击**创建项目**
![32dd095f-82ea-4c1e-a00b-368078285eee.png]
发布商帐户:创建新项目
- 填写基础信息。本指南建议:
- 项目类型:游戏
- 发布平台:PC
- 变现方式:游戏内交易
- 开发阶段:概念
- 类型:冒险
- 游戏引擎:Unity
![5e8ae1cc-0851-4568-9111-5c0ebe288afa.png]
已填写完成的项目详情
- 点击**创建项目**,并记下新生成的**项目 ID**
![f0c2fa2a-8058-468b-9173-50ee1133a0e1.png]
#### 设置登录管理器项目
登录管理器项目用于告知 SDK 您的应用采用哪套身份认证配置,可按身份认证类型和目标平台灵活设置。创建步骤如下:
- 在发布商帐户项目中,前往侧边栏的**玩家管理 > 登录管理器**
![0f5e74d8-5b51-414e-bef3-570fbacbe5f0.png]
- 创建一个新的登录管理器项目
![ed468261-aabb-4c45-a9ec-24815e9d8d10.png]
标准登录管理器项目
- 选择**经典登录**作为基础方式。
![0cfe4ce8-58ad-45f0-8dee-95cd22a9ae17.png]
将登录管理器项目的默认方式配置为经典登录
- 点击**配置**,前往**登录管理器 API 集成**
![cab0aaff-3804-4c1e-a549-15d4c11b3091.png]
- 确保已开启**使用设备 ID 登录**
![6d437782-10c4-4678-95ed-e29d0ce10e4d.png]
开启 API 集成开关以启用设备 ID 身份认证
**设备 ID 并非标准的 PC 登录流程**:设备 ID 身份认证并非 PC 游戏的常规做法,但在本指南中它能帮助我们最快跑通集成流程。正式发布时,请参阅身份认证方式文档了解全部可选方案。
保存设置并返回登录管理器看板,此时即可看到您的**项目 ID** 和**登录管理器 ID**。
![2c7e1788-8d42-4e12-b9b9-fbd449e36466.png]
返回编辑器,替换占位值:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(YOUR_PROJECT_ID)
.SetLoginId("YOUR-LOGIN-UUID")
.Build();
```
### 验证身份认证是否正常工作
运行游戏并查看 Unity Console,检查是否输出了确认商店初始化成功且身份认证已完成的日志条目。
此时还会看到一条提示未返回任何商品的报错日志⸺这在当前阶段完全符合预期,因为我们尚未配置加载商品目录。
![8b7b445e-e128-4d28-89d9-44022466a116.png]
错误提示:暂无可用商品
## 第 2 步:加载商品目录
### 在发布商帐户中创建商品
- 在发布商帐户中打开您的项目,在侧边栏前往**商品管理 > 全部商品**。
![216553c1-e6b5-433c-bd53-b0bc9f8cdf82.png]
在发布商帐户运营看板中进入商品管理页面
- 点击**手动创建 > 虚拟物品**。
![5cd34a17-e0fa-4efe-91d6-a6cae7e6764a.png]
![3db58e33-96f1-4ca7-8f27-e8f33b99b982.png]
- 填写详细信息:
- **SKU**:对应游戏内的商品 ID。
- **名称**:购买流程中展示给玩家看的商品名称。
- **价格**:使用真实货币定价。
- 其余选项暂时保持默认
![2c605619-5d63-4d80-809c-2616c7c15594.png]
**务必将商品标记为“可用”**!保存前,请确保在页面右上角将商品状态切换为“可用”。否则即使 SKU 完全正确,该商品也不会出现在游戏中。后续若遇到“no products found”报错,请优先检查该状态开关。
- 向下滚动页面并点击**创建商品**。
### 将商品目录接入游戏
返回 Integration Widget,选择 **Load Catalog** 步骤。需要添加两段代码。
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
void Start()
{
// ... settings, configuration, module initialization (see "Authenticate" step)
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("ticket.10", ProductType.Consumable)
.AddProduct("ticket.20", ProductType.Consumable)
.AddProduct("ticket.30", ProductType.Consumable);
// ... UnityPurchasing.Initialize() invocation (see "Authenticate" step)
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
// ... callback initialization (see "Authenticate" step)
// Products available via _storeController.products.all
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
// Display product to user
}
}
}
```
**首先**,在 `Start` 函数中通过配置生成器将商品注册到 Unity 的 IAP 层:
**注册商品 SKU**
```csharp
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("full-health", ProductType.Consumable);
```
`ProductType.Consumable` 用于告知 Unity 该商品支持重复购买,这对于玩家可能多次购买的生命值恢复等道具尤为关键。如果 Integration Widget 生成的代码中包含多个示例商品,请将其精简为只保留您自己的商品。
**其次**,在 `OnInitialized` 回调中获取商店控制器和扩展的引用。将它们保存为类字段(`_storeController` 和 `_storeExtensions`),便于后续代码发起购买、查询价格,并在后续步骤中验证交易。
**在 OnInitialized 中保存引用**
```csharp
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_storeExtensions = extensions;
}
```
**从控制器获取商品信息**:保存好控制器引用后,即可遍历已加载的商品目录,读取每件商品的 ID、名称、价格和币种。虽然这不是跑通基础集成的必需步骤,但有助于核验商品目录是否已正确加载,也方便后续搭建商店 UI。 ** 可选:打印已加载的商品日志**
```csharp
foreach (var product in _storeController.products.all)
{
string id = product.definition.id;
string title = product.metadata.localizedTitle;
string price = product.metadata.localizedPriceString;
string currency = product.metadata.isoCurrencyCode;
Debug.Log($"Product: {id}, Title: {title}, Price: {price} {currency}");
}
```
### 验证商品目录是否已加载
运行游戏并查看 Console,此时应当能看到所配置商品的详细信息,且第 1 步出现的“no products”报错已不再出现。
![1f2a1a84-c22d-4f3d-91c3-91f920b25bc7.png]
确认商品已成功请求并拉取完毕
## 第 3 步:购买商品
### 添加购买代码
返回 Integration Widget,选择 **Purchase Product** 步骤。关键新增是 `PurchaseSku()` 函数:
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
// Example purchase method
public void PurchaseSku()
{
_storeController.InitiatePurchase("ticket.10");
}
// Purchase result arrives in ProcessPurchase (see "Finalize Purchase" step)
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
}
```
**购买触发函数**
在此示例中,我们将原函数修改为接收一个 `productID`。
```csharp
public void PurchaseSku(string productID)
{
_storeController.InitiatePurchase(productID);
}
```
`productID` 参数使同一个函数能够复用于商品目录中的任意 SKU。调用该函数时,`InitiatePurchase()` 会在玩家的默认浏览器中拉起支付收银台以完成结算,全程不使用应用内 Web 视图;玩家在浏览器中完成支付后返回游戏即可。交易结束后,Unity IAP 会在成功时触发 `ProcessPurchase()`,或在失败时触发 `OnPurchaseFailed()`。
### 实现 OnPurchaseFailed
**Purchase Product** 步骤还提供了失败处理程序。从 Integration Widget 复制这些代码,替换第 1 步中 `NotImplementedException()` 的占位实现:
**替换两个 OnPurchaseFailed 占位实现**
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// Handle user cancellation here
return;
}
Debug.LogError($"Purchase failed: {product.definition.id}, reason: {failureDescription.reason}, message: {failureDescription.message}");
}
```
两个方法都会先检查用户是否取消(玩家在支付收银台中未完成购买就关闭了页面),并对其他失败原因记录错误。第二个变体包含更详细的失败描述。之所以有两个版本,是因为 Unity IAP 存在两个监听接口,触发的签名略有不同。同时提供两者即可覆盖任一接口的回调。对于本指南,这些实现已经足够。
### 接入您的游戏逻辑
Integration Widget 覆盖了购买机制,但如何触发 `PurchaseSku` 取决于您的游戏。对于 2D Game Kit 演示项目,我们这么做:
#### 单例模式
将该类做成单例,便于在项目的任意脚本中访问。这样设置很快,但在最终发布中您也可以选择其他模式。
```csharp
public class XsollaPayStation : MonoBehaviour, IDetailedStoreListener
{
public static XsollaPayStation Instance { get; private set; }
void Awake()
{
if (Instance != null && Instance != this)
{
Destroy(gameObject);
return;
}
Instance = this;
DontDestroyOnLoad(gameObject);
}
}
```
#### 实时定价辅助函数
我们新增了一个 `GetProductPrice` 函数,用于从商店控制器中读取指定 SKU 的当前价格。在发布商帐户中修改定价后,下次重新加载商品目录时游戏内显示的价格便会自动同步更新。但请注意:如果单次游戏会话期间未重新加载商品目录,玩家看到的仍是修改前的价格。
```csharp
public string GetProductPrice(string productId)
{
if (_storeController == null) return "...";
var product = _storeController.products.WithID(productId);
return product != null ? product.metadata.localizedPriceString : "...";
}
```
#### UI 实现
在单独的 UI 类中,将购买按钮的点击事件绑定为调用 `XsollaPayStation.Instance.PurchaseSku("full-health")`,并使用协程通过 `GetProductPrice()` 更新价格文本。
![c3f96843-18b1-400e-a732-e1e85bdfb2dd.png]
购买生命值按钮的代码实现
### 测试购买流程
运行游戏并触发购买操作,此时默认浏览器应当会打开支付收银台,并展示商品名称、价格及可选支付方式。
由于我们处于沙盒模式,您可以直接在支付收银台中使用测试银行卡进行支付。请使用这些卡而非您自己的卡信息。完整的[测试银行卡列表](https://developers.xsolla.com/dev-resources/testing/test-cards/)可在艾克索拉开发者资源中找到。
完成购买后,在 Unity Console 中查看购买确认日志。
![5516124d-81c6-4efd-b590-05abec78d351.png]
浏览器端结算界面
此时,游戏内尚未发生任何变化⸺购买交易虽已完成结算,但游戏客户端还不知道该如何响应这一购买结果。这正是最后一步要实现的逻辑。
## 第 4 步:完成购买
### 了解客户端侧与服务器侧验证
有两种验证方式可选。
**服务器侧验证**使用 Webhook 或艾克索拉 Events API:先告知 Unity IAP 该笔购买处于待处理状态,再由代码轮询事件队列以等待外部确认;收到确认后,调用 `ConfirmPendingPurchase` 核销该笔交易。
**客户端侧验证**(本指南采用)会跳过上述流程。在交易成功的同一时刻直接在客户端确认购买。无需等待、无需轮询、也不存在“待处理”状态。
**为何直接返回 Purchase Processing Complete**?我们的 ProcessPurchase 会立即返回 PurchaseProcessingResult.Complete,而非 Pending。这是有意设计的:在纯客户端侧方案中,并没有后台服务器或 Events API 维护持久化交易队列,采用 Pending + ConfirmPendingPurchase 模式不会带来任何额外收益。当验证与道具发放全部在客户端完成时,直接返回 Complete 才是恰当做法。
**面向生产环境的服务器侧验证**:客户端侧验证是不错的起点,也适用于许多游戏。但对于应用内经济价值较高,或竞技属性较强的游戏,如果玩家非法获取道具会造成明显影响,建议迁移到基于艾克索拉 Webhook 系统的服务器侧验证。服务器侧验证更难被拦截或篡改,因为交易回执不会经过您无法完全控制的客户端代码。
### 实现 Finalize Purchase
前往 Integration Widget,选择 **Finalize Purchase**,复制 `PurchaseProcessingResult()` 函数。
```csharp
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener
{
// ... fields, methods, callbacks from previous steps
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions.GetExtension().GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is valid — grant the item to the player, then confirm:
_storeController.ConfirmPendingPurchase(product);
}
else
{
// Purchase validation failed — do not award item
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Pending;
}
}
```
以下是我们针对**客户端侧验证**改造后的最终实现:
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = args.purchasedProduct;
var validator = _storeExtensions
.GetExtension()
.GetValidator();
validator.Validate(product.receipt, (success, error) =>
{
if (success)
{
Debug.Log($"Purchase successful: {product.definition.id}");
// Your game logic goes here: grant the item, update state, etc.
}
else
{
Debug.LogWarning($"Validation failed for {product.definition.id}");
}
});
return PurchaseProcessingResult.Complete;
}
```
与 Integration Widget 的默认实现相比,我们移除了服务器侧验证代码,仅使用客户端侧路径。我们会立即返回 `Complete`,并在 `Validate` 回调中处理结果。
### 添加您的游戏逻辑
`Validate` 回调中的成功分支,就是游戏响应已确认购买的位置⸺请务必将发放道具、更新状态等后续游戏逻辑写在该分支内。
对于我们的 2D Game Kit 演示项目,我们:
- 销毁购买 UI 弹窗
- 触发玩家复活函数,从上一个检查点以满生命复活
**成功分支中的示例游戏逻辑**
```csharp
if (success)
{
Debug.Log($"Purchase successful: {product.definition.id}");
// Destroy the purchase popup
if (purchaseUI != null)
{
Destroy(purchaseUI);
}
// Trigger respawn with full health
PlayerController.Instance.RespawnWithFullHealth();
}
```
### 验证完整流程
端到端运行游戏,执行完整测试:
- 玩家死亡,出现弹窗,并显示实时价格的购买选项
- 点击购买按钮,默认浏览器打开支付收银台
- 使用测试银行卡完成购买
- 返回 Unity,玩家以满生命复活,购买弹窗关闭
艾克索拉购买流程演示 查看 Console 中输出的完整购买收尾流程:触发验证、输出购买确认日志,以及关闭该笔交易。
## 您已经构建了什么
至此,您已在 PC 端 Unity 项目中完成了一套完整的艾克索拉支付集成⸺涵盖设备 ID 身份认证、动态商品目录、外部浏览器支付收银台,以及客户端侧购买验证。
最终的类结构应包含:
- **初始化与身份认证**:配置您的项目 ID 和登录管理器 ID
- **商品目录注册**:向 Unity IAP 声明您的商品 SKU
- 将 `PurchaseSku` 绑定到游戏内的 UI 触发入口
- `ProcessPurchase` 立即返回 `Complete`,并触发游戏的购买后逻辑
- 提供两个 `OnPurchaseFailed` 版本,并妥善处理失败
**正式发布前请务必关闭沙盒模式**:如果测试期间调用了 SetSandbox(true),上线发版前请务必将其改为 false。在生产环境中保留沙盒模式开启会导致真实购买无法完成处理。
## 下一步
后续步骤:
- **添加更多商品**。
- 扩展 `AddProduct` 与商店 UI,以支持完整的商品目录
- **迁移至[服务器侧验证](https://developers.xsolla.com/sdk/unity/sdk/validation/#server-side-validation)或 [Events API](https://developers.xsolla.com/sdk/publisher-account/webhooks#enabling-xsolla-events-api)**。
- 正式上线发布时,建议将本指南采用的客户端侧方案升级为基于艾克索拉 Events API 或 Webhook 的服务器侧验证。借助 SDK Explorer 可以直观对比两种方案在代码与流程上的具体差异
- 您可能需要联系您的客户经理,或发送邮件至 [[email protected]](mailto:[email protected]),以为您的项目配置 Events API
- **探索其他[身份认证方式](https://developers.xsolla.com/api/login/getting-user-token)**。
- 设备 ID 上手快捷,但在玩家更换设备后无法保留身份。艾克索拉支持邮箱、社交帐户及平台原生身份认证
- **[配置支付收银台](https://developers.xsolla.com/payment-ui-and-flow/payment-ui/ui-theme-customization/#pay_station_ui_theme_customization_how_it_works)**。
- 在发布商帐户中可配置支付方式、UI 主题和区域设置
- **配置网充商店或艾克索拉游戏启动器**。
- 若计划进行平台外 PC 游戏分发与正式上线,这两项是 值得搭配使用的方案
[艾克索拉 SDK 网站](https://developers.xsolla.com/sdk/)针对本文涵盖的各项功能及更多进阶主题提供了详尽的实战演练、快速指南和视频。跑通基础集成后,不妨再次打开 [SDK Explorer](https://developers.xsolla.com/sdk/demo/) 深入探索。
祝您顺利。遇到问题,艾克索拉开发者社区和支持团队随时提供帮助。
Unity 专用艾克索拉 SDK
https://developers.xsolla.com/sdk/zh/unity
可用Unity 专用艾克索拉 SDK[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
**Unity 专用艾克索拉 SDK** 支持开发者在**移动端**、**PC** 和 **Web** 的 Unity 项目中,通过**艾克索拉支付收银台**无缝集成游戏内支付,为商店内版本包(例如美国地区的 App Store iOS 与 Google Play 版本包)以及商店外分发的游戏版本包(例如 Android APK、已公证的 iOS、PC 独立版)提供商业变现支持⸺全部通过单次集成即可实现。直接触达玩家,掌控结算体验,并保留高达 95% 的收入。游戏还可自动获取新变现工具、监管合规与全球政策变更的相关更新。
深受 Crossout、Modern Warship 与 Fantasy Tales: Sword and Magic 背后开发团队的信赖,助力其在 iOS、Android、PC、Web 及应用商店生态中开展跨平台游戏商务。
## 平台支持
### iOS 与 Android
在**美国** (Epic v. Apple)、**日本**(《移动软件竞争法》)和**巴西**(Apple 与 CADE 和解协议),开发者可以在 iOS 应用内引导玩家前往外部网页支付。根据 **2025 年 10 月 29 日** Epic 诉 Google 案的禁令,美国区 Google Play 应用可以使用 Google Play 以外的支付方式,并提供外部链接跳转。**Unity 专用艾克索拉 SDK** 符合 Apple 修订后的 App Store 指南以及 Google Play 更新后的支付与结算政策。
### 全面覆盖
- **iOS**:完整支持,提供合规的外链支付选项
- **Android**:支持商店外分发与官方支付体系之外的支付方案
- **Windows**:桌面端变现支持
- **macOS**:macOS 应用支持
- **Web**:WebGL 变现支持
## 面向 Unity 开发者的核心优势
**一次集成,覆盖所有平台**
仅需一个 SDK,即可在 iOS、Android、Windows、macOS 和 Web 快速上线。无论 Unity 游戏发布到哪个平台,商业变现体验始终一致⸺且完全由您掌控。**DMA 与法院命令合规**
完全符合 Apple 修订后的 App Store 指南和 Google Play 更新后的支付与结算政策⸺开箱即支持外链支付和官方支付体系之外的支付方案。**收入留存率最高 95%**
在应用商店之外直接连接玩家。绕过平台分成,保留定价权,并建立直接的玩家关系,推动长期参与。**1000+ 种支付方式**
全球支付基础设施覆盖 200+ 个地区、130+ 种货币和 25+ 种 UI 语言⸺内置本地化结算流程和高级反欺诈能力。**专为 Unity 工作流打造**
原生集成 Unity IAP,可通过 Package Manager 轻松安装,并在所有目标平台上支持 Unity 2022.3+ 和 Unity 6+。合规与政策更新自动下发⸺无需手动更新 SDK。
## 开始使用
准备好将艾克索拉 SDK 集成到您的 Unity 项目中了吗?按照“快速开始”指南,几分钟内即可完成 首笔测试支付,也可联系您的客户经理获取个性化集成指导。 **艾克索拉购买按钮**快速路径
网充商店一键购买流程,支持 1000+ 种支付方式⸺无需安装 SDK。可在 Unity 游戏中直接拉起基于浏览器的结算,覆盖 PC、移动端(在适用场景下符合平台政策)与 Web。[了解更多 →](https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button/) [快速开始**集成指南**5 步完成首笔测试支付→](https://developers.xsolla.com/sdk/zh/unity/quick-start/)[快速路径**购买按钮**一键外链支付⸺无需集成完整 SDK→](https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button/)[参考**完整 SDK 文档**高级功能、重试策略、自定义 UI→](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)
Unity 专用艾克索拉 SDK - 移动端
https://developers.xsolla.com/sdk/zh/unity/mobile
ℹ️外部支付外链跳转与官方支付体系外的支付方案 — iOS 和 Android
**iOS**:在美国、日本和巴西,Apple 现已允许开发者引导玩家使用外部网页支付。**艾克索拉 SDK** 符合 Apple 更新后的指南。
**Android⸺自 2025 年 10 月 29 日起生效**:根据 **Epic v. Google** 禁令,美国区 **Google Play** 应用可通过外链跳转引导用户使用**外部支付方式**,接入**官方支付体系之外的支付方案**,且不再受**反引导限制**约束。
针对这 两个平台,推荐采用的最快捷非 SDK 方案是[**通过外链跳转至网充商店的购买按钮** ↗](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase) ([https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)。](https://developers.xsolla.com/solutions/web-shop/other/instant-purchase)%E3%80%82)
⚡ **无缝移动商务**:在 Unity 移动端版本包中即可集成符合 DMA 规范的支付结算与商店外分发能力,并接入超过 **1000 种本地支付方式**。
本指南将协助您在 Android 和 iOS 平台的 Unity 游戏中集成 Unity 专用艾克索拉 SDK 以实现收款。完成后,您将在游戏中搭建起完整的支付系统,并亲身体验艾克索拉如何简化变现流程。
现在就开始,只需简单几步即可让您的游戏具备收款能力!
## 快速开始
本快速开始指南可帮助您轻松集成 Unity 专用艾克索拉 SDK,并在 Unity 游戏中开始收款。本指南使用预配置的测试项目演示核心流程:设置基础用户身份认证、导入商品 (SKU),以及完成一次测试支付。
详细说明请参见[**快速开始**](https://developers.xsolla.com/sdk/zh/unity/quick-start/)。
## 设置发布商帐户
在将艾克索拉 SDK 集成到游戏前 ,需要注册发布商帐户。
发布商帐户是配置艾克索拉各项功能、查看分析数据及管理交易的核心工具,作用类似于管理 SKU 时使用的 Google Play Console 和 App Store Connect。important
您需要拥有已激活的发布商帐户才能获取项目 ID,整个 SDK 集成流程都会用到该 ID。
详细步骤请参见[**设置发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)。
## 安装 SDK
设置好发布商帐户后,下一步是在 Unity 项目中安装 Unity 专用艾克索拉 SDK (Xsolla SDK for Unity) 插件。
通用安装说明请参见[**安装指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)。
#### 平台特定说明
各平台的设置请参见以下链接:
在 Android 上安装 SDK 需要解析项目依赖项。
具体操作方法请参见[**解析 Android 依赖项 ↗**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/resolving-android-dependencies/)。
iOS 无需额外步骤。
## 配置 SDK
安装完成后,继续进行配置。
配置细节请参见[**配置指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。
#### 平台特定说明
各平台的设置请参见以下链接:
### 购买按钮解决方案或网充商店外链跳转(推荐)
important
要启用**仅限美国**的外链跳转(自 **2025 年 10 月 29 日**起生效),请先参照[**此处**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detect-gpb-storefront-android/)提供的指南,检测 **Google Play** 商店的国家/地区代码。
有关配置购买按钮方案或网充商店外链跳转的详细说明,请参见[**此处**](https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button/)。
### 标准方案
通过 Google Play Store 以外的渠道分发应用时,您可能需要检测应用的安装来源。
具体操作方法请参见[**如何检测商店安装来源**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore/)。
如需在美国、日本和巴西引导玩家使用外部网页支付,或在欧洲满足 DMA 应用内支付合规要求,请参见:
- [**如何检测 iOS 商店地区**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/ios-storefront/)
- [**配置 - iOS**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/ios/)
## 初 始化 SDK
配置完成后,您即可在 Unity 项目中初始化 SDK。
详细步骤与最佳实践请参见[**初始化**](https://developers.xsolla.com/sdk/zh/unity/sdk/initialization/)。
## 发起购买
完成 SDK 初始化后,应用已准备好开始处理支付。
详细步骤请参见[**发起购买**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)。
## 收款
SDK 通过**艾克索拉支付收银台**进行安全收款。
以下步骤将引导您完成一次测试收款流程:
- 选择**银行卡**支付方式(使用[**此处 ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) 中列出的任一测试银行卡),并点击**支付**发起支付: ![快速开始 3]
- 等待支付完成: ![快速开始 3]
- 支付完成后,将显示确认信息: ![快速开始 3]
- 选择**银行卡**支付方式: ![快速开始 3]
- 使用[**此处 ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) 中列出的任一测试银行卡,并点击**支付**确认支付: ![快速开始 3]
- 支付完成后,将显示确认信息: ![快速开始 3]
## 购买验证
配置好支付功能后,建议对购买交易进行验证,确保交易安全可靠。
详细步骤请参见[**购买验证**](https://developers.xsolla.com/sdk/zh/unity/sdk/validation/)。
## 测试与沙盒
最后,可在沙盒环境中安全测试完整的支付集成流程,而无需产生真实交易。
详细步骤请参见[**测试与沙盒**](https://developers.xsolla.com/sdk/zh/unity/sdk/testing/)。
## 下一步
恭喜!🎉 您已成功集成 **Unity 专用艾克索拉 SDK**!
现在您的游戏已可接入全球超过 1000 种支付方式,这也为后续集成网充商店等更多艾克索拉解决方案奠定了基础。
购买按钮 - Unity
https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button
为 Unity 应用添加外部支付有两种简单方式:将用户重定向至网充商店,或在应用内启动支付收银台的原生 UI。两种方式均可直接用于生产环境⸺请选择最契合您工作流的方案。 推荐
#### 网充商店外链跳转
在浏览器中将用户重定向至现有的艾克索拉网充商店。
- 已拥有艾克索拉网充商店
- 希望尽量减少代码改动
- 需要 Web 端与移动端的支付一致性
- 正从 Web 端分阶段迁移
#### 购买按钮解决方案
在应用内以原生方式处理完整的支付 UI,无需浏览器重定向。
- 希望完全原生集成
- 需要开箱即用的 1000+ 种支付方式
- 更希望由艾克索拉管理支付 UI
- 希望自动满足各地区合规要求
important
要仅在政策允许的地区启用外链跳转,请先检测商店国家/地区代码:[**Android**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detect-gpb-storefront-android/)(美国,自 2025 年 10 月 29 日起生效)·[**iOS**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/ios-storefront/)(美国、日本和巴西)。
```csharp
// Provide Web Shop URL in settings
var settings = XsollaClientSettings.Builder.Create()
// An URL to your Xsolla-based web shop.
.SetWebShopUrl("https://yourwebshop.xsolla.site")
// A deeplink URL used to return the purchase result to your app.
// E.g. `myapp://open`.
.SetRedirectUrl("<schema>://<host>")
.Build();
// Enable Web Shop simple mode and pass user identifier
var configuration = XsollaClientConfiguration.Builder.Builder.Create()
.SetSettings(settings)
// Make sure the mode is switched to `XsollaClientConfiguration.SimpleMode.WebShop` for link-outs.
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.WebShop)
// User ID to be associated with the purchase.
.SetUserId("<USER_ID>")
.Build();
```
这会 在设备浏览器中打开您的网充商店。订单履约通过服务器侧 Webhook 完成⸺请参见 [Webhook 设置](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/)。
```csharp
var settings = XsollaClientSettings.Builder.Create()
// It's important to set this setting to `true`.
.SetUseBuyButtonSolution(true)
// .. your other settings
.Build();
var configuration = XsollaClientConfiguration.Builder.Builder.Create()
.SetSettings(settings)
// Make sure the mode is switched to `XsollaClientConfiguration.SimpleMode.Off` for the `Buy Button` solution.
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.Off)
// .. your other settings
.Build();
```
在 SDK 配置中启用一次后,购买按钮会自动应用到所有[默认购买流程](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)。高级选项请参见[配置文档](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。 还不确定?
**网充商店**适合已拥有商店或希望以最少改动快速起步的场景。**支付收银台**是实现完全原生集成的最快路径。两者在全球范围内支持相同的支付方式和地区。
Unity 专用艾克索拉 SDK - PC
https://developers.xsolla.com/sdk/zh/unity/pc
信息
**Unity 专用艾克索拉 SDK** 是企业级艾克索拉 SDK 解决方案的升级版,最初专为大型项目集成而设计。
💡 **面向全球的 PC 变现**:借助艾克索拉支付引擎,通过网充商店、购买按钮或直接调用 API 实现合规、本地化的结算流程,在买断制与 F2P 模式下最大化营收。
本指南将协助您在 PC 端的 Unity 游戏中集成 Unity 专用艾克索拉 SDK 以实现收款。完成后,您将在游戏中搭建起完整的支付系统,并亲身体验艾克索拉如何简化变现流程。
现在就开始,只需简单几步即可让您的游戏具备收款能力!
## 快速开始
本快速开始指南可帮助您在 PC 端轻松集成 Unity 专用艾克索拉 SDK,并在 Unity 游戏中开始收款。本指南使用预配置的测试项目演示核心流程:设置基础用户身份认证、导入商品 (SKU),以及完成一次测试支付。
详细步骤请参见[**快速开始指南**](https://developers.xsolla.com/sdk/zh/unity/quick-start/)。
## 设置发布商帐户
在将艾克索拉 SDK 集成到游戏前,需要注册发布商帐户。
发布商帐户是配置艾克索拉各项功能、查看分析数据及管理交易的核心工具,作用类似于管理 SKU 时使用的 Google Play Console 和 App Store Connect。important
您需要拥有已激活的发布商帐户才能获取项目 ID,整个 SDK 集成流程都会用到该 ID。
详细步骤请参见[**设置发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)。
## 安装 SDK
设置好发布商帐户后,下一步是在 Unity 项目中安装 Unity 专用艾克索拉 SDK (Xsolla SDK for Unity) 插件。
安装细节请参见[**安装指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)。
## 配置 SDK
安装完成后,继续进行配置。
配置细节请参见[**配置指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。信息
对于 Unity Editor、Windows 和 macOS 版本包,`WebViewType` 默认设为 `Auto`,并会在系统默认的外部浏览器中打开。
此行为可确保在各平台上的开发与测试期间具备兼容性与一致性。
## 初始化 SDK
配置完成后,您即可在 Unity 项目中初始化 SDK。
详细步骤与最佳实践请参见[**初始化指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/initialization/)。
## 发起购买
完成 SDK 初始化后,应用已准备好开始处理支付。
详细步骤请参见[**发起购买**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)。
## 收款
SDK 通过**艾克索拉支付收银台**进行安全收款。
以下步骤将引导您完成一次测试收款流程:
- 选择**银行卡**支付方式: ![快速开始 3]
- 使用[**此处 ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) 中列出的任一测试银行卡,并点击**支付**确认支付: ![快速开始 3]
- 支付完成后,您会看到确认信息: ![快速开始 3]
## 购买验证
配置好支付功能后,建议对购买交易进行验证,确保交易安全可靠。
详细步骤请参见[**购买验证**](https://developers.xsolla.com/sdk/zh/unity/sdk/validation/)。
## 测试与沙盒
最后,可在沙盒环境中安全测试完整的支付集成流程,而无需产生真实交易。
详细步骤请参见[**测试与沙盒**](https://developers.xsolla.com/sdk/zh/unity/sdk/testing/)。
## 下一步
恭喜!🎉 您已在 PC 端成功集成 **Unity 专用艾克索拉 SDK**!
现在您的游戏已可接入全球超过 1000 种支付方式,这也为后续集成网充商店等更多艾克索拉解决方案奠定了基础。
快速开始 — Unity 专用 SDK
https://developers.xsolla.com/sdk/zh/unity/quick-start
集成 **Unity 专用艾克索拉 SDK**,并完成第一笔测试支付。我们提供了预配置的测试凭证,几分钟内即可上手。
🔥 **经过生产验证**:遵循与 Crossout 和 Modern Warship 等游戏相同的集成路径,开箱即享**符合 DMA 的计费**与 **1000+ 种支付方式**。
## 开始使用
通过 Unity Package Manager 安装 SDK:
- 在 Unity Editor 中,点击 **Window** > **Package Manager**。
- 点击 ➕ 图标并选择 **Add package from git URL...**。
- 输入 `https://github.com/xsolla/xsolla-sdk-unity.git` 并点击 **Add**。
然后配置项目凭证:
- 前往 **Window > Xsolla > SDK > Edit Settings**。
- 在 Inspector 面板中,设置以下测试值:
| 属性 | 值 |
| --- | --- |
| Project ID | 301871 |
| Login ID | dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a |
![设置资源]
更多安装方式请参见[安装详情](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)。 前置条件
请确保已安装 Unity **In-App Purchasing `4.15+`**。
请参见官方 [Unity IAP 设置指南 ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)。](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)%E3%80%82)
⚠️ 当前**暂不支持** Unity **In-App Purchasing `5.x`**。
## 身份认证
将以下内容添加到 `MonoBehaviour` 的 `Start()` 方法中:
```csharp
using UnityEngine.Purchasing;
public class YourSDKIntegrationBehaviour : MonoBehaviour, IDetailedStoreListener {
void Start() {
var settings = XsollaStoreClientSettingsAsset.Instance().settings;
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
// Continue with Load Catalog
}
}
```
这会加载项目设置,并创建启用了沙盒模式和调试日志的 `Configuration`。用于生产环境时,请将测试项目 ID 和登录管理器 ID 替换为您在[**发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)中的对应值。高级选项请参见[配置文档](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。important
如果您使用自己的**项目 ID/登录管理器 ID**,请确保在项目中启用**设备 ID 登录**。启用方法请参见:[https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account)iOS
在美国、日本和巴西,请使用 `WebViewType.External`;而对于欧盟 DMA 场景下的应用内流程,请使用 `WebViewType.Auto`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.External) // or .Auto for EU
.Build();
```
## 加载商品目录
注册商品并初始化 Unity IAP。与需要单独发起异步调用加载商品目录的原生移动 SDK 不同,Unity IAP 会在初始化期间自动拉取商品⸺只需声明商品 SKU 即可。
```csharp
// Inside Start(), after creating configuration:
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder.Instance(module)
.AddProduct("money.100", ProductType.Consumable); // Test product SKU
UnityPurchasing.Initialize(this, configurationBuilder);
```
该代码会注册测试商品并启动购买系统。`OnInitialized` 触发后,商品目录即已加载完毕并可发起购买。有关 Unity IAP 设置和高级选项,请参见[初始化文档](https://developers.xsolla.com/sdk/zh/unity/sdk/initialization/)。
## 购买商品
商品目录加载完成时会触发 `OnInitialized` 回调。可通过该回调发起购买:
```csharp
// IDetailedStoreListener callback — catalog loaded and ready:
public void OnInitialized(IStoreController controller, IExtensionProvider extensions) {
controller.InitiatePurchase("money.100");
}
```
这会打开**艾克索拉支付收银台**,用户在其中完成支付。测试时,请使用[测试银行卡 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/dev-resources/testing/test-cards/):](https://developers.xsolla.com/dev-resources/testing/test-cards/)%EF%BC%9A)
![选择支 付方式]
![处理支付]
![支付已确认]
## 完成购买
购买完成后,处理该购买并向用户发放商品:
```csharp
// IDetailedStoreListener callback — purchase completed:
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args) {
if (args.purchasedProduct.definition.id == "money.100") {
Debug.Log("Purchase consumed - award item to user");
// Award the product (virtual item) to the user here
}
return PurchaseProcessingResult.Complete;
}
```
返回 `PurchaseProcessingResult.Complete` 表示确认该交易。更多错误场景与高级选项参见[购买流程文档](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)。
## 下一步
您已完成完整的支付集成,涵盖身份认证、商品目录加载、购买流程与履约。应用现可在 200+ 个国家/地区接入 1000+ 种支付方式。
- **[设 置项目](https://developers.xsolla.com/sdk/zh/publisher-account/)** — 创建发布商帐户,并将沙盒测试凭证替换为生产环境凭证
- **[购买按钮](https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button/)** — 接入外部支付的最快路径
- **[扩展示例](https://developers.xsolla.com/sdk/zh/unity/quick-start/extended-example/)** — 完整的可运行接入实现
- **[完整 SDK 文档](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)** — 涵盖高级功能、重试策略与自定义 UI
扩展示例 (IAP)
https://developers.xsolla.com/sdk/zh/unity/quick-start/extended-example
**Unity 专用艾克索拉 SDK** 通过扩展模块集成到 Unity InAppPurchasing。
在 iOS 和 Android 上的工作方式相同。
只需在发起购买前,在代码中的任意位置完成该模块的配置和初始化。
## 配置与初始化
前置条件
请确保已安装 Unity **In-App Purchasing `4.15+`**。
请参见官方 [Unity IAP 设置指南 ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)。](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)%E3%80%82)
⚠️ 当前**暂不支持** Unity **In-App Purchasing `5.x`**。
```csharp
public class MyIAPManager
{
// ...
public MyIAPManager()
{
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.SetSandbox(true)
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
builder.AddProduct("money.100", ProductType.Consumable, new IDs
{
{ "money.100", XsollaPurchasingModule.StoreName },
{ "money_100_google", GooglePlay.Name },
{ "money_100_mac", MacAppStore.Name }
});
UnityPurchasing.Initialize(this, builder);
}
// ...
}
```
important
如果您使用自己的**项目 ID/登录管理器 ID**,请确保在项目中启用**设备 ID 登录**。启用方法请参见:[https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account](https://developers.xsolla.com/sdk/publisher-account/login#enable-device-id-login-in-publisher-account) 提示
官方 **Unity IAP** 初始化指南请参见[**此处 ↗**](https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html)。](https://docs.unity3d.com/Packages/[email protected]/manual/UnityIAPInitialization.html)%E3%80%82)
## 完整实现
以下代码基于官方现有的 Unity IAP 示例 **"01 Buying Consumables"**:
[![发布商帐户 6]](https://developers.xsolla.com/sdk/zh/assets/files/example-6b727680d84cf9a5e89ca70611261c35.png/)
代码示例:
```csharp
using UnityEngine;
using UnityEngine.Purchasing;
using UnityEngine.Purchasing.Extension;
using UnityEngine.UI;
using Xsolla.SDK.Common;
using Xsolla.SDK.Store;
using Xsolla.SDK.UnityPurchasing;
namespace Samples.Purchasing.Core.BuyingConsumables
{
public class BuyingConsumables : MonoBehaviour, IDetailedStoreListener
{
IStoreController m_StoreController; // The Unity Purchasing system.
//Your products IDs. They should match the ids of your products in your store.
public string moneyProductId = "money.100";
public string ticketProductId = "ticket.10";
public Text MoneyCountText;
public Text TicketCountText;
int m_MoneyCount;
int m_TicketCount;
void Start()
{
InitializePurchasing();
UpdateUI();
}
void InitializePurchasing()
{
//Remove this line from the original code.
//var builder = ConfigurationBuilder.Instance(StandardPurchasingModule.Instance());
//Add these lines here..
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId(301871)
.SetLoginId("dfcb133b-6d0b-4937-b8d2-c4f4d58fb53a")
.SetSandbox(true)
.Build();
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.Build();
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var builder = ConfigurationBuilder.Instance(module);
//Add products that will be purchasable and indicate its type.
builder.AddProduct(moneyProductId, ProductType.Consumable);
builder.AddProduct(ticketProductId, ProductType.Consumable);
UnityPurchasing.Initialize(this, builder);
}
public void BuyMoney()
{
m_StoreController.InitiatePurchase(moneyProductId);
}
public void BuyTicket()
{
m_StoreController.InitiatePurchase(ticketProductId);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
Debug.Log("In-App Purchasing successfully initialized");
m_StoreController = controller;
}
public void OnInitializeFailed(InitializationFailureReason error)
{
OnInitializeFailed(error, null);
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
var errorMessage = $"Purchasing failed to initialize. Reason: {error}.";
if (message != null)
{
errorMessage += $" More details: {message}";
}
Debug.Log(errorMessage);
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
//Retrieve the purchased product
var product = args.purchasedProduct;
//Add the purchased product to the players inventory
if (product.definition.id == moneyProductId)
{
AddMoney();
}
else if (product.definition.id == ticketProductId)
{
AddTicket();
}
Debug.Log($"Purchase Complete - Product: {product.definition.id}");
//We return Complete, informing IAP that the processing on our side is done and the transaction can be closed.
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
Debug.Log($"Purchase failed - Product: '{product.definition.id}', PurchaseFailureReason: {failureReason}");
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
Debug.Log($"Purchase failed - Product: '{product.definition.id}'," +
$" Purchase failure reason: {failureDescription.reason}," +
$" Purchase failure details: {failureDescription.message}");
}
void AddMoney()
{
m_MoneyCount++;
UpdateUI();
}
void AddTicket()
{
m_TicketCount++;
UpdateUI();
}
void UpdateUI()
{
MoneyCountText.text = $"Your Money: {m_MoneyCount}";
TicketCountText.text = $"Your Tickets: {m_TicketCount}";
}
}
}
```
如何检测 Google Play 商店地区 (Unity/Android)?
https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detect-gpb-storefront-android
通过 **Google Play** 分发应用时,您可能需要检测当前的商店地区,以实现特定地区的功能。商店地区指与用户帐户关联的 Google Play 地区,由 **ISO-3166-1 alpha-2** 格式的两位国家/地区代码标识(例如美国为 `"US"`)。 important
鉴于自 **2025 年 10 月 29 日**起生效的 **Epic 诉 Google** 案禁令,此项检测尤为重要。该禁令允许美国区 **Google Play** 应用**通过外链跳转引导用户使用外部支付方式**、采用**备选结算方案**,并禁止施加**反引导限制**。
通过商店地区检测,您可以:
- 专门面向美国用户启用备选结算方案
- 实现面向不同地区的支付流程
- 根据当地支付与结算法规控制功能可用性
- 确保符合美国法院裁定的合规要求
可以使用以下代码片段获取 Google Play 商店地区的国家/地区代码: important
当**通过 Google Play 商店分发并安装**应用时,此代码片段最为实用。如需检查应用是自 Google Play 商店安装还是通过侧载(第三方应用商店或 APK 分发)安装,可使用 `XsollaStoreClientInfo.IsInstalledFromGooglePlayStore()` 工具函数。 提示
在获取 Google Play 商店地区的国家/地区代码之前,建议(非强制)先确认设备上是否已安装 Google Play 商店,否则商店不可用时查询函数会报错。为此可以使用 `XsollaStoreClientInfo.IsGooglePlayStoreInstalled()` 工具函数。
```csharp
XsollaStoreClientInfo.QueryGooglePlayCountryCodeAsync(
onSuccess: countryCode =>
{
if (countryCode.IsCode("us"))
{
// Handle the US storefront.
}
else
{
// Handle all other storefront variants.
}
},
onError: err =>
{
// Handle the error here.
}
);
```
如何检测应用商店安装来源?
https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore
通过官方应用商店(如 Google Play 商店或 Apple App Store)以外的替代渠道分发应用时,您可能需要检测应用的安装来源。这在以下场景中尤为重要:
- 为不同的替代分发渠道实现差异化支付流程
- 根据安装来源调整应用行为
- 确保符合特定平台的合规要求
- 管控仅在特定分发渠道开放的功能
要检测游戏是否在替代分发渠道(官方应用商店以外)中运行,请使用以下代码片段:
下面提供一些辅助代码片段,可根据安装程序的包名、Google Play 商店的国家/地区代码等因素调整应用行为。
### 如何检查是否已安装 Google Play 商店?
当部分功能根本不应在 Google Play 商店生态系统之外尝试运行时,此检测非常实用。以下代码片段可用于判断设备是否已安装 **Google Play 商店**。
```csharp
if (XsollaStoreClientInfo.IsGooglePlayStoreInstalled())
{
Debug.Log("Google Play Store found!");
}
else
{
Debug.Log("Google Play Store NOT found!");
}
```
### 检查应用是否通过 Google Play 商店安装
以下代码片段可用于判断应用是直接通过 Google Play 商店安装,还是通过侧载方式安装(例如通过 APK 安装)。
```csharp
if (XsollaStoreClientInfo.IsInstalledFromGooglePlayStore())
{
Debug.Log("App was installed from Google Play Store");
}
else
{
Debug.Log("App was NOT installed from Google Play Store");
}
```
### 查询安装程序的包名
如果需要知道应用安装程序的准确包名,请使用以下代码。
```csharp
var installerPackageName = XsollaStoreClientInfo.GetInstallerPackageName();
var matched = installerPackageName.Equals("com.xxx.yyy.zzz", StringComparison.OrdinalIgnoreCase);
if (matched)
{
Debug.Log($"Expected installer package name: {installerPackageName}");
}
else
{
Debug.Log($"Unexpected installer package name: {installerPackageName}");
}
```
如果不关心安装程序的具体包名,倾向于更简化的做法,可以使用以下代码:
```csharp
var matched = XsollaStoreClientInfo.IsInstallerPackageName("com.xxx.yyy.zzz");
if (matched)
{
Debug.Log("Expected installer package name found!");
}
else
{
Debug.Log("Expected installer package name NOT found!");
}
```
### 上报自定义安装来源
每笔购买都会携带应用的安装来源渠道。SDK 会根据安装程序的包名自动检测该渠道。
对于在应用商店之外分发的版本包(例如从您的网站下载的 APK),操作系统上报的可能是浏览器、系统软件包安装程序,或根本没有安装程序。此时请手动设置安装渠道,后续购买将归因到您设置的渠道,而非自动检测到的结果:
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetInstallSource("website")
.Build();
```
```csharp
XsollaPurchasingStoreInfo.GetAppleDistributionStatus((isRunningInAlternativeDistribution, error) =>
{
if (error != null)
Debug.LogError($"Failed to get Apple Distribution: {error}");
else
Debug.Log("Apple Distribution is alternative: " + isRunningInAlternativeDistribution);
});
```
如何检测 iOS 商店地区?
https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/ios-storefront
通过 Apple App Store 分发应用时,您可能需要检测当前的商店地区,以实现特定地区的功能。商店地区代表用户当前使用的 App Store 地区,由三位字母的国家/地区代码标识(例如“USA”代表美国)。
这项检测尤为重要,因为目前已有多地的商店地区允许开发者将玩家引导至外部支付页面⸺**美国**(Epic 诉 Apple 案)、**日本**(《移动软件竞争法》)、**巴西**(CADE 和解协议)以及**欧盟**(《数字市场法案》)。通过商店地区检测,您可以:
- 在允许外部支付的商店地区启用外部支付链接
- 实现特定地区的支付流程
- 根据地区要求控制功能可用性
- 确保符合当地法规
备注
如果应用通过**替代分发渠道**安装(例如 DMA 框架下的替代 App 市场或网页分发),商店地区的国家/地区代码可能无法获取,并会返回**空字符串**。这种情况下,请参阅[**应用商店安装来源检测**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore/)指南,判断应用是否运行在替代分发环境中。
要确定当前的 iOS 商店地区并按地区控制 SDK 功能,请使用以下代码片段:
```csharp
XsollaStoreClientInfo.GetAppleStorefront((storefront, error) =>
{
if (error != null)
{
Debug.LogError($"Failed to get Apple Storefront: {error}");
return;
}
// Storefronts where Apple permits external payments, using an external browser.
// In the EU either flow is allowed, so add its codes here only if you route out to the web.
bool allowsExternalPayments = storefront == "USA" || storefront == "JPN" || storefront == "BRA";
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(allowsExternalPayments
? XsollaClientSettings.WebViewType.External
: XsollaClientSettings.WebViewType.Auto)
.Build();
});
```
Trusted Web Activity (Unity/Android)
https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/trusted-web-activity
[**Trusted Web Activity (TWA) ↗**](https://developer.chrome.com/docs/android/trusted-web-activity) ([https://developer.chrome.com/docs/android/trusted-web-activity](https://developer.chrome.com/docs/android/trusted-web-activity)) 支持 Android 应用通过 Chrome 以全屏模式展示网页内容,不显示任何浏览器界面元素。与 WebView 不同,TWA 在用户的浏览器环境中运行,性能更佳,可调用浏览器功能(如推送通知和后台同步),并能在应用与浏览器之间共享 Cookie、权限和存储。 important
要启用 Trusted Web Activity,请联系您的集成经理,并提供应用的包名和证书哈希值。 您知道吗?
Trusted Web Activity 支持与具体项目无关,直接在应用级别生效⸺仅取决于包名和签名证书。
### 在 SDK 中配置 Trusted Web Activity
配置 SDK 时,按如下方式向配置中传入 Activity 设置:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
// ...other settings
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Trusted)
// ...other settings
.Build();
```
这样可确保支付流程使用 Trusted Web Activity。 注意
Trusted Web Activity 是否可用取决于设备的系统配置,即设备上必须安装兼容的浏览器。如果当前环境不支持 TWA,SDK 会自动回退为默认的支付 Activity 类型(例如 Custom Tabs 或 WebView,具体视运行环境而定)。
TWA 实际效果示例: [](https://developers.xsolla.com/sdk/zh/assets/images/twa-1-737175ed3a44e80fb60131748dda4361.jpg)
### 屏幕方向锁定(可选)
Trusted Web Activity 在显示时原生支持屏幕方向锁定,可在配置阶段通过以下代码进行设置:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
// ...other settings
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
// ...other settings
.Build();
```
方向设置可选以下值:
- `XsollaStoreClientSettings.OrientationLock.Portrait` - 强制以竖屏模式显示 TWA。
- `XsollaStoreClientSettings.OrientationLock.Landscape` - 强制以横屏模式显示 TWA。
- `XsollaStoreClientSettings.OrientationLock.Auto` - 禁用屏幕方向锁定。
### 添加可自定义的启动画面(可选)
Trusted Web Activity 还支持在打开 TWA 前展示可自定义的启动画面。
如需启用该功能,请修改前文添加的[配置项](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/trusted-web-activity#configuring-for-trusted-web-activity-in-the-sdk),采用其中一种支持的方式指定自定义启动画面图片。
TWA 启动画面示例: [](https://developers.xsolla.com/sdk/zh/assets/images/twa-2-fd93e4a14c1a92ff7574a04d1a7abf15.jpg)
#### 为启动画面设置图片
可以通过两种方式提供图片:drawable ID 或图片文件路径:
- 使用 drawable ID: important 需要事先手动将该 drawable 添加到 Android 资源中。 ```csharp var settings = XsollaStoreClientSettings.Builder.Create() // ...other settings .SetWebViewSplashScreenDrawableIdAndroid(<your_splash_screen_drawable_id>) // ...other settings .Build(); ``` 提示 也支持 SVG 格式,但需要封装为有效的 drawable XML。
- 使用文件路径: important 图片文件必须位于应用可访问的路径下。支持所有主流光栅图像格式。 ```csharp var settings = XsollaStoreClientSettings.Builder.Create() // ...other settings .SetWebViewSplashScreenImage(<filepath_to_your_splash_screen_image>) // ...other settings .Build(); ```
备注
如果直接使用 Android 专用艾克索拉 SDK,请访问此页面了解详情:[**Trusted Web Activity - Android**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/trusted-web-activity/)。
配置
https://developers.xsolla.com/sdk/zh/unity/sdk/configuration
在 Unity 中,可通过**设置资源**或**代码**完成配置:
- 资源方式支持**无代码**配置,无需修 改代码即可调整配置。
- **代码**方式更适合需要动态调整配置的应用(例如从应用后端获取开关标志和配置值)。
在 **Unity 编辑器**中:
- 在主菜单中,前往 **Window** > **Xsolla** > **SDK** > **Edit Settings**。
- 打开 **Inspector** 面板。
- 填写 **Project ID** 和 **Login ID** 字段。
[![发布商帐户 6]](https://developers.xsolla.com/sdk/zh/assets/files/settings-5b8f2955492ac0b0b88f04d06f6382a2.png/)提示
如需在代码中访问该资源的设置,请使用以下代码片段:
```csharp
var settings = XsollaStoreClientSettingsAsset.Instance().settings;
```
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetLocalPurchasesRestore(true)
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Auto)
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
.SetUIThemeSize(XsollaStoreClientSettings.ThemeSize.Auto)
.SetUIThemeStyle(XsollaStoreClientSettings.ThemeStyle.Auto)
.SetUICustomTheme("")
.SetUseCloseButton(XsollaStoreClientSettings.CloseButton.Auto)
.SetUIControlTintColor(Color.clear)
.SetUIBarTintColor(Color.clear)
.SetRedirectUrl("")
.SetRedirectButtonText("")
.SetRedirectDelay(6)
.SetEmailCollectionConsentOptIn(null)
.Build();
```
### Android
如需了解平台专属设置(包括 Custom Tabs/TWA 浏览器提供方控制),请参见[**配置 - Android**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/)。
### iOS
important
如需在美国、日本和巴西将玩家引导至外部网页支付,或在欧洲满足 DMA 的应用内支付合规要求,请参见[**配置 - iOS**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/ios/)。
### 购买按钮解决方案
购买按钮解决方案能够以极少的集成工作量提供完整的原生支付体验,通过艾克索拉优化的 UI 组件在应用内处理整个支付流程。
如需查看完整指南(包括网充商店外链跳转与支付收银台的对比、平台说明和示例),请参见[**购买按钮 ⚡**](https://developers.xsolla.com/sdk/zh/unity/mobile/buy-button/)。
**何时使用购买按钮解决方案**:
- 希望快速完成原生支付集成
- 希望由艾克索拉负责支付 UI 与体验优化
- 需要开箱即用地支持多种支付方式
- 希望自动满足各地区的支付合规要求
如需在支付中启用购买按钮解决方案(仅适用于**默认购买流程**),请使用以下代码片段:
```csharp
var settings = XsollaClientSettings.Builder.Create()
.SetUseBuyButtonSolution(true)
.Build();
```
备注
请确保 `XsollaClientConfiguration.SimpleMode` 设置为 `Off`。在网充商店外链跳转模式(`SimpleMode.WebShop`)下,购买按钮解决方案无法使用。
### 网充商店外链跳转
如果希望尽量减少代码改动,可以使用网充商店外链跳转:将用户重定向至现有的艾克索拉网充商店以完成购买。 警告
在网充商店外链跳转模式下,SDK 不会执行原生的应用内支付流程,而是仅打开网充商店并取消所有 SDK 购买回调。请通过网充商店流程(例如 Webhook 或服务器侧逻辑)处理商品发放及支付后的状态更新,切勿依赖 SDK 购买回调。
在设置中填入网充商店 URL,并在配置中启用网充商店简单模式即可完成配置:
```csharp
// Provide Web Shop URL in settings
var settings = XsollaClientSettings.Builder.Create()
.SetWebShopUrl("https://yourwebshop.xsolla.site")
.Build();
// Enable Web Shop simple mode and pass user identifier
var configuration = XsollaClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetSimpleMode(XsollaClientConfiguration.SimpleMode.WebShop)
.SetUserId("<USER_ID>")
.Build();
```
### 已购内容恢复设置
默认情况下,SDK 会自动处理本地已购内容的恢复,以确保用户在重新安装应用,或支付过程中应用崩溃、内存不足时,仍能重新获得此前购买的商品。不过,您应根据后端集成架构调整该行为。
此外,如果倾向于采用无需维护 Webhook 的无服务 器方案,可启用**艾克索拉 Events API** 进行购买内容恢复(详见下文小节),同时保持本地购买内容恢复处于开启状态。
对于基于 Webhook 的集成(即由后端直接接收并处理艾克索拉发送的购买通知),请禁用本地恢复,以免与服务器侧交易管理产生冲突:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetLocalPurchasesRestore(false)
.SetLocalPurchasesRestoreInterval(0)
.Build();
```
- `SetLocalPurchasesRestore`:启用或禁用本地购买恢复(默认 `true`)。
- `SetLocalPurchasesRestoreInterval`:本地购买恢复重试的时间间隔,单位为秒(默认 `0`⸺使用 SDK 默认值)。
注意
**何时禁用本地购买恢复**:
- 后端使用 Webhook 接收艾克索拉发送的购买通知
- 在服务器上管理交易生命周期
- 需要避免本地系统与服务器侧系统重复处理购买
**重要限制**:
- 恢复的购买无法通过标准校验流程进行验证。
- 除非通过 Events API 恢复,否则恢复的购买不包含原始艾克索拉订单标识符。
- 使用 Webhook 时,必须由后端负责完成交易完结处理。
- 如果禁用了本地购买恢复,SDK 既不会执行本地恢复,也不会通过 Events API 执行恢复。
此设置会直接影响交易完结的处理方式。禁用本地恢复后,后端需借助 Webhook 通知管理完整的交易生命周期。请注意,禁用本地恢复后,未完成的交易不会在应用重启时再次触发,因此务必在后端妥善处理。
#### 使用艾克索拉 Events API 进行恢复
**艾克索拉 Events API** 可替代基于 Webhook 的集成方案(在 Webhook 方案中,购买校验、发放等大部分逻辑通常由集成方后端处理)。该 API 不会直接发送 Webhook,而是将其拦截并把负载存入艾克索拉托管的远程队列。这种方式支持无服务器集成,适合缺乏后端资源或无需搭建后端、但仍希望直接在应用内 处理完整交易流程的项目。
通过 Events API 恢复购买时,还会返回原始艾克索拉订单的标识符,便于将已恢复的购买记录与您自身的记录进行比对;而通过物品库恢复时则没有可关联引用的订单信息。 注意
选用艾克索拉 Events API 会禁用项目的 Webhook。换言之,无法同时在后端处理 Webhook 并在应用中使用 Events API。
如需启用该功能,请在发布商帐户中打开项目,前往**项目设置** > **集成设置**,选择**使用 API** 并点击**保存**。详情请参阅[**发布商帐户中的 Events API**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。
##### 在 Unity SDK 中启用 Events
在 SDK 配置中启用基于 Events 的购买恢复:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebhooksMode(XsollaStoreClientSettings.WebhooksMode.EventsApi)
.Build();
```
信息
如需了解更多信息,请参见 [**Webhook 页面**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。 备注
基于 Events 的恢复需要 `SetLocalPurchasesRestore(true)`。如果禁用了本地购买 恢复,SDK 不会查询或使用 Events API 进行恢复。
### 自定义支付收银台域名
可覆盖生产环境和沙盒环境的默认支付收银台域名,适用于为支付收银台配置了自定义域名的场景。
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetCustomPayStationDomain(
domainProduction: "pay.yourdomain.com",
domainSandbox: "sandbox-pay.yourdomain.com"
)
.Build();
```
备注
两个域名都必须是有效的绝对 URI。无效域名会记入日志并被忽略。可为任一域名传入空字符串或 null,以使用其默认值。
### Logo 显示
通过 `VisibleLogo` 设置控制支付收银台中艾克索拉 Logo 的显示:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetVisibleLogo(XsollaClientSettings.VisibleLogo.Auto) // Auto (default)
// .SetVisibleLogo(XsollaClientSettings.VisibleLogo.Show) // Always show
// .SetVisibleLogo(XsollaClientSettings.VisibleLogo.Hide) // Always hide
.Build();
```
**选项**:
- `Auto` - 自动判断是否显示 Logo(默认)
- `Show` - 始终显示艾克索拉 Logo
- `Hide` - 从不显示艾克索拉 Logo
### 基于设置构建配置
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// Set the settings object you've acquired in previous step here..
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.SetLocale("en")
.SetFallbackToDefaultLocaleIfNotSet(true)
.SetFetchProductsWithGeoLocale(false)
.SetFetchPersonalizedProductsOnly(true)
.SetTrackingId("")
.Build();
```
以下是配置构建器方法的完整列表:
| 设置 | 值 | 说明 |
| --- | --- | --- |
| SetSettings | XsollaClientSettings | 上一步构建的设置对象。 |
| SetAccessToken | string | 用于身份认证的访问令牌(参见为配置分配艾克索拉访问令牌)。 |
| SetSandbox | bool | 启用用于测试支付的沙盒模式(默认 false)。 |
| SetLogLevel | XsollaLogLevel | 控制 SDK 日志详细级别(None、Error、Warning、Debug)。 |
| SetDelayedConfigurationTask | Task<OnDelayedConfiguration> | 当访问令牌尚不可用时用于延迟配置的任务(参见延迟提供访问令牌)。 |
| SetLocale | string | 覆盖定价和格式化所用的地区设置(留空字符串表示自动)。 |
| SetFallbackToDefaultLocaleIfNotSet | bool | 未指定覆盖值时使用默认地区设置(默认 false)。 |
| SetFetchProductsWithGeoLocale | bool | 使用基于地理位置检测到的地区设置获取商品(默认 false)。 |
| SetFetchPersonalizedProductsOnly | bool | 仅返回个性化商品,排除已达单用户限购上限的商品(默认 true)。 |
| SetUserId | string | 用户标识符,网充商店外链跳转模式下必填。作为 custom_parameters.custom_user_id 发送,并会在购买 Webhook 中返回;不用于归因(参见 SetAttributionUserId)。 |
| SetAttributionUserId | string | 向归因平台(AppsFlyer、Adjust 等)上报购买事件时用作关联键的 ID,会作为 custom_parameters.custom_id 传递给支付收银台。该值必须与归因 SDK 上报的客户用户 ID 一致,否则购买事件无法与对应用户匹配。留空时,事件将按支付令牌中的用户 ID 进行匹配,默认为玩家的艾克索拉登录管理器用户 ID。1 |
| SetInstallSource | string | (Android, iOS)版本包的分发渠道,例如官网或启动器。该版本包内产生的购买会归因至此渠道,而非自动检测到的渠道(参见上报自定义安装来源)。传入空字符串时:Android 使用系统安装程序来源;iOS 仅在 iOS 17.4 及更高版本上检测渠道(App Store、Web 分发、替代应用商店),更早版本不发送该值。Android 会去除该值的首尾空白字符(纯空白字符视为空字符串);iOS 则原样发送。独立版本包会忽略该设置。 |
| SetTrackingId | string | 用于分析的跟踪 ID(留空字符串表示不发送)。 |
| SetSimpleMode | SimpleMode | 简单模式设置(Off、WebShop、ServerTokens)。 |
| SetCustomPayStationDomain | string, string | 覆盖生产和沙盒环境的支付收银台域名(参见自定义支付收银台域名)。 |
1 如果项目通过服务器侧自定义 ID 登录或 PlayFab 对玩家进行身份认证,或将用户 ID 映射到自定义 JWT 声明,则支付令牌会携带该值而非登录管理器用户 ID。请调用 `SetAttributionUserId`,否则购买事件将无法与归因平台匹配。
### 为配置分配艾克索拉访问令牌
备注
访问令牌的 [**JWT 结构 ↗**](https://developers.xsolla.com/api/login/overview/#section/JWT-structure) ([https://developers.xsolla.com/api/login/overview/#section/JWT-structure)。](https://developers.xsolla.com/api/login/overview/#section/JWT-structure)%E3%80%82) 注意
初始化 SDK 前,必须先获取有效的**访问令牌**。
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("< your access token >")
.Build();
```
如果在构建配置时尚未获取**访问令牌**,可通过 `Task` 将其异步传递给 SDK。此方式最适合无法立即提供**访问令牌**、需在稍后获取(例如 从应用后端获取)的应用。
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetDelayedConfigurationTask( DelayedTask() )
.Build();
async Task<XsollaStoreClientConfiguration.OnDelayedConfiguration> DelayedTask()
{
var result = await Server.GetXsollaTokenAsync();
return configuration => XsollaStoreClientConfiguration.Builder.Update(configuration)
.SetSettings(
XsollaStoreClientSettings.Builder.Update(configuration.settings)
.SetProjectId(result.projectId)
.Build()
)
.SetAccessToken(result.accessToken)
.Build();
}
```
### 运行时更新访问令牌
如果需要在会话期间更新访问令牌(例如刷新后),请使用 `UpdateAccessToken` 方法:
```csharp
storeClient.UpdateAccessToken("<new_access_token>", error =>
{
if (error != null)
{
Debug.LogError($"Failed to update access token: {error.message}");
return;
}
Debug.Log("Access token updated successfully");
});
```
提示
当访问令牌过期需要刷新时,使用此方法即可直接更新令牌,无需重新初始化整个 SDK。
### 使用设备 ID 代替访问令牌
以下示例展示了使用设备 ID 进行身份认证时需设置的字段:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
// ..other properties
.Build();
```
### 使用 OAuth 2.0 代替访问令牌
以下示例展示了使用 OAuth 2.0 进行身份认证时需设置的字段:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetOAuthClientId("< your_oauth_client_id >")
// ..other properties
.Build();
```
备注
在 Android 上,每次通过 OAuth 2.0 客户端登录(包括下方结合 OAuth 2.0 的社交平台登录流程)都会发送重定向 URI;该 URI 必须预先在对应客户端中注册,否则服务器会拒绝登录。各登录方式所使用的 URI 请参见[**登录重定向 URI**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android/#sign-in-redirect-uris)。
### 使用第三方社交平台的访问令牌
以下示例展示了使用社交平台进行身份认证所需的设置:
- **使用 OAuth 2.0** ```csharp var settings = XsollaStoreClientSettings.Builder.Create() .SetProjectId("< your_project_id >") .SetLoginId("< your_login_id >") .SetOAuthClientId("< your_oauth_client_id >") .SetSocialProvider(new XsollaClientSettings.SocialProvider() { name = "epicgames", accessToken = "<social-access-token>" }) // ..other properties .Build(); ```
- **不使用 OAuth 2.0** ```csharp var settings = XsollaStoreClientSettings.Builder.Create() .SetProjectId("< your_project_id >") .SetLoginId("< your_login_id >") .SetSocialProvider(new XsollaClientSettings.SocialProvider() { name = "epicgames", accessToken = "<social-access-token>" }) // ..other properties .Build(); ```
### 深度链接配置
深度链接用于在支付流程完成后将玩家带回游戏。
默认情况下,SDK 会自动处理重定向。仅当需要**覆盖**默认重定向行为时,才需配置以下设置(例如使用自定义重定向 URL、调整自动重定向等待时间,或修改重定向按钮/链接的文案)。 提示
在 **iOS** 上,可使用**通用链接**(HTTPS)将玩家重定向回游戏,避免从外部浏览器返回时弹出“Open in *App Name*?”提示。请参见 [**iOS 通用链接**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-universal-links/)。
**设置重定向 URL 与延迟**:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetRedirectUrl("myapp://payment")
.SetRedirectDelay(6)
.SetRedirectButtonText("Back to the game")
.Build();
```
**参数说明**:
- `SetRedirectUrl`:覆盖购买完成后将玩家重定向回游戏的 URL。
- `SetRedirectDelay`:支付收银台将玩家**自动重定向**回游戏前的延迟时间(单位:秒),使玩家无需手动点击重定向按钮。
- `SetRedirectButtonText`:覆盖支付收银台中重定向按钮/链接的显示文案。
提示
如果覆盖了 `SetRedirectUrl`,可将其设为**自定义 Scheme**(例如 `myapp://...`)或**通用链接** (HTTPS)。请确保已在对应平台的项目设置 (iOS/Android) 中为应用配置好所选链接类型的处理方式。保留 SDK 默认值时,通常无需额外配置。
### 电子邮箱收集同意
在支付流程中启用收集用户电子邮箱的主动勾选同意选项(例如同意接收订阅邮件):
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetEmailCollectionConsentOptIn(true)
.Build();
```
传入 `true` 启用,传入 `false` 禁用,或传入 `null` 使用默认行为。
### 在沙盒模式下测试购买流程
如需了解如何启用沙盒模式,以便在不花费真实货币的情况下测试集成,请参见[**测试**](https://developers.xsolla.com/sdk/zh/unity/sdk/testing/)指南。
配置 - Android
https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/android
### 登录重定向 URI
使用 OAuth 2.0 客户端 (`SetOAuthClientId`) 的登录方式会发送重定向 URI;若该 URI 未在对应客户端中注册,服务器将拒绝登录。在 Android 平台上,每种登录方式对应的 URI 均已固定,无法在 Unity 中更改:
| 登录方式 | 设置/调用 | 需要注册的重定向 URI |
| --- | --- | --- |
| 使用 OAuth 2.0 的设备 ID | SetOAuthClientId,无访问令牌或社交平台 | app://xlogin.<applicationId> |
| 艾克索拉登录管理器小组件 | XsollaLoginClient.Login / LoginSilently | app://xlogin.<applicationId> |
| 令牌刷新 | XsollaLoginClient.RefreshToken,自动刷新 | app://xlogin.<applicationId> |
| 使用 OAuth 2.0 的社交平台访问令牌 | SetOAuthClientId + SetSocialProvider,或 XsollaLoginClient.LoginWithSocialAccount | https://login.xsolla.com/api/blank |
| 不使用 OAuth 2.0 的设备 ID 或社交平台访问令牌,自有访问令牌 (SetAccessToken) | — | 无 |
`<applicationId>` 是应用的包名 (**Player Settings > Other Settings > Package Name**),例如 `app://xlogin.com.example.mygame`。如果使用多个包名发布版本包,请分别为每个包名注册该 URI。
要注册 URI,请在发布商帐户中打开登录管理器项目,前往**安全性 > OAuth 2.0**,将其添加到传给 `SetOAuthClientId` 的客户端的重定向 URI 列表中。
### Custom Tabs / Trusted Web Activity 浏览器选择
使用 `WebViewType.System` 或 `WebViewType.Trusted` 启用 Custom Tabs / TWA 的浏览器提供程序控制。通过 Android 高级设置配置提供程序禁止列表、优先级权重和 TWA 回退:
| 设置 | 值 | 说明 |
| --- | --- | --- |
| SetUserBlacklistedProviders | HashSet<string> | 排除指定的 Custom Tabs/TWA 提供程序,使其不被选用。 |
| SetInternalProviderBlacklistEnabled | bool | 在用户自定义排除之外,同时应用 SDK 的内部提供程序禁止列表。 |
| SetUserBlacklistedTWAProviders | HashSet<string> | 排除指定的 TWA 提供程序;其优先级低于 SetUserBlacklistedProviders。 |
| SetInternalTWAProviderBlacklistEnabled | bool | 在用户自定义排除之外,同时应用 SDK 的内部 TWA 提供程序禁止列表。 |
| SetUserProviderPriorityWeights | Dictionary<string, float> | 通过按包名设置权重来调整提供程序选择优先级(权重越高,优先级越高)。 |
| SetFallbackToFirstAvailableTWAProvider | bool | 当请求的提供程序不支持 TWA 时,回退到首个可用的 TWA 兼容提供程序。 |
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetUserBlacklistedProviders(new HashSet<string>{ "com.android.chrome" })
.SetInternalProviderBlacklistEnabled(true)
.SetUserBlacklistedTWAProviders(new HashSet<string>{ "com.custom.browser" })
.SetInternalTWAProviderBlacklistEnabled(true)
.SetUserProviderPriorityWeights(new Dictionary<string, float>{{ "com.google.android.apps.chrome", 2.0f }})
.SetFallbackToFirstAvailableTWAProvider(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Trusted)
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### 取消原因查询
启用后,SDK 会区分用户关闭支付页面但未支付 (`Cancelled`) 与尝试支付但失败(报告为错误)。禁用此功能(默认)时,两种情况都会报告为 `Cancelled`。
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetQueryCancellationReasonEnabled(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### 从外部浏览器重新拉起应用
当应用在外部浏览器的支付流程中被终止时,支付收银台中的返回应用按钮默认会静默失效。启用此设置后,重定向会把用户带回应用。需要 **`WebViewType.External`**。
```csharp
var advanced = new XsollaClientSettings.AdvancedSettingsAndroid()
.SetRedirectAppRelaunchEnabled(true);
var settings = XsollaStoreClientSettings.Builder.Create()
.SetWebViewType(XsollaStoreClientSettings.WebViewType.External)
.SetAdvancedSettingsAndroid(advanced)
.Build();
```
### WebView 启动画面
设置在 Android WebView 加载支付收银台时显示的启动画面图片:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebViewSplashScreenImage("path/to/splash.png")
.SetWebViewSplashScreenDrawableIdAndroid(0x7f080001) // your Android drawable resource ID
.Build();
```
- `SetWebViewSplashScreenImage`:启动画面图片的文件路径
- `SetWebViewSplashScreenDrawableIdAndroid`:启动画面图片对应的 Android drawable 资源 ID
配置 - iOS
https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/ios
### 将玩家引导至外部网页支付(美国、日本、巴西)
在美国、日本和巴西,Apple 允许开发者将玩家引导至外部网页支付。请使用 `WebViewType.External`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.External)
.Build();
```
### 欧盟 DMA 框架下的应用内支付合规
在欧盟,两种方式均可行:将支付流程保留在应用内,或使用 `WebViewType.External` 将玩家跳转至外部网页。Apple 对这两种方式收取的佣金费率不同,且自 **2026 年 10 月 1 日**起,一经选定某种方式便须保持 12 个月不变。
如需将支付流程保留在应用内,请使用 `WebViewType.Auto`:
```csharp
settings = XsollaClientSettings.Builder.Update(settings)
.SetWebViewType(XsollaClientSettings.WebViewType.Auto)
.Build();
```
针对更复杂的合规场景,您可以通过代码检测用户所在地区与分发渠道,从而自动配置相应设置。欢迎了解如何[**检测 iOS 商店地区**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/ios-storefront/)以便在允许的地区启用外部支付,或[**检测替代应用分发状态**](https://developers.xsolla.com/sdk/zh/unity/sdk/advanced/detectstore/)以便根据应用安装来源启用欧盟专属合规流程。
初始化
https://developers.xsolla.com/sdk/zh/unity/sdk/initialization
在[完成配置](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)后,需要初始化 **Unity 专用艾克索拉 SDK** 并连接到**艾克索拉**服务。 前置条件
请确保已安装 Unity **In-App Purchasing `4.15+`**。
请参见官方 [Unity IAP 设置指南 ↗](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html) ([https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)。](https://docs.unity3d.com/Packages/[email protected]/manual/GettingStarted.html)%E3%80%82)
⚠️ 当前**暂不支持** Unity **In-App Purchasing `5.x`**。
```csharp
public class App : MonoBehaviour, IDetailedStoreListener
{
private IStoreController _storeController;
void Start()
{
// See the configuration step for more details on how to prepare a config.
var configuration = ...
var module = XsollaPurchasingModule.Builder.Create()
.SetConfiguration(configuration)
.Build();
var configurationBuilder = ConfigurationBuilder
.Instance(module)
.AddProduct("product1", ProductType.Consumable)
.AddProduct("product2", ProductType.Consumable)
.AddProduct("product3", ProductType.Consumable)
.AddProduct("product4", ProductType.Consumable);
UnityPurchasing.Initialize(this, configurationBuilder);
}
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
// handle initialized
}
public void OnInitializeFailed(InitializationFailureReason error)
{
// handle initialization failed
}
public void OnInitializeFailed(InitializationFailureReason error, string message)
{
// handle initialization failed
}
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// implement purchase flow
return PurchaseProcessingResult.Complete;
}
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
// handle purchase failed
}
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
// handle purchase failed
}
}
```
```csharp
var storeClient = XsollaStoreClient.Builder.Create()
.SetConfiguration(configuration)
.SetOnRestore((item, error) => {
if (error != null)
{
// handle error
return;
}
// handle delayed purchased item
})
.AddProducts(productIds)
.AddProduct("product1")
.AddProduct("product2")
.AddProduct("product3")
.AddProduct("product4")
.Build();
storeClient.Initialize((products, error) =>
{
if (error != null)
{
// handle error
return;
}
// products contains all requested products
});
```
SDK 仅从您的艾克索拉商品目录中加载虚拟物品,不会返回虚拟货币、捆绑包及其他商品目录类型。
安装
https://developers.xsolla.com/sdk/zh/unity/sdk/installation
在 **Unity** 中安装 **Unity 专用艾克索拉 SDK** 插件有多种方式,均通过 Unity 的 Package Manager 完成。
### 选项 1:通过 Git URL
- 在 Unity 中,依次选择 **Window** > **Package Manager**。
- 点击 ➕ > **Add package from git URL...**。
- 输入: ```text https://github.com/xsolla/xsolla-sdk-unity.git ```
- 点击 **Add**。
备注
如需了解如何通过 Git URL 安装插件,请参阅 [Unity 官方文档 ↗](https://docs.unity3d.com/Manual/upm-ui-giturl.html) ([https://docs.unity3d.com/Manual/upm-ui-giturl.html)。](https://docs.unity3d.com/Manual/upm-ui-giturl.html)%E3%80%82)
### 选项 2:通过 Unity 包 (.unitypackage)
- 选择 **Assets** > **Import Package** > **Custom Package**。随后会打开文件浏览器,提示您选择对应的 .unitypackage 文件。
![安装 1] 备注
有关通过 Unity 包安装插件的更多信息,请访问 [Unity 官方文档 ↗](https://docs.unity3d.com/Manual/AssetPackagesImport.html) ([https://docs.unity3d.com/Manual/AssetPackagesImport.html)。](https://docs.unity3d.com/Manual/AssetPackagesImport.html)%E3%80%82)
### 选项 3:通过 tarball
- 打开 Unity 项目或创建一个新项目。
- 依次选择 **Window** > **Package Manager**。
- 将包添加为依赖项: - 点击 ➕ 图标并选择 **Add package from tarball**。 - 选择已下载的 SDK 包。 - 点击 **Open** 并等待导入完成。
- 如果未安装 **EDM4U** (Google External Dependency Manager),请从 [GitHub ↗](https://github.com/googlesamples/unity-jar-resolver) ([https://github.com/googlesamples/unity-jar-resolver](https://github.com/googlesamples/unity-jar-resolver)) 获取最新版本 (external-dependency-manager-latest.unitypackage) 并将其导入项目中。
备注
有关通过 tarball 安装插件的更多信息,请访 问 [Unity 官方文档 ↗](https://docs.unity3d.com/Manual/upm-ui-tarball.html) ([https://docs.unity3d.com/Manual/upm-ui-tarball.html)。](https://docs.unity3d.com/Manual/upm-ui-tarball.html)%E3%80%82)
解析 Android 依赖项
https://developers.xsolla.com/sdk/zh/unity/sdk/installation/resolving-android-dependencies
要解析 Android 依赖项,请按以下步骤操作:
- 在 **Unity 编辑器**的主菜单中,前往 **Assets** > **External Dependency Manager** > **Android Resolver**,然后点击 **Resolve**。 ![外部依赖项 1]
- 等待依赖项管理器完成解析。
- 解析完成后,屏幕会弹出完成提示窗口。 ![外部依赖项 2]
- 至此所有依赖项均已解析完毕,可安全关闭弹窗。
注意
所有外部依赖项均通过随 SDK 插件内置提供的 Google **External Dependency Manager** (EDM4U) 进行解析,无需直接手动编辑项目的 Gradle 模板脚本来声明原生 Android 库依赖项。建议每次全新安装或升级 SDK 插件版本后都运行一次 EDM4U。
Unity 专用艾克索拉 SDK - 从 2.x 迁移到 3.x
https://developers.xsolla.com/sdk/zh/unity/sdk/migration2xto3x
信息
**Unity 专用艾克索拉 SDK** 是企业级艾克索拉 SDK 解决方案的升级版,专为大型项目集成而设计。
本分步指南适合不同经验水平的开发者,帮助您将 Unity 项目从**艾克索拉 SDK 2.x** 迁移到**艾克索拉 SDK 3.x**。
## 先决条件
- Unity 2022.3+(包含 Unity 6)。
- 备份项目(例如通过 Git)。
## 1. 移除旧版 SDK (2.x)
### 1.1 通过 Unity Package Manager
- 打开 **Packages/manifest.json**。
- 删除以下行: ```json "com.xsolla.mobilesdk": "<version>" ``` 版本 `<version>` 可能类似 **2.0.22**。
- 保存文件。
### 1.2 手动安装 (UnityPackage)
- 在 **Project** 窗口中删除: ```plaintext Assets/Xsolla.MobileSDK ```
- 如果存在以下目录,请一并删除: ```plaintext Packages/com.xsolla.mobilesdk ```
## 2. 安装新版 SDK (3.x)
艾克索拉 SDK 3.x 以 `.unitypackage` 或 `.tar` 形式提供。
请按照[**安装指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)安装新版 SDK (3.x)。
## 3. 解析 Android 依赖项(可选)
安装 3.x 版本后,如果项目明确面向 Android 平台,建议解析 Android 依赖项。
请按照 [**Android 依赖项解析指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/resolving-android-dependencies/)解析 Android 依赖项。 信息
艾克索拉 SDK 依赖 Android AAR,解析器会自动设置所有必需的库。
## 4. 更新命名空间和程序集定义
所有命名空间从 `Xsolla.MobileSDK.*` 更改为 `Xsolla.SDK.*`。请按以下步骤更新:
- 在代码编辑器中打开 **Find and Replace**。
- 将搜索范围设置为项目文件夹。
- 替换所有匹配项,例如: ```diff - using Xsolla.MobileSDK.Common; + using Xsolla.SDK.Common; ```
- 对子命名空间重复此操作:Store、Login、UnityPurchasing 等。
**程序集定义文件 (.asmdef)**
如果在某个程序集定义文件 (.asmdef) 中显式引用了 **Xsolla.MobileSDK**,现在需要将其更新为 **Xsolla.SDK**。
## 5. 更新后的 SDK 配置
### 5.1 基于代码的配置
如果项目使用 `XsollaClientSettings` 配置 SDK:
- 确保所有 `using` 指令引用 3.x 命名空间: ```diff - using Xsolla.MobileSDK.Common; + using Xsolla.SDK.Common; ```
- 使用新类型实例化设置对象: ```csharp var settings = new Xsolla.SDK.Common.XsollaClientSettings(projectId, storeId, accessToken); ```
### 5.2 基于资源的配置
如果使用[**基于资源的设置**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)(位于 **Asset** 选项卡下),无需执行任何额外步骤,设置会自动完成迁移。 提示
强烈建议在迁移后再次检查各参数是否正确。
## 6. 测试与验证
- 重启 Unity 以刷新所有资源。
- 打开 **Window ▶ Package Manager**,确认已安装**艾克索拉 SDK 3.x**。
- 使用艾克索拉 SDK 3.x 构建项目;如果出现错误: - 确认已定位并更新所有命名空间。 - 检查程序集定义是否已指向 3.x,且不再残留 2.x 条目。 - 从菜单打开艾克索拉 SDK 设置并再次检查参数(可选)。 - 确认 Android 依赖项已正确解析(可选)。
## 7. 更多资源
- **SDK 文档**:[https://developers.xsolla.com/sdk/mobilesdk/](https://developers.xsolla.com/sdk/mobilesdk/)
- **Unity 手册 (Importing Packages)**:[https://docs.unity3d.com/Manual/CustomPackages.html](https://docs.unity3d.com/Manual/CustomPackages.html)
如需进一步帮助,请联系 **[[email protected]](mailto:[email protected])**。
购买流程
https://developers.xsolla.com/sdk/zh/unity/sdk/purchase
购买流程是一个多阶段过程,包含[接收付款](https://developers.xsolla.com/sdk/zh/unity/quick-start/#purchase-product)、[验证](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase#validating-purchases-recommended)购买和[核销](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase#consuming-purchased-goods)。
### 启动购买流程
请根据是否使用 Unity InApp Purchasing,选用下方任一代码片段启动购买流程:
```csharp
_storeController.InitiatePurchase(product);
// ...
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// handle the purchased item here
return PurchaseProcessingResult.Complete;
}
```
**高级设置**
通过艾克索拉商店扩展传递购买参数。购买结果会在 `ProcessPurchase` 中返回,与在商店控制器上调用 `InitiatePurchase` 时相同。
```csharp
private IXsollaPurchasingStoreExtension _xsollaExtension;
public void OnInitialized(IStoreController controller, IExtensionProvider extensions)
{
_storeController = controller;
_xsollaExtension = extensions.GetExtension<IXsollaPurchasingStoreExtension>();
}
// ...
var args = XsollaStoreClientPurchaseArgs.Builder.Create()
.SetDeveloperPayload("<your-custom-developer-payload>")
.Build();
_xsollaExtension.InitiatePurchase(product, args);
```
| 构建器方法 | 详情 |
| --- | --- |
| SetDeveloperPayload(string) | 开发者载荷 |
| SetExternalId(string) | 外部 ID |
| SetExternalTransactionToken(string) | 外部交易令牌 |
| SetPaymentMethodId(int?) | 强制指定支付方式 |
```csharp
storeClient.PurchaseProduct(productId, (product, error) =>
{
if (error != null)
{
// handle error
return;
}
var receipt = product.ToReceipt();
// handle the purchased product here (e.g. validate or consume)..
});
```
**高级设置**
如需使用扩展功能,可调用参数更完整的 `XsollaStoreClient.PurchaseProduct()` 重载方法:
```csharp
XsollaStoreClient.PurchaseProduct(
string productId,
XsollaStoreClientPurchaseArgs args,
Action<XsollaStoreClientPurchasedProduct, XsollaStoreClientError> completionHandler
)
```
### 开发者载荷
请参考以下示例,在购买流程中传入您自己的开发者自定义载荷:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
developerPayload = "<your-custom-developer-payload>"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### 外部 ID
支持为交易指定自定义的唯一 ID。注意
请先在发布商帐户中启用外部 ID 支持,否则购买会失败。
请参考以下示例,为购买流程设置外部ID:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
externalId = "<your-custom-unique-external-id"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### 外部交易令牌
将外部交易令牌附加到发起的购买流程中,使其随订单传递并用于向平台回传交易报告。该设置方法在各平台通用,具体用途因目标平台而异:
| 平台 | 是否支持 | 用途 |
| --- | --- | --- |
| Android | ✅ | Google Play 外部交易令牌,用于 User Choice Billing / Google Play 以外的支付方式上报⸺参见向 Google Play 上报外部交易 |
| iOS | ❌ | — |
| Windows | ❌ | — |
| macOS | ❌ | — |
| Web | ❌ | — |
如果在上方未列为支持的平台上设置 `externalTransactionToken`,购买调用会直接报错失败,而不会静默忽略该值。此外,请勿将其与上文的 `externalId` 混淆:后者是艾克索拉自有的商户 ID,用于匹配订单,并非平台令牌。
请参考以下以下示例,随购买流程一并传入该令牌:
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
externalTransactionToken = "<google-play-external-transaction-token>"
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### 强制指定支付方式
支持为购买流程指定特定的支付方式。提示
可在发布商帐户中查看支付方式 ID。
```csharp
var args = new XsollaStoreClientPurchaseArgs() {
paymentMethodId = <payment-id>
};
XsollaStoreClient.PurchaseProduct(
productId, args, completionHandler: (product, err) =>
{
// Handle the result.
}
);
```
### 处理用户取消购买
当玩家取消购买时,请将其与实际错误分开处理。
```csharp
public void OnPurchaseFailed(Product product, PurchaseFailureReason failureReason)
{
if (failureReason == PurchaseFailureReason.UserCancelled)
{
// User cancelled the purchase — don't show an error
return;
}
// Handle other failure reasons
}
// Or (newer API)
public void OnPurchaseFailed(Product product, PurchaseFailureDescription failureDescription)
{
if (failureDescription.reason == PurchaseFailureReason.UserCancelled)
{
// User cancelled the purchase — don't show an error
return;
}
// Handle other failure reasons
}
```
```csharp
void OnPurchase(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
if (error?.code == XsollaStoreClientPurchaseErrorCode.Cancelled)
{
// User cancelled the purchase — don't show an error
return;
}
if (error != null)
{
// Handle other errors
return;
}
// Handle successful purchase
}
```
### 验证购买(推荐)
注意
尽管验证**不是**必需步骤,但仍强烈建议进行验证,以尽量降低欺诈及其他恶意行为的风险。
关于如何验证购买,请参阅[**购买验证**](https://developers.xsolla.com/sdk/zh/unity/sdk/validation/)指南。
### 核销已购商品
购买流程的最后一步是将已购商品发放给用户,并将这些商品标记为“已发放”。这一过程也称为**购买核销**。
使用以下代码完成此操作:
```csharp
_storeController.InitiatePurchase(product);
// ....
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs purchaseEvent)
{
// handle purchased item
return PurchaseProcessingResult.Pending;
}
// ....
_storeController.ConfirmPendingPurchase(product);
```
```csharp
storeClient.ConsumeProduct(item.sku, item.quantity, item.transactionId, error => {
if (error != null)
{
return;
}
// handle purchased item
});
```
important
强烈建议在核销已购商品前,至少采用某种方式完成[**验证**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase#validating-purchases-recommended)。
测试与沙盒
https://developers.xsolla.com/sdk/zh/unity/sdk/testing
本节提供相关代码片段与示例,介绍如何配置沙盒环境以完成测试支付、输出更详细的日志等操作。
### 启用沙盒模式
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetSandbox(true)
.Build();
```
#### 在 Unity 编辑器中测试
在 Unity 编辑器中测试时,会使用当前运行平台(例如 Windows 或 macOS)对应的实现。 注意
在**正式上线**前,请务必将**沙盒**模式**关闭**。
### 启用额外日志
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
注意
在**正式上线**前,请确保已**关闭**调试**日志记录**。
### 测试银行卡
如需查看沙盒模式下用于模拟支付的测试银行卡列表,请参见[此处 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards)。](https://developers.xsolla.com/doc/pay-station/testing/test-cards)%E3%80%82) important
测试银行卡无法在**沙盒模式**以外使用。
购买验证
https://developers.xsolla.com/sdk/zh/unity/sdk/validation
向最终用户发放购买内容前,应对每笔购买交易进行验证。这有助于防范未授权购买,维护应用内经济系统的正常运行。购买验证是防范欺诈、保障收入并维护公平用户体验的关键安全措施。
目前主要提供两种不同的验证方式。
### 服务器侧验证
最安全可靠的验证方式是采用**服务器到服务器** (**S2S**) 通信,使客户端完全不参与验证流程。这能最大限度降低安全风险,确保仅凭直接来自艾克索拉的已验证数据发放权益。
接入艾克索拉时,服务器侧验证通过**基于 Webhook 的模式**实现:
- 用户通过应用完成购买后,艾克索拉服务会自动向您的后端发送 [**Webhook 事件**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#user_validation)。
- 该 Webhook 包含所有必要的购买数据(包括**艾克索拉** `order ID`),供服务器异步验证并处理该笔购买。
- 随后,后端即可根据这些数据更新用户的权益、余额、物品库等,无需客户端提供任何额外输入。
该流程确保客户端无法干预购买结果的判定⸺所有验证逻辑均在服务器端执行,且仅使用直接来自艾克索拉的可信数据。 提示
有关 Webhook 工作原理的更多信息,请参见[**此处**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/)。
### 客户端侧验证
客户端侧验证支持直接在用户设备上验证购买,无需搭建后端(服务器)。虽然这比完全不验证更稳妥,但仍存在明显局限,即任何在客户端运行的逻辑都有可能遭到篡改或恶意利用。
```csharp
public PurchaseProcessingResult ProcessPurchase(PurchaseEventArgs args)
{
var product = purchaseEvent.purchasedProduct;
var validator = extensions.GetExtension<IXsollaPurchasingStoreExtension>().GetValidator();
validator.ValidatePurchase(product.receipt, (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
```csharp
void MyOnPurchaseCallback(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
_storeClient.ValidatePurchase(product.ToReceipt(), (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
Unity 专用艾克索拉 SDK - Web
https://developers.xsolla.com/sdk/zh/unity/web
信息
**Unity 专用艾克索拉 SDK** 是企业级艾克索拉 SDK 解决方案的升级版,最初专为大型项目集成而设计。
本指南将协助您在 Web 端的 Unity 游戏中集成 Unity 专用艾克索拉 SDK 以实现收款。完成后,您将在游戏中搭建起完整的支付系统,并亲身体验艾克索拉如何简化变现流程。
现在就开始,只需简单几步即可让您的游戏具备收款能力!
## 快速开始
本快速开始指南可帮助您在 Web 端轻松集成 Unity 专用艾克索拉 SDK,并在 Unity 游戏中开始收款。本指南使用预配置的测试项目演示核心流程:设置基础用户身份认证、导入商品 (SKU),以及完成一次测试支付。
详细步骤请参见[**快速开始指南**](https://developers.xsolla.com/sdk/zh/unity/quick-start/)。
## 设置发布商帐户
在将艾克索拉 SDK 集成到游戏前,需要注册发布商帐户。
发布商帐户是配置艾克索拉各项功能、查看分析数据及管理交易的核心工具,作用类似于管理 SKU 时使用的 Google Play Console 和 App Store Connect。important
您需要拥有已激活的发布商帐户才能获取项目 ID,整个 SDK 集成流程都会用到该 ID。
详细步骤请参见[**设置发布商帐户**](https://developers.xsolla.com/sdk/zh/publisher-account/)。
## 安装 SDK
设置好发布商帐户后,下一步是在 Unity 项目中安装 Unity 专用艾克索拉 SDK (Xsolla SDK for Unity) 插件。
安装细节请参见[**安装指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/installation/)。
## 配置 SDK
安装完成后,继续进行配置。
配置细节请参见[**配置指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/)。信息
Web 平台不支持使用**设备 ID** 登录,您必须改为提供访问令牌。详情请参见[**通过自定义 ID 进行身份认证**](https://developers.xsolla.com/sdk/zh/publisher-account/login/#login-on-game-server)。
或者,您可以使用[**延迟配置**](https://developers.xsolla.com/sdk/zh/unity/sdk/configuration/#assign-xsolla-access-token-to-the-configuration)功能,将 SDK 初始化推迟到获取访问令牌之后。
## 初始化 SDK
配置完成后,您即可在 Unity 项目中初始化 SDK。
详细步骤与最佳实践请参见[**初始化指南**](https://developers.xsolla.com/sdk/zh/unity/sdk/initialization/)。
## 发起购买
完成 SDK 初始化后,应用已准备好开始处理支付。
详细步骤请参见[**发起购买**](https://developers.xsolla.com/sdk/zh/unity/sdk/purchase/)。
## 收款
SDK 通过**艾克索拉支付收银台**进行安全收款。
以下步骤将引导您完成一次测试收款流程:
- 选择**银行卡**支付方式: ![快速开始 3]
- 使用[**此处 ↗**](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards](https://developers.xsolla.com/doc/pay-station/testing/test-cards)) 中列出的任一测试银行卡,并点击**支付**确认支付: ![快速开始 3]
- 支付完成后,您会看到确认信息: ![快速开始 3]
## 购买验证
配置好支付功能后,建议对购买交易进行验证,确保交易安全可靠。
详细步骤请参见[**购买验证**](https://developers.xsolla.com/sdk/zh/unity/sdk/validation/)。
## 测试与沙盒
最后,可在沙盒环境中安全测试完整的支付集成流程,而无需产生真实交易。
详细步骤请参见[**测试与沙盒**](https://developers.xsolla.com/sdk/zh/unity/sdk/testing/)。
## 下一步
恭喜!🎉 您已在 Web 端成功集成 **Unity 专用艾克索拉 SDK**!
现在您的游戏已可接入全球超过 1000 种支付方式,这也为后续集成网充商店等更多艾克索拉解决方案奠定了基础。
Unreal Engine 专用艾克索拉 SDK 3:抢先体验试点计划
https://developers.xsolla.com/sdk/zh/unreal-pilot
抢先体验Unreal Engine 4.27、5.0–5.8 · Windows 与 Linux
Unreal Engine 专用艾克索拉 SDK 3 目前处于抢先体验阶段。它承接游戏的商业化能力:处理玩家登录、展示商品目录、完成收款并交付已购商品。本文将介绍本次试点计划的内容、需要您配合完成的事项,以及如何开始参与。
支持通过**艾克索拉帐户**、**Steam** 或 **EOS** 登录,且全流程完整支持 **Blueprint**。[加入试点计划](https://developers.xsolla.com/sdk/zh/unreal-pilot#join-the-pilot-program)
## 试点简介
面向 Unreal Engine 的 SDK 3 已完成 MVP 功能集开发,目前处于内部验证阶段。我们已按第一方标准完成了测试,但测试套件只能验证我们预先设想到的路径。真实游戏项目则会带来各种意想不到的组合情况:不同的引擎版本、特殊的登录与物品库配置、仅接入部分功能等,以及我们自己未曾设想过的设计取舍。
如果您手头已有 Unreal Engine 项目,或正准备新建项目,欢迎集成 SDK 3 并进行全面实测。每个项目的配置各不相同,这有利于帮助我们发现未曾考虑到的新情况。
**欢迎仅接入部分功能。**哪怕游戏只用到了 Steam 登录,也是非常有价值的试点样本。只需跑通项目所支持的校验项并提交报告即可。
## 四项能力校验
每项能力校验对应 SDK 在真实游戏中端到端跑通的一个功能模块。此类校验共有四项,仓库中均提供了对应的实操演练指南。
| 校验项 | 验证内容 |
| --- | --- |
| C1 身份认证 | 玩家登录后关闭并重新打开游戏,仍保持登录状态 |
| C2 商品目录同步 | 游戏内购商店正确渲染商品目录中的虚拟物品与货币 |
| C3 购买 | 在 Unreal Engine 内针对商品目录中的商品拉起结算流程 |
| C4 订单完结 | 订单进入最终状态,且所购商品出现在玩家物品库中 |
安装是前提。项目能成功编译后即可开始 C1。
支持三种玩家登录方式:艾克索拉帐户、Steam 或 EOS。我们希望这三种方式都能在真实线上游戏中得到验证,每种方式至少 有一个项目覆盖,且参与项目越多越好。
## SDK 3 的优势
**统一购买路径**
无论玩家采用何种方式登录,购买流程的代码编写方式完全一致。Steam 和 EOS 会返回身份认证票据,并统一解析为单个艾克索拉会话,后续所有处理流程完全相同。**跨引擎一致性**
核心架构与 Unity 3.x SDK 保持 1:1 对应,每个 Unity Package 程序集均映射为对应的 Unreal Engine 插件模块。如果工作室同时基于这两款引擎开发游戏,开发思路可直接平滑迁移。**精简内核**
纯代码实现、极简依赖,仅 IAP 模块依赖 Online Subsystem。测试套件作为配套插件随 SDK 一并提供,可直接基于 Valve 和 Epic 官方示例项目运行。 **自主掌控 Online Subsystem**
SDK 可与 Steam 或 EOS 并存,同时独立维护用于商业化交易的艾克索拉会话。Steam Wallet 和 EOS Ecom 通过统一接口作为真实的 APP 内购 (IAP) 后端运行,并支持按支付渠道分别定价。**一步完成启动器登录态衔接**
玩家从艾克索拉启动器启动游戏时即处 于已登录状态。只需调用 `LoginWithLauncherToken`,SDK 便会直接复用该会话令牌。**全面支持 Blueprint**
SDK 提供的所有功能均可在 Blueprint 中直接调用,并非仅限 C++。
## 支持平台与分发方式
Windows (Win64) 是主要开发宿主环境,具备完整的平台分派能力、全部支付收银台 WebView 路径、沙盒与生产环境运行时切换开关,以及语言区域解析功能。同时支持 Linux(含专用服务器版本包)。macOS、iOS 和 Android 纳入下一里程碑计划。
SDK 仅以源码形式分发,不提供预编译二进制文件,也未在 Fab 上架。插件直接由项目自身的 Unreal Engine 构建流程编译,从而确保程序包跨平台、跨引擎版本兼容。
## 如何开始
配置指南⸺包括文档索引、架构概览、安装步骤以及 Steam/EOS 集成演练⸺均位于试点仓库中。通过下方[加入试点计划](https://developers.xsolla.com/sdk/zh/unreal-pilot#join-the-pilot-program)即可获取仓库与代码访问权限。
## 问题反馈
请在 GitHub 上提交带有 `pilot-ready` 标签的 Issue,或在试 点计划的 [Discord](https://discord.gg/25DNbVVNng) 频道中反馈。任一方式均可在试点周期内直达 SDK 团队。
欢迎提出直接、尖锐的反馈。
需要提前说明的是:仓库中仍留有部分开发阶段的规划与进度跟踪文档,其中一些内容尚未经过人工审阅。如果您遇到重复文档、过期计划或无关联的残留内容,也欢迎一并反馈。
## 加入试点计划
原生 Android — 艾克索拉 SDK 3 集成视频
https://developers.xsolla.com/sdk/zh/video-guides/video-sdk3-native-android
本视频分步演示如何将艾克索拉 SDK 集成到原生 Android 游戏 (Java) 中。视频以一个简单的点击类游戏为例,展示如何在应用内原生拉起安全的支付收银台结算浮层,让玩家无需跳转外部浏览器,即可使用 1000 多种本地化支付方式。
视频涵盖初始设置以及完整集成的四个阶段:
- **设置 SDK** — 在 Gradle 中添加艾克索拉 Maven 仓库和依赖项,然后在主 Activity 中导入包。
- **身份认证** — 在 `onCreate()` 中初始化 `Config` 和 `BillingClient`(配置项目 ID、登录管理器 ID,并启用沙盒模式)。
- **加载商品目录** — 使用 `queryProductDetailsAsync` 查询商品详情。
- **购买商品** — 启动结算流程 (`launchBillingFlow`) 以打开艾克索拉支付收银台浮层。
- **完成购买** — 监听购买结果,调用 `consumeAsync` 核销交易令牌并发放物品。
原生 iOS — 艾克索拉 SDK 3 集成视频
https://developers.xsolla.com/sdk/zh/video-guides/video-sdk3-native-ios
本视频面向 Swift 开发者分步演示如何在原生 iOS 游戏中集成艾克索拉 SDK⸺无需弃用现有的 StoreKit。该 SDK 以轻量封装层的形式接入 `SKPaymentQueue` API,在开发者熟悉的 StoreKit 流程之上无缝叠加身份认证、支付收银台和购买验证能力。
视频涵盖完整集成的四个阶段:
- **身份认证** — 使用项目 ID 和登录管理器项目 ID 构建 `SKPaymentSettings` 对象,启用支付,配置在外部 Safari 中打开支付收银台(符合美国地区合规要求),并设置持久化的匿名用户 ID。
- **加载商品目录** — 使用 `SKProductsRequest` 获取商品,确保 App Store Connect 与发布商帐户中的 SKU 保持一致(仅限虚拟物品)。
- **发起购买** — 切换到主线程执行,设置 `rootViewController` 锚点,并将 `SKPayment` 加入队列。
- **完成购买** — 在发放物品前调用 `validateTransaction`,并确保每个分支最终都调用 `finishTransaction`。
Unity 移动端 — 艾克索拉 SDK 3 集成视频
https://developers.xsolla.com/sdk/zh/video-guides/video-sdk3-unity-mobile
本视频面向 Unity 开发者提供分步演示,讲解如何将艾克索拉 SDK 集成到移动端 (iOS/Android) 游戏中。示例基于 Unity 2D Game Kit 演示项目,实现“购买满血”的即时购买场景,并通过外部浏览器拉 起支付收银台完成结算⸺这一方案符合 2025 年法院裁决后美国地区 iOS 与 Google Play 的合规要求。
视频涵盖完整集成的四个阶段:
- **身份认证** — 采用客户端侧设备 ID 身份认证,使用项目 ID 和登录管理器 ID 初始化 SDK。
- **加载商品目录** — 在 Unity IAP 中注册商品 SKU,并从艾克索拉后端拉取商品目录。
- **购买商品** — 调用 `InitiatePurchase`,跳转至移动端浏览器中的支付收银台。
- **完成购买** — 在 `ProcessPurchase` 中执行客户端侧验证,验证通过后发放物品。
Unity PC — 艾克索拉 SDK 3 集成视频
https://developers.xsolla.com/sdk/zh/video-guides/video-sdk3-unity-pc
本分步视频教程面向 Unity 开发者,演示如何将艾克索拉 SDK 集成到 PC 游戏中以支持平台外分发。视频以 Unity 2D Game Kit 为例,构建了一个典型的即时购买场景⸺玩家阵亡后可付费满血复活⸺并通过支付 收银台完整打通端到端流程。
视频涵盖完整集成的四个阶段:
- **身份认证** — 采用设备 ID 方式(无登录界面),使用项目 ID 和登录管理器 ID 初始化 SDK。
- **加载商品目录** — 在 Unity 的 IAP 层注册商品 SKU,并从艾克索拉获取商品目录。
- **购买商品** — 触发 `InitiatePurchase`,在玩家的默认浏览器中打开支付收银台。
- **完成购买** — 在客户端侧验证交易,验证通过后发放商品。
核心概念 (Android)
https://developers.xsolla.com/sdk/zh/welcome/core-concepts-android
若要在 Google Play 结算库之外接入 **Xsolla SDK** 以支持更广泛的支付方式,需要完成几个关键步骤,以确保集成顺畅并具备相应功能。下文将分块拆解支持更多支付方式所需的**三个核心概念**。
## 身份认证与登录
- [**Google Play Sign-In ↗**](https://support.google.com/googleplay/answer/3129346) ([https://support.google.com/googleplay/answer/3129346):用户会通过](https://support.google.com/googleplay/answer/3129346)%EF%BC%9A%E7%94%A8%E6%88%B7%E4%BC%9A%E9%80%9A%E8%BF%87) Google Play 服务在后台无感登录 Google Play 生态系统,系统会以私密且隐藏的方式向开发者提供用于结算的 ID。
- [**艾克索拉登录管理器**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#authentication):艾克索拉为开发者提供专门用于登录与身份认证的 SDK API,既可与开发者自有服务器集成,也可在轻量级游戏(如超休闲游戏)中直接采用客户端侧身份认证方式。这些 API 负责将用户 ID 或设备 ID 传递给艾克索拉服务,确保艾克索拉各产品能准确识别用户身份(例如支持顺畅的周期性扣款)。身份认证成功后,艾克索拉会返回发起购买流程所需的访问令牌。
## SKU 与 APP 内购 (IAP)
产品术语
在本文档中:
- **IAP(APP 内购)** = Google Play 结算系统的应用内购买机制
- **SKU(库存单位)** = 代码中使用的商品标识符
- **虚拟物品** = 艾克索拉商品目录中的可购商品 (IAP)
从 Google Play 迁移到艾克索拉时,原有的 IAP 会转为艾克索拉商品目录中的虚拟物品,每件虚拟物品都带有独立的 SKU 供代码调用。
- [**Google Play Billing ↗**](https://developer.android.com/google/play/billing/getting-ready#products) ([https://developer.android.com/google/play/billing/getting-ready#products):在](https://developer.android.com/google/play/billing/getting-ready#products)%EF%BC%9A%E5%9C%A8) Google Play 结算系统中,商品(也称为 SKU 或 IAP)由唯一的**产品 ID**(例如 'com.company.gameapp.keys_1')和描述性的**产品名称**(例如 '5 Keys')标识。例如,'5 Keys' 可能代表一个售价 1 美元的钥匙包。
- **艾克索拉商品目录**:艾克索拉商品目录将您的数字商品作为[**虚拟物品**](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/) (IAP) 进行管理。从 Google Play 结算系统迁移时,开发者只需从 Google Play Console 导入现有的产品 ID,每件商品都会转为带有专属 SKU 标识符的虚拟物品供代码调用。
## 初始化支付收 银台
- **支付收银台**是用户完成购买的入口,需要传入访问令牌和具体的 SKU(例如 'keys_1')来指明要购买的虚拟物品 (IAP)。开发者必须确保这两项配置无误,让用户获得与 Google Play 结算系统一致的顺畅购买体验。
- 配置好[虚拟物品](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/) (IAP) 并获取[访问令牌](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/android/#authentication)(例如基于用户/设备 ID 或通过自有服务器获取)后,下一步关键操作就是[初始化支付收银台](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/android/),创建订单并正式开启交易流程。
## Webhook
[Webhook](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) 是系统在发生特定事件时发送的事件通知。当特定事件触发时,艾克索拉会发起 HTTP 请求,将事件数据传输至您的游戏服务器(在超休闲游戏等纯客户端简化集成场景下,也可传输至客户端)。游戏客户端或服务器正是依靠这些 Webhook 来接收支付成功或失败以及用户身份认证结果等关键通知。
在部分地区,Google 会对外部交易收取佣金,并要求您进行上报。该上报是集成的一部分,基于上述 Webhook 数据构建。参见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/)。
## 结论
按照上述步骤将原有体系平滑接入艾克索拉生态后,开发者即可突破 Google Play 结算库的局限,通过一套完善的备选方案在全球范围内开通更丰富的支付方式。这一拓展不仅能支撑更多元化的变现策略,还能借助艾克索拉完备的增值解决方案提升用户参与度。
如需了解受监管的 Google Play 结算计划相关指南,请参见 [Google Play 用户自选结算方式参考指南](https://developers.xsolla.com/sdk/zh/mobilesdk/addendum/android/google-play-user-choice-billing/)。
核心概念 (iOS)
https://developers.xsolla.com/sdk/zh/welcome/core-concepts-ios
若要在 Apple StoreKit 框架之外接入**艾克索拉 SDK** 以支持更广泛的支付方式,需要完成几个关键步骤,以确保集成顺畅、功能完备。下文将分块拆解在 iOS 上支持更多支付方式所需的**核心概念**:
## 身份认证与登录
- **了解 Apple ID / 帐户**:iOS 用户通常会在其设备上登录 Apple ID,为交易提供无缝的身份层。
- [**艾克索拉登录管理器**](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/):艾克索拉为开发者提供专门用于登录与身份认证的 SDK API,既可与开发者自有服务器集成,也可在轻量级游戏(如超休闲游戏)中直接采用客户端侧身份认证方式。这些 API 负责将用户 ID 或设备 ID 传递给艾克索拉服务,确保艾克索拉各产品能准确识别用户身份(例如支持顺畅的周期性扣款)。身份认证成功后,艾克索拉会返回发起购买流程所需的访问令牌。
## SKU 与 APP 内购 (IAP)
产品术语
在本文档中:
- **IAP(APP 内购)** = StoreKit 的应用内购买机制
- **SKU(库存单位)** = 代码中使用的商品标识符
- **虚拟物品** = 艾克索拉商品目录中的可购商品 (IAP)
从 App Store 迁移到艾克索拉时,原有的 IAP 会转为艾克索拉商品目录中的虚拟物品,每件虚拟物品都带有独立的 SKU 供代码调用。
- [**通过 StoreKit 框架销售的 APP 内购 ↗**](https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases) ([https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases):iOS](https://developer.apple.com/help/app-store-connect/manage-in-app-purchases/create-consumable-or-non-consumable-in-app-purchases)%EF%BC%9AiOS) 应用内的产品通过“产品 ID”(例如 `com.game.key_1`)进行标识,并配有“参考名称”(例如“Key Pack 1”)。在此示例中,它指的是价值 1 美元的钥匙包。
- **艾克索拉商品目录**:艾克索拉商品目录将您的数字商品作为[**虚拟物品**](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/) (IAP) 进行管理。将这些商品迁移到艾克索拉时,开发者需要从 App Store Connect 导入现有的 **App Store Connect 产品 ID**。每件商品都会转为带有专属 SKU 标识符的虚拟物品供代码调用,确保 App Store 生态中的商品能够准确映射并保持同步。
## 初始化支付收银台
- 在[设置 SKU](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/) 并[获取访问令牌](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/configuration/ios/)(例如基于用户/设备 ID 或通过自有服务器获取)后,下一步是[初始化支付收银台](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/purchase/ios/),创建订单并正式开启交易流程。
- 支付收银台需要传入访问令牌和具体的 SKU(例如“key_1”)来指明要购买的虚拟物品 (IAP)。开发者需要确保这两项配置无误,让用户获得与 StoreKit 框架一致的顺畅购买体验。
## Webhook
[Webhook](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/) 是系统在发生特定事件时发送的事件通知。当特定事件触发时,艾克索拉会发起 HTTP 请求,将事件数据传输至您的游戏服务器(在超休闲游戏等纯客户端简化集成场景下,也可传输至客户端)。游戏客户端或服务器正是依靠这些 Webhook 来接收支付成功或失败以及用户身份认证结果等关键通知。
## 替代支付方式与 App Store 政策
随着 App Store 政策的近期调整,开发者在部分地区拥有了更多接入替代支付方式的选择。艾克索拉 SDK 可帮助您顺畅落地这些新方案,同时确保符合 Apple 的各项指南要求。 备注
如需实现特定地区的支付方式,可以使用 [iOS 商店地区检测](https://developers.xsolla.com/sdk/zh/mobilesdk/sdk/advanced/ios-storefront/)功能,根据用户当前的 App Store 地区启用或禁用相应支付方式,确保符合各地区的政策与合规要求。
在部分地区,Apple 会对外部购买收取佣金,并要求您进行上报。该上报是集成的一部分,基于上述 Webhook 数据构建。参见[向 Apple 报告外部购买](https://developers.xsolla.com/sdk/zh/compliance/ios/)。
## 结论
按照上述步骤将原有体系平滑接入艾克索拉生态后,开发者即可突破 StoreKit 的局限,通过一套完善的备选方案在全球范围内开通更丰富的支付方式。这一拓展不仅能支撑更多元化的变现策略,还能借助艾克索拉完备的增值解决方案提升用户参与度,同时持续满足 iOS 平台的各项合规要求。
移动游戏分发术语表:DMA 时代与美国法院裁决
https://developers.xsolla.com/sdk/zh/welcome/glossary
## 简介
《数字市场法案》(DMA) 和美 国法院裁决为移动游戏的分发与变现引入了新概念。本术语表旨在阐释这些术语,并说明**艾克索拉 SDK** 如何在这一不断演变的行业格局中支持开发者。
随着行业不断适应监管变化,理解新的分发方式和支付方案至关重要。**艾克索拉 SDK** 助力开发者从容应对这一新生态,提供合规解决方案,开拓新的变现渠道。
**艾克索拉 SDK** 支持以下关键概念:
## iOS / Apple App Store:
- **外部支付链接(美国、日本、巴西、欧盟)**: - Apple 现已允许开发者在**美国**(Epic 诉 Apple 案,2025 年 4 月)、**日本**(《移动软件竞争法》,2025 年 12 月 18 日生效)、**巴西**(Apple 与 CADE 反垄断和解协议,2026 年 6 月 18 日生效)和**欧盟**(《数字市场法案》)将玩家引导至外部网页支付 - 为上述市场的用户接入跳转至艾克索拉支付收银台或网充商店的外部链接 - 使用 iOS 商店地区检测功能识别用户所属的商店地区,并启用对应的区域支付流程 - **艾克索拉 SDK** 符合 Apple 最新指南 - 将玩家跳转至网页支付页面时,配置 `openExternalBrowser = true` - 各市场的规则**并不相同**。在美国商店地区,无需申请专项授权 (entitlement),且 Apple 目前不对这类交易收取佣金。而在**日本**、**巴西**和**欧盟**,开发者需要获取 Apple 专项授权,Apple 会 收取佣金,且必须向 Apple 上报相关交易。参见[向 Apple 报告外部购买](https://developers.xsolla.com/sdk/zh/compliance/ios/)
- iOS 上的[**替代 App 市场 ↗**](https://developer.apple.com/support/alternative-app-marketplace-in-the-eu) ([https://developer.apple.com/support/alternative-app-marketplace-in-the-eu):](https://developer.apple.com/support/alternative-app-marketplace-in-the-eu)%EF%BC%9A) - Apple 对第三方替代应用商店的官方称谓,已在欧盟市场推出,并自 2026 年 6 月起在巴西开放 - 在 App Store 以外渠道的应用内支付中接入艾克索拉支付收银台 - 借助艾克索拉支付收银台的充值方案,为您的应用市场钱包提供充值能力 - Apple 会对通过此方式分发的应用收取佣金,且市场运营方也须履行各自的报告义务。请查阅您所在地区的 Apple 现行条款。在欧盟,自 2026 年 10 月 1 日起适用**核心技术佣金 (Core Technology Commission)**,按数字销售额分成,取代此前按安装次数计费的“核心技术费 (Core Technology Fee)”
- iOS 上的[**网页分发 ↗**](https://developer.apple.com/support/web-distribution-eu) ([https://developer.apple.com/support/web-distribution-eu):](https://developer.apple.com/support/web-distribution-eu)%EF%BC%9A) - Apple 对通过发行商官网在 iOS 上进行侧载分发的官方称谓 - 直接通过您的官网向用户分发应用 - 绕开 App Store 结算体系,通过艾克索拉支付收银台直接实现应用内支付 - Apple 仍会对以此方式售卖的数 字商品收取费用⸺在欧盟,自 2026 年 10 月 1 日起适用**核心技术佣金 (Core Technology Commission)**。在测算利润率前,请先查阅 Apple 的现行条款
- 面向 iOS 的[**公证 (Notarization) ↗**](https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization) ([https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization):](https://developer.apple.com/help/app-store-connect/distributing-apps-in-the-european-union/submit-for-notarization)%EF%BC%9A) - Apple 针对 App Store 以外渠道分发所设的轻量级审核流程 - 确保应用通过基础安全性与完整性检查 - **艾克索拉 SDK** 兼容通过公证的应用,全面保障安全标准
- App Store 上的[**替代支付选项 ↗**](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu) ([https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu):](https://developer.apple.com/support/payment-options-on-the-app-store-in-the-eu)%EF%BC%9A) - 在 Apple 允许的地区,通过**艾克索拉 SDK** 在 App Store 应用内集成艾克索拉支付收银台 - 为用户提供覆盖 200+ 个国家/地区的 1,000+ 种支付方式 - Apple 会对这类交易收取佣金,并要求您上报交易。参见[向 Apple 报告外部购买](https://developers.xsolla.com/sdk/zh/compliance/ios/) - 在欧盟,自 **2026 年 10 月 1 日**起,您可以与替代支付方式并列提供 Apple APP 内购,但所选的支付方案组合一经确定即锁定 12 个月,请在发版前妥善规划
## Android / Google Play:
- **通过外链跳转的外部支付方式与备选结算方案(美国)** — 自 2025 年 10 月 29 日起上线: - 根据 **Epic 诉 Google** 案禁令⸺美国第九巡回上诉法院于 2025 年 7 月 31 日维持原判 (147 F.4th 917),美国最高法院于 2025 年 10 月 6 日驳回暂缓执行申请⸺美国区 **Google Play** 应用可通过**外链跳转引导用户使用外部支付方式**,并可使用**备选结算方案**。2026 年 7 月,Epic 与 Google 仅撤回了请求按拟议和解方案修改该禁令的联合动议⸺并未撤回和解协议本身,协议中的商业条款(费率表、注册应用商店)仍独立适用。2024 年 10 月签发的原始禁令仍为现行有效的法院命令;其书面有效期自签发之日起为期三年,但受落地延迟影响,各方对实际到期日说法不一(有观点认为截至 2027 年 11 月,也有观点认为更晚)⸺制定业务规划前请先核查法院案卷记录 - 在美国,开发者不再受**反引导限制 (anti-steering restrictions)** 约束 - 开发者必须加入相应的 Google 计划并接受更新后的服务条款:用于外链跳转至外部购买页面的[**外部内容链接计划 ↗**](https://support.google.com/googleplay/android-developer/answer/16470497) ([https://support.google.com/googleplay/android-developer/answer/16470497),或用于在应用内使用非](https://support.google.com/googleplay/android-developer/answer/16470497)%EF%BC%8C%E6%88%96%E7%94%A8%E4%BA%8E%E5%9C%A8%E5%BA%94%E7%94%A8%E5%86%85%E4%BD%BF%E7%94%A8%E9%9D%9E) Google 结算体系的[**备选结算系统计划 ↗**](https://support.google.com/googleplay/android-developer/answer/16497028) ([https://support.google.com/googleplay/android-developer/answer/16497028)。开发者可同时参与这两项计划](https://support.google.com/googleplay/android-developer/answer/16497028)%E3%80%82%E5%BC%80%E5%8F%91%E8%80%85%E5%8F%AF%E5%90%8C%E6%97%B6%E5%8F%82%E4%B8%8E%E8%BF%99%E4%B8%A4%E9%A1%B9%E8%AE%A1%E5%88%92) - Google 目前尚未对这类美国区交易收取费用或要求上报交易⸺这两项要求均自 2026 年 10 月 1 日起实施 - 类似计划已在其他地区上线且需缴费⸺用户自选结算方式、外部优惠 (EEA)、结算方式选择(英国/EEA)以及外部支付(日本)。Google 目前已对这些交易收取佣金并要求您上报交易,详见[向 Google Play 报告外部交易](https://developers.xsolla.com/sdk/zh/compliance/android/) - 为美国用户接入跳转至艾克索拉支付收银台或网充商店的外部链接 - 使用 Google Play 商店地区检测功能识别美国用户(国家/地区代码“US”),并启用对应的区域支付流程 - **艾克索拉 SDK** 确保面向美国市场的应用完全符合 Google 修订后的合规要求
- [**Android 侧载 ↗**](https://developer.android.com/distribute/marketing-tools/alternative-distribution) ([https://developer.android.com/distribute/marketing-tools/alternative-distribution):](https://developer.android.com/distribute/marketing-tools/alternative-distribution)%EF%BC%9A) - 支持直接从网站或第三方渠道安装应用 (APK) - 接入支付且无需向 Google 缴纳分成(0% 费用) - 完全自主掌控应用的分发与变现 - **艾克索拉 SDK** 可与侧载应用无缝集成 - **开发者验证要求(即将生效)**:自 2026 年 3 月起,Google 要求所有开发者[**注册并验证身份 ↗**](https://developer.android.com/developer-verification) ([https://developer.android.com/developer-verification),侧载应用同样适用。自](https://developer.android.com/developer-verification)%EF%BC%8C%E4%BE%A7%E8%BD%BD%E5%BA%94%E7%94%A8%E5%90%8C%E6%A0%B7%E9%80%82%E7%94%A8%E3%80%82%E8%87%AA) 2026 年 9 月起率先在部分地区(巴西、印尼、新加坡、泰国)强制执行,并计划于 2027 年及以后推广至全球。未经验证的开发者所发布的应用将在通过认证的 Android 设备上被拦截。详见 [**Google 的验证指南 ↗**](https://support.google.com/android-developer-console/answer/16561738) ([https://support.google.com/android-developer-console/answer/16561738](https://support.google.com/android-developer-console/answer/16561738))
- APK 市场推广与分发: - 与 Digital Turbine 等渠道合作扩大触达范围,并在 Android 设备上实现 APK 即时安装 - 开拓 Google Play 之外的新获客渠道,走出自主增长路径 - 艾克索拉兼容各类 APK 分发归因工具,确保您能够持续优化投放效果
## 结论
受 DMA、美国法院裁决(包括 2025 年 4 月 30 日的 iOS 裁决及 2025 年 10 月 29 日生效的 Epic 诉 Google 案禁令)、日本与巴西出台的外部支付新规以及不断演进的平台政策推动,移动游戏行业格局正迅速变化。**艾克索拉 SDK** 提供完善的工具套件,助您从容应对这些变化,在所有可用渠道实现营收与用户触达最大化。
我们会定期更新此信息。如需了解最新详情,请查看[资讯动态](https://developers.xsolla.com/sdk/zh/documentation-changelog/)。 如需获取针对性指导,请咨询您的商务拓展代表或客户成功经理。
借助**艾克索拉 SDK**,您的游戏将在这一瞬息万变的市场环境中抢占先机,拓展全新的营收来源与创新分发渠道。
Windows 专用艾克索拉 SDK
https://developers.xsolla.com/sdk/zh/windows
可用Windows 专用艾克索拉 SDK[SDK Explorer →](https://developers.xsolla.com/sdk/demo/)
**Windows 专用艾克索拉 SDK** 为 Microsoft 平台上的游戏提供商店外交易、APP 内购与全球支付能力。通过**一次集成**,该 SDK 让开发者能够直接触达玩家、掌控结算体验,并保留最高 95% 的分成收入。在政策允许的场景下,还支持与商店内结算并行展示,便于灵活制定支付策略与忠诚度激励方案。游戏还可自动同步新型变现工具、监管合规及全球政策调整等方面的后续更新。
借助内置的 **IAP 商品目录同步**、面向**灵活打款**的简化税务入驻流程,以及对**更多支付方式和本地货币**的支持,艾克索拉 SDK 让 Windows 游戏能够轻松跨商店、跨地区拓展业务。开发者只需专注于游戏研发,支付、打款与合规等繁杂事务均由艾克索拉妥善处理。
## 平台支持
### Epic Games Store 与第三方支付交易
Epic Game Store 的政策允许开发者采用其他支付方式(包括基于浏览器的支付流程),前提是由开发者自行负责支付处理与履约。详情请参见 Epic 官方文档。
这意味着开发者既可与商店自有交易体系并行运行自有支付系统,也可直接替代商店交易,借助双渠道结算、网充商店购买及玩家激励等功能,全面掌控面向玩家的优惠方案。更多详情请参见[**此文章**](https://developers.xsolla.com/sdk/zh/windowstores/epic/)。
### 游戏引擎覆盖范围
信息
如果您的项目使用 Unity,建议集成 **Unity 专用艾克索拉 SDK**。详情请访问[**此页面**](https://developers.xsolla.com/sdk/zh/unity/)。
- **Unity**:对于使用 Unity 构建的 Windows 游戏,请采用 [**Unity 专用艾克索拉 SDK**](https://developers.xsolla.com/sdk/zh/unity/)。
- **自研引擎**:提供 C++ 和 C# 版本的[**原生 SDK**](https://developers.xsolla.com/sdk/zh/windowstores/sdk/installation/),兼具高度灵活性。
- **Defold**:可通过 **Defold 专用艾克索拉 SDK** 快速集成支付功能,该 SDK 已上架 Defold Asset Portal。
- **更多支持即将推出**:更多引擎适配正在推进中,敬请关注!
## 面向 Windows 开发者的核心 优势
**一次集成,适配多商店**
仅需接入一套 SDK,即可在 Epic Games Store 及其他 Windows 商店快速上线。无论游戏在何处发行,您的变现策略都能保持一致并完全自主掌控。**双渠道结算支持**
为玩家并列提供多种结算选项,由玩家自主选择支付方式。回馈忠实玩家、激发良性竞争,让商业化本身成为游戏亮点。更多详情请参见[最佳实践](https://developers.xsolla.com/sdk/zh/windowstores/epic/dual-billing/)。**跨平台商品目录同步**
轻松将应用内购商品(以带 SKU 的虚拟物品形式)同步至艾克索拉商品目录,无需在多个商店的开发者后台之间频繁切换,也不必重复维护多套商品定义。**灵活打款,无需繁琐手续**
商户入驻与税务合规往往耗时费力⸺艾克索拉提供顺畅的全球税务信息填报流程与灵活的打款方案,助您更快开启变现。**更多支付方式,覆盖全球**
艾克索拉原生支持更多全球支付方式、更多本地货币、本地化结算流程、先进的反欺诈机制及合规支付处理,开箱即用。
## 开始使用
**艾克索拉购买按钮**快速路径
网充商店一键购买流程,支持 1000+ 种支付方式⸺无需安装 SDK。可在 Windows 游戏内直接拉起基于浏览器的结算。[了解更多 →](https://xsolla.com/mobile-buy-button) [EPIC GAMES**Epic Games Store**通过双渠道结算与网充商店在 Epic 上开启商业化交易→](https://developers.xsolla.com/sdk/zh/windowstores/epic/)[SDK 文档**安装指南**面向 C++ 和 C# 引擎的分步 SDK 集成指南→](https://developers.xsolla.com/sdk/zh/windowstores/sdk/installation/)
艾克索拉 SDK:助力 Epic Games Store 游戏拓展商业化能力
https://developers.xsolla.com/sdk/zh/windowstores/epic
Epic Games Store 政策允许开发者接入其他支付方式,让游戏工作室能够自由选用最契合自身业务的工具。艾克索拉的 SDK 与各项服务既可与 Epic 原生交易系统并行运行,也可直接将其替代⸺助您优化结算体验、精简日常运营,并与玩家建立更紧密的联结。
## 以玩家为核心的变现机遇
**兼顾玩家权益的双渠道结算**: 艾克索拉 SDK 支持**双渠道结算**,让您能够在商店原生结算之外并列提供艾克索拉结算通道。您可以通过赠礼、返利或额外游戏内货币激励玩家选用⸺同时确保全流程合规透明。更多详情请参见[**双渠道结算最佳实践**](https://developers.xsolla.com/sdk/zh/windowstores/epic/dual-billing/)。 示 例文案
“使用艾克索拉支付,额外多得 10%!”
您也可以直接用艾克索拉 SDK 替代平台原生交易系统,全面掌控商业化变现、定价策略、商品目录和玩家数据。
**通过购买按钮开启网页端购买**: 借助艾克索拉[**购买按钮**](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop/#buy-button-seamless-web-shop-integration),您可以从游戏内直接发起安全、可定制的支付流程,将玩家引导至浏览器中的网页结算页面,充分发挥顺畅结算与已保存支付方式的优势。
购买按钮易于实现,并可与游戏内逻辑和后端系统无缝集成。
**搭建支持 Epic 登录的网充商店**: 您还可以通过由艾克索拉建站器和支付收银台驱动的[**网充商店**](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop/)向玩家提供直购服务。玩家现可使用 Epic Account 登录,您也可以开启[**设备 ID 身份认证**](https://developers.xsolla.com/sdk/zh/publisher-account/login/),打造顺畅且与帐户绑定的购买体验。
## Epic Games Store 的集成选项
艾克索拉提供持续扩充的 SDK 矩阵,全面支持通过 Epic Games Store 发行的游戏:
- **Unity SDK**:**[Unity 专用艾克索拉 SDK](https://developers.xsolla.com/sdk/zh/unity/)** 是基于 Unity 开发的游戏理想的开箱即用方案。
- **Windows SDK**:原生 **[Windows SDK](https://developers.xsolla.com/sdk/zh/windowstores/sdk/installation/)**(C++ 和 C#),适 用于自研技术栈。
- **Defold SDK**:面向 Defold 引擎游戏的轻量级集成方案,可通过 Defold Asset Portal 获取。
- **Mobile SDK**:专为 **Epic Games Mobile Store** 打造的原生 **[iOS 和 Android SDK](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/)**,支持独立于传统应用商店结算体系之外的一键购买。
- **网充商店 + Sign in with Epic**:[**网充商店**](https://developers.xsolla.com/sdk/zh/mobilesdk/quick-start/webshop/)可与艾克索拉 SDK 形成互补,助力打造直达玩家的商业化闭环。
## 您的游戏,您的玩家
艾克索拉的各项工具旨在为您减负,而非增加额外开销。借助集中式 SKU 管理、全球支付覆盖及友好的玩家结算体验,您只需专注于打磨游戏并为玩家提供丰富选择⸺新时代游戏商业化背后的繁杂事务皆由艾克索拉为您妥善处理。
## 下一步
- **[SDK 文档](https://developers.xsolla.com/sdk/zh/windowstores/sdk/installation/)** - 按照分步指南将 SDK 集成到您的 Windows 游戏中
- **[联系支持 ↗](https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk)** ([https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk](https://xsolla.com/epic-games-store?utm_medium=marketing&utm_content=windows-sdk)) - 联系您的客户经理,获取个性化的集成指导
使用艾克索拉简化 SKU 与 IAP 商品目录管理
https://developers.xsolla.com/sdk/zh/windowstores/epic/catalog-sync
跨多个系统维护游戏内商品目录,是游戏商业化运营中既繁琐又至关重要的一环。不同平台对定义虚拟物品、管理 SKU 以及同步更新商品目录各有要求,往往需要在各渠道开发者后台、后端服务和游戏客户端逻辑之间反复手动操作。
借助艾克索拉的商品目录同步功能,开发者可以将**发布商帐户**作为唯一可信数据源⸺在此集中管理所有 IAP 定义⸺并自动保持各系统间的游戏商品目录一致。具体配置方法请参见[**此文章**](https://developers.xsolla.com/sdk/zh/publisher-account/virtual-items/)。
## 工作原理
将游戏接入艾克索拉后,只需在发布商帐户中一次性配置好艾克索拉商品目录(包括带 SKU 的虚拟物品/IAP、定价、商品类型、捆绑包等),随后即可将这些商品定义直接拉取并应用于:
- 游戏客户端(通过 SDK 或 API)
- 后端服务
- 网充商店或购买按钮配置
如此一来,商品名称、价格、上架状态或各项配置的任何修改都只需在一处完成⸺即发布 商帐户⸺所有变更便会自动同步至各个系统。
## 优势
- **减少人为失误**:跨多个系统手动录入商品目录极易出现拼写错误、价格配置有误或 SKU 不匹配,自动同步可彻底消除此类风险。
- **节省时间**:避免在各个平台或开发环境重复工作。一次更新,全面同步。
- **提升跨渠道一致性**:无论玩家是在任一游戏客户端版本内购买,还是通过网充商店购买,看到的商品与价格始终完全一致。
- **支持 A/B 测试与 LiveOps 常态化运营**:商品目录变更可集中实时发布,便于轻松测试优惠方案、调整活动定价或快速上线新捆绑包。
- **日常维护更省心**:团队可将商品目录管理工作交由 LiveOps 运营、产品或商业化变现团队负责,无需占用研发资源,也不必开放各分发平台后台权限。
## 适用场景
如果您的游戏在多个应用商店发行、提供网页端购买,或需要频繁更新 IAP 商品,通过发布商帐户同步商品目录能显著降低维护成本并提升变现体系的稳定性。即便目前仅在单一商店发行,这项功能同样能简化日常运营,为后续后端扩展留足空间。
双渠道结算最佳实践
https://developers.xsolla.com/sdk/zh/windowstores/epic/dual-billing
在 Windows 游戏中接入双渠道结算,能够在结算环节赋予玩家更多选择权⸺而这种选择应当真正为玩家带来实惠。正如 Epic Games 在官方指南中所倡导的,平台鼓励开发者提供多种支付选项,让不同渠道围绕玩家价值展开良性竞争。
同时向玩家提供 Epic 内置支付系统与艾克索拉等外部支付选项时,关键在于确保两种方式都公平透明、物有所值。一项行之有效的最佳实践是:让您提供的回馈权益至少与平台原生福利持平,甚至更具吸引力。
建议至少提供同等力度的实际返利⸺既可以是额外的游戏内货币、附赠道具内容,也可以是直观清晰的激励优惠,例如:“使用艾克索拉支付,额外多得 5%!”
这样既能让玩家花同样的钱获得更高回报、传递尊重玩家自主选择的态度,也能自然吸引玩家尝试备选结算通道。
落地双渠道结算时,建议把握以下要点:
- **清晰透明**:在结算界面醒目展示返利信息。恰当排布提示文案或图标,既能自然引导玩家选择,又不会干扰正常游戏体验。
- **保持奖励平衡**:不要过度优化某一种支付流程。目标是提供选择,而不是强推。
- **测试玩家偏好**:哪怕是小幅返利(即便只有 5%–10%),也可能显著改变玩家的支付倾向。不妨通过 A/B 测试对比不同优惠力度和文案表述,找出最能打动目 标玩家群体的方案。
归根结底,良好的结算体验应当围绕自主选择、公平对等与彼此信任来构建玩家关系。双渠道结算的初衷并非强行将玩家从某一支付渠道引开⸺而是把决定权交给玩家,由他们自行判断哪种方式更具价值。
配置
https://developers.xsolla.com/sdk/zh/windowstores/sdk/configuration
要配置 SDK,请使用以下代码:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetRestorePurchasesOnInit(true)
.SetWebViewType(XsollaStoreClientSettings.WebViewType.Auto)
.SetWebViewOrientationLock(XsollaStoreClientSettings.OrientationLock.Auto)
.SetUIThemeSize(XsollaStoreClientSettings.ThemeSize.Auto)
.SetUIThemeStyle(XsollaStoreClientSettings.ThemeStyle.Auto)
.SetUICustomTheme("")
.SetUseCloseButton(XsollaStoreClientSettings.CloseButton.Auto)
.SetUIControlTintColor(Color.clear)
.SetUIBarTintColor(Color.clear)
.SetRedirectUrl("")
.SetRedirectButtonText("")
.SetRedirectDelay(6)
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
```
### 事件
**艾克索拉 Events API** 可替代基于 Webhook 的集成方案(后者通常由接入方后端负责购买验证、权益发放等大部分逻辑)。该 API 不会直接发送 Webhook,而是先将其拦截,并把负载存入由艾克索拉托管的远程队列中。这种方式支持无服务器集成,适合缺少后端开发资源或无需自建后端、但仍希望在应用内直接处理完整交易流程的项目。
通过 Events API 恢复购买时,还会返回原始艾克索拉订单的标识符,便于将已恢复的购买记录与您自身的记录进行比对;而通过物品库恢复时则没有可关联引用的订单信息。 注意
选用艾克索拉 Events API 会禁用项目的 Webhook。换言之,无法同时在后端处理 Webhook 并在应用中使用 Events API。
如需启用该功能,请在发布商帐户中打开项目,前往**项目设置** > **集成设置**,选择**使用 API** 并点击**保存**。详情请参阅[**发布商帐户中的 Events API**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。
以下是在 SDK 中启用事件功能所需的最简事件配置:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
//..
.SetWebhooksMode(XsollaStoreClientSettings.WebhooksMode.EventsApi)
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
//..
settings->SetWebhooksMode(CXsollaClientSettings::WebhooksMode::EventsApi);
```
信息
如需了解更多信息,请参见 [**Webhook 页面**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#enabling-xsolla-events-api)。
### 基于设置构建配置
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// Set the settings object you've acquired in previous step here..
.SetSettings(settings)
.SetSandbox(true)
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
configuration->SetSettings(settings);
configuration->SetSandbox(true);
configuration->SetLogLevel(CXsollaClientConfiguration::XsollaLogLevel::Debug);
```
### 为配置分配艾克索拉访问令牌
备注
访问令牌的 [**JWT 结构 ↗**](https://developers.xsolla.com/api/login/overview/#section/JWT-structure) ([https://developers.xsolla.com/api/login/overview/#section/JWT-structure)。](https://developers.xsolla.com/api/login/overview/#section/JWT-structure)%E3%80%82) 注意
初始化 SDK 前,必须先获取有效的**访问令牌**。
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
.SetSettings(settings)
.SetAccessToken("< your access token >")
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
configuration->SetSettings(settings);
configuration->SetAccessToken("< your access token >");
```
### 使用设备 ID 代替访问令牌
以下示例展示了使用设备 ID 进行身份认证时需设置的字段:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
```
### 使用 OAuth 2.0 代替访问令牌
以下示例展示了使用 OAuth 2.0 进行身份认证时需设置的字段:
```csharp
var settings = XsollaStoreClientSettings.Builder.Create()
.SetProjectId("< your_project_id >")
.SetLoginId("< your_login_id >")
.SetOAuthClientId("< your_oauth_client_id >")
// ..other properties
.Build();
```
```cpp
auto settings = CXsollaClientSettings::Create();
settings->SetProjectId("< your_project_id >");
settings->SetLoginId("< your_login_id >");
settings->SetOAuthClientId("< your_oauth_client_id >")
```
### 在沙盒模式下测试购买流程
如需了解如何启用沙盒模式,避免在测试集成时产生真实扣款,请参阅[**测试**](https://developers.xsolla.com/sdk/zh/windowstores/sdk/testing/)指南。
初始化
https://developers.xsolla.com/sdk/zh/windowstores/sdk/initialization
在[完成配置](https://developers.xsolla.com/sdk/zh/windowstores/sdk/configuration/)后,需要初始化 **Windows 专用艾克索拉 SDK** 并连接到**艾克索拉**服务。
```csharp
var storeClient = XsollaStoreClient.Builder.Create()
.SetConfiguration(configuration)
.SetOnRestore((item, error) => {
if (error != null)
{
// handle error
return;
}
// handle delayed purchased item
})
.AddProducts(productIds)
.AddProduct("product1")
.AddProduct("product2")
.AddProduct("product3")
.AddProduct("product4")
.Build();
storeClient.Initialize((products, error) =>
{
if (error != null)
{
// handle error
return;
}
// products contains all requested products
});
```
```cpp
auto products = std::vector<std::string>{
"product1",
"product2",
"product3",
};
auto client = new CXsollaStoreClient(configuration, products, [](std::shared_ptr<CXsollaStoreClientPurchasedProduct> product, std::shared_ptr<CXsollaStoreClientError> error) {
std::cout << "C++ Restore successful for product: " << product->GetSku() << "\n";
});
client->Initialize([client](std::vector<std::shared_ptr<CXsollaStoreClientProduct>> products, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Initialization successful.\n";
} else {
std::cout << "C++ Initialization failed with error code: " << error->GetMessage() << "\n";
}
});
```
SDK 仅从您的艾克索拉商品目录中加载虚拟物品,不会返回虚拟货币、捆绑包及其他商品目录类型。
安装
https://developers.xsolla.com/sdk/zh/windowstores/sdk/installation
#### 选项 1:从压缩包安装
- 将 SDK 解压到项目中。
- 在项目中添加依赖项。
购买流程
https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase
购买流程是一个多阶段过程,包括[支付收款](https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase#starting-purchasing-flow)、[购买验证](https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase#validating-purchases-recommended)和[商品核销](https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase#consuming-purchased-goods)。
### 启动购买流程
请根据是否使用 Unity InApp Purchasing,选用下方任一代码片段启动购买流程:
```cs
storeClient.PurchaseProduct(productId, (product, error) =>
{
if (error != null)
{
// handle error
return;
}
var receipt = product.ToReceipt();
// handle the purchased product here (e.g. validate or consume)..
});
```
```cpp
client->PurchaseProduct(productId,
[](std::shared_ptr<CXsollaStoreClientPurchasedProduct> product, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Purchase successful for product: " << product->GetSku() << "\n";
auto receipt = CXsollaStoreClientHelpers::ConvertToReceipt(product)
// handle the purchased product here (e.g. validate or consume)..
}
else {
std::cout << "C++ Purchase failed with error code: " << error->GetMessage() << "\n";
}
}
);
```
### 验证购买(推荐)
注意
尽管验证**不是**必需步骤,但仍强烈建议进行验证,以尽量降低欺诈及其他恶意行为的风险。
关于如何验证购买,请参阅[**购买验证**](https://developers.xsolla.com/sdk/zh/windowstores/sdk/validation/)指南。
### 核销已购商品
购买流程的最后一步是将已购商品发放给用户,并将这些商品标记为“已发放”。这一过程也称为**购买核销**。
使用以下代码完成此操作:
```cs
storeClient.ConsumeProduct(item.sku, item.quantity, item.transactionId, error => {
if (error != null)
{
return;
}
// handle purchased item
});
```
```cpp
client->ConsumeProduct( item->GetSku(), item->GetQuantity(), item->GetTransactionId(),
[](std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Consume successful.\n";
} else {
std::cout << "C++ Consume failed with error code: " << error->GetMessage() << "\n";
}
}
);
```
important
强烈建议在核销已购商品前,至少采用某种方式完成[**验证**](https://developers.xsolla.com/sdk/zh/windowstores/sdk/purchase#validating-purchases-recommended)。
测试与沙盒
https://developers.xsolla.com/sdk/zh/windowstores/sdk/testing
本节提供相关代码片段与示例,介绍如何配置沙盒环境以完成测试支付、输出更详细的日志等操作。
### 启用沙盒模式
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetSandbox(true)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
// ...
configuration->SetSandbox(true);
```
#### 在 Unity 编辑器中测试
在 Unity 编辑器中测试时,会使用当前运行平台(例如 Windows 或 macOS)对应的实现。 注意
在**正式上线**前,请务必将**沙盒**模式**关闭**。
### 启用额外日志
```csharp
var configuration = XsollaStoreClientConfiguration.Builder.Create()
// ...
.SetLogLevel(XsollaLogLevel.Debug)
.Build();
```
```cpp
auto configuration = CXsollaClientConfiguration::Create();
// ...
configuration->SetLogLevel(CXsollaClientConfiguration::XsollaLogLevel::Debug);
```
注意
在**正式上线**前,请确保已**关闭**调试**日志记录**。
### 测试银行卡
如需查看沙盒模式下用于模拟支付的测试银行卡列表,请参见[此处 ↗](https://developers.xsolla.com/doc/pay-station/testing/test-cards) ([https://developers.xsolla.com/doc/pay-station/testing/test-cards)。](https://developers.xsolla.com/doc/pay-station/testing/test-cards)%E3%80%82) important
测试银行卡无法在**沙盒模式**以外使用。
购买验证
https://developers.xsolla.com/sdk/zh/windowstores/sdk/validation
向最终用户发放购买内容前,应对每笔购买交易进行验证。这有助于防范未授权购买,维护应用内经济系统的正常运行。购买验证是防范欺诈、保障收入并维护公平用户体验的关键安全措施。
目前主要提供两种不同的验证方式。
### 服务器侧验证
最安全可靠的验证方式是采用**服务器到服务器** (**S2S**) 通信,使客户端完全不参与验证流程。这能最大限度降低安全风险,确保仅凭直接来自艾克索拉的已验证数据发放权益。
接入艾克索拉时,服务器侧验证通过**基于 Webhook 的模式**实现:
- 用户通过应用完成购买后,艾克索拉服务会自动向您的后端发送 [**Webhook 事件**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/#user_validation)。
- 该 Webhook 包含所有必要的购买数据(包括**艾克索拉** `order ID`),供服务器异步验证并处理该笔购买。
- 随后,后端即可根据这些数据更新用户的权益、余额、物品库等,无需客户端提供任何额外输入。
该流程确保客户端无法干预购买结果的判定⸺所有验证逻辑均在服务器端执行,且仅使用直接来自艾克索拉的可信数据。 提示
有关 Webhook 工作原理的更多信息,请参见[**此处**](https://developers.xsolla.com/sdk/zh/publisher-account/webhooks/)。
### 客户端侧验证
客户端侧验证支持直接在用户设备上验证购买,无需搭建后端(服务器)。虽然这比完全不验证更稳妥,但仍存在明显局限,即任何在客户端运行的逻辑都有可能遭到篡改或恶意利用。
```csharp
void MyOnPurchaseCallback(XsollaStoreClientPurchasedProduct product, XsollaStoreClientError error)
{
_storeClient.ValidatePurchase(product.ToReceipt(), (success, error) =>
{
if (error == null && success)
{
// Purchase is Valid, handle the purchased item..
}
else
{
// Purchase is NOT valid or there was an error performing validation..
}
});
}
```
```cpp
client->ValidatePurchase(
CXsollaStoreClientHelpers::ConvertToReceipt(product),
[client, product](bool valid, std::shared_ptr<CXsollaStoreClientError> error) {
if (error == nullptr) {
std::cout << "C++ Purchase validation successful. Valid: " << (valid ? "true" : "false") << "\n";
} else {
std::cout << "C++ Purchase validation failed with error code: " << error->GetMessage() << "\n";
}
}
);
```