دمج مكتبة الفوترة في Google Play للألعاب المخصَّصة للكمبيوتر في تطبيقك

يمكنك تحقيق الربح من لعبتك من خلال بيع منتجات رقمية باستخدام خدمة "الفوترة في Google Play". وتوفّر حزمة تطوير البرامج (SDK) واجهات برمجة تطبيقات لعرض المنتجات المتاحة للشراء وبدء مسار الشراء ومعالجة عمليات الشراء. يتم إجراء طلبات البيانات من واجهات برمجة التطبيقات للفوترة هذه باستخدام حساب Google الذي تم تشغيل اللعبة من خلاله داخل برنامج "ألعاب Google Play"، ولا تتطلّب أي خطوات إضافية لتسجيل الدخول.

إذا كنت قد أجريت عملية التكامل مع مكتبة الفوترة في Play على Android، من المفترض أن تكون واجهات برمجة التطبيقات هذه مألوفة لك. يمكن إعادة استخدام أي عمليات تكامل من جهة الخادم مع Play Billing في ألعاب الكمبيوتر الشخصي لأنّها متطابقة على كل من Android والكمبيوتر الشخصي.

المتطلبات الأساسية

الخطوة 1: إنشاء BillingClient

منذ الإصدار 26.3.312.0

بالنسبة إلى الإصدار 26.3.312.0 من حزمة تطوير البرامج (SDK) والإصدارات الأحدث، استخدِم 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 إنشاء مثيل إلا باستخدام الدالة الإنشائية التلقائية. لا تتوفّر خيارات الضبط المتقدّمة في هذه الإصدارات. .

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 حرفًا).
  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() عند بدء التشغيل أو عند العودة إلى المقدّمة. أكمِل عملية التحقّق ومنح إذن الاستخدام والإقرار أو الاستهلاك على الخادم باستخدام واجهات برمجة التطبيقات لخدمة "الفوترة في Play" من جهة الخادم. يستخدم هذا الدمج من جهة الخادم نقاط النهاية نفسها في الخلفية ومسار التحقّق نفسه في لعبة Android مدمجة مع "الفوترة في 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: اختبار عملية التكامل

أنت الآن جاهز لاختبار التكامل مع خدمة "الفوترة في Play". لإجراء الاختبارات خلال مرحلة التطوير، ننصحك بالاستعانة بمختبِري التراخيص. يمكن للمختبِرين المرخَّصين الوصول إلى عمليات الدفع الاختبارية التي تتجنّب تحصيل أموال حقيقية مقابل عمليات الشراء.

للحصول على تعليمات حول كيفية إعداد مختبِري الترخيص ومجموعة من الاختبارات اليدوية التي ننصح بإجرائها، يُرجى الاطّلاع على المستندات حول كيفية اختبار دمج Google Play Billing Library.