Chấp nhận thanh toán Stripe trong Android flows

Bạn có thể bán gói đăng ký Stripe từ một flow được xây dựng trong Flow & Paywall Builder. Flow hiển thị các mức giá Stripe của bạn, và các nút trong flow sẽ mở PaymentSheet của Stripe lên trên flow. Sau khi thanh toán, Stripe sẽ thông báo cho Adapty. Adapty cấp mức độ truy cập cho người dùng và gắn doanh thu vào flow, placement của nó, cũng như biến thể A/B test tương ứng. Hãy dùng cách thiết lập này để bán gói đăng ký cho các dịch vụ mà người dùng sử dụng bên ngoài ứng dụng, chẳng hạn như thành viên sự kiện trực tiếp, thẻ tham gia lớp học, hoặc giao hàng định kỳ.

Important

Google Play yêu cầu sử dụng hệ thống thanh toán của mình cho hàng hóa và dịch vụ kỹ thuật số. Google Play không cho phép sử dụng hệ thống thanh toán của mình cho hàng hóa vật lý và dịch vụ vật lý (Chính sách thanh toán). Thanh toán in-app qua Stripe dành cho hàng hóa vật lý và các dịch vụ mà người dùng sử dụng bên ngoài ứng dụng.

Cách hoạt động

  1. Ứng dụng của bạn lấy giá Stripe từ backend, sau đó truyền chúng vào flow dưới dạng custom tags và hiển thị flow.
  2. Người dùng nhấn vào một nút trong flow. Nút đó kích hoạt một hành động tùy chỉnh, và ứng dụng của bạn nhận được action ID.
  3. Ứng dụng của bạn yêu cầu backend tạo một gói đăng ký Stripe. Backend thêm ID người dùng và variation ID của flow vào metadata của gói đăng ký.
  4. Ứng dụng của bạn mở PaymentSheet lên trên flow, và người dùng thanh toán hóa đơn đầu tiên của gói đăng ký.
  5. Stripe gửi một webhook đến Adapty. Adapty cấp mức độ truy cập cho hồ sơ người dùng có ID tương ứng, và gán lượt mua cho biến thể flow đó.
  6. Ứng dụng của bạn đóng flow và chờ cho đến khi hồ sơ người dùng có mức độ truy cập đó.

Trước khi bắt đầu

Hãy đảm bảo rằng bạn đã:

  1. Stripe đã kết nối với ứng dụng Adapty của bạn: Làm theo hướng dẫn Kết nối Stripe với Adapty, cho cả chế độ test và chế độ live. Giữ Profile creation behavior ở mức Use customer_user_id from metadata (default).
  2. Một sản phẩm và giá Stripe cho mỗi gói: Tạo sản phẩm trên Stripe với giá theo chu kỳ, ví dụ như hàng tháng hoặc hàng năm.
  3. Một sản phẩm Adapty cho mỗi mức giá Stripe: Thêm Stripe product ID và price ID vào sản phẩm Adapty, và gán mức độ truy cập mà gói đó mở khóa. Mức độ truy cập đại diện cho quyền sử dụng dịch vụ, chẳng hạn như tư cách thành viên đang hoạt động, chứ không phải các tính năng kỹ thuật số trong ứng dụng. Nếu không có sản phẩm Adapty, Adapty sẽ không ghi lại giao dịch mua.
  4. Adapty Android SDK 4.0.0 trở lên, cùng với module android-ui: Kích hoạt SDK bằng key của ứng dụng Adapty mà bạn đã kết nối với Stripe. Adapty chỉ nhận webhook của Stripe cho ứng dụng đó. Xác định người dùng bằng customer user ID, và chỉ hiển thị flow này cho những người dùng đã đăng nhập và được xác định. Adapty sử dụng ID này để tìm hồ sơ người dùng nhận mức độ truy cập.
  5. Stripe Android SDK 20.46.0 trở lên (com.stripe:stripe-android) trong ứng dụng của bạn. Xem Accept a payment trong tài liệu Stripe.
  6. Một backend có thể gọi Stripe API bằng secret key của Stripe, hoặc bằng restricted key do bạn tự tạo có quyền ghi Customers và Subscriptions. Đừng tái sử dụng restricted key mà bạn đã tạo cho Adapty: đó là key của Adapty và nó không có quyền ghi mà backend của bạn cần. Hãy giữ key trên server của bạn.

Hiển thị giá Stripe trong flow

Flow hiển thị giá Stripe thông qua các thẻ tùy chỉnh. Thẻ tùy chỉnh là một giá trị văn bản mà ứng dụng của bạn truyền vào flow khi hiển thị flow đó. Adapty không định dạng giá trị thẻ tùy chỉnh, vì vậy hãy truyền mỗi mức giá theo đúng định dạng mà người dùng sẽ thấy, chẳng hạn như “$29.00”.

  1. Trong Flow & Paywall Builder, tạo một biến String cho mỗi mức giá, ví dụ stripe_monthly_price và stripe_annual_price, rồi chọn Value comes from outside the app. Đặt Initial value của mỗi biến bằng mức giá hiện tại của bạn. Người dùng sẽ thấy giá trị ban đầu này nếu ứng dụng không tải được giá, vì vậy hãy đặt giá trị ban đầu bằng đúng giá Stripe của bạn.
  2. Chèn từng tag vào một phần tử văn bản, chẳng hạn như nhãn của một nút gói.
  3. Trong ứng dụng của bạn, lấy giá từ backend trước khi tải flow.
  4. Truyền giá vào tham số tagResolver của AdaptyFlowView.showFlow hoặc AdaptyFlowScreen.

Hàm sau tải flow, tạo tag resolver với các Stripe price của bạn. Nó cũng trả về variationId của flow, vì backend của bạn sẽ ghi ID này vào Stripe subscription. Bạn hiển thị flow trong Mở PaymentSheet từ flow.


class StripeFlow(
    val configuration: AdaptyUI.FlowConfiguration,
    val variationId: String,
    val tagResolver: AdaptyUiTagResolver,
)

suspend fun loadStripeFlow(): StripeFlow {
    // If the prices fail to load, the flow shows the tags' initial values
    val prices = try {
        Backend.fetchPrices()
    } catch (e: IOException) {
        emptyMap()
    }
    val customTags = mapOf(
        "stripe_monthly_price" to prices["monthly"],
        "stripe_annual_price" to prices["annual"],
    )

    val flow = awaitAdapty { callback -> Adapty.getFlow("YOUR_PLACEMENT_ID", callback = callback) }
    val preferredLocales = LocaleListCompat.getAdjustedDefault().toLanguageTags().split(",")
    val configuration = awaitAdapty { callback ->
        AdaptyUI.getFlowConfiguration(flow, preferredLocales, callback = callback)
    }
    return StripeFlow(
        configuration = configuration,
        variationId = flow.variationId,
        tagResolver = AdaptyUiTagResolver { tag -> customTags[tag] },
    )
}

// Turns an Adapty SDK callback into a suspend call
suspend fun <T> awaitAdapty(call: (ResultCallback<T>) -> Unit): T =
    suspendCancellableCoroutine { continuation ->
        call { result ->
            when (result) {
                is AdaptyResult.Success -> continuation.resume(result.value)
                is AdaptyResult.Error -> continuation.resumeWithException(result.error)
            }
        }
    }

Backend là client cho các endpoint của backend, từ Tạo gói đăng ký trên backend của bạn. Adapty SDK trả kết quả qua callback, vì vậy awaitAdapty chuyển đổi một callback thành suspend call cho các coroutine trong hướng dẫn này.

Thêm các nút mở PaymentSheet

Mỗi nút bán một gói Stripe sẽ kích hoạt một custom action. Ứng dụng của bạn nhận được action ID và mở PaymentSheet cho gói đó.

  1. Trong Flow & Paywall Builder, thêm một nút cho mỗi gói Stripe.
  2. Gán action Custom Action cho mỗi nút, và nhập action ID, ví dụ như buy_stripe_monthly và buy_stripe_annual.
  3. Xuất bản flow, và thêm nó vào một placement.

Ứng dụng của bạn ánh xạ mỗi ID hành động vào một gói. Flow không gửi bất kỳ dữ liệu nào kèm theo hành động, vì vậy ID hành động phải xác định được gói đó.

Tạo gói đăng ký trên backend của bạn

PaymentSheet thanh toán cho một đối tượng Stripe mà backend của bạn tạo ra. Trong hướng dẫn này, backend của bạn tạo một gói đăng ký Stripe, và PaymentSheet thanh toán hóa đơn đầu tiên của gói đăng ký đó. Backend của bạn đặt hai key trong metadata của gói đăng ký:

  • customer_user_id: ID người dùng trong Adapty. Adapty cấp mức độ truy cập cho hồ sơ người dùng có ID này.
  • variation_id: ID biến thể của flow, do app của bạn gửi lên backend. Adapty gán doanh thu cho biến thể flow này, placement và A/B test của nó.
Warning

Adapty không ghi nhận thanh toán cho PaymentIntent mà bạn tạo độc lập, không gắn với gói đăng ký hay hóa đơn nào. Người dùng thanh toán xong nhưng không nhận được mức độ truy cập.

Tạo hai endpoint. Endpoint đầu tiên trả về giá đã được định dạng cho các thẻ tùy chỉnh. Endpoint thứ hai tạo gói đăng ký và trả về các giá trị mà PaymentSheet cần. Trước khi tạo gói đăng ký, endpoint thứ hai kiểm tra xem người dùng có gói đăng ký đang hoạt động hay không, để tránh trường hợp người dùng thanh toán hai lần cho cùng một gói.

Ví dụ này sử dụng Node.js với ES modules ("type": "module" trong package.json), Express, và thư viện stripe phiên bản 18 trở lên. Thay db bằng cơ sở dữ liệu của bạn:


const app = express();
app.use(express.json());

const stripe = new Stripe(process.env.STRIPE_SECRET_KEY);

const prices = {
  monthly: 'price_...', // your Stripe price IDs
  annual: 'price_...',
};

// Prices for the custom tags, such as { "monthly": "$29.00", "annual": "$249.00" }.
// You can cache the response.
app.get('/prices', async (req, res) => {
  try {
    const result = {};
    for (const [plan, priceId] of Object.entries(prices)) {
      const price = await stripe.prices.retrieve(priceId);
      // Assumes a currency with two decimal places. Format for your users' locale.
      result[plan] = new Intl.NumberFormat('en-US', {
        style: 'currency',
        currency: price.currency.toUpperCase(),
      }).format(price.unit_amount / 100);
    }
    res.json(result);
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not load prices' });
  }
});

app.post('/subscriptions', async (req, res) => {
  // req.user comes from your authentication middleware. Its ID is the same
  // customer user ID that your app passes to Adapty.identify().
  const customerUserId = req.user.id;
  // variationId affects only attribution, so the backend doesn't need to trust it
  const { plan, variationId } = req.body;
  if (!prices[plan]) {
    return res.status(400).json({ error: 'Unknown plan' });
  }

  try {
    // One Stripe customer per user, stored in your database
    let customerId = await db.getStripeCustomerId(customerUserId);
    if (!customerId) {
      const customer = await stripe.customers.create({ metadata: { customer_user_id: customerUserId } });
      customerId = customer.id;
      await db.saveStripeCustomerId(customerUserId, customerId);
    }

    // Don't sell a second subscription to a user who already has one
    for (const status of ['active', 'trialing', 'past_due']) {
      const existing = await stripe.subscriptions.list({ customer: customerId, status, limit: 1 });
      if (existing.data.length > 0) {
        return res.status(409).json({ error: 'You already have a subscription' });
      }
    }

    const subscription = await stripe.subscriptions.create({
      customer: customerId,
      items: [{ price: prices[plan] }],
      payment_behavior: 'default_incomplete',
      payment_settings: { save_default_payment_method: 'on_subscription' },
      metadata: {
        customer_user_id: customerUserId,
        variation_id: variationId,
      },
      expand: ['latest_invoice.confirmation_secret'],
    });

    res.json({
      subscriptionId: subscription.id,
      clientSecret: subscription.latest_invoice.confirmation_secret.client_secret,
      publishableKey: process.env.STRIPE_PUBLISHABLE_KEY,
    });
  } catch (error) {
    console.error(error);
    res.status(500).json({ error: 'Could not create the subscription' });
  }
});

app.listen(process.env.PORT ?? 3000);

Với payment_behavior: 'default_incomplete', gói đăng ký sẽ chờ đến khi thanh toán lần đầu được thực hiện. Stripe sẽ kích hoạt gói đăng ký khi người dùng thanh toán trong PaymentSheet. Nếu người dùng đóng PaymentSheet mà chưa thanh toán, Stripe sẽ hủy gói đăng ký sau khoảng 23 giờ và Adapty sẽ không ghi nhận giao dịch đó. Để biết thêm về cách thiết lập Stripe đầy đủ, hãy xem Build a subscriptions integration trong tài liệu Stripe.

Mã đọc client secret từ latest_invoice.confirmation_secret, yêu cầu Stripe API version 2025-03-31.basil trở lên. Thư viện stripe sử dụng version này từ phiên bản 18. Nếu bạn gọi Stripe API trực tiếp mà không dùng thư viện, hãy đặt header Stripe-Version. Với API version cũ hơn, hãy expand latest_invoice.payment_intent và đọc payment_intent.client_secret thay thế.

Trong ứng dụng của bạn, hãy gọi hai endpoint này. Gửi thông tin xác thực của người dùng kèm theo mỗi request, theo yêu cầu của backend:


object Backend {
    private const val BASE_URL = "https://YOUR_BACKEND"

    class Subscription(
        val subscriptionId: String,
        val clientSecret: String,
        val publishableKey: String,
    )

    class BackendException(message: String) : IOException(message)

    suspend fun fetchPrices(): Map<String, String> {
        val json = send("prices")
        return json.keys().asSequence().associateWith { json.optString(it) }
    }

    suspend fun createSubscription(plan: String, variationId: String): Subscription {
        val body = JSONObject()
            .put("plan", plan)
            .put("variationId", variationId)
        val json = send("subscriptions", body)
        return Subscription(
            subscriptionId = json.requireString("subscriptionId"),
            clientSecret = json.requireString("clientSecret"),
            publishableKey = json.requireString("publishableKey"),
        )
    }

    private suspend fun send(path: String, body: JSONObject? = null): JSONObject =
        withContext(Dispatchers.IO) {
            val connection = URL("$BASE_URL/$path").openConnection() as HttpURLConnection
            try {
                // add your authentication header
                if (body != null) {
                    connection.requestMethod = "POST"
                    connection.doOutput = true
                    connection.setRequestProperty("Content-Type", "application/json")
                    connection.outputStream.use { it.write(body.toString().toByteArray()) }
                }
                val statusCode = connection.responseCode
                val stream = if (statusCode == 200) connection.inputStream else connection.errorStream
                val text = stream?.bufferedReader()?.use { it.readText() }.orEmpty()
                val json = try {
                    JSONObject(text)
                } catch (e: JSONException) {
                    null
                }
                if (statusCode != 200) {
                    // Use the backend's message when the response has one
                    val message = json?.optString("error").orEmpty()
                    throw BackendException(message.ifEmpty { "The server returned HTTP $statusCode." })
                }
                json ?: throw BackendException("The server returned an invalid response.")
            } finally {
                connection.disconnect()
            }
        }

    private fun JSONObject.requireString(key: String): String =
        optString(key).ifEmpty { throw BackendException("The response has no $key.") }
}

Mở PaymentSheet từ flow

Ứng dụng của bạn mở PaymentSheet khi một nút trong flow kích hoạt custom action, và đóng flow khi thanh toán thành công:

  1. Ánh xạ ID hành động tùy chỉnh vào một gói. Bỏ qua các lần chạm, và nút đóng của flow, trong khi ứng dụng của bạn đang chờ backend hoặc hiển thị PaymentSheet. Như vậy, một lần chạm chỉ tạo một gói đăng ký.
  2. Yêu cầu backend tạo gói đăng ký, và truyền vào gói cùng variationId của flow.
  3. Hiển thị PaymentSheet lên trên flow, và xử lý kết quả trả về:
    • Completed: Đóng flow. Sau khi đóng, chờ mức độ truy cập.
    • Canceled: Không làm gì. Người dùng vẫn ở trên flow và có thể chọn gói khác.
    • Failed: Hiển thị lỗi. Người dùng vẫn ở trên flow và có thể thử lại.
  4. Xử lý hành động đóng của flow. Handler hành động của bạn thay thế handler mặc định của SDK, vốn có chức năng đóng flow. Đối với hành động mở URL, hãy gọi handler mặc định để mở URL đó.
  5. Tạo PaymentSheet trong onCreate của activity, hoặc trong composable của bạn ở mỗi lần composition. Stripe đăng ký PaymentSheet cho một kết quả activity, và activity không thể đăng ký sau khi đã khởi động.

Bước 1–3 giống nhau trong Views và Jetpack Compose, vì vậy hướng dẫn này gộp chúng vào một ViewModel. ViewModel cũng lưu trạng thái flow đã tải và trạng thái thanh toán khi Android tạo lại activity, ví dụ khi người dùng xoay màn hình trong khi PaymentSheet đang mở:


class StripeCheckout : ViewModel() {
    companion object {
        // Custom action IDs from the flow, mapped to your backend's plan keys
        val plans = mapOf(
            "buy_stripe_monthly" to "monthly",
            "buy_stripe_annual" to "annual",
        )
    }

    sealed interface Event {
        class PresentPaymentSheet(val subscription: Backend.Subscription) : Event
        class ShowError(val error: Throwable) : Event
    }

    private val _flow = MutableStateFlow<StripeFlow?>(null)
    /** The flow to show, or `null` when the flow is closed. */
    val flow: StateFlow<StripeFlow?> = _flow.asStateFlow()

    private val _events = Channel<Event>(Channel.BUFFERED)
    val events = _events.receiveAsFlow()

    private var isLoadingFlow = false
    private var isPaying = false

    fun showFlow() {
        if (isLoadingFlow || _flow.value != null) return
        isLoadingFlow = true
        viewModelScope.launch {
            try {
                _flow.value = loadStripeFlow()
            } catch (e: AdaptyError) {
                // handle the error
            } finally {
                isLoadingFlow = false
            }
        }
    }

    fun closeFlow() {
        if (isPaying) return
        _flow.value = null
    }

    /** Creates the subscription for a plan, and asks the screen to open PaymentSheet. */
    fun pay(plan: String) {
        val variationId = _flow.value?.variationId ?: return
        if (isPaying) return
        isPaying = true
        viewModelScope.launch {
            try {
                val subscription = Backend.createSubscription(plan, variationId)
                _events.send(Event.PresentPaymentSheet(subscription))
            } catch (e: IOException) {
                isPaying = false
                _events.send(Event.ShowError(e))
            }
        }
    }

    /** Pass this function to PaymentSheet as its result callback. */
    fun onPaymentSheetResult(result: PaymentSheetResult) {
        isPaying = false
        when (result) {
            is PaymentSheetResult.Completed -> {
                _flow.value = null
                unlockAfterPayment()
            }
            is PaymentSheetResult.Canceled -> Unit // the user stays on the flow
            is PaymentSheetResult.Failed -> _events.trySend(Event.ShowError(result.error))
        }
    }

    private fun unlockAfterPayment() {
        viewModelScope.launch {
            if (waitForAccess()) {
                // unlock the service
            } else {
                // tell the user that the payment is processing, and how to reach your support
            }
        }
    }
}

fun presentPaymentSheet(
    paymentSheet: PaymentSheet,
    context: Context,
    subscription: Backend.Subscription,
) {
    PaymentConfiguration.init(context, subscription.publishableKey)
    val configuration = PaymentSheet.Configuration.Builder("YOUR_BUSINESS_NAME").build()
    paymentSheet.presentWithPaymentIntent(subscription.clientSecret, configuration)
}

fun showPaymentError(context: Context, error: Throwable) {
    AlertDialog.Builder(context)
        .setTitle("The payment didn't go through")
        .setMessage(error.localizedMessage)
        .setPositiveButton("OK", null)
        .show()
}

Trình lắng nghe sự kiện của flow sẽ chuyển các hành động của flow đến StripeCheckout. Nó kế thừa AdaptyFlowDefaultEventListener, vì vậy các sự kiện không được override vẫn giữ nguyên cách xử lý mặc định:


class StripeFlowEventListener(
    private val checkout: StripeCheckout,
) : AdaptyFlowDefaultEventListener() {

    override fun onActionPerformed(action: AdaptyUI.Action, context: Context) {
        when (action) {
            AdaptyUI.Action.Close -> checkout.closeFlow()
            is AdaptyUI.Action.Custom -> {
                val plan = StripeCheckout.plans[action.customId] ?: return
                checkout.pay(plan)
            }
            // The default handler opens the URL
            is AdaptyUI.Action.OpenUrl -> super.onActionPerformed(action, context)
        }
    }
}

Sau đó hiển thị flow và trình bày PaymentSheet khi StripeCheckout yêu cầu:

Tạo PaymentSheet trong onCreate và hiển thị flow trong một container phủ lên màn hình của bạn. Đặt cho view của flow một ID ổn định để nó giữ được trạng thái của flow khi Android tái tạo activity:


class MembershipActivity : AppCompatActivity() {
    private val checkout: StripeCheckout by viewModels()
    private val eventListener by lazy { StripeFlowEventListener(checkout) }
    private lateinit var paymentSheet: PaymentSheet
    private lateinit var flowContainer: FrameLayout

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_membership)
        // A FrameLayout over the whole screen, empty while the flow is closed
        flowContainer = findViewById(R.id.flow_container)
        findViewById<Button>(R.id.become_member_button).setOnClickListener {
            checkout.showFlow()
        }

        // PaymentSheet registers for an activity result, so create it in onCreate
        paymentSheet = PaymentSheet.Builder(checkout::onPaymentSheetResult).build(this)

        lifecycleScope.launch {
            // Also shows the flow again after the activity is recreated
            checkout.flow.collect(::showFlow)
        }
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.STARTED) {
                checkout.events.collect { event ->
                    when (event) {
                        is StripeCheckout.Event.PresentPaymentSheet ->
                            presentPaymentSheet(paymentSheet, this@MembershipActivity, event.subscription)
                        is StripeCheckout.Event.ShowError ->
                            showPaymentError(this@MembershipActivity, event.error)
                    }
                }
            }
        }
    }

    private fun showFlow(stripeFlow: StripeFlow?) {
        flowContainer.removeAllViews()
        if (stripeFlow == null) return

        val flowView = AdaptyFlowView(this)
        // A stable ID keeps the flow's state when the activity is recreated.
        // Declare it in res/values/ids.xml: <item name="stripe_flow_view" type="id" />
        flowView.id = R.id.stripe_flow_view
        flowContainer.addView(flowView)
        flowView.showFlow(
            stripeFlow.configuration,
            products = null,
            eventListener = eventListener,
            tagResolver = stripeFlow.tagResolver,
        )
    }
}

Nếu flow của bạn cũng bán sản phẩm Google Play, Adapty SDK sẽ thực hiện các giao dịch mua. Để xử lý các sự kiện mua hàng, hãy override các phương thức event trong StripeFlowEventListener, như mô tả trong Xử lý flow event.

Mở khóa quyền truy cập sau khi thanh toán

Sau khi thanh toán, Adapty nhận webhook từ Stripe và cấp mức độ truy cập trong vài giây. SDK làm mới hồ sơ người dùng mỗi phút một lần, vì vậy hãy truy vấn hồ sơ người dùng cho đến khi mức độ truy cập được kích hoạt:


suspend fun waitForAccess(): Boolean {
    repeat(20) {
        val profile = try {
            awaitAdapty<AdaptyProfile> { callback -> Adapty.getProfile(callback) }
        } catch (e: AdaptyError) {
            null
        }
        if (profile?.accessLevels?.get("YOUR_ACCESS_LEVEL")?.isActive == true) return true
        delay(3.seconds)
    }
    return false
}

Thông thường mức độ truy cập sẽ được kích hoạt trong vài giây. Nếu sau 60 giây vẫn chưa được kích hoạt, hãy kiểm tra các lần giao nhận của Adapty webhook endpoint trong cài đặt webhook của Stripe.

Để hiển thị xác nhận sau khi thanh toán, chẳng hạn như màn hình chào mừng, hãy hiển thị nó từ ứng dụng của bạn khi mức độ truy cập đã được kích hoạt. Bạn cũng có thể xây dựng màn hình đó dưới dạng một flow thứ hai, thêm vào placement riêng của nó và hiển thị sau khi flow đầu tiên đóng lại. Phản hồi kết quả mua hàng hướng dẫn cách thiết lập một flow thứ hai cho trường hợp này.

Cho phép người dùng quản lý gói đăng ký

Gói đăng ký Stripe không hiển thị trong phần gói đăng ký của người dùng trên ứng dụng Google Play Store. Để cho phép người dùng hủy hoặc thay đổi phương thức thanh toán, hãy thêm một nút vào ứng dụng của bạn — ví dụ trên màn hình tài khoản — để mở cổng khách hàng Stripe. Backend của bạn sẽ tạo một phiên portal cho khách hàng Stripe của người dùng và trả về URL của phiên đó.

Khi người dùng hủy, Stripe thông báo cho Adapty, và Adapty cập nhật mức độ truy cập. Để biết cách Adapty xử lý việc hủy ngay lập tức và hủy vào cuối kỳ, xem Hủy đăng ký.

Kiểm tra tích hợp

Sử dụng chế độ thử nghiệm của Stripe, được kết nối với ứng dụng Adapty của bạn:

  1. Chạy ứng dụng với Adapty SDK key của ứng dụng Adapty mà bạn đã kết nối với Stripe.
  2. Mở flow. Các nút sẽ hiển thị giá mà ứng dụng của bạn truyền vào, không phải giá trị ban đầu của custom tag.
  3. Nhấn vào nút của một gói Stripe. Trong PaymentSheet, thanh toán bằng thẻ test Stripe 4242 4242 4242 4242, bất kỳ ngày hết hạn nào trong tương lai, và bất kỳ mã CVC nào.
  4. Xác nhận rằng flow đóng lại và mức độ truy cập của hồ sơ người dùng trở thành active trong vài giây.
  5. Trong Adapty Dashboard, mở Event Feed. Sự kiện mua hàng sẽ có store: stripe, flow_id và flow_name của flow của bạn, flow_variation_id bằng với variationId mà ứng dụng của bạn đã gửi, và placement ID của bạn trong developer_id. Đối với giao dịch mua qua Stripe, variation_id có cùng giá trị với flow_variation_id.

Các giao dịch mua ở chế độ test có môi trường Sandbox. Chúng xuất hiện trong Event Feed và trên hồ sơ người dùng, nhưng không hiển thị trong analytics hoặc trong các chỉ số của flow, vì những phần này chỉ tính các giao dịch mua trên môi trường production.

Nếu giao dịch mua không xuất hiện trong Adapty, hãy kiểm tra xem ứng dụng của bạn có đang dùng SDK key của Adapty app đã kết nối với Stripe không, rằng một sản phẩm Adapty đã tồn tại cho Stripe price đó, và metadata của gói đăng ký có chứa customer_user_id hay không. Ngoài ra, xem thêm Xử lý sự cố trong hướng dẫn tích hợp Stripe.

Giới hạn

  • Flow không nhận được kết quả từ Stripe: Flow không thể chuyển sang màn hình khác sau khi thanh toán Stripe thành công, bị hủy, hoặc thất bại. App của bạn sẽ đóng flow và hiển thị nội dung tiếp theo.
  • Giá trong custom tag là văn bản thuần túy: Flow hiển thị giá trị custom tag đúng như app của bạn truyền vào, và không tự tính toán các giá trị khác từ đó, chẳng hạn như giá theo tuần hay mức giảm giá. Hãy truyền từng giá trị đó dưới dạng tag riêng biệt.
  • Giá trị custom tag cố định trong suốt thời gian flow đang mở: Để hiển thị giá mới, hãy tải lại flow.