Quantcast
Jump to content


Recommended Posts

Posted

2024-11-14-01-banner_v2.jpg

Samsung In-App Purchase (IAP) offers developers a robust solution for handling digital transactions within mobile applications available on Galaxy Store. Whether it is selling digital goods, handling subscriptions, or managing refunds, Samsung IAP is designed to offer a smooth, secure experience. The Samsung IAP Orders API expands the scope of these benefits. You can fetch all the payments and refunds history according to specified dates. This content guides you through the essential components for implementing both the Samsung IAP and Samsung IAP Orders APIs.

undefined
Figure 1: Sample Application UI

In this tutorial, we provide a sample application called Book Spot, which offers users the option to subscribe to their favorite books and consumable items, such as text fonts, for purchase. After purchase, users can consume the item. Finally, developers can view all their payment and refund history on specific dates by calling the Samsung IAP Orders API from the back-end server.

Prerequisites

Before implementing in-app purchases in your app, do the following to enable a smooth and effective execution of the process while developing your own application:

  1. Integrate the Samsung IAP SDK into your application. For more information about the IAP SDK integration, you can follow the Integration of Samsung IAP Services in Android Apps article.
  2. Upload the application for Beta testing on Samsung Galaxy Store. A step-by-step guide with screenshots has been provided in the documentation. For more details, see the section “Production Closed Beta Test” on the Test Guide.
  3. Finally, create items on the Seller Portal so that users can purchase or subscribe to them while using the application. For more details about the available items that the Seller Portal supports, see the Programming Guide.

For the sample application, we have already completed these steps. Some example items were already created in Seller Portal, such as books and fonts so that you can consume and subscribe to them while using this sample application.

Implementation of Item Purchase

Now that the application and items are ready, you can implement the purchase functionality in your application like in the sample below:

  • When clicking "Buy," the startPayment() method is called, specifying parameters for item ID and the OnPaymentListener interface, which handles the results of the payment transaction.
  • The onPayment() callback returns whether the purchase has succeeded or failed. The purchaseVo object is instantiated and in case it is not null, it holds the purchase results.
  • If the purchase is successful, then it validates the purchase showing its ID. If the purchase is not successful, a purchaseError message is shown. For more information, check the Purchase an in-app item section.
iapHelper.startPayment(itemId, String.valueOf(1), new OnPaymentListener() {
    @Override
    public void onPayment(@NonNull ErrorVo errorVo, @Nullable PurchaseVo purchaseVo) {
        if (purchaseVo != null) {
            // Purchase Successful
            Log.d("purchaseId" , purchaseVo.getPurchaseId().toString());
            Toast.makeText(getApplicationContext() ,"Purchase Successfully",
                    Toast.LENGTH_SHORT).show();
        } else {
            Log.d("purchaseError" , errorVo.toString());
            Toast.makeText(getApplicationContext() ,"Purchase Failed",
                    Toast.LENGTH_SHORT).show();
        }
    }
});

Implementation of Item Consumption

After successfully purchasing an item, the user can then consume it. In the sample code below, when "Consumed" is selected, the consumePurchaseItems() triggers the consume functionality. This is necessary as items must be marked as consumed so they can be purchased again:

  • The consumePurchaseItems() method is called specifying the parameters for purchaseId and the OnConsumePurchasedItemsListener() interface, which handles the item data and results.
  • This code also checks if consuming the purchased items succeeded or failed:
    • If the errorVo parameter is not null and there is no error with the purchase, which can be verified with the IAP_ERROR_NONE response code, then the “Purchase Acknowledged” message is displayed.
    • However, if there is an error, the errorVo parameter returns an error description with the getErrorString() getter, along with the “Acknowledgment Failed” message.
iapHelper.consumePurchasedItems(purchaseId, new OnConsumePurchasedItemsListener() {
    @Override
    public void onConsumePurchasedItems(@NonNull ErrorVo errorVo, @NonNull
    ArrayList<ConsumeVo>arrayList) {
        if (errorVo != null && errorVo.getErrorCode() == iapHelper.IAP_ERROR_NONE) {
            Toast.makeText(getApplicationContext() ,"Purchase Acknowledged",
                    Toast.LENGTH_SHORT).show();
        } else {
            Toast.makeText(getApplicationContext(), "Acknowledgment Failed: " +
                            errorVo.getErrorString(), Toast.LENGTH_SHORT).show();
        }
    }
});

Implementation of Item Subscription

Besides purchasing and consuming items, you can also subscribe to them in your applications. Similar to the validation done for the consumable item purchase, you validate the subscription with a purchase ID if the purchase is successful. Use the same code snippet specified for “Item Purchase.” For more information, check the Implementation of Item Purchase section.

Implementation of the Samsung IAP Orders API

The Samsung IAP Orders API is used to view all payments and refunds on a specific date. It does this by fetching the payments and refunds history within the date you specified. Let’s implement the Samsung IAP Orders API and create a server to listen to its notifications. Through server-to-server communication, the API returns all orders data for the application.

Configuring the Server

You can develop a Spring Boot server for this purpose. Here are the guidelines on how to set up this server:

  1. Set up a Spring Boot Project. For more information, follow the steps on Developing Your First Spring Boot Application.
  2. Set up your server endpoint:
    • Create a controller for the Samsung IAP Orders API in an integrated development environment (IDE) after importing the Spring Boot project you created. This helps managing all in-app order-related activities and processing them within your application.

    • The controller receives POST requests sent from Samsung’s IAP orders service ensuring the communication with your application.

Get Payment and Refund History

To view all payments and refunds:

  1. You must make a POST request to the Samsung IAP Orders API endpoint with the required headers specified below.
  2. If you specify a date, all the payment history for this date is returned. Otherwise, it only returns all the data from the day before the current date.

API Endpoint: https://devapi.samsungapps.com/iap/seller/orders

Method: POST

Headers:

Add the following fields to the request header. For more information, see the Create an Access Token page, which helps you understand how to create the access token in detail. The token is used for authorization. You can also get the Service Account ID by clicking the Assistance > API Service tabs on Seller Portal. For more details, read the section Create a service account and visit Seller Portal.

Header Name

Description

Required/Optional

Values

Content-Type

Format of the request body

Required

application/json

Authorization

Authorization security header

Required

Bearer: access_token

Service Account ID

This ID can be created in Seller Portal and is used to generate the JSON Web Token (JWT)

Required

service-account-id

Parameters:

The following parameters can be used to build your POST request.

Name

Type

Required/Optional

Description

sellerSeq

String

Required

Your seller deeplink, which is found in your profile in Seller Portal and consists of a 12-digit number.

packageName

String

Optional

Used to view payment and refund data. You can provide the application package name. When a package name is not specified, the data for all applications is shown.

requestDate

String

Optional

Specify a date from which to view the payment and refund data. If the date is not specified, the data from a day before your current date is returned.

continuationToken

String

Optional

Use this if you want to check if there is a continuation for the data on the next page. If there is no more data, the response is null.

To implement REST API support, add the following OkHttp library dependencies to your application's build.gradle file:

implementation 'com.squareup.okhttp3:okhttp: version'
implementation 'com.google.code.gson:gson: version'

A detailed description of the request items can be found in the Request section of the Samsung IAP Orders API documentation. For more information on the server communication, see Samsung IAP Server API. Here is a brief summary of the code below:

  1. A POST request is mapped to the /orders URL, which logs the request.
  2. The previously described parameters containing the data you specified are formatted in a JSON body using the String.format() method.
  3. The outgoing request is logged in a JSON body format.
  4. A RequestBody is instantiated containing the JSON data, formatted for an HTTP request to be sent to the server with the specified token and Service Account ID.
  5. This code also handles multiple results your request can return:
    • The onFailure() method is called when the network request fails for some reason, providing any error details using the IOException exception.
    • If the request succeeds, the onResponse() method returns the response body or any response exception found.
@RestController
@RequestMapping(value = "/iap", method = RequestMethod.POST)
public class OrdersController {

    private final OkHttpClient client = new OkHttpClient();

    @GetMapping("/orders")
    public void sendToServer() {
        System.out.println("POST request received"); // Log the request

        // Define parameters values, use according to your requirement

        // String packageName = "com.example.app_name ";
        // String requestDate = "20240615";
        // String continuationToken = "XXXXXXXXXXX…….XXXXXX";

        String sellerSeq = "0000000XXXXX";

      

        // Create the JSON body, use packageName, requestDate, continuationToken according to your requirement
        String jsonBody = String.format(
                "{\"sellerSeq\":\"%s\"}",
                sellerSeq   
        );


        // Create the request body
        RequestBody body = RequestBody.create(jsonBody, MediaType.parse("application/json;     charset=utf-8"));

        // Access token 
        String token = "0DjT9yzrYUKDoGbVUlXXXXXX";

        // Build the request
        Request request = new Request.Builder()
                .url("https://devapi.samsungapps.com/iap/seller/orders")
                .post(body)
                .addHeader("Authorization","Bearer " + token)
                .addHeader("service-account-id", "85412253-21b2-4d84-8ff5-XXXXXXXXXXXX")
                .addHeader("content-type", "application/json")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                System.err.println("Request failed: " + e.getMessage());
            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {
                if (response.isSuccessful()) {
                    String responseBody = response.body().string();
                    System.out.println("Response: " + responseBody);
                } else {
                    System.err.println("Unexpected response code: " + response.code());
                    System.err.println("Response body: " + response.body().string());
                }
                response.close(); // Close the response body
            }
        });
    }
}

Congratulations! You have just built the Spring Boot server to handle API POST requests using the OkHttpClient to manage HTTP requests and responses for your sample application.

Example Response

As previously mentioned, a JSON-formatted response is returned to your request. For detailed descriptions of each response body element, see the “Response” section of the Samsung IAP Orders API documentation. The following output format is a sample in which only some of the response-body data is presented.

  • In this case, the continuationToken parameter key returns null because there is no continuation for the data on the next page.
  • The orderItemList parameter key lists all the orders with specific details, such as orderId, countryId, packageName, among others.
{
  "continuationToken": null,
  "orderItemList": [
    {
      "orderId": "S20230210KR019XXXXX",
      "purchaseId": "a778b928b32ed0871958e8bcfb757e54f0bc894fa8df7dd8dbb553cxxxxxxxx",
      "contentId": "000005059XXX",
      "countryId": "USA",
      "packageName": "com.abc.xyz"
    },
    {
      "orderId": "S20230210KR019XXXXX",
      "purchaseId": "90a5df78f7815623eb34f567eb0413fb0209bb04dad1367d7877edxxxxxxxx",
      "contentId": "000005059XXX",
      "countryId": "USA",
      "packageName": "com.abc.xyz"
    },
  ]
}

Usually, the responses contain all the relevant information about user purchases, such as the in-app item title, price, and payment status. Therefore, you can use the information and create views for an easier order management.

Conclusion

You have learned how to implement item purchase, consumption, and registration, as well as how to integrate the Samsung IAP Orders API and configure a server to fetch all the payment and refund history within specific dates.

Integrating the Samsung IAP Orders API functionality into your server is an essential step in managing your application payments history to ensure a seamless experience to users. Now, you can implement the Samsung IAP Orders API into your application to track all payments, refunds and make your business more manageable.

For additional information on this topic, see the resources below:

View the full blog at its source



  • Replies 0
  • Created
  • Last Reply

Top Posters In This Topic

Popular Days

Top Posters In This Topic

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...
  • Similar Topics

    • By Samsung Newsroom
      Samsung Electronics today announced that The Premiere 8K, the company’s flagship premium projector, has received the industry’s first 8K Association (8KA) certification for 8K projectors. This recognition underscores Samsung’s leadership in projection technology while setting a new benchmark for the industry.
       
      “The Premiere 8K receiving the industry’s first 8KA certification is a major milestone as it officially demonstrates the new potential of projector technology.” said Taeyoung Son, Executive Vice President of Visual Display Business at Samsung Electronics. “We are committed to expanding the 8K ecosystem by continuously and extensively integrating new technologies.”
       
       
      Raising the Bar for 8K Projection Standards

       
      The 8KA is a global consortium of leading technology companies dedicated to advancing the adoption and standardization of 8K technology. On Dec 10, the organization introduced its New Projector certification program for 8K projectors, a significant step in the development of the 8K ecosystem.
       
      The 8KA certification evaluates a comprehensive set of standards critical to delivering an immersive viewing experience. These include resolution (7680 x 4320), brightness, contrast and color gamut to ensure vivid detail in both highlights and shadows. The criteria also encompass high dynamic range (HDR) for enhanced visual depth, 8K upscaling to refine lower-resolution content and immersive audio capabilities that support the latest formats for synchronized, high-quality sound that matches 8K’s stunning picture quality.
       
      Samsung’s The Premiere 8K excelled across all these categories, becoming the first in the industry to receive the certification.
       
       
      Bringing Unmatched Immersion to the Home Cinema

       
      Unveiled at CES 2024, The Premiere 8K transforms home entertainment with groundbreaking features and cutting-edge technology. It is the first projector to offer 8K wireless connectivity, enabling seamless streaming without complex setups. Using ultra-short throw (UST) technology with advanced aspherical mirrors, it delivers stunning, high-resolution visuals from a short distance, eliminating the need for ceiling mounts or additional installations.
       
      The Premiere 8K is designed to deliver a truly immersive experience. With 4,500 ISO Lumens of brightness, it produces vibrant, lifelike visuals — even in well-lit spaces — while its Sound-on-Screen technology integrates the top speaker module and software algorithms for an immersive sound experience.
       
      With this 8KA certification, Samsung has reaffirmed its leadership in display innovation and further solidified its reputation as a pioneer in ultra-premium technology.
      View the full article
    • By mramnesia97
      My Samsung Smart TV's (Model Code: QE55Q80AATXXC) app window is completely broken. I'm trying to enable developer mode but as soon as I enter "Apps" the window is frozen. I cannot scroll or click on anything. I can activate to press the 123 digits, but nothing happens when I try to input 1,2,3,4,5
      I've tried resetting the TV completely, unplugged it, cleared cache and everything else I can think off.
      What could possibly cause the Apps drawer to not work and be completely frozen?
    • By Samsung Newsroom
      Samsung is expanding its partnership with Art Basel to Art Basel Miami Beach. Following the debut as Art Basel’s first-ever Official Visual Display partner in Basel, Switzerland earlier this year, complete with an immersive Collectors Lounge experience. Through this unique partnership, Samsung is also launching a new initiative with Art Basel to bring curated collections of contemporary artworks from Art Basel’s renowned exhibiting galleries exclusively to the Samsung Art Store. A new collection will be shared once a quarter with the first collection launching today.
       
      ▲ Fred Tomaselli’s Irwin’s Garden (detail) (2023) shown on The Frame by Samsung. Photo: Samsung
       
      The Samsung Art Store is available on The Frame, the best-selling lifestyle TV from Samsung that doubles as a piece of art. Subscribers around the world can experience gallery highlights from Art Basel, which joins other renowned collections such as those from The Metropolitan Museum of Art, The Museum of Modern Art and The Musée d’Orsay available on the Samsung Art Store. The latest partnership with Art Basel underscores Samsung’s commitment to making world-class art accessible to anyone with The Frame through its innovative platform. 
       
       
      Samsung Art Store Subscribers Get an Exclusive Look
      Art Basel Miami Beach is the premier global art fair of the Americas with cultural significance attracting thousands of art enthusiasts every year. For the first time, this exclusive experience is being delivered directly to the screens of millions of people through The Frame.
       
      Ahead of Art Basel Miami Beach, Samsung Art Store subscribers will have access to a curated collection of 15+ select works from Art Basel’s galleries, some of which will be displayed at the highly anticipated fair, taking place from December 6-8, 2024 at the Miami Beach Convention Center. The collection features pieces from international contemporary galleries, including James Cohan, Kasmin, moniquemeloche, mor charpentier, Nara Roesler, Roberts Projects and Tina Kim, offering subscribers a unique, front-row look at some of Art Basel’s incredible works of art.
       
      ▲ Candida Alvarez’s Mostly Clear (detail) (2023) shown on The Frame by Samsung. Photo: Samsung
       
      Founded in 1970 by gallerists from Basel, Art Basel is the world’s premier art fair for modern and contemporary art. This year in Miami Beach, Art Basel will bring together 286 leading international galleries from 38 countries to present artworks of the highest quality across all media — from painting and sculpture to photography and digital works. Art Basel will once again reaffirm its unparalleled position as a platform for discovery and encounters that drive the art world.
       
      “Art Basel’s mission is to power the world of art by connecting leading artists and galleries with art loving audiences,” said Noah Horowitz, CEO of Art Basel. “Our collaboration with Samsung allows us to extend that reach like never before by broadening access to leading galleries and significant works from established artists to a new generation of emerging talents.”
       
      Yong Su Kim, EVP and Global Head of Video Services and Partnerships at Samsung, echoed the excitement surrounding this partnership. “Art Basel represents the pinnacle of contemporary art, and we are thrilled to amplify that experience with leading display technology that brings art to millions of people,” Kim said. “Through the Samsung Art Store and the lifelike visuals of The Frame, we are making it possible for anyone to experience Art Basel and take part in an iconic cultural moment.”
       
       
      Samsung Art Store Collectors Lounge to Feature Industry Panels, Interactive Activation and More
      As the Official Display Partner of Art Basel Miami Beach, Samsung is hosting a dedicated Samsung Art Store Collectors Lounge from December 4-8 under the concept, “Bringing Art Home,” where attendees can enjoy remarkable artworks on The Frame’s museum-worthy display. In addition, visitors will see The Frame showcased with unique bezels in various colors and designs from DecoTVFrames, an official Samsung partner exclusively available for The Frame.
       
      The Frame will also be installed throughout the fair to present visitors with a variety of vivid screen experiences.
       
      In addition to its dynamic Collectors Lounge experience, Samsung is hosting a series of panel discussions featuring influential voices from the contemporary art world. These sessions include:
       
      Celebrating Women in Art and Technology — Innovation and Expression
      An engaging panel led by Daria Greene, Head of Global Curation at Samsung. This discussion celebrates the journey of female artists and innovators who are redefining the intersection of art and technology. Gain insights into how digital platforms are amplifying voices and breaking new ground in contemporary art. The Future of Digital Art — Innovation, Rights and Connectivity
      Explore the future of digital art in this thought-provoking panel, moderated by Maya Harris, Head of Business Development and Strategic Partnerships at Samsung. This session delves into how technology is reshaping artistic rights, accessibility and the ways institutions and artists connect with global audiences.  
      As the home for Samsung Art Store, The Frame has been refreshed in 2024 to deliver an even more complete artistic and aesthetic experience. That includes Pantone Validated ArtfulColor Certification,1 the industry leading color experts. The Frame is the world’s first and only art TV to achieve this validation, ensuring natural and realistic visuals that wouldn’t look out of place in a gallery. It also sports an Anti-Reflection with Matte Display, helping you limit light distractions so your artwork appears even more true-to-life. The Frame hangs just like a picture flush against the wall and is available in class sizes ranging from 32 to 85 inches.
       
      The Frame also delivers value-add features that you can only find from Samsung — the #1 global TV brand for 18 years and counting.2 Samsung technology makes everything you watch look clearer and crisper, while you enjoy access to 2,700+ free channels, including 400+ premium channels on Samsung TV Plus.3 You can also game without a console through Samsung Gaming Hub,4 use your TV as your smart home hub and ensure your personal data is protected by Samsung Knox security.
       
       
      1 Pantone company provides a universal language of color, called Pantone Matching System, that enables color-critical decisions through every stage of the workflow for brands and manufacturers.
      2 Source: Omdia, Jan 2024. Results are not an endorsement of Samsung. Any reliance on these results is at the third party’s own risk.
      3 Available for free on Samsung Smart TVs released after 2016, Galaxy devices, Smart Monitors, Family Hub refrigerators and the web.
      4 Available games and content may vary by country and model and are subject to change without notice. Certain games require a separate controller. Internet connection and subscription may be required. Requires a Samsung account.
      View the full article
    • By Alex
      Three weeks ago, the company released in India the Samsung Z1, its first smartphone powered by Tizen, a homegrown alternative to Google Inc.’s Android operating system.
       
      This week, Samsung is pushing the Samsung Z1 into Bangladesh, a neighbor of India with more than 150 million people and a similarly low rate of smartphone penetration.
       
      After several missteps and rethinks, Samsung’s strategy for its Tizen smartphones is taking a clear shape: the company is aiming the fledgling platform squarely at first-time smartphone users, many of whom may not even have a bank account. The Samsung Z1 is selling in India for about $90.
       
      To that end, Samsung has been touting the “lightweight” nature of the Tizen operating system, meaning that it requires relatively little computing power and can handle most tasks without requiring pricey high-end specifications.
       
      That same lightweight approach has also allowed Samsung to use Tizen as the platform for many of the devices it is hoping will populate its “connected home,” from televisions to smart watches and home appliances.
       
      Despite concerns that Samsung’s new smartphone would face stiff competition in India, where several local handset makers are touting low-end smartphones — some of them in partnership with Google — Samsung says that its Tizen smartphones have received “positive responses” there.
       
      Positive enough, it seems, to at least push Tizen into a second country.
       
      Source: http://blogs.wsj.com/digits/2015/02/06/samsung-extends-tizen-smartphone-to-bangladesh/





×
×
  • Create New...