Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
tutorials
blogintroduction the samsung iap subscription server apis empower developers to efficiently manage samsung in-app purchase (iap) subscriptions, including cancellation, refund, revocation, and status check. these apis serve as the foundation for implementing subscription management features within your application management server. integrating the samsung iap server apis with your backend server simplifies subscription management. this integration allows you to cancel subscriptions and prevent further billing for users, revoke access to subscription-based content, process refunds based on user requests, and check subscription status to determine validity and current state. a well-structured backend implementation streamlines subscription management, ensuring customers receive reliable service and minimizing potential issues related to billing, access, and refunds. prerequisites to establish server-to-server communication between the samsung iap service and your server, follow these essential steps. develop a subscription application – ensure your application supports subscription operations. upload binary for beta testing – submit your application for testing in seller portal. create subscriptions – set up subscription products in seller portal for user subscriptions. completing these steps ensures a seamless integration of samsung iap into your application. for detailed guidance, visit register an app and in-app items in seller portal. implementation of the samsung subscription apis the samsung iap subscription server apis are used to manage subscription-related operations, including cancellations, revocations, refunds, and status checks. to leverage these apis effectively, setting up a backend server is essential. this secure server-to-server communication facilitates efficient handling of all subscription-related operations between the samsung iap service and your server. api overview the samsung iap subscription server api provides endpoints for efficiently managing subscription-based operations. it allows developers to cancel, revoke, refund, and check the status of subscriptions. this api also facilitates robust operations and efficient management of user subscriptions, all while ensuring security and authentication through the use of appropriate headers. base endpoint the samsung iap subscription server apis need a secure endpoint for managing subscriptions. https://devapi.samsungapps.com/iap/seller/v6/applications/<packagename>/purchases/subscriptions/<purchaseid> more detailed information is available through the support documentation. headers to ensure secure communication with the samsung iap service, the following headers must be included in every request. content-type – defines the format of the request body. for json content, use application/json. authorization – uses an access token for authentication. the format should be (bearer <access_token>). refer to the create an access token page for details on generating an access token. service account id – obtained from seller portal under assistance > api service. this id is required to generate a json web token (jwt). for more detailed information, visit the create a service account section in seller portal. these headers collectively ensure secure and authenticated api requests, enabling seamless integration with the samsung iap service. supported methods the samsung iap subscription server api enables efficient subscription management. developers can cancel, revoke, or refund subscriptions using patch requests, and check subscription status using get requests. configuring the server you can develop a spring boot server for this purpose. here are the guidelines for setting it up. create a spring boot project - for detailed steps, refer to developing your first spring boot application. set up the server endpoint: create a controller for samsung iap subscription apis within your ide after importing the spring boot project. this controller manages all in-app subscription activities. the controller performs patch and get requests with the samsung iap service, ensuring communication with your server. performing a patch request the patch request is used to cancel, refund, or revoke a subscription. follow these steps to proceed. creating a request body to cancel, refund, or revoke a subscription, a specific request body must be created for each operation. when interacting with samsung iap service, you send a well-structured api request tailored to the specific action you wish to execute. below are the request formats for various subscription operations. // cancel a subscription requestbody body = requestbody.create( mediatype.parse("application/json"), "{\"action\" : \"cancel\"}" ); // revoke a subscription requestbody body = requestbody.create( mediatype.parse("application/json"), "{\"action\" : \"revoke\"}" ); // refund a subscription requestbody body = requestbody.create( mediatype.parse("application/json"), "{\"action\" : \"refund\"}" ); building the patch request (cancel, revoke or refund subscription) the patch method in rest apis is used for partial updates of resources, enabling you to send only the specific fields that need modification rather than the entire resource. the patch request needs a request body to specify the intended action. to execute a subscription management request, you must construct a secure http request that includes all necessary headers and authentication details. request request = new request.builder() .url(api_url) .patch(body) .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); executing the patch request once the patch request is prepared, execute it using the okhttpclient, ensuring proper request handling and response processing. @crossorigin(origins = "*") @requestmapping(value = "/cancel", method = requestmethod.patch ) public void patchrequest(){ // set request body as json with required action. // initialize patch request, set body, add headers, and finalize setup. client.newcall(request).enqueue(new callback() { @override public void onfailure(call call, ioexception e) { // handle exception } @override public void onresponse(call call, response response) throws ioexception { // handle response response.close(); } }); } example response this response indicates that the request was processed successfully and without errors. { "code" : "0000", "message" : "success" } performing a get request the get request is used to retrieve the status of a subscription. follow these steps to proceed. building the get request the get method is primarily used to retrieve or read data from a server. to check the status of a subscription, the get method is required to retrieve detailed item information. this type of request does not require a request body; only the necessary headers for authentication are needed. request request = new request.builder() .url(api_url) .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); executing the get request once the get request is prepared, execute it using the okhttpclient to retrieve and efficiently process the response data. @getmapping("/get") public void getrequest(){ // initialize get request, add headers, and finalize setup. client.newcall(request).enqueue(new callback() { @override public void onfailure(call call, ioexception e) { // handle exception } @override public void onresponse(call call, response response) throws ioexception { // handle response } }); } example response if the get request executes successfully, it returns the status of the subscription as a response. { "subscriptionpurchasedate": "2025-04-28 04:54:06 utc", "subscriptionenddate": "2025-04-28 05:54:06 utc", "subscriptionstatus": "cancel", "subscriptionfirstpurchaseid": "55541a3d363c9dee6194614024ee2177c72a9dec51fe8dba5b44503f57dc9aec", "countrycode": "usa", "price": { "localcurrencycode": "usd", "localprice": 15, "supplyprice": 15 }, ... } deploying and testing the server for the server to perform api calls, it can use a publicly accessible url. you can deploy the project to obtain the url. for testing purposes, you might deploy it on a platform like codesandbox, which provides a publicly accessible url similar to https://abcde-8080.csb.app/iap/xxxx. conclusion by properly integrating the samsung iap subscription server apis, developers can ensure seamless handling of subscription-related actions within their applications. the implementation of secure server-to-server communication guarantees efficient subscription management and significantly enhances the overall user experience. references download sample server source code samsung iap subscription documentation integrate the samsung in-app purchase orders api with your application
Md. Hossain
tutorials
blogsamsung 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 on your server to easily manage your application. this content guides you through the essential components for implementing both the samsung iap and samsung iap orders apis. figure 1: sample application ui in this tutorial, we provide a sample android application called book spot, which offers users the option to subscribe to their favorite books and consumable items, such as text fonts, for purchase. this user application is provided to help you to integrate samsung iap sdk with your applicaiton. finally, we also provide a sample server application to view all the payment and refund history on specific dates by calling the samsung iap orders api from the back-end server. prerequisites before implementing the samsung iap order api on your server, you need to perform iap functionalities to retrieve purchase history. you need to integrate samsung iap with your application. if you don't have an app yet, follow these steps to ensure a smooth and effective process. step 1: implement samsung iap in your app to integrate the iap system into your application, follow this general flow. integrate the samsung iap sdk into your application. initiate item purchase by calling startpayment() with the necessary parameters, such as the item id and a listener to handle the results. after the transaction, verify whether the purchase is successful with iap/v6/receipt. this involves checking if the purchase id is valid. follow the ensuring secure purchases using the samsung iap server api for more details. once the purchase is confirmed, allow the item to be consumed using consumepurchaseitems(). this step ensures that the item can be repurchased if needed. for more information about the iap sdk integration, you can follow the integration of samsung iap services in android apps article. also get help from the sample android application. step 2: upload your application upload the application for beta testing on 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” in the test guide. step 3: purchase items finally, create products in seller portal so that users can purchase or subscribe to them while using the application. for more details about the available items that seller portal supports, see the programming guide. 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 response. through server-to-server communication, the api returns all order data for the application. overview of the orders api to view all payments and refunds: you must make a post request to the samsung iap orders api endpoint with the required headers specified below. if you specify a date, all the payment history within 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 will help 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. configuring the server you can develop a spring boot server for this purpose. here are the guidelines on how to set up this server. set up a spring boot project. for more information, follow the steps in developing your first spring boot application. 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. to ensure smooth communication with the samsung iap orders api, it's essential to structure your server requests effectively. below is a clear and concise breakdown of the process. 1. setup dependencies 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' 2. define parameters encapsulate request parameters for cleaner handling. public class orderrequest { private final string sellerseq; public orderrequest(string sellerseq) { this.sellerseq = sellerseq; } public string tojson() { return string.format("{\"sellerseq\":\"%s\"}", sellerseq); } } 3. build the http request centralize request configuration for maintainability. public class orderservice { private static final string api_url = "https://devapi.samsungapps.com/iap/seller/orders"; private static final string token = "0djt9yzryukdogbvulxxxxxx"; private static final string service_account_id = "85412253-21b2-4d84-8ff5-xxxxxxxxxxxx"; private final okhttpclient client = new okhttpclient(); public void sendorderrequest(string sellerseq) { orderrequest orderrequest = new orderrequest(sellerseq); requestbody body = requestbody.create(orderrequest.tojson(), mediatype.parse("application/json; charset=utf-8")); request request = new request.builder() .url(api_url) .post(body) .addheader("authorization", "bearer " + token) .addheader("service-account-id", service_account_id) .addheader("content-type", "application/json") .build(); executerequest(request); } } 4. handle response ensure robust error handling for api calls. private void executerequest(request request) { 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 { try (responsebody responsebody = response.body()) { if (!response.issuccessful()) { system.err.printf("unexpected response [%d]: %s%n", response.code(), responsebody.string()); return; } system.out.println("response: " + responsebody.string()); } } }); } 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 api 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. 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 product title, price, and payment status. therefore, you can use the information and create views for an easier order management. noteif the iap operating mode is configured to test mode, the api response is empty. this is because the api is configured to operate and return a response only in production mode. conclusion you have learned how to implement product 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. related resources for additional information on this topic, see the resources below: android sample application source code sample server application source code add samsung in-app purchase service to your app samsung iap orders api integration of samsung iap services in android apps
Md. Hossain
tutorials
blogsamsung wallet partners can create and update card templates to meet their business needs through the wallet partners portal. however, if the partner has a large number of cards, it can become difficult to manage them using the wallet partners portal website. to provide partners with more flexibility, samsung provides server apis so that partners can easily create and modify samsung wallet card templates without using the wallet partners portal. with these apis, partners can also create their own user interface (ui) or dashboard to manage their cards. in this article, we implement the add wallet card templates api to create a card template for a coupon in the wallet partners portal. we focus on the api implementation only and do not create a ui for card management. prerequisites if you are new to samsung wallet, complete the onboarding process and get the necessary certificates. as a samsung wallet partner, you need permission to use this api. only authorized partners are allowed to create wallet card templates using this api. you can reach out to samsung developer support for further assistance. api overview the rest api discussed in this article provides an interface to add wallet card templates directly from the partner's server. this api utilizes a base url, specific headers, and a well-structured body to ensure seamless integration. url: this is the endpoint where the request is sent to create a new wallet card template. https://tsapi-card.walletsvc.samsung.com/partner/v1/card/template headers: the information provided in the headers ensures secure communication between the partner's server and samsung's server. authorization: the bearer token. see the json web token documentation for details. x-smcs-partner-id: this is your partner id. the partner id gives you permission to use the api. x-request-id: use a randomly generated uuid string in this field. body: the body must be in the jwt token format. convert the payload data (card template in json format) into a jwt token. for more details about the api, refer to the documentation. implementation of the api to create a card template the add wallet card templates api allows you to add a new card template to the wallet partners portal. you can also create the card in the portal directly, but this api generates a new card template from your server, without requiring you to launch the wallet partners portal. follow these steps to add a new card template. step 1: extracting the keys extract the following keys from the certificates. these keys are used while generating the jwt token. rsapublickey partnerpublickey = (rsapublickey) readpublickey("partner.crt"); rsapublickey samsungpublickey = (rsapublickey) readpublickey("samsung.crt"); privatekey partnerprivatekey = readprivatekey("private_key.pem"); extracting the public keys use the following code to extract the partner public key and the samsung public key from the partner.crt and samsung.crt certificate files, respectively. you received these certificate files during the onboarding process. private static publickey readpublickey(string filename) throws exception { // load the certificate file from resources classpathresource resource = new classpathresource(filename); try (inputstream in = resource.getinputstream()) { certificatefactory certfactory = certificatefactory.getinstance("x.509"); x509certificate certificate = (x509certificate) certfactory.generatecertificate(in); return certificate.getpublickey(); } } extracting the private key the following code extracts the private key from the .pem file you generated during the onboarding process. this key is needed to build the auth token. private static privatekey readprivatekey(string filename) throws exception { string key = new string(files.readallbytes(new classpathresource(filename).getfile().topath())); key = key.replace("-----begin private key-----", "").replace("-----end private key-----", "").replaceall("\\s", ""); byte[] keybytes = base64.getdecoder().decode(key); keyfactory keyfactory = keyfactory.getinstance("rsa"); return keyfactory.generateprivate(new pkcs8encodedkeyspec(keybytes)); } step 2: generating the authorization token samsung's server checks the authorization token of the api request to ensure the request is from an authorized partner. the authorization token is in the jwt format. follow these steps to create an authorization token: building the auth header create an authheader. set “auth” as its payload content type to mark it as an authorization token. as you can create multiple certificates, use the corresponding certificate id of the certificate that you use in the project. you can get the certificate id from “my account > encryption management” of the wallet partners portal. // create auth header jsonobject authheader = new jsonobject(); authheader.put("cty", "auth"); authheader.put("ver", 3); authheader.put("certificateid", certificateid); authheader.put("partnerid", partnerid); authheader.put("utc", utctimestamp); authheader.put("alg", "rs256"); creating the payload create the payload using the authheader. follow this code snippet to create the payload. // create auth payload jsonobject authpayload = new jsonobject(); authpayload.put("api", new jsonobject().put("method", "post").put("path", "/partner/v1/card/template")); authpayload.put("refid", uuid.randomuuid().tostring()); building the auth token finally, generate the authorization token. for more details, refer to the “authorization token” section of the security page private static string generateauthtoken(string partnerid, string certificateid, long utctimestamp, privatekey privatekey) throws exception { // create auth header // create auth payload // return auth token return jwts.builder() .setheader(authheader.tomap()) .setpayload(authpayload.tostring()) .signwith(privatekey, signaturealgorithm.rs256) .compact(); } step 3: generating a payload object token the request body contains a parameter named “ctemplate” which is a jwt token. follow these steps to create the “ctemplate.” creating the card template object select the proper card template you want to create from the card specs documentation. get the payload object as json format. now create the jsonobject from the json file using the following code snippet. // creating card template object jsonobject cdatapayload = new jsonobject(); cdatapayload.put("cardtemplate", new jsonobject() .put("prtnrid", partnerid) .put("title", "sample card") .put("countrycode", "kr") .put("cardtype", "coupon") .put("subtype", "others") .put("saveinserveryn", "y")); generating the jwe token create the jwe token using the following code snippet. for more details about the jwe format, refer to the “card data token” section of the security page. // jwe payload generation encryptionmethod jweenc = encryptionmethod.a128gcm; jwealgorithm jwealg = jwealgorithm.rsa1_5; jweheader jweheader = new jweheader.builder(jwealg, jweenc).build(); rsaencrypter encryptor = new rsaencrypter((rsapublickey) samsungpublickey); jweobject jwe = new jweobject(jweheader, new payload(string.valueof(cdatapayload))); try { jwe.encrypt(encryptor); } catch (joseexception e) { e.printstacktrace(); } string payload = jwe.serialize(); building the jws header next, follow this code snippet to build the jws header. set “card” as the payload content type in this header. // jws header jwsheader jwsheader = new jwsheader.builder(jwsalgorithm.rs256) .contenttype("card") .customparam("partnerid", partnerid) .customparam("ver", 3) .customparam("certificateid", certificateid) .customparam("utc", utctimestamp) .build(); building the jws token generate the jws token from the previously generated jwe token and, finally, get the “ctemplate” jwt. follow the “jws format” section of the security page. private static string generatecdatatoken(string partnerid, publickey partnerpublickey, publickey samsungpublickey, privatekey partnerprivatekey, string certificateid, long utctimestamp) throws exception { // creating card template object // jwe payload generation // jws header // jws token generation jwsobject jwsobj = new jwsobject(jwsheader, new payload(payload)); rsakey rsajwk = new rsakey.builder((rsapublickey) partnerpublickey) .privatekey(partnerprivatekey) .build(); jwssigner signer = new rsassasigner( ); jwsobj.sign(signer); return jwsobj.serialize(); } step 4: building the request as all of the required fields to create the request have been generated, you can now create the request to add a new template. follow the code snippet to generate the request. private static request buildrequest(string endpoint, string partnerid, string requestid, string authtoken, string cdatatoken) { // prepare json body jsonobject cdatajsonbody = new jsonobject(); cdatajsonbody.put("ctemplate", cdatatoken); requestbody requestbody = requestbody.create( mediatype.parse("application/json; charset=utf-8"), cdatajsonbody.tostring() ); // build http request request request = new request.builder() .url(endpoint) .post(requestbody) .addheader("authorization", "bearer " + authtoken) .addheader("x-smcs-partner-id", partnerid) .addheader("x-request-id", requestid) .addheader("x-smcs-cc2", "kr") .addheader("content-type", "application/json") .build(); return request; } step 5: executing the request if the request is successful, a new card is added to the wallet partners portal and its “cardid” value is returned as a response. private static void executerequest(request request) { // execute http request try (response response = client.newcall(request).execute()) { if (response.issuccessful()) { system.out.println("wallet card template added successfully: " + response.body().string()); } else { system.out.println("failed to add wallet card template: " + response.body().string()); } } } implement as a server at this point, you can add a webpage ui for creating card templates and deploy it as a web service. in this sample project, there is no ui added. but, you can deploy this sample as a web service and test it. conclusion this tutorial shows you how you can create a new samsung wallet card template directly from your server by using a rest api. now that you can implement the api, you can add a ui and make it more user-friendly. also implement the updating wallet cards templates api for better card management. references for additional information on this topic, refer to the resources below: sample project code. business support for special purposes documentation.
M. A. Hasan Molla
tutorials
blogin-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: 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. 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 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. 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 } 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(); } 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); } 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: 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. 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. 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 } notefor different event types, it sends different data claims. for more detailed information regarding data claims, see data claims. 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: download the sample spring boot server samsung iap instant server notification documentation integrate the samsung in-app purchase orders api with your application
Md. Hossain
tutorials
blogintroduction the samsung iap publish api enables developers to efficiently manage in-app purchase (iap) products within applications. this api serves as the foundation for handling crud (create, read, update, delete) operations related to digital products available for purchase. developers can use this api to view existing in-app products, register new products, modify product details such as price and description, and remove products that are no longer needed. as a part of this article, we will develop a backend application server and a web application to streamline samsung iap product management. the backend server will communicate with the samsung server through the samsung iap publish api, handling requests related to iap products to ensure smooth integration and operation. the web application will provide an intuitive, user-friendly interface, allowing developers and administrators to visually manage samsung iap products in a structured and organized manner. by implementing this system, developers can significantly reduce manual effort while maintaining better control over their iap products. additionally, the publish api enables a unified product backend, helping standardize workflows, enforce consistent policies, and maintain clear audit trails—further enhancing the design and operational efficiency of iap management. to begin, you need to have a mobile application in galaxy store so that you can create samsung iap products. if you do not have one, follow the integration of samsung iap services in android apps article. api overview the samsung iap publish api allows developers to manage iap products in their applications by viewing, creating, updating, modifying, and deleting products. base url the base url for accessing the samsung iap publish api endpoints is. https://devapi.samsungapps.com/iap/v6/applications/:packagename/items replace packagename with the actual package name of your application to access the relevant samsung iap endpoints. supported method the samsung iap publish api allows fetching a list of available products or viewing detailed information about a specific product using get requests. to register a new product, developers can send a post request, while updating an existing product requires a put request. if only partial modifications are needed, a patch request is needed. finally, products can be removed with a delete request. header add the following fields to the request header. authorization: this field requires bearer token which is the access token from galaxy store authentication server. for more information, see the create an access token page. service account id: get the service account id value by clicking the assistance > api service tabs on the seller portal. for more details, read the section create a service account and follow step 6. content-type: use application/json as value. implementation of samsung publish api the samsung iap publish api helps to manage iap products by performing crud operations such as viewing, creating, updating, and removing products. to use these operations, we need to set up a server that processes api requests and executes these operations as instructed. first, create a server. once the server is ready, we can integrate the samsung api for server-to-server communication. in this example, we use okhttp for network communication to call the api. the front-end communicates with the spring boot server, and the spring boot server, in turn, interacts with the samsung iap service. implementation of the "create product" operation a post request is needed to create a new product. for more details, refer to the documentation. private static final string create_api_url = "https://devapi.samsungapps.com/iap/v6/applications/com.example.bookspot/items"; @postmapping(value = "/create", consumes = org.springframework.http.mediatype.application_json_value) public responseentity<string> createitem(@org.springframework.web.bind.annotation.requestbody string requestbody) { okhttp3.mediatype mediatype = okhttp3.mediatype.parse("application/json"); okhttp3.requestbody body = okhttp3.requestbody.create(mediatype, requestbody); request request = new request.builder() .url(create_api_url) .post(body) .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); try (response response = client.newcall(request).execute()) { string responsestring = response.body() != null ? response.body().string() : "no response body"; return responseentity.status(response.code()).body(responsestring); } catch (ioexception e) { return responseentity.status(500).body("error: " + e.getmessage()); } } example response after successful execution of the post request, the server will respond with the status 200 (success). below is the visual representation of the operation. figure 1: ui representation of create product operation for a list of possible response codes when a request fails, refer to failure response codes. implementation of the "view product list" operation to view the already created products, we need to fetch them from the samsung server. for this, we need to build a get request to retrieve the products. for more details, refer to the documentation. private static final string view_api_url = "https://devapi.samsungapps.com/iap/v6/applications/com.example.bookspot/items?page=1&size=20"; @getmapping("/get") public responseentity<string> getrequest() { request request = new request.builder() .url(view_api_url) .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); try (response response = client.newcall(request).execute()) { if (!response.issuccessful()) { string error = response.body() != null ? response.body().string() : "unknown error"; return responseentity.status(response.code()).body("failed: " + error); } string json = response.body() != null ? response.body().string() : "{}"; return responseentity.ok() .contenttype(org.springframework.http.mediatype.application_json) .body(json); } catch (ioexception e) { return responseentity.status(500).body("error: " + e.getmessage()); } } example response after the request is successfully sent to the server, it will respond with the status code 200. below is the visual representation of the product retrieval process. figure 2: ui representation of view product list operation for a list of possible response codes when a request fails, refer to failure response codes. implementation of the "modify product" operation to modify the listed products, we need to create a put request based on the required fields and perform the modification operation accordingly. for more details, refer to the documentation. private static final string modify_api_url = "https://devapi.samsungapps.com/iap/v6/applications/com.example.bookspot/items"; @putmapping(value = "/update", consumes = org.springframework.http.mediatype.application_json_value) public responseentity<string> updateitem(@requestbody string requestbody) { okhttp3.mediatype mediatype = okhttp3.mediatype.parse("application/json"); okhttp3.requestbody body = okhttp3.requestbody.create(mediatype, requestbody); request request = new request.builder() .url(modify_api_url) .put(body) .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); try (response response = client.newcall(request).execute()) { string responsestring = response.body() != null ? response.body().string() : "no response body"; return responseentity.status(response.code()).body(responsestring); } catch (ioexception e) { return responseentity.status(500).body("error: " + e.getmessage()); } example response below is a visual representation of a response to a successful modification request. figure 3: ui representation of modify product operation for a list of possible response codes when a request fails, refer to failure response codes. implementation of the "remove product" operation to delete a product from the server, we need to make a delete request using the necessary fields and execute the item removal operation accordingly. for more details, refer to the documentation. private static final string remove_api_url = "https://devapi.samsungapps.com/iap/v6/applications/com.example.bookspot/items"; @deletemapping("/delete/{itemid}") public responseentity<string> deleteitem(@pathvariable string itemid) { string deleteurl = remove_api_url + "/" + itemid; request request = new request.builder() .url(deleteurl) .delete() .addheader("content-type", "application/json") .addheader("authorization", "bearer " + access_token) .addheader("service-account-id", service_account_id) .build(); try (response response = client.newcall(request).execute()) { string responsestring = response.body() != null ? response.body().string() : "no response body"; return responseentity.status(response.code()).body(responsestring); } catch (ioexception e) { return responseentity.status(500).body("error: " + e.getmessage()); } } example response below is a visual representation of the item retrieval process after a successful remove operation. figure 4: ui representation of delete product operation for a list of possible response codes when a request fails, refer to failure response codes. deploy the server you can deploy your server to codesandbox for testing purposes. you also can use any other hosting site according to your requirements. conclusion by effectively incorporating the samsung iap publish api, you can create your own webview to easily manage your iap products. references for additional information on this topic, refer to the resources. download the sample spring boot server code download the sample structured spring boot server code samsung iap publish documentation
Md. Hossain
tutorials
blogin a previous blog article, we learned about samsung wallet’s server notification api and how to use this api to receive server notifications about samsung wallet card updates in a user’s samsung galaxy devices. this time, we look at the partner server api called “get card data” and how partners can use this api in order to add, update, or cancel issued wallet cards in user’s devices. prerequisites the prerequisites needed for this article are similar to those for our previous article about samsung wallet server apis. namely, we require a partner server where we can set up the get card data api endpoint. in order to set up and test this api, you need to: complete the samsung wallet onboarding process. create a samsung wallet card template. launch the wallet card template and have it in either the verifying or active status so that the card can be added to a user’s device. have an existing server to set up the get card data api endpoint. you can use codesandbox or a similar online hosting service for testing. configure your firewall (if you use any) to accept incoming connections from the samsung wallet server (34.200.172.231 and 13.209.93.60). when you have completed all the prerequisites, proceed to the next step to configure your wallet card template to send requests to your server. setting up the get card data api in the samsung wallet partners portal, open the desired wallet card template and then edit it to set the following “get” field: go to the wallet partners portal. from the wallet cards dropdown, select “manage wallet card.” click the name of the wallet card you want to edit. click “edit” and then scroll down to the “partner get card data” section to modify the partner server url. click “save” to set the server url for the card. get card data api specification for a complete description of the get card data api specification, please check the samsung wallet documentation. method: the get card data api uses a get method to fetch card information from the server. api path: the api path for the request is fixed and uses the “partner get card data” server url that you configured in the previous section. the samsung wallet server sends the get request to this exact url whenever it needs to fetch card data from the partner server. the format for the api path url for the complete get card data request is: {partner server url}/cards/{cardid}/{refid} if the samsung wallet server needs to fetch specific fields from the card data instead of the entire card, then it uses the additional query parameter named “fields” at the end of the url: {partner server url}/cards/{cardid}/{refid}?fields={fields} request header: the samsung wallet server includes 2 fields in the header when calling the get card data endpoint: authorization and x-request-id. an authorization bearer token is provided in the authorization field, so that the partner can verify the request before providing the data. request payload: the request does not contain any payload. expected response payload: the response to the get card data request must contain the card data in one of the following two formats: plain card data in the raw json format. encrypted card data in the cdata format. when the fields query parameter is used in the request url, the card data returned in the response can provide only the fields included in the request. however, it is acceptable to return the entire card data in the response as well. implementing the get card data api we will extend the spring server from the previous article to create the get card data api endpoint. in the api, we need to do 2 things: verify the incoming request to check that it is authentic and actually coming from the samsung wallet server. send the requested card’s data back as the response. the verification part is similar to the verification steps performed in the previous article. the request header contains the authorization bearer token, which we can use to verify the request. after verification, it is necessary to send back valid card data in the response to this get request. we can return either the plain card data or encrypt and tokenize it into cdata. in this implementation, we return the plain card data in the json format. in this example, we use a raw json file from a plaintext file called ticket_ref-001.json for simplicity. the complete get card data api implementation will therefore be as follows: @restcontroller @requestmapping("/cards") class carddatacontroller { // data transmit link @getmapping(path = ["/{cardid}/{refid}"]) fun providecarddata(@pathvariable cardid: string, @pathvariable refid: string, @requestparam("fields", defaultvalue = "") fields: string, @requestheader("authorization") authtoken: string, @requestheader("x-request-id") requestid: string,): string { if(verifyauthtoken(authtoken)){ return jwtgen.getplaincarddata() } else{ return httpstatus.unauthorized.tostring() } } } next, define the getplaincarddata() function, where the cdata is generated using the data provided in the ticket_ref-001.json file. fun getplaincarddata():string{ val data:string = getstringfromfile("sample/payload/ticket_ref-001.json") return data } warningalways verify the authenticity of the get card data request before returning the data in response. the authenticity of the request can be verified using the authorization token provided in the request header. adding cards to samsung wallet using data fetch link once you have configured the get card data api for your server, you can use the api to add cards to the user’s device directly. this is called the data fetch link and unlike the standard approach, it is not necessary to send the card information in the cdata format. instead, you can simply provide the user with the url and they can then add the card to their device by clicking the url. the url format for adding card data is as follows: https://a.swallet.link/atw/v3/{certificateid}/{cardid}#clip?pdata={pdata} so, for example, if your certificateid is a123, cardid is 3h844abcdefg00, and refid is ref-001, then the slim api url for the add to wallet operation is: https://a.swallet.link/atw/v3/a123/3h844abcdefg00#clip?pdata=ref-001 to add the card to their wallet using this method, the user needs to simply visit this url from their device. once the user clicks the link, the samsung wallet server requests the card data from the previously configured get card data api and adds the wallet card to the device. notethe only information required to add a card to the device is the pdata (also known as refid). ensure that this value is a unique hash identifier so that it cannot be easily compromised by third parties figure 1: adding a card to the wallet using data fetch link updating card data using an update notification samsung wallet allows partners to update any issued card’s data using the previously configured get card data api. the card data can be updated in one of the following two ways: the card data is refreshed automatically every time the user opens the card in the detail view. the card data update is triggered manually when the partner sends an update notification. in this case, the card data is updated even when samsung wallet is running in the background, and it is not necessary to open the card in the detail view. when an update notification is sent, the state of the card is immediately updated on the device. afterwards, when the user opens samsung wallet in their device, the card data attributes are refreshed by calling the get card data api. this ensures that the wallet card data is always updated right before the user views it. in order to update card data manually and notify the user about the change, we need to configure the changes in the card data and then send an update notification to the samsung wallet server. once the update notification api is called following the specification, the card’s status and data are updated on the user’s device automatically. samsung wallet uses the refid as the unique identifier of samsung wallet cards. therefore, the refid of the specific card must be included in the payload of the update notification request in order to update the card. the complete specification for the update notification api can be found in the documentation: method: post api path: the request needs to be sent at:{samsung wallet server domain url}/{cc2}/wltex/cards/{cardid}/updates for the samsung wallet server domain url, we can either use the public domain (https://tsapi-card.walletsvc.samsung.com) or the private domain we received in our api callback. request header: the header must contain the authorization, x-smcs-partner-id, and x-request-id request header fields. the samsung wallet server uses this header information to verify the authenticity of the request. additionally, the header also needs to specify the content-type header, which must be set to application/json. request payload: the payload of the update notification must contain the card type, refid, and the new state of the card. optionally, the payload can also contain the fields to be updated so that only those specific fields are retrieved and updated. the payload must be in the following json format: { "card": { "type": "{card type}", "data": [ { "refid": "{ref id}", "state": "{update/deleted/expired}", "fields": "{fields, comma-separated, optional}" } ] } } steps for using the update notification: configure the authorization token. prepare the card data in your server for updating. prepare the header and payload with the refid of the selected card for updating. send the post request to the samsung wallet server for updating. once you send the update notification post request following the specification, the samsung wallet server updates the card on the user’s device. let us modify the data of the previously added card from our server and then call the update notification api. configuring the authorization token all samsung wallet server apis require the use of a bearer authorization token in order to ensure the security and authenticity of the request. you can find the complete specification of the authorization token required by samsung wallet in the documentation the authorization token generation process is very similar to generating cdata, except that for cdata, the payload needs to be encrypted first. for the authorization token, the payload is in plaintext and only contains the api path for verification. to create the bearer authorization token: configure the json payload that describes the method and api path of the request. configure a custom jws header following the jwt format specification. create a jws object using the payload and custom jws header. sign and validate the complete jws object with your partner private and public keys using the rs256 asymmetric algorithm. the complete function to generate the authorization token is given below: fun generateauthorizationtoken(): string{ val payload:string = getstringfromfile("sample/payload/api_path.json") .replace("{refid}", refid) .replace("{method}","get") .replace("{path}","/wltex/cards/cardid/updates/") val jwsalg = jwsalgorithm.rs256 val utc = system.currenttimemillis() val jwsheader = jwsheader.builder(jwsalg) .contenttype("auth") .customparam("partnerid", partner_id) .customparam("certificateid", "a123") .customparam("ver", "3") .customparam("utc", utc) .build() val jwsobj = jwsobject(jwsheader, payload(payload)) val rsajwk = rsakey.builder(partnerpublickey as rsapublickey) .privatekey(partnerprivatekey) .build() val signer: jwssigner try { signer = rsassasigner(rsajwk) jwsobj.sign(signer) } catch (e: joseexception) { e.printstacktrace() } return jwsobj.serialize() } preparing card data for update once the update notification is sent, the samsung wallet server queries the get card data api endpoint for the updated card data and then updates the wallet card with the latest data provided by the api. so before calling the update notification, make sure the card data provided by the api is up-to-date. for our example, let us change the value of the seatnumber field from a-07 to e-05 before calling the update notification api. prepare the request header and payload for the update notification the post request header contains the following fields: authorization, x-smcs-partner-id, and x-request-id. for our example, we set our partner id as the x-smcs-partner-id, a randomly generated code as x-request-id, and generate a bearer token following the authorization token generation process mentioned previously and use it as the authorization field value. next, we set the json payload, according to the previously mentioned format: { "card": { "type": "ticket", "data": [ { "refid": "ref-001", "state": "updated" } ] } } since the fields field is optional, we have omitted it in this example. sending the update notification to the samsung wallet server once everything is ready, we send the update notification post request to the samsung wallet server. we can use any method to send the request, such as postman, curl, or a plain http request. make sure that the update notification is sent immediately after generating the authorization token, as the token only has a ttl (time to live) of 30 seconds. once the update notification is sent, the user should immediately receive a “card information updated” push notification informing them of the card update. afterwards, the next time the user opens the samsung wallet application, the card details are up-to-date and the user can see their new seat number in their card. figure 2: updating card data using an update notification cancelling an event using a cancel notification there are times when you might need to cancel an event and recall all the issued wallet cards for it. in such case, samsung wallet makes it possible to cancel all issued cards with a specific eventid and send a notification regarding the cancelation to all users with the cards associated with the event. therefore, it is no longer necessary to modify issued cards one-by-one using their refid. instead the card issuer can cancel all cards under the event at one time. the process of sending a cancel notification is the same as the update notification process, except for the following differences: the payload needs to contain the eventid instead of the refid the state must always be canceled the post request endpoint url is:{samsung wallet server domain url}/{cc2}/wltex/cards/{cardid}/cancels you can find the complete specification for the cancel notification api in the samsung wallet documentation. now let us send a cancel notification following the same process as update notification: configure the authorization token. prepare the payload with the eventid for cancellation. send the post request to the samsung wallet server for cancellation. for our example, we add a few cards with the same event id to our wallet in different devices, then send a cancel notification following the specification. once the cancel notification is sent, all samsung wallet cards with the given eventid are deleted automatically from all devices and the affected users receive a "ticket canceled" push notification. figure 3: canceling an event using a cancel notification conclusion in this article, we have learned how to configure our server to use the get card data api, as well as how to use various samsung wallet server apis to add, update, delete, and cancel samsung wallet cards from user devices. if you have any further queries regarding this process, feel free to reach out to us through the samsung developers forum.
Mobassir Ahsan
tutorials mobile, game
blogin-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. 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.
Jakia Sultana
Develop Samsung Wallet
docapi guidelines adding wallet card specs data transmit link the most common and straightforward method is the data transmit link approach, which securely includes tokenized data in the atw link the atw link format for this method is as follows the name data transmit link has been changed from typical flow type value description url https //a swallet link/atw/v3/{cardid}#clip?cdata={cdata} path parameters cardid string required wallet card identifier issued from partner portal when the partner managersigns up for partner services and registers the wallet card they want to service hash path parameters #clip string required parameters for the hash link* the first letter is capitalized query parameters cdata string required actual payload data in basic json format to communicate between partnersand samsung wallet this must be secured in jwt json web token format * see security [example] https //a swallet link/atw/v3/1656147182764415319#clip?cdata=eyjjdhkioijkv1qilcjhbgcioijsinrpbwvzdgftcci6imnyzwf0zwqgdgltzsisinbhcnruzxjjrci6inbhcnruzxigsuqifq … … … … dn0_oz3xcr0juq3mlszliutxfotewnz0mqj7kinjysnm5xfwqt5vcn20peebelgux8vjxly4_9g4bhq-hd4o9poyutuawew yzdlmtfho -nycel3t0yznzad2kck_hrtwigeerhlgn6ydaq_fpfdslxsa3zjtnpg3wcuqew5cidpbpfswbqlropqepnawg5nlm3dkaa4a1dzazmbsr1bgzhrh_viknx3cy5mo0jnbexl_yiz5_wb379uyswumqipitzvg2ijyvfht17i4 data fetch link in cases involving sensitive data or when providing static links, data fetch link method is highly recommended links using this approach include only a unique reference id, and wallet cards are added by querying data through get card data path as specified in partner portal the name data fetch link has been changed from slim data flow please be aware that if the link is exposed to unintended users, it can be exploited please prepare the integration with this in mind it is crucial to ensure that the refid, used for a reference value, is generated in a manner that is not easily deducible by potential attackers type value escription url https //a swallet link/atw/v3/{certificateid}/{cardid}#clip?pdata={pdata} path parameters certificateid string 4 conditional certificate identifier based on a csr during onboarding 4 digits alphanumeric * must be generated from partner portal cardid string 32 required wallet card identifier * it must be generated from partners portal hash path parameters #clip string 5 required parameters for the hash link query parameter pdata string 2048 required unique id defined by content providers this has identification for each user's wallet card contents * for secure transactions, a reference id refid must be in a form that cannot be inferred [example] example web link https //a swallet link/atw/v3/ymtt/1656147182764415319#clip?pdata=sighcziwm9g updating wallet card specs the added users’ cards allow updating its data using server interactions find the card details to configure api on partner portal if partners want to manage the added cards samsung server will notify the result of 'add to wallet' via send card state partners get the callback url for samsung server api from send card state payload using the callback url, partners can make actions for the added cards via samsung server api depending on the interfaces, samsung server triggers specific operations for example, when update notification is called, samsung server calls partners' server to look up the updated contents partner server api samsung server can call the following api by using endpoint on the registered card information if the partner server manages an inbound allow list, contact us to register samsung server ip address get card data returns the current information of the card [request] type value description method get url {partner server url}/cards/{cardid}/{refid}?fields={fields} headers authorization string 1024 required credential token the token can have prefix "bearer" as an authorization type, e g , bearer <credentials> * see authorization token x-request-id string 32 required request identifier randomly generated uuid string path parameters cardid string 32 required wallet card identifier * see the "add to wallet" interfaces refid string 32 required a unique content identifier defined by the content provider query parameter fields string 128 optional attributes which intended to retrieve can be specified using commas , as separators e g balance,barcode value payload n/a example get /cards/12584806754/ref-20230304-0003 [response] type value description http status 200 ok 204 no content payload option1 cdata string 4096 conditional card object json * this field needs to be encrypted * see security payload option2 card object conditional card information * card object as an alternative to cdata * if the card includes sensitive data, it is highly recommended to use cdata card type string 16 required wallet card type * see wallet cards card data[] array of object required wallet card data container data[] refid string 32 required a unique content identifier defined by the content provider data[] createdat long 13 required timestamp of data epoch timestamp in milliseconds data[] updatedat long 13 required timestamp of data epoch timestamp in milliseconds data[] state string 16 required wallet card state for example, active, updated, expired, redeemed, held, deleted, canceled, pending, suspended * see card states for details data[] language string 8 required default content language code e g , en, ko data[] attributes object required card data attributes data[] attributes {fields} attribute fields by card type *see wallet cards data[] localization[] array of object optional information for multilingual support localization[] language string 8 required multilingual content language code e g , en, ko localization[] attributes {fields} for displaying a given language, "data[] attributes" can be replaced by localized versions *see wallet cards [example option1 ] { "cdata" "eyjhbgcioijiuzi1niisinr5cci6ikpxvcj9 eyjzdwiioiixmjm0nty3odkwiiwibmftzsi6ikpvag4grg9liiwiawf0ijoxnte2mjm5mdiyfq sflkxwrjsmekkf2qt4fwpmejf36pok6yjv_adqssw5c" } [example option2 ] { "card" { "type" "ticket", "subtype" "movies", "data" [{ "refid" "ref-20230304-001", "createdat" 1612660039000, "language" "en", "attributes" { "title" "samsung wallet" *see wallet cards }, "localization" [{ "language" "ko", "attributes" { "title" "삼성월렛" } }] }] } } [example filtered using select parameter ] get /cards/12584806754/ref-20230304-0003?select=idphoto { "card" { "type" "ticket", "subtype" "entrances", "data" [{ "refid" "ref-20230304-0003", "createdat" 1612660039000, "language" "en", "attributes" { "idphoto" "{idphoto data}" } }] } } /** or **/ { "cdata" tokenize{data} } [result] http status code description 200 ok success 204 no content card doesn't exist 400 bad request requests cannot or will not be processed the request due to something that is perceived to be a client error 401 unauthorized authorization token is invalid or expired 500 internal server error server encountered an unexpected condition that prevented it fromfulfilling the request 503 service unavailable server is not ready to handle the request send card state partners can manage the state or history of the card using this api if the card state is changed on the samsung device, samsung calls this api using a refid [request] type value description method post url {partner server url}/cards/{cardid}/{refid} headers authorization string 1024 required credential token the token can have prefix "bearer" as an authorization type, e g , bearer <credentials> * see authorization token /wallet/api_new/references/security html x-request-id string 32 required request identifier randomly generated uuid string path parameters cardid string 32 required wallet card identifier * see the ["add to wallet" interfaces]["add to wallet" interfaces_] refid string 32 required a unique content identifier defined by the content provider query parameters cc2 string 2 required country code cc2 for samsung server api event string 16 required events on wallet carde g , added, updated, deleted, provisioned* see card states for details payload callback string 1024 optional callback url for samsung server api [example] post /cards/12584806754/ref-20230304-001?cc2=us&event=added { "callback" "https //us-tsapi walletsvc samsung com" } [response] type value description http status 200 ok payload n/a example 200 ok [result] http status code description 200 ok success 401 unauthorized authorization token is invalid or expired 500 internal server error server encountered an unexpected condition that prevented it from fulfilling the request 503 service unavailable server is not ready to handle the request samsung server api partners can notify their contents changes with the following api service domain environment domain public domain https //tsapi-card walletsvc samsung com private domain ‘callback’ field from send card state api request payload the domains can be selectively used depending on your service requirement if the service needs to register static ips on your system, we recommend using private domain in this case, use the domain received in the request 'callback' field from send card state api if the service does not require ip registration, public domain can be a good choice in this case, country code cc2 is required as a path parameter to configure integration for each environment, register a new card service and get new card id to guarantee safe communication, servers should configure token-based authentication see authorization token for the details update notification if wallet card data content is updated, send a notification to the samsung server [request] type value description method post url {cc2}/wltex/cards/{cardid}/updates headers authorization string 1024 required credential token the token can have prefix "bearer" as an authorization type, e g , bearer <credentials> * see authorization token x-smcs-partner-id string 32 required partner id x-request-id string 32 required request identifier randomly generated uuid string path parameters cc2 string 2 conditional country code cc2 from send card state * required if using public domain cardid string 32 required wallet card identifier granted from partners portal payload card object required wallet card object card type string 16 required wallet card type * see wallet cards card data[] array of object required wallet card data container data[] refid string 32 required unique content identifier defined by the content provider data[] state string 16 required wallet card state for example, active, updated, expired, redeemed, held, deleted, suspended * see card states for details data[] fields string 128 optional wallet cards attributes which has been updated can be specified using commas , as separators it is used when 'data[] state' is updated e g balance,barcode value* supported wallet card types generic [example] post /wltex/cards/12584806754/notification /** header **/ authorization bearer eyjjdhkioijbvvriiiwidmvyijoxlcjwyxj0bmvyswqioiixmjg1o x-smcs-partner-id partner-id-0001 x-request-id req-202303140003 /** payload **/ /** case 1 in general cases **/ { "card" { "type" "ticket", "data" [ { "refid" "ref-ticket-0001", "state" "updated" } ] } } /** case 2 in case of deletion **/ { "card" { "type" "boardingpass", "data" [ { "refid" "ref-boardingpass-0001", "state" "deleted" } ] } } /** case 3 when a specific field is updated **/ { "card" { "type" "idcard", "data" [ { "refid" "ref-idcard-0001", "state" "updated", "fields" "balance" } ] } } [response] type value description http status 200 ok 204 no content payload n/a example 200 ok [result] http status code description 200 ok success 204 no content card doesn’t exist 400 bad request requests cannot or will not be processed the request due to somethingthat is perceived to be a client error 401 unauthorized authorization token is invalid or expired 500 internal server error server encountered an unexpected condition that prevented it fromfulfilling the request 503 service unavailable server is not ready to handle the request cancel notification if a cancelation happens for events such as performances, sports, movies, and journeys, partners can send a notification about it and set all of the related cards to expire this api does not support updates for specific attributes on the card [request] type value description method post url {cc2}/wltex/cards/{cardid}/cancels headers authorization string 1024 required credential token the token can have prefix "bearer" as an authorization type, e g , bearer <credentials> *see authorization token x-smcs-partner-id string 32 required partner id x-request-id string 32 required request identifier randomly generated uuid string path parameters cc2 string 2 conditional country code cc2 from send card state * required if using public domain cardid string 32 required wallet card identifier granted from the partners portal payload card object required wallet card object card type string 16 required wallet card type * see wallet cards card data[] array of object required wallet card data container data[] eventid string 32 conditional required if card type has been set as ‘ticket’ data[] vehicle number string 32 conditional required if "card type" has been set as "boardingpass" data[] estimated oractualstartdate long 13 data[] state string 16 required wallet card state for example canceled* see card states for details [example] post /wltex/cards/12584806754/cancelation /** header **/ authorization bearer eyjjdhkioijbvvriiiwidmvyijoxlcjwyxj0bmvyswqioiixmjg1o x-smcs-partner-id partner-id-0001 x-request-id req-202303140004 /** payload **/ /** a movie ticket has been canceled **/ { "card" { "type" "ticket", "data" [ { "eventid" "event-722164a1a7", "state" "canceled" } ] } } [response] type value description http status 200 ok payload n/a example 200 ok [result] http status code description 200 ok success 204 no content card doesn’t exist 400 bad request requests cannot or will not be processed the request due to somethingthat is perceived to be a client error 401 unauthorized authorization token is invalid or expired 500 internal server error server encountered an unexpected condition that prevented it fromfulfilling the request 503 service unavailable server is not ready to handle the request
Develop Samsung IAP
docverify a purchase iap/v6/receipt enables your server and client app to verify that a specified in-app product purchase and payment transaction was successfully completed the api returns a json object with a successful status and details about a successful transaction and the product or with a failure status this api can help to prevent malicious purchases and ensure that purchase and payment transactions were successful when the client app experiences network interruptions after a product purchase and payment transaction request get https //iap samsungapps com/iap/v6/receipt?purchaseid={purchaseid value} query parameters parameter type description purchaseid string required unique identifier of the in-app product purchase transactionnote the purchase id is assigned by samsung iap your app receives it in the purchasevo object of the onpaymentlistener interface your app must send the id to your server independently of samsung iap example get http //iap samsungapps com/iap/v6/receipt?purchaseid=7efef23271b0a48746a9d7c391e367c7a802980d391d7f9b75010e8138c66c36 response noteresponse parameters may be added, changed, and deleted parameters parameter type description itemid string unique identifier of the in-app product registered in seller portal paymentid string unique identifier assigned to the in-app product payment transaction when it was successful orderid string unique identifier assigned to the purchase receipt packagename string package name of the app with a completed transaction itemname string title of the in-app product registered in seller portal itemdesc string brief explanation of the in-app product registered in seller portal purchasedate string date and time of the product purchase and payment transaction yyyy-mm-dd hh mm ss gmt paymentamount string total amount, including the in-app product price and all applicable taxes, billed to the user status string processing result of the request for the receipt "success" success"fail" failed"cancel" the purchase transaction was cancelednote for canceled transactions, the old iap/getpurchasereceipt only passed "fail", but the iap/v6/receipt passes "cancel" and transaction information together paymentmethod string type of payment option used to purchase the product"credit card", "mobile micro purchase", "prepaid card", "psms", "carrier billing" and others mode string iap operating mode in effect at the time of purchase "test" developer test mode which always returns success or fail result"production" production mode consumeyn string for consumable items only, whether or not the item has been reported as consumed and is available for purchase again "y" consumed"n" not consumed comsumedate string date and time when the consumable item was reported as consumed yyyy-mm-dd hh mm ss gmt consumedevicemodel string model name of the device that reported the item as consumed acknowledgeyn string whether or not acknowledge that the user has been granted entitlement for the purchased non-consumable item or subscription "y" acknowledged"n" not acknowledged acknowledgedate string date and time when the purchase of non-consumable item or subscription was acknowledged yyyy-mm-dd hh mm ss gmt acknowledgedevicemodel string model name of the device that acknowledged non-consumable item or subscription passthroughparam string deprecated since iap 6 4 0transaction id created by your app for securityreturned only if the pass-through parameter was set note the old iap/getpurchasereceipt passed the base64 encoded value, but the iap/v6/receipt passes the value as it is set in the game currencycode string currency code 3 characters of the purchaser's local currency for example, eur, gbp, usd currencyunit string symbol of the purchaser's local currency for example, €, £, or $ canceldate string for canceled transaction only, date and time the purchase transaction was canceled yyyy-mm-dd hh mm ss gmt note added since iap/v6/receipt obfuscatedaccountid string obfuscated account id which you sent when you called startpayment or changesubscriptionplan obfuscatedprofileid string obfuscated profile id which you sent when you called startpayment or changesubscriptionplan errorcode integer for failed request only, error code errormessage string for failed request only, detailed error message example success { "itemid" "57515", "paymentid" "20191129013006730832tran", "orderid" "s20191129kra1908197", "packagename" "com samsung android test", "itemname" "test pack", "itemdesc" "iap test item best value!", "purchasedate" "2019-11-29 01 32 41", "paymentamount" "100 000", "status" "success", "paymentmethod" "credit card", "mode" "production", "consumeyn" "y", "consumedate" "2019-11-29 01 33 28", "consumedevicemodel" "sm-n960n", "acknowledgeyn" "y", "acknowledgedate" "2025-03-20 06 58 06", "acknowledgedevicemodel" "sm-n960n", "passthroughparam" "test_pass_through", "currencycode" "krw", "currencyunit" "₩", "obfuscatedaccountid" "b2jmdxnjyxrlzefjy291bnrjza==", "obfuscatedprofileid" "b2jmdxnjyxrlzfbyb2zpbgvjza==" } fail errorcode errormessage 1 "fail" 1000 detailed message about an unexpected system error for example, "parsing error" 9135 "not exist order" 9153 "wrong param invalid purchaseid " { "status" "fail", "errorcode" 9135, "errormessage" "not exist order" } canceled purchase transaction { "itemid" "57515", "paymentid" "zpmtid20191128kra1908196", "orderid" "s20191128kra1908196", "itemname" "test pack", "itemdesc" "iap test item best value!", "purchasedate" "2019-11-28 10 18 09", "paymentamount" "0 000", "paymentmethod" "free", "mode" "production", "consumeyn" "y", "consumedate" "2019-11-28 10 18 11", "consumedevicemodel" "sm-g965f", "acknowledgeyn" "y", "acknowledgedate" "2025-03-20 06 58 06", "acknowledgedevicemodel" "sm-n960n", "passthroughparam" "test_pass_through", "currencycode" "krw", "currencyunit" "₩", "status" "cancel", "canceldate" "2019-11-29 00 01 52" } additional samsung iap server apis additional samsung iap server-to-server apis are provided as part of the galaxy store developer api and have different requirements purchase acknowledgment - consume or acknowledge a purchased product check status of subscription - get the subscription status, including subscription information and purchase information the following samsung iap server soap apis have been deprecated and are no longer supported create a service token soap check subscription status soap
tutorials mobile, game
blogselling digital content is a popular business all over the world. if you are interested in selling your digital items in the samsung ecosystem, then you need to learn about the samsung in-app purchase (iap) sdk. you can implement samsung iap in your android, unity, and unreal applications. since server to server communication is more secure and reliable, payment transaction should be verified from the iap server. this is the second of two blogs on this topic. in the first part, we discussed how to integrate samsung’s iap server api into your app’s server. in this blog, we will learn how to communicate with your server through an android app. please go through the documentation of samsung iap sdk to integrate samsung iap sdk in your app. then build your own app server for server verification which is covered in the first part of this blog. to know about server api, read samsung iap server api. get started let’s learn through a simple android game. this game has an item which can only be used for a certain period of time. so, it is a subscription type item. if a user buys this item, then the item will be available after purchase verification. when the app is launched, the app checks if this item is already subscribed or not. there can be one of two results: the item is not subscribed, then the app offers to subscribe this item. the item is subscribed then the app gets the current status of this subscription through getsubscriptionstatus server api. the subscription status can be active or cancel. subscription can be canceled for various reasons. if the iap server returns the subscription status as ‘cancel’ then the app notifies it to the user. implementation of these two cases are discussed in the next sections. implement android iap at first, integrate samsung iap sdk in your android app and register it in the seller office to test in-app items. when the app is launched, call getownedlist() api. it returns a list of in-app items that the app user currently has from previous purchases. if the item is not in this list, then the app offers to purchase the item. to purchase any item, call startpayment(). this api notifies the end user if the purchase succeeded or failed. if the purchase is successful, then do the server verification. if your app’s server validates the purchase, then make the item available to the user, otherwise request user to purchase it again. public void onpayment(errorvo _errorvo, purchasevo _purchasevo) { if (_errorvo != null) { if (_errorvo.geterrorcode() == iaphelper.iap_error_none) { if (_purchasevo != null) { if (mpassthroughparam != null && _purchasevo.getpassthroughparam() != null) { if (mpassthroughparam.equals(_purchasevo.getpassthroughparam())) { if (_purchasevo.getitemid().equals(item_id_subscription)) { mmainactivity.setbackgroundpurchaseid(_purchasevo.getpurchaseid()); new purchaseverification(mmainactivity).execute(_purchasevo.getpurchaseid()); } } } } } } } if the item is available in this list, then detailed information of this item such as purchase id will be available in the ownedproductvo type arraylist. to call getsubscriptionstatus server api, we need the purchase id of the item. so, send this id to your app’s server to get the status of the subscribed item. public void ongetownedproducts(errorvo _errorvo, arraylist<ownedproductvo> _ownedlist) { if (_errorvo != null) { if (_errorvo.geterrorcode() == iaphelper.iap_error_none) { if (_ownedlist != null) { for (ownedproductvo item : _ownedlist) { if (item.getitemid().compareto(itemname.item_id_subscription) == 0) { // check whether subscription is canceled or not. new subscriptiondetails(mmainactivity).execute(item.getpurchaseid()); } } } } else { log.e(tag, "ongetownedproducts errorcode [" + _errorvo.geterrorcode() +"]"); } } } connect your app with your app server create an asynchronous task for communicating with the server. this task has two parts. one is to send purchase id to your app server and the other is to receive the result from the app server. use doinbackground() method for these two tasks. return this result to your main ui through onpostexecute() method. create a class which extends asynctask<string,void,string> for server verification. then write the following code in doinbackground() method to send the purchase id: cookiehandler.setdefault( new cookiemanager( null, cookiepolicy.accept_all ) ); try{ url url = new url("http:// "); //url of your app’ server urlconnection connection = url.openconnection(); connection.setdooutput(true); connection.setdoinput(true); outputstreamwriter out = new outputstreamwriter(connection.getoutputstream(); string y = ""; for(int i = 0;i < x.length;i++) { y = y + x[i]; } out.write(y); out.close(); }catch(exception e){ } receive to the server verification result using the following code: string output = ""; bufferedreader in = new bufferedreader(new inputstreamreader(connection.getinputstream())); string s = ""; while((s = in.readline())!= null) { output = output + s; in.close(); } return output; now, create an interface called serverresponse and implement it in an activity where you want to show the result from your app’s server. public interface serverresponse { void processfinish(string output); } after receiving the result from the server, return the result to your main ui through onpostexecute() method. protected void onpostexecute(string result) { serverresponse.processfinish(result); } test your app let’s test the app. upload your web app onto a server. then use that url in your app to check server verification in doinbackground() method. keep in mind that samsung in-app purchase can’t be tested in an emulator of android studio. so use a samsung device to test your app. read the test guide before starting to test your app. a simple android game is attached at the end of this article where app to server communication is implemented. this game has a blue background image which can be subscribed. if this item is not in an active subscription period, then the app offers to subscribe the background. if the user purchases the item, then the game verifies the purchase through the server. if the purchase is verified, then it shows that the subscription status is activated and the app makes the item available. if the user unsubscribes the item from the galaxy store, subscription status becomes ‘cancel’. however, as the active subscription period has not ended yet, the item is still available in the app. wrapping up in these two blogs, we have covered the full communication between your app, server and iap server. now you will be able to implement purchase verification through your server. if your app is free but has some premium contents, then you can monetize your app. samsung in-app purchase provides many ways to earn money from your app. go to galaxy store games to find out more details about it. download the simple android game from galaxy store download the simple android game from here 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.
Jakia Sultana
We use cookies to improve your experience on our website and to show you relevant advertising. Manage you settings for our cookies below.
These cookies are essential as they enable you to move around the website. This category cannot be disabled.
These cookies collect information about how you use our website. for example which pages you visit most often. All information these cookies collect is used to improve how the website works.
These cookies allow our website to remember choices you make (such as your user name, language or the region your are in) and tailor the website to provide enhanced features and content for you.
These cookies gather information about your browser habits. They remember that you've visited our website and share this information with other organizations such as advertisers.
You have successfully updated your cookie preferences.