Quantcast
Jump to content


Recommended Posts

Posted

2025-03-25-01-banner.jpg

In-App purchases are crucial for many applications, and the Samsung In-App Purchase (IAP) service helps developers manage purchases, subscriptions, and refunds efficiently. To keep your server in sync with user transactions, Samsung IAP Instant Server Notification (ISN) sends real-time notifications to your backend server when purchase-related events occur.

ISN for Samsung IAP is a method used by Samsung's system to notify your server about user activities related to in-app items and subscriptions. When a change occurs, Samsung sends a notification to your server. A list of all events that trigger a notification is available here.

In this article, we will build a Spring Boot server that handles these notifications.

Prerequisites

To implement ISN for Samsung IAP, it is important to focus on the requirements that helps you to most easily implement the process:

  1. Create an IAP public key in the Seller Portal. This key is used to authenticate the notifications you receive and verify that they are from the Samsung IAP ISN system. The steps you need to follow are outlined in the Create an IAP public key in Seller Portal documentation.
  2. Create an in-app item in the Seller Portal. Follow the related documentation to create an in-app item.

ISN Structure

The ISN for Samsung IAP service sends a notification to the application developer server. The structure of the notification is always a base64-encoded JSON Web Token (JWT) and consists of three parts. The three parts are:

  • Header
  • Payload
  • Signature

Header

The JWT uses a JOSE (JavaScript Object Signing and Encryption) header. Similar to the envelope of a letter, the header indicates the type of notification being sent. For additional information, refer to the Samsung IAP ISN Header article.

Example encoded header:

eyJ0eXAiOiJKV1QiLCJhbGciOiJSXXXXXXXX

Example decoded header:

{
   "alg" : "RS256",
   "typ" : "JWT"
}

Payload

The payload is the actual content of the message, like the letter inside the envelope. This part contains the crucial information you need, like the user’s subscription details, the product they have subscribed to, and the current status of the subscription.

More details about the payload check are available in the following documentation and Data claims section.

Example encoded payload:

eyJpc3MiOiJpYXAuc2Ftc3VuZ2FwcHMuY29tIiwic3ViIjoiRVZFTlRfTkFNRSIsImF1ZCI6WyJjb20ucGFja2FnZS5uYW1lIl0sIm5iZiI6MTcxNzIwNCwiaWF0IjoxNzE3MjA0LCJkYXRhIjp7InNlbGxlck5hbWUiOm51bGwsIm
NvbnRlbnROYW1lIjoiTWFydGluZSJ9LCJ2ZXJzaW9uIjoXXXXXXXX

Example decoded payload:

{
    "iss": "iap.samsungapps.com",
    "sub": "EVENT_NAME",
    "aud": ["com.package.name"],
    "nbf": 1717XXXXXX,
    "iat": 1717XXXXXX,
    "data": {..},
    "version": "X.0"
}

Signature

The signature is the security feature that acts as a digital stamp to prove the message is genuine and hasn’t been tampered with. You can use this signature to verify that the data in the payload is authentic and was created by Samsung.

Further information is provided in the signature documentation.

Now that we know the structure of the ISN for Samsung IAP, we can configure the server to handle it.

Server Configuration

According to the ISN for Samsung IAP requirements, you must set up a server to receive the notifications.

Below, we create a Spring Boot server. Use your preferred IDE (Integrated Development Environment) or online Spring Initializr to create a Spring Boot server. Follow the steps below to set up your own server.

Step 1: Set Up a Spring Boot Project

  • Use the Spring Initializr tool to create a new project.
  • Choose the following dependency: Spring Web
  • Generate and download the project.

Step 2: Import the Project into IDE

  • Open the project in the IDE (IntelliJ, Eclipse, etc.)

Step 3: Set Up ISN Endpoint

  1. Create a controller for ISN Notifications in the IDE after importing the Spring Boot project. The controller receives POST requests (Subscription, Refund and Cancel) sent from Samsung’s IAP server.

  2. Add necessary dependencies in the build.gradle file:

{
   implementation 'com.auth0:java-jwt:4.0.0' //For JWT verifier
   implementation 'org.json:json:20230227'    // For JSON parsing
}
  1. Load the public key detailed in the prerequisite section:
  private String loadPublicKey(String fileName) throws IOException {
        ClassPathResource resource = new ClassPathResource(fileName);
        StringBuilder contentBuilder = new StringBuilder();

        try (InputStream inputStream = resource.getInputStream();
            BufferedReader reader = new BufferedReader(new  
            InputStreamReader(inputStream))) {
            String line;
            while ((line = reader.readLine()) != null) {
                contentBuilder.append(line).append("\n");
            }
        }
        return contentBuilder.toString();
    }
  1. Remove headers, footers, and whitespace from the public key and convert it to the RSAPublicKey format.
    private RSAPublicKey getRSAPublicKeyFromPEM(String pem) throws Exception {
        String publicKeyPEM = pem
                .replace("-----BEGIN PUBLIC KEY-----", "")
                .replace("-----END PUBLIC KEY-----", "")
                .replaceAll("\\s", ""); // Remove headers, footers, and whitespace

        byte[] encoded = Base64.getDecoder().decode(publicKeyPEM);
        KeyFactory keyFactory = KeyFactory.getInstance("RSA");
        X509EncodedKeySpec keySpec = new X509EncodedKeySpec(encoded);
        return (RSAPublicKey) keyFactory.generatePublic(keySpec);
    }
  1. Create a JWT verifier with RSAPublicKey and, finally, verify the JWT. If the verification is successful, decode the JWT to retrieve the decoded JSON payload. The decoded payload contains the message of the notification.
   private void verifyToken(String token, RSAPublicKey publicKey) {
        try {
            // Create JWT verifier with RSA public key
            Algorithm algorithm = Algorithm.RSA256(publicKey, null);

            // Verify the JWT token
            JWTVerifier verifier = JWT.require(algorithm)
                    .withIssuer("iap.samsungapps.com")
                    .build();
            DecodedJWT jwt = verifier.verify(token);

            // Decode the JWT token
            String payloadJson = new String(Base64.getDecoder().decode(jwt.getPayload()));
            JSONObject jsonObject = new JSONObject(payloadJson);

            //Print decoded JSON payload
            System.out.println("Payload as JSON: " + jsonObject.toString(4)); 
        } catch (JWTVerificationException e) {
            System.out.println("Invalid token: " + e.getMessage());
        }
    }

In this sample project, we have only printed the payload data to the console. You can use this according to your requirements.

Step 4: Deploy the Server

The server needs a publicly accessible URL to receive ISN notifications. In our project, we have used CodeSandbox to get the publicly accessible URL for the server. Once you deploy the project on CodeSandbox, you will get a publicly accessible URL that looks like this: https://abcde-8080.csb.app/iap/isn.

Testing with Seller Portal

Test your server with Samsung Galaxy Store Seller Portal:

  1. Set the CodeSandbox URL as the ISN URL in Seller Portal.

    • Go to the In-App Purchase section and create items with the required details.
    • In the "ISN URL" field, set the publicly accessible server URL.
  2. After setting the URL, click the Test button. A notification will be sent to the specified server immediately. You will also receive a notification on the server that you just deployed in the CodeSandbox.

undefined
Figure 1: Testing with Seller Portal

Testing with a Sample Application

Now it is time to test the ISN for Samsung IAP from the user application. Further details are provided in the Integrate the Samsung In-App Purchase Orders API with Your Application article. Download the sample application from this blog and then follow the instructions until you reach the "Implementation of Item Subscription" section.

In the sample application, after clicking the "Buy" button, startPayment() is called. The onPayment() callback returns an indication of whether the purchase succeeds or fails. If the purchase is successful, the IAP server sends a notification to your server.

  iapHelper.startPayment(itemId, String.valueOf(1), new OnPaymentListener() {
            @Override
            public void onPayment(@NonNull ErrorVo errorVo, @Nullable PurchaseVo purchaseVo) {
                if (purchaseVo != null) {
                    Log.d("purchaseId" , purchaseVo.getPurchaseId().toString());
                    //  Purchase successfull 
                }else {
                    Log.d("purchaseError" , errorVo.toString());
                }
            }
        });

Example Response

After successfully purchasing an item, a JSON response is returned. For more information on each parameter, you can check the Item purchased documentation.

Example JSON response:

 "data" : {
   "itemId": "example_item_id",
   "orderId": "XXXX40601KRA00XXXXX",
   "purchaseId": "XXXXX7245d57cc1ba072b81d06e6f86cd49d3da63854538eea689273787XXXXX",
   "testPayYn": "N",
   "betaTestYn": "N",
   "passThroughParam": null
}

Conclusion

By implementing the ISN for Samsung IAP with your server, you can easily and securely stay in sync with user in-app purchases.

Integrating ISN for Samsung IAP helps you improve your application management experience and grow your application’s revenue. Following this guide will help you smoothly set up the system and provide a better way to manage your application.

References

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
      In-app purchases and subscriptions are the most common and popular ways to monetize an app. Samsung In-App purchase (IAP) is a payment service, which allows you to sell your in-app items that are distributed through the Samsung Galaxy Store. Samsung IAP offers an SDK for Android, Plugins for Unity and Unreal applications, and Server APIs. In this article, we will learn about how to implement Samsung IAP Server API in your app’s server.
      Why you need to have your own server
      In some cases, your app may experience network interruptions after an item purchase and payment transaction. Malicious attacks can happen which may create security issues in your app. Moreover, malicious users may get your premium contents without buying it if the content is embedded within the app. So, you can reduce these problems by using a server for your app to validate the purchase receipt, provide contents from the server and store the payment related data.
      Why IAP Server APIs are required
      Samsung provides IAP Server APIs to prevent malicious purchases and to handle these challenging scenarios. These APIs let you verify a purchase and get detailed information about a subscription. You will be able to know whether a subscription is going to expire soon, or the cause of the subscription cancellation from Server APIs. It will help you to manage subscriptions and to promote your content based on this data.
      It is not mandatory to implement IAP Server APIs. You can communicate with the IAP Server directly from your app. However, if you want to validate the purchase receipt and get detailed information about a subscription then IAP Server APIs offer great flexibility.
      A server-side application is required for implementing IAP Server APIs. Your application requests the server to fetch some data from the IAP server. Your server gets this data from the IAP server by using Server APIs and returns the data to your app. We will discuss this data flow process between an app, server and IAP server in two parts. In this blog, we discuss how to integrate Samsung’s IAP server API into your app’s server. In the second part, we will cover communication between your app and server.
      Please go through the documentation of Samsung IAP SDK to integrate Samsung IAP SDK into your app. To know about server APIs, read Samsung IAP Server API. The following scenario gives you a snapshot of the communication between your app, server and IAP server.


      Figure 1: Overview Diagram of Samsung IAP Server API

      Here, we assume that you have completed your app successfully by implementing Samsung IAP SDK and registered it in the seller office to test in-app items. Now you are ready to create your app server.
      Get Started
      At first, let’s create a Java dynamic web application by using Servlet for the app server. Server API will be implemented here to communicate with the Samsung IAP server. For simplicity, we have created two servlets for processing the two requests. One is for validating a purchase of an item and another is to check out the status of a subscription item. The client app sends the request to the respective servlet. The respective servlet processes the request and returns the output. The client app executes a task as per the result from the servlet.


      Figure 2: Communication with Servlets

      Servlets
      In Java, a servlet is a type of Java class which runs in a Java-enabled server and handles HTTP requests. We will need a web container that supports Servlet technology, so we have used Apache Tomcat 7.0 as a server. We have already mentioned creating two servlets for the two processes. Each servlet has three parts:
      Getting purchase ID from the client app Processing the specific task using this purchase ID Returning the result to the client app Getting purchase ID from client app
      The purchase ID of an item is required to verify payment transaction and to call getSubscriptionStatus. We need to send purchase ID from the client app to our server. Servlet receives that purchase ID in doPost() method.
      int length = request.getContentLength(); byte[] input = new byte[length]; ServletInputStream in = request.getInputStream(); int c, count = 0 ; while ((c = in.read(input, count, input.length - count)) != -1) { count += c; } in.close(); String recievedString = new String(input); response.setStatus(HttpServletResponse.SC_OK); String purchaseStatus = PurchaseVerification(recievedString); // to verify a purchase String subscriptionStatus = ServerStatusVerification(recievedString); // to get status of subscription item Verify a purchase
      iap/v6/receipt enables your server and client app to verify that a specified in-app item purchase and payment transaction was successfully completed. Here, we use HTTP request to validate the purchase. A JSON Object is returned with detailed information of a purchase. See the following code snippet in PurchaseVerification() method for validating a purchase:
      String PurchaseStatus=""; String url="https://iap.samsungapps.com/iap/v6/receipt?purchaseID="+PurchaseId; URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream())); String inputLine; StringBuffer res = new StringBuffer(); while ((inputLine = in.readLine()) != null) { res.append(inputLine); } in.close(); JSONObject myresponse = new JSONObject(res.toString()); PurchaseStatus = myresponse.get("status").toString(); Create a service token
      A service token is needed to authenticate getSubscriptionStatus SOAP requests. At first, we need to create a SOAP Web Service Client from a WSDL file. So, we have generated JAX-WS portable artifacts from WSDL that can be packaged in a web application archive (WAR) file. JAX-WS-Stubs (artifacts) can be generated from a given WSDL using the wsimport.
      The WSDL link is: https://iap.samsungapps.com/iap/ws/RTCService?wsdl
      After generating JAX-WS portable artifacts, we have written a class called SubscriptionDetails to create service token using Secret ID. To know your secret ID, go to your Profile page and scroll to the information for Seller Page table.
      RtcService rtcService = new RtcService(); RTCService2 rtcimpl = rtcService.getRTCServiceImplPort(); CreateServiceTokenResponse serviceTokenOutput = new CreateServiceTokenResponse(); CreateServiceToken serviceToken = new CreateServiceToken(); serviceToken.setSecret(secretId); try { serviceTokenOutput.setOutput(rtcimpl.createServiceToken(serviceToken.getSecret())); } catch(Exception e) { } Check subscription status
      getSubscriptionStatus is used to get subscription status, item information, and purchase information of a specified Auto Recurring Subscription (ARS) item that was previously purchased. After getting the service token, we have used SOAP request to get subscription status in SubscriptionDetails class.
      GetSubscriptionStatusWS subscriptionStatus = new GetSubscriptionStatusWS(); try { subscriptionStatus = rtcimpl.getSubscriptionStatus(purchaseid, serviceTokenOutput.getOutput()); } catch(Exception e) {} return subscriptionStatus; Finally, using the following code snippet in ServerStatusVerification() method we can get the subscription status:
      SubscriptionDetails Sub = new SubscriptionDetails(); GetSubscriptionStatusWS subscriptionStatus = new GetSubscriptionStatusWS(); subscriptionStatus = Sub.SoapData(PurchaseId); String Status = subscriptionStatus.getSubscriptionStatus().toString(); return Status; Return the result to client app
      Now return the result of PurchaseVerification() or ServerStatusVerification() method to the client app.
      OutputStreamWriter writer = new OutputStreamWriter(response.getOutputStream()); writer.write(status); writer.flush(); writer.close(); Testing
      Let’s test the application. Call PurchaseVerification() or ServerStatusVerification() method by passing a purchase ID in doGet() method and call doGet() method in doPost() by passing the request and response.
      protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String x = ServerStatusVerification("3fc70af0a118909d0c8b04eaa1eaee823795c982fc8e39f87faa12c58be43f05"); } Run the app on the Apache Tomcat 7.0 server. If your servlet works perfectly then create a .war file for this java application. There are many cloud service providers such as AWS, Heroku which you can use for your server. After creating a .war file, deploy it on a cloud. Get the URL of your app from the cloud service provider and use that URL to test the server APIs by using any browser.
      Conclusion
      Server application is not only useful for security issues but also helpful for marketing. If you provide same premium contents in the multiple platforms, then you can use this server application for all applications. You can keep a record of the detailed information of purchased items and subscriptions which can be helpful for your business in many aspects. For example, you can store your user’s subscription status. Based on this data, you can promote a new item, provide offers to potential users and give recommendations to the new users.
      We are at the end of this article and hope you found the information helpful. See the next blog for part two.
      View the full blog at its source





×
×
  • Create New...