שילוב של ספריית החיוב ב-Google Play למחשבים מקומיים באפליקציה

אפשר לייצר הכנסות מהמשחק על ידי מכירת מוצרים דיגיטליים באמצעות החיוב ב-Play. ה-SDK כולל ממשקי API שמאפשרים להציג מוצרים שזמינים לרכישה, להפעיל את תהליך הרכישה ולעבד רכישות. הקריאות לממשקי ה-API האלה לחיוב מתבצעות באמצעות חשבון Google שהפעיל את המשחק בתוך הלקוח של Google Play Games, ולא נדרשים שלבי כניסה נוספים.

אם שילבתם את ספריית החיובים ב-Android Play, ממשקי ה-API האלה של החיוב ב-Play אמורים להיות מוכרים לכם. אפשר להשתמש בכל שילוב בצד השרת עם Play Billing גם במשחקים למחשב, כי הם זהים ב-Android ובמחשב.

דרישות מוקדמות

שלב 1: יצירת BillingClient

מאז גרסה 26.3.312.0

בגרסת SDK‏ 26.3.312.0 ואילך, משתמשים ב-BillingClientParameters כדי להגדיר וליצור מופע של BillingClient. כך אפשר להפעיל תכונות ספציפיות במהלך האתחול, כמו רכישות בהמתנה.

// Set up initialization parameters
BillingClientParams params;
params.enable_pending_purchases = true;

// Instantiate the BillingClient with parameters
BillingClient billing_client(params);

לפני 26.3.312.0

בגרסאות SDK שקודמות ל-26.3.312.0, ה-BillingClient תומך רק בהפעלה באמצעות ה-constructor שמוגדר כברירת מחדל. בגרסאות האלה אין אפשרויות הגדרה מתקדמות. .

BillingClient billing_client;

שלב 2: שליחת שאילתה לגבי רכישות קודמות ורכישות שהושלמו מחוץ לאפליקציה

כשהאפליקציה מופעלת או כשהיא חוזרת לפעול בחזית, שולחים שאילתה לגבי הרכישות. הפעולה הזו נדרשת כדי לזהות רכישות שבוצעו מחוץ למשחק או כדי לפתוח את הגישה לרכישות שהמשתמש ביצע בעבר.

  1. שולחים שאילתה לגבי רכישות באמצעות BillingClient::QueryPurchases.

  2. ממשיכים בעיבוד הרכישות.

// Query for purchases when:
// - Application starts up
// - Application window re-enters the foreground
auto promise = std::make_shared<std::promise<QueryPurchasesResult>>();
billing_client.QueryPurchases([promise](QueryPurchasesResult result) {
   promise->set_value(std::move(result));
});

auto query_purchases_result = promise->get_future().get();
if (query_purchases_result.ok()) {
  auto purchases = query_purchases_result.value().product_purchase_details;
  // Process the purchases
} else {
  // Handle the error
}

שלב 3: הצגת מוצרים שזמינים לקנייה

עכשיו אתם יכולים לשלוח שאילתות לגבי המוצרים הזמינים ולהציג אותם למשתמשים. שאילתה לקבלת פרטי המוצר היא שלב חשוב לפני הצגת המוצרים למשתמשים, כי היא מחזירה מידע על המוצר שמותאם למיקום.

לפני שמציעים מוצר למכירה, צריך לבדוק אם הוא כבר נמצא בבעלות המשתמש. אם למשתמש יש מוצר מתכלה שעדיין נמצא בהיסטוריית הרכישות שלו, אתם צריכים לצרוך את המוצר לפני שהוא יוכל לקנות אותו שוב.

  1. שולחים שאילתה לגבי פרטי המוצר באמצעות BillingClient::QueryProductDetails. מעבירים את מזהי המוצרים שרשמתם ב-Google Play Console.
  2. מציגים את ProductDetails, שכולל את השם המותאם לשוק המקומי ואת מחיר המוצר.
  3. שומרים את offer_token של המוצר. הוא משמש להפעלת תהליך רכישה של המוצר.
QueryProductDetailsParams params;
params.product_ids.push_back({"example_costmetic_1", ProductType::kTypeInApp});
params.product_ids.push_back({"example_costmetic_1", ProductType::kTypeInApp});
params.product_ids.push_back({"example_battle_pass", ProductType::kTypeInApp});

auto promise = std::make_shared<std::promise<QueryProductDetailsResult>>();
billing_client.QueryProductDetails(params, [promise](QueryProductDetailsResult result) {
   promise->set_value(std::move(result));
});

auto query_product_details_result = promise->get_future().get();
if (query_product_details_result.ok()) {
   auto product_details = query_product_details_result.value().product_details;
   // Display the available products and their offers to the user
} else {
   // Handle the error
}

שלב 4: הפעלת תהליך רכישה

כשהמשתמש מביע כוונה לקנות מוצר שהצגתם לו, אתם מוכנים להפעיל את תהליך הרכישה.

תהליך הרכישה מתבצע בתוך המשחק באמצעות שכבת-על חלקה שמבוססת על WebView:

ממשק התשלום לרכישה קלה מתוך המשחק
תהליך תשלום חלק ברכישות מתוך המשחק
  1. כדי להתחיל, צריך להתקשר למספר BillingClient::LaunchPurchaseFlow(). מעבירים את הערך LaunchPurchaseFlowParams עם הערך offer_token שהתקבל כששלחתם שאילתה לגבי פרטי המוצר. כדי לתמוך בזיהוי של מעשי מרמה וניצול לרעה ולקשר רכישות לחשבונות במשחק בקצה העורפי, אפשר להגדיר את obfuscated_account_id למזהה חשבון במשחק (עד 64 תווים) שהוא יציב, מגובב (hashed) ומידע שלא מאפשר זיהוי אישי.
  2. אחרי שהרכישה תושלם, המערכת תקרא לפונקציית ההמשך עם התוצאה.
  3. אם הפעולה בוצעה בהצלחה, ההמשך יכיל ProductPurchaseDetails. ממשיכים בתהליך הרכישה.
LaunchPurchaseFlowParams params { product_offer.offer_token };
// Recommended: attach a stable, non-PII hashed in-game account ID (max 64 chars)
params.obfuscated_account_id = hashed_in_game_account_id;

auto promise = std::make_shared<std::promise<LaunchPurchaseFlowResult>>();
billing_client.LaunchPurchaseFlow(params, [promise](LaunchPurchaseFlowResult result) {
   promise->set_value(std::move(result));
});
// The purchase flow has started and is now in progress.

auto launch_purchase_flow_result = promise->get_future().get();

// The purchase flow has now completed.
if (launch_purchase_flow_result.ok()) {
   auto purchase = launch_purchase_flow_result.value().product_purchase_details;
   // Process the purchase
} else if (launch_purchase_flow_result.code() == BillingError::kUserCanceled) {
   // Handle an error caused by the user canceling the purchase flow
} else {
   // Handle any other error codes
}

שלב 5: עיבוד רכישה

עיבוד באמצעות שרת בק-אנד

במשחקים עם שרת בק-אנד, צריך לשלוח את purchase.purchase_token (יחד עם purchase.obfuscated_account_id, אם הוא מוגדר) לשרת הבק-אנד אחרי ש-LaunchPurchaseFlow() מצליח, וגם לכל הרכישות שלא עובדו שהוחזרו על ידי BillingClient::QueryPurchases() בזמן ההפעלה או כשחוזרים לחזית. משלימים את האימות, הענקת ההרשאות והאישור או הצריכה בשרת באמצעות ממשקי ה-API של החיוב ב-Play בצד השרת. השילוב הזה בצד השרת משתמש באותן נקודות קצה (endpoint) בקצה העורפי ובאותו תהליך אימות כמו במשחק ל-Android שמשולב עם החיוב ב-Google Play.

void ProcessPurchasesWithServer(std::vector<ProductPurchaseDetails> purchases) {
   for (const auto& purchase : purchases) {
      if (purchase.purchase_state != PurchaseState::kPurchaseStatePurchased) {
         // Notify the user that payment is pending before granting entitlement.
         continue;
      }
      // Send purchase.purchase_token, purchase.product_id, and
      // purchase.obfuscated_account_id to your backend server to verify using
      // the Play Developer API, grant entitlement, and acknowledge or consume.
   }
}

תהליך ללא שרת בק-אנד

  1. כדי לוודא שהתשלום של המשתמש לא בהמתנה, בודקים שהערך של ProductPurchaseDetails::purchase_state הוא PurchaseState::kPurchaseStatePurchased. אם סטטוס הרכישה הוא "בהמתנה", צריך להודיע למשתמש שהוא צריך לבצע שלבים נוספים כדי לקבל את המוצר שרכש.

  2. נותנים למשתמש גישה למוצר שנרכש ומעדכנים את אחסון ההרשאות של המשחק.

  3. לרכישות של מוצרים שלא נצרכים (מוצרים שאפשר לרכוש רק פעם אחת), בודקים אם הרכישה כבר אושרה באמצעות ProductPurchaseDetails::is_acknowledged.

    1. אם הרכישה לא אושרה, צריך להודיע ל-Google שהמשתמש מקבל הרשאה למוצר באמצעות קריאה ל-BillingClient::AcknowledgePurchase.
  4. לרכישות של מוצרים מתכלים (מוצרים שאפשר לרכוש יותר מפעם אחת), צריך להודיע ל-Google שהמשתמש מקבל הרשאה למוצר באמצעות קריאה ל-BillingClient::ConsumePurchase.

void ProcessPurchasesWithoutServer(std::vector<ProductPurchaseDetails> purchases) {
   std::vector<std::string> entitled_product_ids;
   for (const auto& purchase : purchases) {
      auto was_successful = ProcessPurchasePurchaseWithoutServer(purchase);
      if (was_successful) {
         entitled_product_ids.push_back(purchase.product_id);
      }
   }

   // Note that non-consumable products that were previously purchased may have
   // been refunded. These purchases will stop being returned by
   // `QueryPurchases()`. If your game has given a user access to one of these
   // products storage they should be revoked.
   //
   // ...
}

bool ProcessPurchasePurchaseWithoutServer(ProductPurchaseDetails purchase) {
   auto is_purchase_completed =
      purchase.purchase_state == PurchaseState::kPurchaseStatePurchased;
   if (!is_purchase_completed) {
      // Notify the user that they need to take additional steps to complete
      // this purchase.
      return false;
   }

   // Determine if the product ID is associated with a consumable product.
   auto is_consumable = IsConsumableProductId(purchase.product_id);
   if (is_consumable) {
      // Grant an entitlement to the product to the user.
      // ...
      // Then, notify Google by consuming the purchase.

      ConsumePurchaseParams params { purchase.purchase_token };
      auto promise = std::make_shared<std::promise<ConsumePurchaseResult>>();
      billing_client.ConsumePurchase(params, [promise](ConsumePurchaseResult result) {
         promise->set_value(std::move(result));
      });

      auto consume_purchase_result = promise->get_future().get();
      if (!consume_purchase_result.ok()) {
         // Examine the failure code & message for more details & notify user
         // of failure.
         // ...
         return false;
      }

      return true;
   }

   // Otherwise the product is assumed to be a non-consumable.

   // Grant an entitlement to the product to the user.
   // ...
   // Then, notify Google by acknowledging the purchase (if not already done).

   if (purchase.is_acknowledged) {
      return true;
   }

   AcknowledgePurchaseParams params { purchase.purchase_token };
   auto promise = std::make_shared<std::promise<AcknowledgePurchaseResult>>();
   billing_client.AcknowledgePurchase(params, [promise](AcknowledgePurchaseResult result) {
      promise->set_value(std::move(result));
   });

   auto acknowledge_purchase_result = promise->get_future().get();
   if (!acknowledge_purchase_result.ok()) {
      // Examine the failure code & message for more details & notify user
      // of failure.
      // ...
      return false;
   }

   return true;
}

אישור רכישות בצד הלקוח

אימות בצד הלקוח מספק שכבת אבטחה נוספת על ידי אימות חתימת הרכישה ישירות בלקוח המשחק:

ארכיטקטורה של אימות חתימת רכישה בצד הלקוח
ארכיטקטורה של אימות רכישות בצד הלקוח

אתם מקבלים את signature מ-ProductPurchaseDetails. השדה signature נחתם באמצעות המפתח הפרטי שלכם עם אלגוריתם החתימה SHA1withRSA. כדי לאמת באמצעות המפתח הציבורי:

#include <openssl/bio.h>
#include <openssl/err.h>
#include <openssl/evp.h>
#include <openssl/pem.h>
#include <openssl/rsa.h>
#include <openssl/sha.h>

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

// Decodes a Base64 string into a vector of bytes using OpenSSL BIOs.
std::vector<unsigned char> base64_decode(const std::string& base64_string) {
    BIO *bio, *b64;
    b64 = BIO_new(BIO_f_base64());
    BIO_set_flags(b64, BIO_FLAGS_BASE64_NO_NL);
    bio = BIO_new_mem_buf(base64_string.data(), base64_string.length());
    bio = BIO_push(b64, bio);

    std::vector<unsigned char> decoded_data;
    decoded_data.resize(base64_string.length());
    int length = BIO_read(bio, decoded_data.data(), decoded_data.size());
    if (length > 0) {
      decoded_data.resize(length);
    } else {
      decoded_data.clear();
    }
    BIO_free_all(bio);
    return decoded_data;
}

// Reads a PEM-encoded public key string and returns an EVP_PKEY object.
EVP_PKEY* createPublicKey(const std::string& publicKeyPem) {
  BIO* bio = BIO_new_mem_buf(publicKeyPem.data(), publicKeyPem.length());
  EVP_PKEY* pkey = PEM_read_bio_PUBKEY(bio, nullptr, nullptr, nullptr);
  BIO_free(bio);
  return pkey;
}

// Verifies the RSA-SHA1 signature of given data using a public key.
bool verifySignature(const std::string& publicKeyPem,
                     const std::string& originalData,
                     const std::string& signature_b64) {
  std::vector<unsigned char> signature = base64_decode(signature_b64);
  EVP_PKEY* pkey = createPublicKey(publicKeyPem);
  if (!pkey) {
    std::cerr << "Error loading public key." << std::endl;
    ERR_print_errors_fp(stderr);
    return false;
  }

  EVP_MD_CTX* mdctx = EVP_MD_CTX_new();
  if (!mdctx) {
    std::cerr << "EVP_MD_CTX_new failed." << std::endl;
    EVP_PKEY_free(pkey);
    return false;
  }

  if (EVP_DigestVerifyInit(mdctx, nullptr, EVP_sha1(), nullptr, pkey) <= 0 ||
      EVP_DigestVerifyUpdate(mdctx, originalData.c_str(),
                             originalData.length()) <= 0) {
    EVP_MD_CTX_free(mdctx);
    EVP_PKEY_free(pkey);
    std::cerr << "Error during EVP_DigestVerifyInit or EVP_DigestVerifyUpdate."
              << std::endl;
    return false;
  }

  int result = EVP_DigestVerifyFinal(
      mdctx, reinterpret_cast<const unsigned char*>(signature.data()),
      signature.size());

  EVP_MD_CTX_free(mdctx);
  EVP_PKEY_free(pkey);

  if (result == 0) {
    std::cerr << "Signature verification failed." << std::endl;
    return false;
  } else if (result != 1) {
    std::cerr << "Error during signature verification." << std::endl;
    ERR_print_errors_fp(stderr);
    return false;
  }

  return true;
}

שלב 6: בודקים את השילוב

עכשיו אפשר לבדוק את השילוב של מערכת החיוב ב-Google Play. כדי לבצע בדיקות במהלך שלב הפיתוח, מומלץ להשתמש בבודקי רישיונות. בודקי רישיונות יכולים לגשת לתשלומי בדיקה כדי להימנע מחיוב בכסף אמיתי על רכישות.

במאמר בדיקת השילוב של ספריית החיובים ב-Google Play מוסבר איך להגדיר בודקי רישיונות ואיך לבצע בדיקות ידניות.