Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add support for idempotency key on Stripe token API requests #1775

Merged
merged 1 commit into from
Nov 3, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ class AsyncTaskTokenController(
}

progressDialogController.show(R.string.progressMessage)
stripe.createToken(cardToSave, tokenCallback)
stripe.createToken(cardToSave, callback = tokenCallback)
}

private class TokenCallbackImpl constructor(
Expand Down
9 changes: 7 additions & 2 deletions stripe/src/main/java/com/stripe/android/ApiRequest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -39,6 +39,10 @@ internal class ApiRequest internal constructor(
options.stripeAccount?.let {
mapOf("Stripe-Account" to it)
}.orEmpty()
).plus(
options.idempotencyKey?.let {
mapOf("Idempotency-Key" to it)
}.orEmpty()
).plus(
languageTag?.let { mapOf("Accept-Language" to it) }.orEmpty()
)
Expand Down Expand Up @@ -67,7 +71,7 @@ internal class ApiRequest internal constructor(

@Throws(UnsupportedEncodingException::class, InvalidRequestException::class)
override fun getOutputBytes(): ByteArray {
return createQuery().toByteArray(charset(CHARSET))
return query.toByteArray(charset(CHARSET))
}

override fun toString(): String {
Expand All @@ -93,7 +97,8 @@ internal class ApiRequest internal constructor(
*/
internal data class Options internal constructor(
val apiKey: String,
val stripeAccount: String? = null
internal val stripeAccount: String? = null,
internal val idempotencyKey: String? = null
) {
init {
ApiKeyValidator().requireValid(apiKey)
Expand Down
85 changes: 71 additions & 14 deletions stripe/src/main/java/com/stripe/android/Stripe.kt
Original file line number Diff line number Diff line change
Expand Up @@ -501,7 +501,7 @@ class Stripe internal constructor(
* See [Retrieve a source](https://stripe.com/docs/api/sources/retrieve).
*
* @param sourceId the [Source.id] field of the desired Source object
* @param clientSecret the [Source.getClientSecret] field of the desired Source object
* @param clientSecret the [Source.clientSecret] field of the desired Source object
* @return a [Source] if one could be found based on the input params, or `null` if
* no such Source could be found.
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
Expand Down Expand Up @@ -530,18 +530,22 @@ class Stripe internal constructor(
* See [Create an account token](https://stripe.com/docs/api/tokens/create_account).
*
* @param accountParams the [AccountParams] used to create this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
* @param callback a [ApiResultCallback] to receive the result or error
*/
@UiThread
@JvmOverloads
fun createAccountToken(
accountParams: AccountParams,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
val params = accountParams.toParamMap()
.plus(stripeNetworkUtils.createUidParams())
createTokenFromParams(
params,
Token.TokenType.ACCOUNT,
idempotencyKey,
callback
)
}
Expand All @@ -553,7 +557,10 @@ class Stripe internal constructor(
* See [Create an account token](https://stripe.com/docs/api/tokens/create_account).
*
* @param accountParams params to use for this token.
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
*
* @return a [Token] that can be used for this account.
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
Expand All @@ -563,11 +570,15 @@ class Stripe internal constructor(
@Throws(AuthenticationException::class, InvalidRequestException::class,
APIConnectionException::class, APIException::class)
@WorkerThread
fun createAccountTokenSynchronous(accountParams: AccountParams): Token? {
@JvmOverloads
fun createAccountTokenSynchronous(
accountParams: AccountParams,
idempotencyKey: String? = null
): Token? {
return try {
stripeRepository.createToken(
accountParams.toParamMap(),
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
Token.TokenType.ACCOUNT
)
} catch (exception: CardException) {
Expand All @@ -582,18 +593,22 @@ class Stripe internal constructor(
* See [Create a bank account token](https://stripe.com/docs/api/tokens/create_bank_account).
*
* @param bankAccount the [BankAccount] used to create this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
* @param callback a [ApiResultCallback] to receive the result or error
*/
@UiThread
@JvmOverloads
fun createBankAccountToken(
bankAccount: BankAccount,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
val params = bankAccount.toParamMap()
.plus(stripeNetworkUtils.createUidParams())
createTokenFromParams(
params,
Token.TokenType.BANK_ACCOUNT,
idempotencyKey,
callback
)
}
Expand All @@ -605,7 +620,10 @@ class Stripe internal constructor(
* See [Create a bank account token](https://stripe.com/docs/api/tokens/create_bank_account).
*
* @param bankAccount the [Card] to use for this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
*
* @return a [Token] that can be used for this [BankAccount]
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
Expand All @@ -617,33 +635,40 @@ class Stripe internal constructor(
@Throws(AuthenticationException::class, InvalidRequestException::class,
APIConnectionException::class, CardException::class, APIException::class)
@WorkerThread
fun createBankAccountTokenSynchronous(bankAccount: BankAccount): Token? {
@JvmOverloads
fun createBankAccountTokenSynchronous(
bankAccount: BankAccount,
idempotencyKey: String? = null
): Token? {
val params = bankAccount.toParamMap()
.plus(stripeNetworkUtils.createUidParams())
return stripeRepository.createToken(
params,
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
Token.TokenType.BANK_ACCOUNT
)
}

/**
* Create a PII token asynchronously.
*
*
* See [Create a PII account token](https://stripe.com/docs/api/tokens/create_pii).
*
* @param personalId the personal id used to create this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
* @param callback a [ApiResultCallback] to receive the result or error
*/
@UiThread
@JvmOverloads
fun createPiiToken(
personalId: String,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
createTokenFromParams(
PiiTokenParams(personalId).toParamMap(),
Token.TokenType.PII,
idempotencyKey,
callback
)
}
Expand All @@ -655,7 +680,10 @@ class Stripe internal constructor(
* See [Create a PII account token](https://stripe.com/docs/api/tokens/create_pii).
*
* @param personalId the personal ID to use for this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
*
* @return a [Token] that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
Expand All @@ -665,10 +693,14 @@ class Stripe internal constructor(
@Throws(AuthenticationException::class, InvalidRequestException::class,
APIConnectionException::class, CardException::class, APIException::class)
@WorkerThread
fun createPiiTokenSynchronous(personalId: String): Token? {
@JvmOverloads
fun createPiiTokenSynchronous(
personalId: String,
idempotencyKey: String? = null
): Token? {
return stripeRepository.createToken(
PiiTokenParams(personalId).toParamMap(),
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
Token.TokenType.PII
)
}
Expand All @@ -679,13 +711,20 @@ class Stripe internal constructor(
* See [Create a card token](https://stripe.com/docs/api/tokens/create_card).
*
* @param card the [Card] used to create this payment token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
* @param callback a [ApiResultCallback] to receive the result or error
*/
@UiThread
fun createToken(card: Card, callback: ApiResultCallback<Token>) {
@JvmOverloads
fun createToken(

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Out of curiosity... how does @jvmoverloads work for a function like this, where the 2nd arg is optional -- but the 3rd is not? Does a Java caller always need to specify idempotencyKey since it is positionally before a non optional argument?

Copy link
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@markfi-stripe good question. I verified that it works as intended - idempotencyKey becomes optional.

Screen Shot 2019-11-03 at 6 11 16 PM

card: Card,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
createTokenFromParams(
stripeNetworkUtils.createCardTokenParams(card),
Token.TokenType.CARD,
idempotencyKey,
callback
)
}
Expand All @@ -697,6 +736,8 @@ class Stripe internal constructor(
* See [Create a card token](https://stripe.com/docs/api/tokens/create_card).
*
* @param card the [Card] to use for this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
*
* @return a [Token] that can be used for this card
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
Expand All @@ -708,10 +749,14 @@ class Stripe internal constructor(
@Throws(AuthenticationException::class, InvalidRequestException::class,
APIConnectionException::class, CardException::class, APIException::class)
@WorkerThread
fun createCardTokenSynchronous(card: Card): Token? {
@JvmOverloads
fun createCardTokenSynchronous(
card: Card,
idempotencyKey: String? = null
): Token? {
return stripeRepository.createToken(
stripeNetworkUtils.createCardTokenParams(card),
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
Token.TokenType.CARD
)
}
Expand All @@ -720,16 +765,20 @@ class Stripe internal constructor(
* Create a CVC update token asynchronously.
*
* @param cvc the CVC used to create this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
* @param callback a [ApiResultCallback] to receive the result or error
*/
@UiThread
@JvmOverloads
fun createCvcUpdateToken(
@Size(min = 3, max = 4) cvc: String,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
createTokenFromParams(
CvcTokenParams(cvc).toParamMap(),
Token.TokenType.CVC_UPDATE,
idempotencyKey,
callback
)
}
Expand All @@ -739,7 +788,10 @@ class Stripe internal constructor(
* or your app will crash.
*
* @param cvc the CVC to use for this token
* @param idempotencyKey optional, see [Idempotent Requests](https://stripe.com/docs/api/idempotent_requests)
*
* @return a [Token] that can be used for this card
*
* @throws AuthenticationException failure to properly authenticate yourself (check your key)
* @throws InvalidRequestException your request has invalid parameters
* @throws APIConnectionException failure to connect to Stripe's API
Expand All @@ -749,22 +801,27 @@ class Stripe internal constructor(
@Throws(AuthenticationException::class, InvalidRequestException::class,
APIConnectionException::class, CardException::class, APIException::class)
@WorkerThread
fun createCvcUpdateTokenSynchronous(cvc: String): Token? {
@JvmOverloads
fun createCvcUpdateTokenSynchronous(
cvc: String,
idempotencyKey: String? = null
): Token? {
return stripeRepository.createToken(
CvcTokenParams(cvc).toParamMap(),
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
Token.TokenType.CVC_UPDATE
)
}

private fun createTokenFromParams(
tokenParams: Map<String, Any>,
@Token.TokenType tokenType: String,
idempotencyKey: String? = null,
callback: ApiResultCallback<Token>
) {
tokenCreator.create(
tokenParams,
ApiRequest.Options(publishableKey, stripeAccountId),
ApiRequest.Options(publishableKey, stripeAccountId, idempotencyKey),
tokenType, null,
callback
)
Expand Down
21 changes: 11 additions & 10 deletions stripe/src/main/java/com/stripe/android/StripeRequest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,14 @@ internal abstract class StripeRequest(
* @return if the HTTP method is [Method.GET], return URL with query string;
* otherwise, return the URL
*/
val url: String
internal val url: String
@Throws(UnsupportedEncodingException::class, InvalidRequestException::class)
get() = if (Method.GET == method) urlWithQuery() else baseUrl

val contentType: String
internal val contentType: String
get() = "$mimeType; charset=$CHARSET"

val headers: Map<String, String>
internal val headers: Map<String, String>
get() {
return createHeaders()
.plus(HEADER_USER_AGENT to getUserAgent())
Expand All @@ -40,21 +40,22 @@ internal abstract class StripeRequest(
@Throws(UnsupportedEncodingException::class, InvalidRequestException::class)
internal abstract fun getOutputBytes(): ByteArray

val baseHashCode: Int
internal val baseHashCode: Int
get() = Objects.hash(method, baseUrl, params)

internal abstract fun createHeaders(): Map<String, String>

@Throws(InvalidRequestException::class, UnsupportedEncodingException::class)
fun createQuery(): String {
return flattenParams(params).joinToString("&") {
urlEncodePair(it.key, it.value)
internal val query: String
@Throws(InvalidRequestException::class, UnsupportedEncodingException::class)
get() {
return flattenParams(params).joinToString("&") {
urlEncodePair(it.key, it.value)
}
}
}

@Throws(InvalidRequestException::class, UnsupportedEncodingException::class)
private fun urlWithQuery(): String {
val query = createQuery()
val query = this.query
return if (query.isEmpty()) {
baseUrl
} else {
Expand Down
Loading