I have an App Store ProductView with two switch statements. The upper one catches mainly loading errors, and the lower completion handler catches other StoreKit errors. I am setting the StoreKit configuration file to test for the error Verification: Revoked Certificate.
Clicking the in-app purchase button results in "You're all set" followed by (after tapping OK) "Certificate Revoked". It is basically saying that the purchase was successful, but that it failed.
From comments in my code, I see in the console that the flow was case success, case success -> verificationResult, and finally case unverified revokedCertificate.
Does the order of the switch case statements matter? Is there any way to prevent the You're all set from appearing?
VStack {
ProductView(id: productID)
.productViewStyle(.large)
.storeProductTask(for: productID, action: { state in
print(state)
switch state {
case .failure(let error):
self.error = .error(error)
case .loading:
break
case .unavailable:
self.error = .error(NSError(domain: "Store is unavailable", code: 0, userInfo: nil))
case .success(let success):
break
@unknown default:
break
}
})
}
.padding()
.onInAppPurchaseCompletion { product, result in
switch result {
case .success(let verificationResult):
// Check whether the JWS passes StoreKit verification.
switch verificationResult {
case .success(let t):
switch t {
case .verified(let transaction):
if transaction.productType == product.type, transaction.productID == productID {
if transaction.revocationDate == nil, transaction.revocationReason == nil {
purchaseState = true
await transaction.finish()
} else {
}
} else {
// invalid product
}
case .unverified(_, let error):
self.error = .error(error)
}
case .userCancelled: // user tapped x button
break
case .pending: // purchase options: interrupted purchase enabled
break
@unknown default:
break
}
case .failure(let error):
self.error = .error(error)
}
}
Answer
Embora você não possa evitar a mensagem do sistema, você pode gerenciar a sequência de feedback para o usuário no seu aplicativo:
Exibir uma mensagem clara imediatamente: Assim que você detectar o erro de "Certificado Revogado" (dentro do
case .verified(let transaction)
ondetransaction.revocationDate != nil
), você deve imediatamente atualizar a UI do seu aplicativo para informar o usuário sobre a falha e o motivo. Por exemplo, você pode exibir um alerta, uma mensagem de erro na tela ou desabilitar funcionalidades relacionadas à compra.Swift
case .verified(let transaction): if transaction.productType == product.type, transaction.productID == productID { if transaction.revocationDate == nil, transaction.revocationReason == nil { purchaseState = true await transaction.finish() } else { // Certificado revogado ou transação revogada. // Aqui você exibe sua própria mensagem de erro para o usuário. self.error = .error(NSError(domain: "PurchaseError", code: 1, userInfo: [NSLocalizedDescriptionKey: "A compra não pôde ser concluída devido a um certificado revogado. Por favor, tente novamente mais tarde ou contate o suporte."])) // Não chame transaction.finish() para transações revogadas, // a menos que você tenha uma lógica específica para elas. // O StoreKit pode limpar essas transações automaticamente em alguns casos. } } else { // produto inválido self.error = .error(NSError(domain: "PurchaseError", code: 2, userInfo: [NSLocalizedDescriptionKey: "Produto da transação não corresponde."])) }
Gerenciar o estado
purchaseState
: Certifique-se de quepurchaseState
só seja definido comotrue
se a compra for realmente válida e verificada. Em caso de certificado revogado,purchaseState
deve permanecerfalse
(ou ser redefinido) e você deve apresentar o erro.
Ao fazer isso, embora o usuário veja o "You're all set" momentaneamente, ele será rapidamente seguido pela mensagem de erro do seu aplicativo, o que comunica a falha de forma mais eficaz e reduz a confusão.
Em resumo, a arquitetura do StoreKit, especialmente com os arquivos de configuração, separa a confirmação inicial da compra da validação posterior. Concentre-se em fornecer um feedback claro ao usuário no seu aplicativo assim que você detectar a falha de verificação.