借助 Credential Manager API,您可以向 Android 持有者(也称为“钱包”)应用签发凭据。本指南介绍了如何将凭据保存到用户的首选持有者。
实现
本部分详细介绍了签发数字凭据所需的步骤。
添加依赖项
将以下依赖项添加到 Gradle 构建脚本中:
Kotlin
dependencies { implementation("androidx.credentials:credentials:1.7.0-alpha02") implementation("androidx.credentials:credentials-play-services-auth:1.7.0-alpha02") }
Groovy
dependencies { implementation "androidx.credentials:credentials:1.7.0-alpha02" implementation "androidx.credentials:credentials-play-services-auth:1.7.0-alpha02" }
初始化 Credential Manager
初始化 CredentialManager 类的实例。
val credentialManager = CredentialManager.create(context)
创建发放请求
数字凭据创建请求应包含遵循 OpenID4VCI 标准协议的 JSON 字符串。以下是 OpenID4VCI 请求的示例:
"requests": [
{
"protocol": "openid4vci-v1",
"data": {
"credential_issuer": "https://digital-credentials.dev",
"credential_configuration_ids": [
"com.emvco.payment_card"
],
"grants": {
"urn:ietf:params:oauth:grant-type:pre-authorized_code": {
"pre-authorized_code": "..."
}
}
}
}
]
创建包含签发请求的 CreateDigitalCredentialRequest。
val issuanceRequestJson = "{ ... }" // Your issuance JSON
val createRequest = CreateDigitalCredentialRequest(
requestJson = issuanceRequestJson,
origin = null
)
发出签发请求
使用 createCredential 函数向用户持有者发放凭据。此函数会启动 Credential Manager 底部动作条选择器,让用户选择他们希望将凭据存储在哪个持有者应用中。
try {
val response = credentialManager.createCredential(
context = context,
request = createRequest
)
handleSuccess(response as CreateDigitalCredentialResponse)
} catch (e: CreateCredentialException) {
handleCreateException(e)
}
处理响应
在您发出签发请求后,系统会返回 CreateDigitalCredentialResponse。此响应包含一个 responseJson 字符串,用于描述签发结果。
fun handleSuccess(response: CreateDigitalCredentialResponse) {
val responseJson = response.responseJson
// Parse responseJson according to your protocol (e.g. OpenID4VCI)
}
处理异常
如果签发流程失败,createCredential 会抛出 CreateCredentialException,您的应用应处理此异常:
fun handleCreateException(e: CreateCredentialException) {
when (e) {
is CreateCredentialCancellationException -> {
// The user canceled the flow
}
is CreateCredentialInterruptedException -> {
// The flow was interrupted (e.g. by another UI element)
}
is CreateCredentialNoCreateOptionException -> {
// No wallet application is available to handle the request
}
is CreateCredentialUnsupportedException -> {
// The device or the system doesn't support this request
}
is CreateCredentialProviderConfigurationException -> {
// There is a configuration issue with the wallet provider
}
is CreateCredentialCustomException -> {
// A protocol-specific error occurred
val errorType = e.type
val errorMessage = e.message
}
is CreateCredentialUnknownException -> {
// An unknown error occurred
}
else -> {
// Generic error handling
}
}
}