Quantcast
Jump to content

Integrating Samsung IAP in Your Unity Game


Recommended Posts

2021-05-11-01-banner.jpg

Galaxy Store is one of the top app stores to sell your Android games in many different countries. You can also sell various in-app purchase (IAP) items inside your games using the Samsung IAP SDK. As many of you now use the Unity engine to develop your games, Samsung has introduced a Unity plugin for the Samsung IAP SDK that enables you to implement IAP features. Follow the steps outlined in this blog to easily implement the Unity plugin into your project and utilize the Samsung IAP functionalities.

Prerequisites

It is assumed you are already familiar with the Samsung IAP procedure. If not, please read the IAP Helper programming guide carefully before proceeding further. After that, download the Samsung IAP Unity plugin package and go through its documentation. To avoid compatibility issues, make sure you meet the system requirements.

There are three types of IAP items:

  1. Consumable: can be used only one time and re-purchasable
  2. Non-consumable: can be used any number of times and not re-purchasable
  3. Subscription: can be used any number of times while it is active

For this example, we have developed a basic coin collecting game in Unity for Android and added UI buttons that allow users to buy IAP items (consumable and non-consumable) and a subscription. The “Buy Super Jump” button initiates purchasing a super jump item from Galaxy Store using the Samsung IAP SDK. Super jump is a consumable item which enables the player to jump higher than normal. Similarly, the “Upgrade Player” button initiates purchasing a player upgrade, which is a non-consumable item. This blog only covers consumable and non-consumable purchases, we’ll discuss subscriptions in a future blog.


2021-05-11-01-01.jpgFigure 1: Preview of the sample game developed in Unity.


Note: You are required to develop your game/application in Unity beforehand to integrate the IAP Unity plugin into it.

Integrate the Samsung IAP Unity plugin

After creating the game in Unity, you need to enable Samsung IAP functionalities in your project. Follow the steps below:

  1. Import the Samsung IAP Unity plugin package into the project. In Unity, click Assets -> Import Package -> Custom Package and select the downloaded plugin package.
  2. You can now see the Plugins folder under your Assets folder and the “SamsungIAP.cs” script at Assets/Plugins/Script.
  3. Copy or move the “SamsungIAP.cs” script into the default scripts folder of your project (where all the scripts are kept together) so that other scripts can access it easily. If you don’t already have a scripts folder, create a new one and keep all your project scripts together along with “SamsungIAP.cs.”
  4. Create an empty game object in the Hierarchy tab and drag-and-drop the “SamsungIAP.cs” script onto it. In our sample project, we have renamed the game object as “SamsungIAP.”
  5. Click on the “SamsungIAP” game object and check if the IAP functionality is enabled in the Inspector, as shown below:

2021-05-11-01-02.jpgFigure 2: Samsung IAP is enabled for the project.


Set the IAP operation mode

IAP supports three operational modes. The production mode is for enabling billing for item purchases and the other two are for testing IAP functions without billing the game users for item purchases. The default operation mode is set to OPERATION_MODE_TEST with the return value as Success, but you can set the return value to Failure instead, or switch to OPERATION_MODE_PRODUCTION by checking (√) the Production Build checkbox in the Inspector as shown in figure 2. You can learn more about the IAP operation modes and how they work from here.

Register the game and IAP items in Seller Portal

To process/test the Samsung IAP operations, both your game and any IAP items need to be registered in Seller Portal. Follow the steps below:

  1. Ensure you have switched the platform of your game to Android and the package name is different from the apps registered in other app stores. You can rename the package name of your project from Player Settings -> Other Settings.
  2. Save your Unity project and build the APK file. In Unity, go to File -> Build Settings and then click the Build button.
  3. Follow the steps listed in Register an app and in-app items in Seller Portal and complete the registration of your game and IAP items accordingly. For our sample game, we have registered a consumable and a non-consumable item with the IDs “BuySuperJump” and “BuyUpgradedPlayer” respectively. Keep the item IDs in mind as they will be required when initiating the purchases.
  4. You can add testers (non-licensed and licensed) in the Binary tab of Seller Portal while registering your game in the manner covered in the previous step. Licensed testers are not charged for purchasing any IAP items. You can register the licensed testers in your Seller Portal profile. See IAP Testing for more information.

Get previously purchased items

Make sure to retrieve any previously purchased non-consumable and unconsumed items every time the user starts the game. Use the GetOwnedList() method of the IAP plugin to get information about the items the user has already purchased. However, please note there is a script called “player.cs” in our project which is added to the main player game object as a component. From now on we will be editing the code in “player.cs” to enable all the Samsung IAP functions for this project. Follow the steps below:

  1. Add the following line at the beginning to access the Samsung IAP libraries in this script.

    using Samsung; 
    
  2. Call the GetOwnedList() method whenever the game launches by adding the following line at the beginning of the Start() method. Learn more about the GetOwnedList() method here.

    SamsungIAP.Instance.GetOwnedList(ItemType.all, OnGetOwnedList);
    
  3. After the processing of the GetOwnedList() method is completed, the OnGetOwnedList callback is triggered, which receives information about the specified purchased items and API call processing. We need to implement this callback method under the same class as in the following;

    void OnGetOwnedList(OwnedProductList _ownedProductList){
         if(_ownedProductList.errorInfo != null){
             if(_ownedProductList.errorInfo.errorCode == 0){// 0 means no error
                 if(_ownedProductList.results != null){
                     foreach(OwnedProductVo item in _ownedProductList.results){
                             if(item.mConsumableYN == "Y"){
                             //consume the consumable items and OnConsume callback is triggered afterwards                                                                      SamsungIAP.Instance.ConsumePurchasedItems(item.mPurchaseId, OnConsume);
                     }
                     if(item.mItemId == "BuySuperJump"){
                         superJump++;
                     }
                     else if(item.mItemId == "BuyUpgradedPlayer"){                         
                              playerMaterial = Resources.Load<Material>("playerMaterial");
                              MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
                              meshRenderer.material = playerMaterial;                        
                     }                    
                 }
             } 
         }
    }
    

As you can see, some actions have been taken inside the game depending on the respective item IDs. For example, the super jump counter has been increased and the material of the player gets changed. If there is any consumable item which has not been reported as consumed, then the ConsumePurchasedItems() method is invoked. We describe this method in the next section.

Consume purchased consumable items

Use the ConsumePurchasedItems() method to report the purchased consumable item as consumed, which enables the item to be purchased again. See Acknowledge a purchased consumable item to understand this process better. When the process of the ConsumePurchasedItems() method in the previous section is finished, the item data and processing results are returned to the OnConsume callback method. We need to implement this method in the same way under the same class as we implemented the OnGetOwnedList method earlier.

void OnConsume(ConsumedList _consumedList){
     if(_consumedList.errorInfo != null){
         if(_consumedList.errorInfo.errorCode == 0){
             if(_consumedList.results != null){
                 foreach(ConsumeVo item in _consumedList.results){
                        if(item.mStatusCode == 0){
                            //successfully consumed and ready to be purchased again.
                        }
                 }
             }
         }
     }
}

Get purchasable IAP items

The users may want to see details of the available IAP items in the store for the game. The GetProductsDetails() method helps to retrieve detailed information (for example, item name, price, or ID) about the IAP items registered in your game that are available for users to purchase. There is a UI button “Available Items” in our sample game for querying the purchasable items. After clicking this button, brief information for each item is presented in a simple dropdown list next to the button (see figure 3). To get the list of available items:

  1. Declare a button variable and a dropdown variable in the beginning of the “player.cs” script.

    public Button getProductsButton;
    public Dropdown itemList;
    
  2. Add a listener method for the “Available Items” button at the end of the Start() method.

    getProductsButton.onClick.AddListener(OnGetProductsButton);
    
  3. To initiate the GetProductsDetails() method, we need to implement the listener OnGetProductsButton() method.

    void OnGetProductsButton(){
         //get all the product details
         SamsungIAP.Instance.GetProductsDetails("", OnGetProductsDetails); 
    }  
    
  4. After the processing is completed on the server side, the OnGetProductsDetails callback is triggered, which contains information about the available IAP items. Implement this callback method and add information of each item to the dropdown method so that the users can see them easily. In the example, we show only the item name and price.

    void OnGetProductsDetails(ProductInfoList _productList){
         if (_productList.errorInfo != null){
              if (_productList.errorInfo.errorCode == 0){// 0 means no error
                   if (_productList.results != null){
                        itemList.ClearOptions();
                        List<string> optionItems = new List<string>();
                        int i = 1;
                        foreach (ProductVo item in _productList.results){
                                string temp = i+ ". " + item.mItemName + ": $ " + item.mItemPrice;
                                optionItems.Add(temp);
                                i++;
                        }
                        itemList.AddOptions(optionItems);
                   }
              }
         }
    }
    

2021-05-11-01-03.jpgFigure 3: Showing the available IAP items in the game.


The information about all IAP items is shown in the dropdown menu as a list. You can show only one specific item or more items by specifying their IDs in the GetProductsDetails() method if you want. Learn more about the method here.

Purchase IAP items

There are two UI buttons (see figures 1 and 3) in our sample game, namely “Buy Super Jump” and “Upgrade Player,” for purchasing consumable and non-consumable items, respectively. The variables for these two buttons are declared in the beginning of the Start() method and two listener methods: OnBuySuperJumpButton() and OnUpgradePlayerButton() are added at the end of the Start() method of “player.cs” script. Consequently, tapping on these buttons invokes the corresponding methods in the script. Follow the steps below to complete in-app purchasing:

  1. To enable the “Buy Super Jump” and the “Upgrade Player” buttons purchasing a super jump and a player upgrade, we need to instantiate the StartPayment() method inside the button listeners with the corresponding item IDs.
    void OnBuySuperJumpButton(){
         //purchase a consumable item
         SamsungIAP.Instance.StartPayment("BuySuperJump", "", OnPayment);        
    }
    
    void OnUpgradePlayerButton(){
         //purchase a non-consumable item
         SamsungIAP.Instance.StartPayment("BuyUpgradedPlayer", "", OnPayment);
    }
    
  2. After the payment processing is completed, the OnPayment callback is triggered, which contains information about the purchased item, the transaction, and API call processing. We need to implement this callback method and act according to the item IDs as in the following:
    void OnPayment(PurchasedInfo _purchaseInfo){
         if(_purchaseInfo.errorInfo != null){
             if(_purchaseInfo.errorInfo.errorCode == 0){
                 if(_purchaseInfo.results != null){
                     //your purchase is successful
                     if(_purchaseInfo.results.mConsumableYN == "Y"){
                         //consume the consumable items                                                                                                                                                                SamsungIAP.Instance.ConsumePurchasedItems(_purchaseInfo.results.mPurchaseId, OnConsume);
                     }
                     if(_purchaseInfo.results.mItemId == "BuySuperJump"){
                         superJump++;
                     }
                     else if(_purchaseInfo.results.mItemId == "BuyUpgradedPlayer"){
                             playerMaterial = Resources.Load<Material>("playerMaterial");
                             MeshRenderer meshRenderer = GetComponent<MeshRenderer>();
                             meshRenderer.material = playerMaterial;
                     }
                 }
             }
         }
    }
    
  3. For the ConsumePurchasedItems() method, we have already implemented the OnConsume listener method.

In this way, in-app purchasing is fully implemented for both consumable and non-consumable items. Next, build the project, run it on your Galaxy device, and check that the IAP works flawlessly. In addition, you may update the APK of your game in Seller Portal and submit a beta version for more IAP testing. See the Test Guide to learn more about testing. Do not forget to switch the IAP operation mode to OPERATION_MODE_PRODUCTION before submitting the game to be published.

Conclusion

This tutorial explains the entire procedure of integrating the Samsung IAP Unity plugin and using the IAP functionalities for a sample game. Therefore, we hope that you can make use of this tutorial and develop an in-app purchase enabled game for Galaxy Store using Unity and sell your game items successfully to generate revenue.

Follow Up

This site has many resources for developers looking to build for and integrate with Samsung devices and services. Stay in touch with the latest news by creating a free account or by subscribing to our monthly newsletter. Visit the Marketing Resources page for information on promoting and distributing your apps. Finally, our developer forum is an excellent way to stay up-to-date on all things related to the Galaxy ecosystem.

View the full blog at its source

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.
Note: Your post will require moderator approval before it will be visible.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
 Share

  • Similar Topics

    • By STF News
      View the full blog at its source
    • By Alex
      Starting this year, Samsung's Tizen app store is no longer accessible, both to new and existing users. Last year in June, the company closed registrations and made the store available only to existing users and they could only get previously downloaded apps.

      After December 31, 2021, however, the Tizen app store is permanently closed. So in case you are using a Samsung Z series smartphone, it might be time to switch over to Android or iOS. The last Samsung Z4 phone running Tizen OS was released back in 2017 so it was kind of an expected turn of events.
      It seems like the company is dropping its Tizen project after this year's Galaxy Watch4 series is running on Google's Wear OS and all future Galaxy watches will do the same.
      Source: https://www.gsmarena.com/samsung_shuts_down_the_tizen_app_store-news-52598.php
    • By STF News
      Since it opened in 2004, the Leeum Museum of Art has earned a reputation as a cultural space where traditional, modern and international artworks that span a range of eras and styles are brought together. After the pandemic required it to close for nineteen months, the renovated museum has now reopened with new exhibits that include advanced technological displays which provide enhanced viewing of its expansive collection.
       
      As technology continues to enter the art world in ways that haven’t been seen before, the display and creation of digital art are becoming increasingly common. Amid this climate, Samsung Electronics has partnered with the Leeum Museum of Art to promote the convergence of art and technology and allow people to experience 5,000 years of history with a curated collection in the Art Store on The Frame.
       
      Samsung Newsroom reached out to Kwang-bae Lee, a curator at the Leeum Museum of Art, to get the inside scoop on the museum’s reopening, its collections and its collaboration with Samsung.
       
       
      Transcending Time and Space With Artworks That Span Eras and Styles
      ▲ Exterior view of the Leeum Museum of Art
       
      The Samsung Foundation of Culture established the Leeum Museum of Art in Hannam-dong, Seoul, Korea in 2004 in order to preserve its cultural assets and share them with the public. It was designed by acclaimed architects, Mario Botta, Jean Nouvel and Rem Koolhaas, and is highly regarded for its architectural value and harmonious design which blends with nature. With its unfailing dedication to holding exhibitions and showcasing its expansive collection, the museum now has one of the most broadly representative and varied collections in South Korea. Today, the Leeum is known as an open museum where various artistic styles, from traditional Korean art to vibrant and modern contemporary pieces from both Korea and abroad, can coexist. The museum has also been utilizing digital technology in its exhibits for the past ten years with this technology allowing, old artworks to be displayed in new and exciting ways. In this way, the Leeum seeks to head toward the future while not forgetting about the past. The museum is currently using a variety of state-of-the-art devices for both exhibition and education purposes.
       
      ▲ The interior of the Leeum Museum of Art
       
      During the renovation period, the Leeum launched new permanent exhibits featuring both traditional and modern artworks. It also revived a special exhibition entitled “Human, 7 questions”, which is designed to offer visitors a chance to reflect on humanity as the source of art and contemplate the meaning of human existence during times of crisis. It has also installed a massive Media Wall in its lobby, allowing users to appreciate the artwork of Jennifer Steinkamp upon entering the museum.
       
      “Following the Leeum’s reopening, people seem to be paying special attention to the new collections and special exhibitions we have opened,” said Lee. “I am excited to have visitors come in and see the new and improved space for themselves as they enjoy the full experience the renovated museum offers.”
       
       
      Samsung and Leeum Usher in a New Era of Digital Art
      The partnership between Samsung Electronics and the Leeum is also playing an important role in the ongoing unification of art and technology. Thanks to the fact that works curated by the museum are included on The Frame, users can now view them not just outside of the museum, but across the world. As Korean culture continues to grow more popular and expand into new countries, the introduction of this collection on the Art Store opens new opportunities for users around the world to experience the beauty of Korean traditional art.
       
      ▲ Lidded Bowl (National Treasure), 11th-12th century (Goryeo Dynasty)
       
      Curators spent a great amount of time and effort selecting a collection that shines a light on the artistry and aesthetic of Korean art for display on The Frame. Because of this, viewers can now enjoy beautiful patterns on metal, subtly colored pottery and vibrant paintings from the comfort of their homes.
       
      “Technology allows visitors to appreciate finer details in an artwork – whether it is a picture, a text, or a voice – that they may not have noticed before,” Lee said. “As technologies continue developing, our appreciation and understanding of art will expand beyond what we could ever have imagined.”
       
      ▲ Daoist Immortals, Kim Hong Do, 1776 (Joseon Dynasty)
       
      Samsung Electronics and Leeum have been cooperating on using technology to promote art since the museum opened in 2004. Beyond digital art displays, this partnership has also demonstrated how digital archives can play an important role in preserving historical legacies.
       
      “In this era, when we have access to abundance of masterpieces, the best of art and technology have to come together to complement one another,” Lee commented. “We hope our collaboration with Samsung will eventually come to be regarded as a masterpiece in and of itself.”
       
      The collection of artworks curated by the Leeum is available in the Art Store on The Frame today.
       
      Check out some of the Leeum’s top picks for The Frame below.
       

      View the full article
    • By STF News
      Samsung’s The Frame Art Store not only offers customization to fit any home décor and stunning QLED picture quality, but also transforms the user’s display into a window to the world. In October, the Art Store is introducing its partnership with Whanki Museum and the collection of world-renowned artist Kim Whanki.
       
      As a pioneer of Korean abstract painting, Kim Whanki created his unique and characteristic art with refined, formative expression that is based on Korean lyricism. He was recognized for his artworks in centers for modern art that include Paris and New York.
       
      Samsung Electronics has been partnering with Whanki Museum since 2018 to introduce a range of Kim Whanki’s artworks to global customers and provide easier access to Korean modern art.
       
      Samsung Newsroom reached out to Whanki Museum curator Min-A Sung to talk about how art can serve as a medium for both communication and empathy.
       
       
      Fostering Artistic Energy and ‘Art For All’
      ▲ Exterior view of Whanki Museum
       
      Whanki Museum, established in 1992, creates a variety of artistic and cultural content through the research, exhibition and publication of the work of contemporary artists. The museum also provides educational programs and seeks to embody the philosophy of ‘Art for All’ by running a range of programs that expose disadvantaged groups to art and culture. “Whanki Museum will become an open venue for facilitating communication and building empathy based on artistic energy,” says the museum representative. “The partnership with The Frame Art Store provides increased opportunities for us to share our culture and art.”
       
      ▲ Inside Whanki Museum
       
       
      How Samsung Communicates With Global Consumers Through The Frame Art Store
      The museum representative also mentions that the ways people consume art are changing. “Art now influences our day-to-day lives,” they say. “In order to keep up with these shifts, we need to introduce new ways for people to experience art, and try to partner with experts to combine art and IT technology.”
       
      ▲ Morning Star, 1964
       
      The representative adds that they have high hopes for the collaboration between the museum and Samsung. “Vivid color and contrast, which deliver a refined sense of rhythm, are key aspects of Kim’s artistic style,” they say. “The Frame’s QLED 4K display is the perfect medium for his work to be showcased to viewers around the world.”
       
      With Quantum Dot technology that allows more than a billion colors to be displayed at 100% color volume, The Frame allows artistic intent to come through vividly on a bright screen with accurate color reproduction.
       
       
      Master KIM Whanki’s Artistic Vision Realized on The Frame
      Whanki Museum has introduced ten of Kim’s major works to The Frame Art Store since 2018. This has allowed users to enjoy major works such as Deer and Eternity Song, as well as a variety of pieces that were not easily accessible to the public before.
       
      ▲ 12-V-70 #172, 1970
       
      In addition to displaying Kim’s artworks, The Frame Art Store also provides background information on the pieces. “The curatorial department has created descriptions for each artwork to provide resources that deliver a range of perspectives and introduce Kim’s artistic vision to more people,” relates the representative. “We hope the detailed explanations provided by Whanki Museum will help users experience the pieces in vivid and stunning quality, just as though they were viewing them in a gallery.”
       
      The Frame Art Store offers a comprehensive, ever-expanding collection of artworks to satisfy customers’ needs and match any environment or atmosphere. Its catalog now includes around 1,500 artworks from a range of periods and styles that were sourced from 40 famous museums and galleries and are displayed in exceptional 4K resolution.
       

      View the full article
    • By STF News
      Are your apps ready for the recently unveiled Galaxy Z Fold3? For your app to work seamlessly on foldable devices, it will need to correctly handle App Continuity and Flex Mode.
      With Remote Test Lab, you can test your apps on a real Galaxy Z Fold3. To begin, create an account or login on Samsung Developers, and then visit this link to access the Galaxy Z Fold3.
      Other recent devices, such as the Galaxy Tab S7+, Galaxy S21 Ultra, and Galaxy Note20 Ultra are also available on Remote Test Lab.
      View the full blog at its source
×
×
  • Create New...