-
Notifications
You must be signed in to change notification settings - Fork 50
/
PaywallFragment.kt
94 lines (82 loc) · 2.97 KB
/
PaywallFragment.kt
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package com.revenuecat.sample.ui.paywall
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.revenuecat.purchases.*
import com.revenuecat.purchases.models.StoreProduct
import com.revenuecat.purchases.models.SubscriptionOption
import com.revenuecat.sample.R
import com.revenuecat.sample.extensions.buildError
class PaywallFragment : Fragment() {
private lateinit var root: View
private lateinit var linearLayoutManager: LinearLayoutManager
private lateinit var recyclerView: RecyclerView
private lateinit var adapter: PaywallAdapter
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?,
): View {
root = inflater.inflate(R.layout.fragment_paywall, container, false)
recyclerView = root.findViewById(R.id.paywall_list)
recyclerView.setHasFixedSize(true)
linearLayoutManager = LinearLayoutManager(context)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
recyclerView.layoutManager = linearLayoutManager
adapter = PaywallAdapter(null, didChoosePaywallItem = { item: PaywallItem ->
when (item) {
is PaywallItem.Product -> {
purchaseProduct(item.storeProduct)
}
is PaywallItem.Option -> {
purchaseOption(item.subscriptionOption)
}
is PaywallItem.Title -> {
// Do nothing
}
}
})
recyclerView.adapter = adapter
/*
Load offerings when the paywall is displayed
*/
fetchOfferings()
return root
}
private fun fetchOfferings() {
Purchases.sharedInstance.getOfferingsWith { offerings: Offerings ->
adapter.offering = offerings.current
adapter.notifyDataSetChanged()
}
}
private fun purchaseProduct(item: StoreProduct) {
Purchases.sharedInstance.purchaseWith(
PurchaseParams.Builder(requireActivity(), item).build(),
onError = { error, userCancelled ->
if (!userCancelled) {
buildError(context, error.message)
}
},
onSuccess = { _, _ ->
activity?.finish()
},
)
}
private fun purchaseOption(item: SubscriptionOption) {
Purchases.sharedInstance.purchaseWith(
PurchaseParams.Builder(requireActivity(), item).build(),
onError = { error, userCancelled ->
if (!userCancelled) {
buildError(context, error.message)
}
},
onSuccess = { _, _ ->
activity?.finish()
},
)
}
}