Skip to content

Commit

Permalink
Update Google Pay integration example (#1668)
Browse files Browse the repository at this point in the history
`IsReadyToPayRequest.newBuilder()` is deprecated.
Use `IsReadyToPayRequest.fromJson()` instead.
  • Loading branch information
mshafrir-stripe authored Oct 7, 2019
1 parent d1f9dd6 commit 8243675
Show file tree
Hide file tree
Showing 5 changed files with 86 additions and 65 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,8 +60,8 @@ class CustomerSessionActivity : AppCompatActivity() {
resultCode == Activity.RESULT_OK && data != null) {
val paymentMethod =
PaymentMethodsActivityStarter.Result.fromIntent(data)?.paymentMethod
if (paymentMethod?.card != null) {
selectedSourceTextView.text = buildCardString(paymentMethod.card!!)
paymentMethod?.card?.let { card ->
selectedSourceTextView.text = buildCardString(card)
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import androidx.recyclerview.widget.LinearLayoutManager
import com.stripe.android.PaymentConfiguration
import com.stripe.example.R
import com.stripe.example.Settings
import kotlinx.android.synthetic.main.activity_launcher.*

class LauncherActivity : AppCompatActivity() {

Expand All @@ -21,12 +22,14 @@ class LauncherActivity : AppCompatActivity() {

PaymentConfiguration.init(this, Settings.PUBLISHABLE_KEY)

val examples = findViewById<androidx.recyclerview.widget.RecyclerView>(R.id.examples)
val linearLayoutManager = androidx.recyclerview.widget.LinearLayoutManager(this)
linearLayoutManager.orientation = androidx.recyclerview.widget.LinearLayoutManager.VERTICAL
examples.setHasFixedSize(true)
examples.layoutManager = linearLayoutManager
examples.adapter = ExamplesAdapter(this)
val linearLayoutManager = LinearLayoutManager(this)
linearLayoutManager.orientation = LinearLayoutManager.VERTICAL

examples.run {
setHasFixedSize(true)
layoutManager = linearLayoutManager
adapter = ExamplesAdapter(this@LauncherActivity)
}
}

private class ExamplesAdapter constructor(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -56,17 +56,16 @@ class PayWithGoogleActivity : AppCompatActivity() {
*/
private fun isReadyToPay() {
progressBar.visibility = View.VISIBLE
val request = IsReadyToPayRequest.newBuilder()
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_CARD)
.addAllowedPaymentMethod(WalletConstants.PAYMENT_METHOD_TOKENIZED_CARD)
.build()
val request = IsReadyToPayRequest.fromJson(
createBaseCardPaymentMethodParams().toString()
)

paymentsClient.isReadyToPay(request)
.addOnCompleteListener { task ->
progressBar.visibility = View.INVISIBLE

try {
val result = task.getResult(ApiException::class.java)!!
if (result) {
if (task.isSuccessful) {
Toast.makeText(this@PayWithGoogleActivity,
"Google Pay is ready",
Toast.LENGTH_SHORT).show()
Expand Down Expand Up @@ -110,9 +109,9 @@ class PayWithGoogleActivity : AppCompatActivity() {
}
AutoResolveHelper.RESULT_ERROR -> {
val status = AutoResolveHelper.getStatusFromIntent(data)
val statusMessage = if (status != null) status.statusMessage else ""
val statusMessage = status?.statusMessage ?: "unknown"
Toast.makeText(this@PayWithGoogleActivity,
"Got error " + statusMessage!!,
"Got error: $statusMessage",
Toast.LENGTH_SHORT).show()
}

Expand Down Expand Up @@ -161,6 +160,33 @@ class PayWithGoogleActivity : AppCompatActivity() {
isPhoneNumberRequired: Boolean = true,
isEmailRequired: Boolean = true
): PaymentDataRequest {
return PaymentDataRequest.fromJson(
createBaseRequest()
.put("allowedPaymentMethods", JSONArray().put(
createCardPaymentMethod(isBillingAddressRequired, isPhoneNumberRequired)
))
.put("transactionInfo", JSONObject()
.put("totalPrice", "10.00")
.put("totalPriceStatus", "FINAL")
.put("currencyCode", "USD")
)
.put("merchantInfo", JSONObject()
.put("merchantName", "Example Merchant"))
.put("emailRequired", isEmailRequired)
.toString()
)
}

private fun createBaseRequest(): JSONObject {
return JSONObject()
.put("apiVersion", 2)
.put("apiVersionMinor", 0)
}

private fun createCardPaymentMethod(
isBillingAddressRequired: Boolean = true,
isPhoneNumberRequired: Boolean = true
): JSONObject {
/**
* Billing address format required to complete the transaction.
*
Expand All @@ -177,43 +203,33 @@ class PayWithGoogleActivity : AppCompatActivity() {
.put("phoneNumberRequired", isPhoneNumberRequired)
.put("format", billingAddressFormat)

val cardPaymentMethodParams = JSONObject()
.put("allowedAuthMethods", JSONArray()
.put("PAN_ONLY")
.put("CRYPTOGRAM_3DS"))
.put("allowedCardNetworks",
JSONArray()
.put("AMEX")
.put("DISCOVER")
.put("JCB")
.put("MASTERCARD")
.put("VISA"))
val cardPaymentMethodParams = createBaseCardPaymentMethodParams()
.put("billingAddressRequired", isBillingAddressRequired)
.put("billingAddressParameters", billingAddressParams)

val cardPaymentMethod = JSONObject()
return JSONObject()
.put("type", "CARD")
.put(
"parameters", cardPaymentMethodParams
)
.put("tokenizationSpecification",
GooglePayConfig(this).tokenizationSpecification)
}

val paymentDataRequest = JSONObject()
.put("apiVersion", 2)
.put("apiVersionMinor", 0)
.put("allowedPaymentMethods", JSONArray().put(cardPaymentMethod))
.put("transactionInfo", JSONObject()
.put("totalPrice", "10.00")
.put("totalPriceStatus", "FINAL")
.put("currencyCode", "USD")
private fun createBaseCardPaymentMethodParams(): JSONObject {
return JSONObject()
.put("allowedAuthMethods", JSONArray()
.put("PAN_ONLY")
.put("CRYPTOGRAM_3DS")
)
.put("allowedCardNetworks",
JSONArray()
.put("AMEX")
.put("DISCOVER")
.put("JCB")
.put("MASTERCARD")
.put("VISA")
)
.put("merchantInfo", JSONObject()
.put("merchantName", "Example Merchant"))
.put("emailRequired", isEmailRequired)
.toString()

return PaymentDataRequest.fromJson(paymentDataRequest)
}

companion object {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -172,7 +172,7 @@ class PaymentSessionActivity : AppCompatActivity() {

override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
paymentSession.handlePaymentData(requestCode, resultCode, data!!)
paymentSession.handlePaymentData(requestCode, resultCode, data ?: Intent())
}

override fun onDestroy() {
Expand Down Expand Up @@ -224,9 +224,9 @@ class PaymentSessionActivity : AppCompatActivity() {
activity.selectPaymentButton.isEnabled = true
activity.selectShippingButton.isEnabled = true

if (activity.paymentSessionData != null) {
activity.paymentSessionData?.let { paymentSessionData ->
activity.resultTitleTextView.visibility = View.VISIBLE
activity.resultTextView.text = activity.formatStringResults(activity.paymentSessionData!!)
activity.resultTextView.text = activity.formatStringResults(paymentSessionData)
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ class RedirectActivity : AppCompatActivity() {
private val compositeDisposable = CompositeDisposable()

private lateinit var cardInputWidget: CardInputWidget
private lateinit var mRedirectAdapter: RedirectAdapter
private lateinit var redirectAdapter: RedirectAdapter
private lateinit var errorDialogHandler: ErrorDialogHandler
private lateinit var redirectDialogController: RedirectDialogController
private lateinit var progressDialogController: ProgressDialogController
Expand Down Expand Up @@ -60,25 +60,27 @@ class RedirectActivity : AppCompatActivity() {
val linearLayoutManager = LinearLayoutManager(this)
recyclerView.setHasFixedSize(true)
recyclerView.layoutManager = linearLayoutManager
mRedirectAdapter = RedirectAdapter()
recyclerView.adapter = mRedirectAdapter
redirectAdapter = RedirectAdapter()
recyclerView.adapter = redirectAdapter
}

override fun onNewIntent(intent: Intent) {
super.onNewIntent(intent)
if (intent.data != null && intent.data!!.query != null) {
// The client secret and source ID found here is identical to
// that of the source used to get the redirect URL.
val clientSecret = intent.data!!.getQueryParameter(QUERY_CLIENT_SECRET)
val sourceId = intent.data!!.getQueryParameter(QUERY_SOURCE_ID)
if (clientSecret != null &&
sourceId != null &&
clientSecret == redirectSource!!.clientSecret &&
sourceId == redirectSource!!.id) {
updateSourceList(redirectSource)
redirectSource = null

intent.data?.let { data ->
if (data.query != null) {
// The client secret and source ID found here is identical to
// that of the source used to get the redirect URL.
val clientSecret = data.getQueryParameter(QUERY_CLIENT_SECRET)
val sourceId = data.getQueryParameter(QUERY_SOURCE_ID)
if (clientSecret != null && sourceId != null &&
clientSecret == redirectSource?.clientSecret &&
sourceId == redirectSource?.id) {
updateSourceList(redirectSource)
redirectSource = null
}
redirectDialogController.dismissDialog()
}
redirectDialogController.dismissDialog()
}
}

Expand Down Expand Up @@ -116,7 +118,7 @@ class RedirectActivity : AppCompatActivity() {
val threeDSecureStatus = sourceCardData?.threeDSecureStatus

// Making a note of the Card Source in our list.
mRedirectAdapter.addItem(
redirectAdapter.addItem(
source.status,
threeDSecureStatus,
source.id,
Expand All @@ -139,7 +141,7 @@ class RedirectActivity : AppCompatActivity() {
* to verify the third-party approval. The only information from the Card source
* that is used is the ID field.
*
* @param sourceId the [Source.getId] from the [Card]-created [Source].
* @param sourceId the [Source.id] from the [Card]-created [Source].
*/
private fun createThreeDSecureSource(sourceId: String) {
// This represents a request for a 3DS purchase of 10.00 euro.
Expand Down Expand Up @@ -175,21 +177,21 @@ class RedirectActivity : AppCompatActivity() {
val sourceRedirect = source.redirect
val redirectUrl = sourceRedirect?.url
if (redirectUrl != null) {
redirectDialogController.showDialog(redirectUrl, source.sourceTypeData!!)
redirectDialogController.showDialog(redirectUrl, source.sourceTypeData.orEmpty())
}
}

private fun updateSourceList(source: Source?) {
if (source == null) {
mRedirectAdapter.addItem(
redirectAdapter.addItem(
"No source found",
"Stopped",
"Error",
"None")
return
}

mRedirectAdapter.addItem(
redirectAdapter.addItem(
source.status,
"complete",
source.id,
Expand Down

0 comments on commit 8243675

Please sign in to comment.