<uses-permission android:name="com.android.vending.BILLING" />
IInAppBillingService inAppBillingService; ServiceConnection serviceConnection = new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { inAppBillingService = IInAppBillingService.Stub.asInterface(service); } @Override public void onServiceDisconnected(ComponentName name) { inAppBillingService = null; } }; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Intent serviceIntent = new Intent("com.android.vending.billing.InAppBillingService.BIND"); serviceIntent.setPackage("com.android.vending"); bindService(serviceIntent, serviceConnection, Context.BIND_AUTO_CREATE); ... } @Override public void onDestroy() { super.onDestroy(); if (serviceConnection != null) { unbindService(serviceConnection); } }
class InAppProduct { public String productId; public String storeName; public String storeDescription; public String price; public boolean isSubscription; public int priceAmountMicros; public String currencyIsoCode; public String getSku() { return productId; } String getType() { return isSubscription ? "subs" : "inapp"; } } List<InAppProduct> getInAppPurchases(String type, String... productIds) throws Exception { ArrayList<String> skuList = new ArrayList<>(Arrays.asList(productIds)); Bundle query = new Bundle(); query.putStringArrayList("ITEM_ID_LIST", skuList); Bundle skuDetails = inAppBillingService.getSkuDetails( 3, context.getPackageName(), type, query); ArrayList<String> responseList = skuDetails.getStringArrayList("DETAILS_LIST"); List<InAppProduct> result = new ArrayList<>(); for (String responseItem : responseList) { JSONObject jsonObject = new JSONObject(responseItem); InAppProduct product = new InAppProduct(); // "com.example.myapp_testing_inapp1" product.productId = jsonObject.getString("productId"); // product.storeName = jsonObject.getString("title"); // product.storeDescription = jsonObject.getString("description"); // "0.99USD" product.price = jsonObject.getString("price"); // "true/false" product.isSubscription = jsonObject.getString("type").equals("subs"); // "990000" = x 1000000 product.priceAmountMicros = Integer.parseInt(jsonObject.getString("price_amount_micros")); // USD product.currencyIsoCode = jsonObject.getString("price_currency_code"); result.add(product); } return result; }
// List<InAppProduct> purchases = getInAppPurchases("inapp", "com.example.myapp_testing_inapp1"); // List<InAppProduct> subscriptions = getInAppPurchases("subs", "com.example.myapp_testing_subs1");
private static final int REQUEST_CODE_BUY = 1234; public static final int BILLING_RESPONSE_RESULT_OK = 0; public static final int BILLING_RESPONSE_RESULT_USER_CANCELED = 1; public static final int BILLING_RESPONSE_RESULT_SERVICE_UNAVAILABLE = 2; public static final int BILLING_RESPONSE_RESULT_BILLING_UNAVAILABLE = 3; public static final int BILLING_RESPONSE_RESULT_ITEM_UNAVAILABLE = 4; public static final int BILLING_RESPONSE_RESULT_DEVELOPER_ERROR = 5; public static final int BILLING_RESPONSE_RESULT_ERROR = 6; public static final int BILLING_RESPONSE_RESULT_ITEM_ALREADY_OWNED = 7; public static final int BILLING_RESPONSE_RESULT_ITEM_NOT_OWNED = 8; public static final int PURCHASE_STATUS_PURCHASED = 0; public static final int PURCHASE_STATUS_CANCELLED = 1; public static final int PURCHASE_STATUS_REFUNDED = 2; public void purchaseProduct(InAppProduct product) throws Exception { String sku = product.getSku(); String type = product.getType(); // // String developerPayload = "12345"; Bundle buyIntentBundle = inAppBillingService.getBuyIntent( 3, context.getPackageName(), sku, type, developerPayload); PendingIntent pendingIntent = buyIntentBundle.getParcelable("BUY_INTENT"); startIntentSenderForResult(pendingIntent.getIntentSender(), REQUEST_CODE_BUY, new Intent(), Integer.valueOf(0), Integer.valueOf(0), Integer.valueOf(0), null); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_CODE_BUY) { int responseCode = data.getIntExtra("RESPONSE_CODE", -1); if (responseCode == BILLING_RESPONSE_RESULT_OK) { String purchaseData = data.getStringExtra("INAPP_PURCHASE_DATA"); String dataSignature = data.getStringExtra("INAPP_DATA_SIGNATURE"); // readPurchase(purchaseData); } else { // } } } private void readPurchase(String purchaseData) { try { JSONObject jsonObject = new JSONObject(purchaseData); // , null String orderId = jsonObject.optString("orderId"); // "com.example.myapp" String packageName = jsonObject.getString("packageName"); // "com.example.myapp_testing_inapp1" String productId = jsonObject.getString("productId"); // unix-timestamp long purchaseTime = jsonObject.getLong("purchaseTime"); // PURCHASE_STATUS_PURCHASED // PURCHASE_STATUS_CANCELLED // PURCHASE_STATUS_REFUNDED int purchaseState = jsonObject.getInt("purchaseState"); // "12345" String developerPayload = jsonObject.optString("developerPayload"); // , // String purchaseToken = jsonObject.getString("purchaseToken"); // ... } catch (Exception e) { ... } }
private void readMyPurchases() throws Exception { readMyPurchases("inapp"); // readMyPurchases("subs"); // } private void readMyPurchases(String type) throws Exception { String continuationToken = null; do { Bundle result = inAppBillingService.getPurchases( 3, context.getPackageName(), type, continuationToken); if (result.getInt("RESPONSE_CODE", -1) != 0) { throw new Exception("Invalid response code"); } List<String> responseList = result.getStringArrayList("INAPP_PURCHASE_DATA_LIST"); for (String purchaseData : responseList) { readPurchase(purchaseData); } continuationToken = result.getString("INAPP_CONTINUATION_TOKEN"); } while (continuationToken != null); }
private void consumePurchase(String purchaseToken) throws Exception { int result = inAppBillingService.consumePurchase(GooglePlayBillingConstants.API_VERSION, context.getPackageName(), purchaseToken); if (result == GooglePlayBillingConstants.BILLING_RESPONSE_RESULT_OK) { // ... } else { // ... } }
Service account: New service account
Service account name: a name to choose from
Role: do not choose, it is not needed now
Key type: JSON
{ "type": "service_account", "project_id": "project-name", "private_key_id": "1234567890abcdef1234567890abcdef", "private_key": "-----BEGIN PRIVATE KEY-----\XXXXX.....XXXXX\n-----END PRIVATE KEY-----\n", "client_email": "myaccount@project-name.iam.gserviceaccount.com", "client_id": "12345678901234567890", "auth_uri": "https://accounts.google.com/o/oauth2/auth", "token_uri": "https://accounts.google.com/o/oauth2/token", "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/myaccount%40project-name.iam.gserviceaccount.com" }
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential; import com.google.api.client.googleapis.javanet.GoogleNetHttpTransport; import com.google.api.client.http.HttpTransport; import com.google.api.client.json.jackson2.JacksonFactory; import com.google.api.services.androidpublisher.AndroidPublisher; import com.google.api.services.androidpublisher.AndroidPublisherScopes; import com.google.api.services.androidpublisher.model.ProductPurchase; import com.google.api.services.androidpublisher.model.SubscriptionPurchase; import java... public class GooglePlayService { private final Map<String, AndroidPublisher> androidPublishers = new HashMap<>(); private String readCredentialsJson(String packageName) { // JSON- ... } private AndroidPublisher getPublisher(String packageName) throws Exception { if (!androidPublishers.containsKey(packageName)) { String credentialsJson = readCredentialsJson(packageName); InputStream inputStream = new ByteArrayInputStream( credentialsJson.getBytes(StandardCharsets.UTF_8)); HttpTransport transport = GoogleNetHttpTransport.newTrustedTransport(); GoogleCredential credential = GoogleCredential.fromStream(inputStream) .createScoped(Collections.singleton( AndroidPublisherScopes.ANDROIDPUBLISHER)); AndroidPublisher.Builder builder = new AndroidPublisher.Builder( transport, JacksonFactory.getDefaultInstance(), credential); AndroidPublisher androidPublisher = builder.build(); androidPublishers.put(packageName, androidPublisher); } return androidPublishers.get(packageName); } public ProductPurchase getPurchase(String packageName, String productId, String token) throws Exception { AndroidPublisher publisher = getPublisher(packageName); AndroidPublisher.Purchases.Products.Get get = publisher .purchases().products().get(packageName, productId, token); return get.execute(); } public SubscriptionPurchase getSubscription(String packageName, String productId, String token) throws Exception { AndroidPublisher publisher = getPublisher(packageName); AndroidPublisher.Purchases.Subscriptions.Get get = publisher .purchases().subscriptions().get(packageName, productId, token); return get.execute(); } }
String purchaseToken = jsonObject.getString("purchaseToken");
Source: https://habr.com/ru/post/313416/
All Articles