Хочу реализовать в приложении покупку, чтобы отключилась реклама. Нашла код на гитхаб и реализовала для своего примера. Но после оплаты:
В консоли разработчика висит что платеж не Оплачен несколько минут, затем меняется на Оплачен. Через In-App Billing вроде сразу оплачивался
Когда второй раз в приложении нажимаю купить пишет что платеж отклонен (если денег не хватает) и повторно разрешает купить, если на счету есть. Почему так?
IAPHelper.class
public class IAPHelper {
private String TAG = IAPHelper.class.getSimpleName();
private Context context;
private BillingClient mBillingClient;
private IAPHelperListener IAPHelperListener;
private List<String> skuList;
/**
* To instantiate the object
* @param context It will be used to get an application context to bind to the in-app billing service.
* @param IAPHelperListener Your listener to get the response for your query.
* @param skuList
*/
public IAPHelper(Context context, IAPHelperListener IAPHelperListener, List<String> skuList) {
this.context = context;
this.IAPHelperListener = IAPHelperListener;
this.skuList = skuList;
this.mBillingClient = BillingClient.newBuilder(context)
.enablePendingPurchases()
.setListener(getPurchaseUpdatedListener())
.build();
if (!mBillingClient.isReady()) {
Log.d(TAG, "BillingClient: Start connection...");
startConnection();
}
}
/**
* To establish the connection with play library
* It will be used to notify that setup is complete and the billing
* client is ready. You can query whatever you want.
*/
private void startConnection() {
mBillingClient.startConnection(new BillingClientStateListener() {
@Override
public void onBillingSetupFinished(BillingResult billingResult) {
int billingResponseCode = billingResult.getResponseCode();
Log.d(TAG, "onBillingSetupFinished: " + billingResult.getResponseCode());
if (billingResponseCode == BillingClient.BillingResponseCode.OK) {
getPurchasedItems();
getSKUDetails(skuList);
}
}
@Override
public void onBillingServiceDisconnected() {
Log.d(TAG, "onBillingServiceDisconnected: ");
}
});
}
/**
* Get purchases details for all the items bought within your app.
*/
public void getPurchasedItems() {
Purchase.PurchasesResult purchasesResult = mBillingClient.queryPurchases(BillingClient.SkuType.INAPP);
if (IAPHelperListener != null)
IAPHelperListener.onPurchasehistoryResponse(purchasesResult.getPurchasesList());
}
/**
* Perform a network query to get SKU details and return the result asynchronously.
*/
public void getSKUDetails(List<String> skuList) {
final HashMap<String, SkuDetails> skuDetailsHashMap = new HashMap<>();
SkuDetailsParams skuParams = SkuDetailsParams.newBuilder().setType(BillingClient.SkuType.INAPP).setSkusList(skuList).build();
mBillingClient.querySkuDetailsAsync(skuParams, new SkuDetailsResponseListener() {
@Override
public void onSkuDetailsResponse(BillingResult billingResult, List<SkuDetails> skuDetailsList) {
if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK && skuDetailsList != null) {
for (SkuDetails skuDetails : skuDetailsList) {
skuDetailsHashMap.put(skuDetails.getSku(), skuDetails);
}
if (IAPHelperListener != null)
IAPHelperListener.onSkuListResponse(skuDetailsHashMap);
}
}
});
}
/**
* Initiate the billing flow for an in-app purchase or subscription.
*
* @param skuDetails skudetails of the product to be purchased
* Developer console.
*/
public void launchBillingFLow(final SkuDetails skuDetails) {
if(mBillingClient.isReady()){
BillingFlowParams mBillingFlowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build();
mBillingClient.launchBillingFlow((Activity) context, mBillingFlowParams);
}
}
/**
* Your listener to get the response for purchase updates which happen when, the user buys
* something within the app or by initiating a purchase from Google Play Store.
*/
private PurchasesUpdatedListener getPurchaseUpdatedListener() {
return (billingResult, purchases) -> {
int responseCode = billingResult.getResponseCode();
if (responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
//here when purchase completed
for (Purchase purchase : purchases) {
//I have named sku in such a way that I get sku name as "type_name" for ex: "nc_ring"
//For non consumable I will acknowledge purchase
//For consumable I will consume purchase
String type = purchase.getSku().split("_")[0];
if(type.equals("nc"))
acknowledgePurchase(purchase);
else
consumePurchase(purchase);
}
} else if (responseCode == BillingClient.BillingResponseCode.USER_CANCELED) {
// Handle an error caused by a user cancelling the purchase flow.
Log.d(TAG, "user cancelled");
} else if (responseCode == BillingClient.BillingResponseCode.SERVICE_DISCONNECTED) {
Log.d(TAG , "service disconnected");
startConnection();
}
};
}
public void acknowledgePurchase(Purchase purchase) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED
&& isSignatureValid(purchase)) {
//This is for Consumable product
AcknowledgePurchaseParams acknowledgePurchaseParams = AcknowledgePurchaseParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
mBillingClient.acknowledgePurchase(acknowledgePurchaseParams, new AcknowledgePurchaseResponseListener() {
@Override
public void onAcknowledgePurchaseResponse(BillingResult billingResult) {
Log.d("purchase", "Purchase Acknowledged");
}
});
if (IAPHelperListener != null)
IAPHelperListener.onPurchaseCompleted(purchase);
}
}
public void consumePurchase(Purchase purchase) {
if (purchase.getPurchaseState() == Purchase.PurchaseState.PURCHASED
&& isSignatureValid(purchase)) {
//This is for Consumable product
ConsumeParams consumeParams = ConsumeParams.newBuilder()
.setPurchaseToken(purchase.getPurchaseToken())
.build();
mBillingClient.consumeAsync(consumeParams, new ConsumeResponseListener() {
@Override
public void onConsumeResponse(BillingResult billingResult, String s) {
Log.d("purchase", "Purchase Consumed");
}
});
if (IAPHelperListener != null)
IAPHelperListener.onPurchaseCompleted(purchase);
}
}
private boolean isSignatureValid(Purchase purchase) {
return Security.verifyPurchase(Security.BASE_64_ENCODED_PUBLIC_KEY, purchase.getOriginalJson(), purchase.getSignature());
}
/**
* Call this method once you are done with this BillingClient reference.
*/
public void endConnection() {
if (mBillingClient != null && mBillingClient.isReady()) {
mBillingClient.endConnection();
mBillingClient = null;
}
}
/**
* Listener interface for handling the various responses of the Purchase helper util
*/
public interface IAPHelperListener {
void onSkuListResponse(HashMap<String, SkuDetails> skuDetailsHashMap);
void onPurchasehistoryResponse(List<Purchase> purchasedItem);
void onPurchaseCompleted(Purchase purchase);
}
}
Security.class
public class Security {
private static final String TAG = Security.class.getSimpleName();
private static final String KEY_FACTORY_ALGORITHM = "RSA";
private static final String SIGNATURE_ALGORITHM = "SHA1withRSA";
//This you will get from Services & API in your application console
public static String BASE_64_ENCODED_PUBLIC_KEY = "MyKEY";
/**
* Verifies that the data was signed with the given signature, and returns
* the verified purchase. The data is in JSON format and signed
* with a private key. The data also contains the {@link Purchase.PurchaseState}
* and product ID of the purchase.
* @param base64PublicKey the base64-encoded public key to use for verifying.
* @param signedData the signed JSON string (signed, not encrypted)
* @param signature the signature for the data, signed with the private key
*/
public static boolean verifyPurchase(String base64PublicKey, String signedData, String signature) {
if (TextUtils.isEmpty(signedData) || TextUtils.isEmpty(base64PublicKey) ||
TextUtils.isEmpty(signature)) {
Log.e(TAG, "Purchase verification failed: missing data.");
return false;
}
PublicKey key = Security.generatePublicKey(base64PublicKey);
return Security.verify(key, signedData, signature);
}
/**
* Generates a PublicKey instance from a string containing the
* Base64-encoded public key.
*
* @param encodedPublicKey Base64-encoded public key
* @throws IllegalArgumentException if encodedPublicKey is invalid
*/
private static PublicKey generatePublicKey(String encodedPublicKey) {
try {
byte[] decodedKey = Base64.decode(encodedPublicKey, Base64.DEFAULT);
KeyFactory keyFactory = KeyFactory.getInstance(KEY_FACTORY_ALGORITHM);
return keyFactory.generatePublic(new X509EncodedKeySpec(decodedKey));
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
Log.e(TAG, "Invalid key specification.");
throw new IllegalArgumentException(e);
}
}
/**
* Verifies that the signature from the server matches the computed
* signature on the data. Returns true if the data is correctly signed.
*
* @param publicKey public key associated with the developer account
* @param signedData signed data from server
* @param signature server signature
* @return true if the data and signature match
*/
private static boolean verify(PublicKey publicKey, String signedData, String signature) {
byte[] signatureBytes;
try {
signatureBytes = Base64.decode(signature, Base64.DEFAULT);
} catch (IllegalArgumentException e) {
Log.e(TAG, "Base64 decoding failed.");
return false;
}
try {
Signature sig = Signature.getInstance(SIGNATURE_ALGORITHM);
sig.initVerify(publicKey);
sig.update(signedData.getBytes());
if (!sig.verify(signatureBytes)) {
Log.e(TAG, "Signature verification failed.");
return false;
}
return true;
} catch (NoSuchAlgorithmException e) {
Log.e(TAG, "NoSuchAlgorithmException.");
} catch (InvalidKeyException e) {
Log.e(TAG, "Invalid key specification.");
} catch (SignatureException e) {
Log.e(TAG, "Signature exception.");
}
return false;
}
}
About.class
public class AboutActivity extends AppCompatActivity
implements NavigationView.OnNavigationItemSelectedListener, IAPHelper.IAPHelperListener{
private BillingClient mBillingClient;
IAPHelper iapHelper;
HashMap<String, SkuDetails> skuDetailsHashMap = new HashMap<>();
final String PAY = "tovar";
private List<String> skuList = Arrays.asList(PAY);
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
***
iapHelper = new IAPHelper(this, this, skuList);
}
@Override
protected void onResume() {
super.onResume();
Button radio = findViewById(R.id.PAY);
radio.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
launch(PAY);
}
});
}
private void launch(String sku){
if(!skuDetailsHashMap.isEmpty())
iapHelper.launchBillingFLow(skuDetailsHashMap.get(sku));
}
@Override
public void onSkuListResponse(HashMap<String, SkuDetails> skuDetails) {
skuDetailsHashMap = skuDetails;
}
@Override
public void onPurchasehistoryResponse(List<Purchase> purchasedItems) {
if (purchasedItems != null) {
for (Purchase purchase : purchasedItems) {
//Update UI and backend according to purchased items if required
// Like in this project I am updating UI for purchased items
//Если товар купен уже
String sku = purchase.getSku();
switch (sku) {
case PAY:
System.out.println("PAY");
break;
}
}
}
}
@Override
public void onPurchaseCompleted(Purchase purchase) {
Toast.makeText(getApplicationContext(), "Purchase Successful", Toast.LENGTH_SHORT).show();
updatePurchase(purchase);
}
private void updatePurchase(Purchase purchase) {
String sku = purchase.getSku();
switch (sku) {
case PAY:
System.out.println("PAY");
break;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
if (iapHelper != null) {
iapHelper.endConnection();
}
}
}