Payments Module for Cocos

With the now.gg Payments Module for Cocos, you can implement in-app purchases within your game on the Cocos platform.

To integrate now.gg Payments:

  1. Download and Import the Payments module for cocos.
  2. Add required dependencies.
  3. Implement now.gg Payments to your project.

Note: Your project’s minimum Android SDK version must not be lower than version 19.

Download and Import the Module

The now.gg Payments Module for Cocos is included within the download package (nowgg_sdk_cocos-1.2.6.2001.zip).

To add now.gg Payments module within your cocos project:

  1. Download the package containing the latest version of now.gg Payments module for Cocos.
  2. After downloading the package, import the Payments module to your project. To do this:
    • Copy the nowggsdk directory from the download package to proj.android > app > jni, as shown below.
      cocos_nowgg
    • Copy the libs directory from the download package to proj.android >app directory, as shown below.
      cocos_nowgg

Add Dependencies

Once the now.gg Payments module has been imported, you should now add the required dependencies to your project.

  1. Locate the CMakeLists.txt file, present in the root directory of your project.
    • Add the following code to the if(ANDROID) section of your CMakeLists.txt file:
      list(APPEND GAME_HEADER
            proj.android/app/jni/nowggsdk/include/nowgg_sdk.h
            )
      
    • Next, add the following code to the if(ANDROID) section of your CMakeLists.txt file. This will add nowggsdk to your project:
      add_library(nowggsdk STATIC IMPORTED)
       set_target_properties(nowggsdk PROPERTIES IMPORTED_LOCATION ${CMAKE_CURRENT_SOURCE_DIR}/proj.android/app/jni/nowggsdk/${ANDROID_ABI}/libnowggsdk.a)
       target_link_libraries(${APP_NAME} nowggsdk)
    • Lastly, add the following line to your gradle.propertiesfile located in proj.android directory:
      android.useAndroidX=true
      
  2. Locate HelloWorldScene.h class by navigating to cocosSDKsample > classes within the download package.
    • Include now.gg_sdk.h
      #include "../proj.android/app/jni/nowggsdk/include/nowgg_sdk.h" 
      
    • Inherit public nowgg::NowGGSDKListener
      class HelloWorld : public cocos2d::Scene, public nowgg::NowGGSDKListener
      
  3. Now, add the following virtual functions in the HelloWorldScene class:
    private:
         virtual void onInitialized(bool success) override;
         virtual void onPurchaseUpdated(const vector<nowgg::Product*> p) override;
         virtual void onPurchaseCancelled(int code, string msg) override;
         virtual void onPurchaseConsumed(string token) override;
    

    Note: Add the definitions for the virtual functions mentioned above, in HelloWorldScene.cpp.

  4. Add the following dependencies to your build.gradle file located in proj.android > app directory.
    dependencies {
         implementation (files("libs/billingclient.aar"))
         implementation (files("libs/nowggsdk.aar"))
         implementation 'androidx.appcompat:appcompat:1.4.1'
         api 'com.google.code.gson:gson:2.8.6'
         implementation 'com.squareup.retrofit2:retrofit:2.9.0'
         implementation 'com.squareup.okhttp3:logging-interceptor:3.9.0'
         implementation 'com.squareup.retrofit2:converter-scalars:2.9.0'
         implementation 'com.squareup.retrofit2:converter-gson:2.9.0'
     }
    

Implement now.gg Payments

Once the module has been imported and the dependencies have been added, you should now implement now.gg Payments with your app/game.

1. Check if now.gg IAP is available

To check if the now.gg IAP service is available on the device:

bool isIAPAvailable = NowGGSDK::isNowGGIapAvailable();

Note:

  • The responses related to now.gg IAP service availability is received using the onInitialized callback function.
  • A boolean success will be returned if now.gg IAP service is available on the device.
  • You should only continue with now.gg IAP implementation if the IAP service is available on the device.

2. Implement now.gg IAP

  1. Add Products Ids and Initialize SDK

    This step will allow you to add the in-app purchase products using product ids in your app/game and initialize the SDK.

    Create a vector of all the productIds that you wish to add and pass those in the init function, as illustrated below:

    void nowGGIAPInit()
     {
     bool isIAPAvailable = NowGGSDK::isNowGGIapAvailable();
     if (isIAPAvailable)
     {
     vector<string> productIds {"coin1", "coin2", "coin3"};
    
     NowGGSDK::init("PAYMENT_ID", productIds);
     }
     }
    • As an example, we have added three IAP products with productIds “coin1”, “coin2”, and “coin3” with “PAYMENT_ID”.
    • Similarly, you can add other products according to your implementation with the corresponding product ids you may have added on nowStudio.

    Note:

    • PAYMENT_ID is a unique identifier for your app.
    • Each app that you add on the nowStudio generates a unique PAYMENT_ID.
      • The corresponding PAYMENT_ID can be found within the App Details section of nowStudio – more information.
  2. Get Product Details

    After successful initialization, you can get the product details in your app. To get product details (SkuDetails) use the getProductDetails function as illustrated below:

    vector<SkuDetails*> skuDetails =  NowGGSDK::getProductDetails();

    Note: You should call the getProductDetails function only after INIT success.

  3. Initiate Purchase

    After you have the product details, you can initiate a product purchase by calling the purchase() function along with the product id, as illustrated below:

    NowGGSDK::purchase(<product id of the product>, "inapp");
    

    Note:

    • ProductId is a unique identifier for the in-app product(s) that you have defined within nowStudio for your specific App (App Id).
    • Product prices are fetched from the price template you created within the nowStudio.
    • Currently, we only support ‘inapp’ product types. Subscription products are coming soon.
  4. Assigning the purchased products to a User

    After a successful purchase, you can assign the purchased product to the user by using the consume() function as illustrated below:

    NowGGSDK::consume(<purchaseToken associated with a purchased product>);
    

    Note:

    • You will receive the purchaseToken after a product has been purchased.
    • The onPurchaseConsumed callback is called on successful operation.

Purchase Verification

now.gg Payments utilize a public key to verify in-app purchases, enabling you to establish the authenticity of a purchase. It is recommended to authenticate every purchase prior to assigning the product to the user.

Verify purchase with your Public Key

You can either verify purchase(s) locally or use a backend server. However, we recommend using your backend server to verify a purchase.

The following code segment illustrates the verification of purchase(s) using a backend server. You can refer to the Sample project for more details.

void VerifyValidSignatureOnBackendServer(std::string originalJson, std::string signature)
 {
     __android_log_print(ANDROID_LOG_DEBUG, "TAG", "VerifyValidSignatureOnBackendServer called with signature %s \n", signature.c_str());
 
     cocos2d::network::HttpRequest* request = new cocos2d::network::HttpRequest();
     request->setUrl("<your cloud url here>);
     request->setRequestType(cocos2d::network::HttpRequest::Type::POST);
     std::vector<std::string> headers;
     headers.push_back("Content-Type, application/x-www-form-urlencoded");
     request->setHeaders(headers);
     request->setResponseCallback([](network::HttpClient* sender, network::HttpResponse* response)
         {
             if (!response->isSucceed()) {
                 __android_log_print(ANDROID_LOG_DEBUG, "TAG", "VerifyValidSignatureOnBackendServer failed \n");
                 return;
             }
             __android_log_print(ANDROID_LOG_DEBUG, "TAG", "VerifyValidSignatureOnBackendServer success \n");
             std::vector<char>* buffer = response->getResponseData();

             char* json = (char*)malloc(buffer->size() + 1);
             std::string s2(buffer->begin(), buffer->end());
             strcpy(json, s2.c_str());
             __android_log_print(ANDROID_LOG_DEBUG, "TAG", "VerifyValidSignatureOnBackendServer response: %s \n", json);
         });

     string data = "data=" + originalJson + "&signature=" + url_encode(signature);
     __android_log_print(ANDROID_LOG_DEBUG, "TAG", "VerifyValidSignatureOnBackendServer data:%s \n", data.c_str());
     request->setRequestData(data.c_str(), strlen(data.c_str()));
     cocos2d::network::HttpClient::getInstance()->send(request);
     request->release();
 }        

Backend Server Verification

The download package contains a sample implementation to verify a purchase using a backend server which you can use to write your implementation.

The sample implementation includes:

  • PurchaseVerification class: Located within CocosSDKSample >Classes directory in the download package. It contains a sample code to send purchase data and signature to the backend server.
  • Server.py: Located separately within the download package. It includes sample Python code to run a local server and perform backend verification.

Local Verification

We have provided a sample implementation within the Sample Project to verify purchases locally. You can use it to write your implementation.

In the sample implementation:

  • You can refer to the VerifyPurchaseLocally function of the PurchaseVerification class.

Sample Project

We have also included a Sample project in the download package. You can refer to this project to understand the IAP flow using now.gg Payments.

The sample project is included in the package in the cocosSDKSample directory.

×
Text copied to clipboard
Link copied to clipbord
Questions? Please reach out to us at dev-support@now.gg