Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
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-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
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
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
Develop Samsung IAP
docsamsung iap publish api the samsung iap publish api is used to view, register, modify, and remove samsung in-app purchase iap products before you can start using the iap publish api, you must meet all requirements and use the required authorization header parameters in your requests see get started with the iap apis for more information noteusing the iap publish api to register, modify, or delete a product immediately changes it within the content, even when the content is in the for sale state the following is a quick reference to the iap publish apis name request description view product list get /iap/v6/applications/ packagename/items request a list of product information within a scope appropriate for the page and size view individual product get /iap/v6/applications/ packagename/items/ id request detailed information on one product create product post /iap/v6/applications/ packagename/items register an in-app product modify product put /iap/v6/applications/ packagename/items modify an in-app product partial product modification patch /iap/v6/applications/ packagename/items modify the specified parameters of an in-app product remove product delete /iap/v6/applications/ packagename/items/ id remove an in-app product see in-app purchase for more information about iap functionality in seller portal view product list request a list of product information within a scope appropriate for the page and size request get /iap/v6/applications/ packagename/items?page={}&size={} name type in description page int query required number of pages of content to return size int query required number of products to be returned on a page curl \ -x get \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ "https //devapi samsungapps com/iap/v6/applications/com package name/items?page=1&size=20" response parameters name type description id string unique identifier of the in-app product registered in seller portal title string title of the in-app product registered in seller portal description string brief explanation of the in-app product registered in seller portal type string in-app product type item goods and services that charge users on a one-time basis non_consumable an item that is purchased only once and remains effective or available in the app at all times, even after deletion and re‑installation of the app for example, game boards or an upgrade starting from june 2025, the non_consumable type has been deprecated, and the ability to register new non-consumable items through the publish api will no longer be possible please refer to the programming guide for more information status string product distribution status in seller portal published product is for sale in galaxy store unpublished product is not available in galaxy store removed product has been removed from galaxy store itempaymentmethod phonebillstatus boolean whether or not the product is paid with an automatic payment on a phone bill true the product is paid by an automatic payment on a phone bill false the product is not paid by an automatic payment on a phone bill usdprice number the base price in usd united states of america dollars of the product the price can be set between 0 and 400 prices[] countryid string three-character country code iso 3166 of the country where the product is sold prices[] currency string three-character currency code iso 4217 of the specified country's currency for example, eur, gbp, usd prices[] localprice string price of the product in the specified country's currency totalcount number number of products listed in the response success status 200 success { "itemlist" [ { "id" "one_gallon_gas", "title" "1 gallon gas", "description" "fuel for driving game", "type" "item", "status" "published", "itempaymentmethod" { "phonebillstatus" true }, "usdprice" 0 900, "prices" [ { "countryid" "kor", "currency" "krw", "localprice" "1000 000" }, { "countryid" "usa", "currency" "usd", "localprice" "0 900" }, ] }, ], "totalcount" 3 } see failure response codes for a list of possible response codes when a request fails view individual product request detailed information about one product request get /iap/v6/applications/ packagename/items/ id name type description id string required unique identifier of the in-app product registered in seller portal curl \ -x get -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ "https //devapi samsungapps com/iap/v6/applications/com package name/items/one_gallon_gas" response see view product response parameters for a description of the response parameters success status 200 success { "id" "one_gallon_gas", "title" "1 gallon gas", "description" "fuel for driving game", "type" "item", "status" "published", "itempaymentmethod" { "phonebillstatus" true }, "usdprice" 0 900, "prices" [ { "countryid" "kor", "currency" "krw", "localprice" "1000 000" }, { "countryid" "usa", "currency" "usd", "localprice" "0 900" }, ] } see failure response codes for a list of possible response codes when a request fails create product register an in-app product request post /iap/v6/applications/com package name/items name type description id string required unique identifier of the in-app product registered in seller portal title string required title of the in-app product registered in seller portal description string required brief explanation of the in-app product registered in seller portal type string optional in-app product type item goods and services that charge users on a one-time basis status string required product distribution status in seller portal published product is for sale in galaxy store unpublished product is not available in galaxy store removed product has been removed from galaxy store itempaymentmethod phonebillstatus boolean required whether or not the product is paid with an automatic payment on a phone bill true the product is paid by an automatic payment on a phone bill false the product is not paid by an automatic payment on a phone bill usdprice number required the base price in usd united states of america dollars of the product the price can be set between 0 and 400 prices[] countryid string required three-character country code iso 3166 of the country where the product is sold prices[] currency string three-character currency code iso 4217 of the specified country's currency for example, eur, gbp, usd prices[] localprice string required price of the product in the specified country's currency curl \ -x post \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ -d '{"id" "one_gallon_gas","title" "1 gallon gas","description" "fuel for driving game","type" "item","status" "published","itempaymentmethod" {"phonebillstatus" true},"usdprice" 0 99,"prices" [{"countryid" "kor","currency" "krw","localprice" "1000"},{"countryid" "usa","currency" "usd","localprice" "0 99"}]}' \ "https //devapi samsungapps com/iap/v6/applications/com package name/items" response success status 200 success { "id" "one_gallon_gas", "type" "item", "status" "published", "prices" [ { "countryid" "kor", "currency" "krw", "localprice" "1000 000" }, { "countryid" "usa", "currency" "usd", "localprice" "0 99" }, ] } see failure response codes for a list of possible response codes when a request fails modify product modify an in-app product the request replaces all existing information, except the content id, of the product tipto modify an app, use the response from view individual product to create the input required for this request request put /iap/v6/applications/ packagename/items see create product request for a description of the request parameters curl \ -x put \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ -d '{"id" "one_gallon_gas","title" "1 gallon gas","description" "fuel for driving game fix","type" "item","status" "published","itempaymentmethod" {"phonebillstatus" true},"usdprice" 1,"prices" [{"countryid" "kor","currency" "krw","localprice" "1000"},{"countryid" "usa","currency" "usd","localprice" "1"}]}' \ "https //devapi samsungapps com/iap/v6/applications/com package name/items" response success status 200 success { "id" "one_gallon_gas", "type" "item", "status" "published", "prices" [ { "countryid" "kor", "currency" "krw", "localprice" "1000 000" }, { "countryid" "usa", "currency" "usd", "localprice" "1" }, ] } see failure response codes for a list of possible response codes when a request fails partial product modification modify the title, countryid, or localprice of an in-app product the id cannot be modified parameters that are not specified are not modified request patch /iap/v6/applications/ packagename/items name type description id string required unique identifier of the in-app product registered in seller portal title string title of the in-app product registered in seller portal prices[] countryid string three-character country code iso 3166 of the country where the product is sold prices[] localprice string price of the product in the specified country's currency curl \ -x patch \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ -d '{"id" "one_gallon_gas","title" "2 gallon gas"}' \ "https //devapi samsungapps com/iap/v6/applications/com package name/items" response success status 200 success { "id" "one_gallon_gas", "type" "item", "status" "published" } see failure response codes for a list of possible response codes when a request fails remove product remove an in-app product request delete /iap/v6/applications/ packagename/items/ id name type in description id string path required unique identifier of the in-app product registered in seller portal curl \ -x delete -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ "https //devapi samsungapps com/iap/v6/applications/com package name/items/one_gallon_gas" response success status 200 ok { "id" "one_gallon_gas" } see failure response codes for a list of possible response codes when a request fails failure response codes the following are response codes you may see when the request fails status code and message 400bad request 109 subscription is not yet supported117 price is under minimum value for example, the local price of 0 69 is lower than the minimum price of 0 99 118 price is lower than minimum unit for example, the local price of 1 099 does not match the minimal price unit of 0 01119 price exceeds maximum value120 non-consumable type is no longer supported400 bad request with wrong in-app product information 401unauthorized 101 user doesn't have permission to change this app103 failed to verify gateway server authorization 404not found 104 content doesn't exist please create content first 106 itemgroup doesn't exist in production level need to publish iap-supported app 110 product does not exist 409conflict 105 the product already exists with the requested id107 there are multiple itemgroupids or itemids with the requested packagename
Develop Samsung IAP
docunity plugin samsungiap_unity_plugin_v6 3 2 unitypackage 225kb sep 17, 2025 the samsung iap unity plugin comes with all the content necessary for your integration integrate samsung iap into your app this section explains how to use samsung in-app purchase iap functionality by integrating the samsung iap unity plugin system requirements to avoid compatibility issues, the plugin requires the following tools unity hub android sdk unity 2017 3 1 or later noteplease double check the version of all tools otherwise it will cause compatibility issues import samsung iap plugin download the plugin file in unity, click assets → import package → custom pacakge check plugins folder which contains all samsung iap related scripts and libraries notefor details about samsung iap method calls, see the programming guide implement samsung iap this section explains the fundamental aspects of integrating samsung iap functionality into your android app by making plugin method calls to support the offering and sale of in-app products samsung iap script drag-and-drop the samsungiap script into the gameobject of your choice set the iap operation mode use the setoperationmode method to set the operation mode cautionensure the operation mode is set to operation_mode_production before submitting for beta test or normal publication in other words, operation_mode_test or operation_mode_test_failure must be set only if the app status in seller portal is registering or updating mode description operation_mode_production startpayment requests are processed as specified, financial transactions do occur for successful requests, and actual results are returned successful or failed note for all other iap requests only products purchased in operation_mode_production mode are considered owned products operation_mode_test startpayment requests are processed as specified, except financial transactions do not occur licensed testers are not billed for product purchases , and successful results are always returned for details of the payment window shown in operation_mode_test mode, see the payment window note for all other iap requests only products purchased in operation_mode_test mode are considered owned products in order to purchase in-app products, testers must be registered as a license tester in the seller's seller portal profile in this mode, licensed testers always get your in-app products for free all other users see an error message if they try to purchase an in-app product operation_mode_test_failure all iap requests fail it is meant to be negative testing to ensure that your app can handle errors such as improper input and user actions code snippet samsungiap instance setoperationmode operationmode operation_mode_test ; get user-owned products requirementyou must call getownedlist whenever launching the application in order to check for unconsumed items or subscription availability use the getownedlist method to get information about some or all of the products the user has already purchased product type description item returns all purchased non-consumable items, consumable items that have not been consumed subscription returns all active subscriptions all returns all purchased non-consumable items, consumable items that have not been consumed and active subscriptions noteboth purchased consumable items that were previously reported as consumed and expired subscriptions are not returned code snippet samsungiap instance getownedlist itemtype all, ongetownedlist ; after processing is complete, the ongetownedlist callback is triggered, which contains information about the specified purchased products and api call processing get in-app product details use the getproductsdetails method to get detailed information for example, item id, price, and description about some or all of the in-app products registered to your app that are available for user purchase specify one or more unique in-app item id values comma delimited to get information about the specified products specify an empty string "" to get information about all registered products code snippet // get information about 3 in-app products samsungiap instance getproductsdetails "com mygame product1, com mygame product2, com mygame product3", ongetproductsdetails ; // get information about all in-app products samsungiap instance getproductsdetails "", ongetproductsdetails ; after processing is complete, the ongetproductsdetails callback is triggered, which contains information about the specified products and api call processing purchase an in-app product use the startpayment method to initiate a purchase and payment transaction for a specified in-app product you can specify your own pass-through parameter and use it for purchase and payment verification code snippet samsungiap instance startpayment "com mygame product1", "pass_through_value", onpayment ; after processing is complete, the onpayment callback is triggered, which contains information about the purchased product, the transaction, and api call processing acknowledge a purchased consumable item use the consumepurchaseditems method and the purchase id of a consumable in-app item to enable it to be purchased again whether or not the user has actually used the item your app receives an item's purchaseid in the onpayment and ongetownedlist callbacks specify one or more unique purchaseid values, comma delimited code snippet samsungiap instance consumepurchaseditems "purchaseid_1, purchaseid_2, purchaseid_3", onconsume ; after processing is complete, the onconsume callback is triggered, which contains information about the consumed item and api call processing get promotion eligibility for subscription use the getpromotioneligibility method to get the pricing options of a subscription, such as free trials and introductory prices, applicable to the customer specify one or more unique subscription id values, comma delimited code snippet samsungiap instance getpromotioneligibility "subscitemid_1, subscitemid_2", ongetpromotioneligibility ; after processing is complete, the ongetpromotioneligibility callback is triggered, which contains information about the pricing policy list and api call processing change subscription plan use the changesubscriptionplan method to allow your customer to change their existing subscription to another tier of the same subscription proration mode description instant_prorated_date the subscription is upgraded or downgraded immediately any time remaining is adjusted based on the price difference and credited toward the new subscription by pushing forward the next billing date there is no any additional payment instant_prorated_charge for upgraded subscriptions only the subscription is upgraded immediately but the billing cycle remains the same the price difference for the remaining period is then charged to the user instant_no_proration for upgraded subscriptions only the subscription is upgraded immediately and the new price is charged when the subscription renews the billing cycle remains the same deferred the subscription is upgraded or downgraded when the subscription renews when the subscription renews, the new price is charged a downgrade is always executed with this mode see proration modes for more details about the four modes code snippet samsungiap instance changesubscriptionplan "olditemid", "newitemid", prorationmode instant_prorated_charge, "pass_through_value", onchangesubscriptionplan ; after processing is complete, the onchangesubscriptionplan callback is triggered, which contains information about the purchased product, the transaction, and api call processing
Develop Samsung IAP
docsamsung iap orders api the samsung in-app purchase iap orders api is used to view all payments and refunds on a specific date before you can start using the iap orders api, you must meet all requirements and use the required authorization header parameters in your requests see get started with the iap apis for more information view payments and refunds view all payments and refunds on a specific date request post /iap/seller/orders name type description sellerseq string required your seller deeplink in seller portal, a 12-digit number to find your seller deeplink, log in to seller portal and go to profile > information for seller page packagename string optional the package name of the app for which you want to view payment and refund data if no packagename is specified, data is returned for all apps to find an app's package name, log in to seller portal, go to apps, select the app, open the binary tab, and click the file name requestdate string optional the specific day for which you want to view payments and refunds if no date is specified, yesterday's date is used format yyyymmdd continuationtoken string optional request the next page of payment/refund data a page contains up to 100 products if a continuationtoken is not specified, the first page of data is displayed if more than one page of data is available, the response includes a continuationtoken use this token to request the next page of data if the continuationtoken returned in the response is null, this means the previous page of data is the last page to contain product information curl \ -x post \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" \ -d '{"sellerseq" "000123456789","packagename" "com samsung android sample","requestdate" "20230615","continuationtoken" "e5ec039730164c50277f9a231b74c1b6e035d9184160d8b3d6b3de1f62691328fbe4c0c4863da52b3bcecef44a4c7acb974c674728c3cb173cb339bd41783f2c"}' \ "https //devapi samsungapps com/iap/seller/orders" use cases parameters included data retrieved sellerseq yesterday's payments and refunds for all apps sellerseq, packagename yesterday's payments and refunds for the specified app sellerseq, requestdate payments and refunds for all apps for the specified date sellerseq, packagename, requestdate payments and refunds for the specified app and the specified date response parameters name type description continuationtoken string if more than 1 page of data 100 products is available to view, a continuationtoken is sent in order to request and view the next page of data if the continuationtoken is null, this means the previous page of data is the last page to contain product information orderid string unique identifier assigned to the purchase receipt purchaseid string unique identifier of the in-app product purchase transaction contentid string content id of the application registered in seller portal countryid string three-character country code iso 3166 of the country where the product is sold packagename string package name of the application registered in seller portal itemid string unique identifier of the in-app product registered in seller portal itemtitle string title of the in-app product registered in seller portal status string order status 2 payment successfully completed3 payment canceled refund if you want to test the "payment canceled" status, contact customer support at seller portal > help > contact us > contact us at the customer center include the orderid of the purchase so that we can change the order status to "payment canceled " ordertime datetime timestamp utc when the order was requested completiontime datetime timestamp utc when the payment was successfully completed refundtime datetime timestamp utc when the payment was canceled by the admin localcurrency string currency symbol of the country's currency where the product was purchased for example, $ localcurrencycode string three-character currency code iso 4217 of the country's currency where the product was purchased for example, eur, gbp, usd localprice string price of the product in the country where the product was purchased usdprice string price in u s dollars usd exchangerate string usd exchange rate at the time of purchase mcc string sim card country code subscriptionorderid string if the purchased product is a subscription, the origin order id of the subscription freetrialyn string if the subscription is purchased during a free trial period y the subscription was purchased during a free trial period n the subscription was not purchased during a free trial period tieredsubscriptionyn string if the subscription is purchased as a lower-tier/introductory or regular-tier/regular subscription y the subscription was purchased as a lower-tier or introductory subscription n the subscription was purchased as a regular-tier or regular subscription { "continuationtoken" "5b5496f44417c9f6b42c8768cbd3f5b5621cdd4021308af81c1e49b77602e9074ab", "orderitemlist" [ { "orderid" "s20230210kr01922227", "purchaseid" "a778b928b32ed0871958e8bcfb757e54f0bc894fa8df7dd8dbb553c81b048343", "contentid" "000005059222", "countryid" "usa", "packagename" "com samsung android sample" }, { "orderid" "s20230210kr01922227", "purchaseid" "90a5df78f7815623eb34f567eb0413fb0209bb04dad1367d7877edfa136321", "contentid" "000005059222", "countryid" "usa", "packagename" "com samsung android sample" }, ] } see failure response codes for a list of possible response codes when a request fails failure response codes the following are response codes you may see when the request fails status code and message 400bad request slr_4001 seller is not matchedslr_4009 continuation token is invalidslr_4010 decrypted continuation token consists of invalid data typeslr_4011 date format is invalid use the format yyyymmdd 401unauthorized slr_4008 failed to verify gateway server authorization
Develop Samsung IAP
docget started with the samsung iap apis the samsung in-app purchase iap apis provide the following functionality orders - view payments and refunds for a specific date publish - view, register, modify, and remove iap products purchase acknowledgment - consume or acknowledge a purchased product subscription - cancel, refund, revoke or check the status of iap subscriptions to start using the iap apis, you must meet certain requirements and use the required authorization header parameters described below requirements in order to use the iap apis, the following is required the iap apis are part of the galaxy store developer api you must meet all of the requirements of the galaxy store developer api including, but not limited to, creating the access token, including the access token in the authorization header of every iap api call, and having commercial seller status to manage in-app purchase products the iap apis must be connected with the content in the in app purchase tab area of seller portal to create this connection, you must either initially distribute your content using the content publish api or the content must be in the for sale state in seller portal if this connection does not exist, matching product information cannot be retrieved you must integrate the iap sdk into your app all binaries registered in your content must support iap if these requirements are not met, error code 106 is returned authorization header parameters every request must include authorization header parameters which specify the content type, your access token, and service account id see create an access token for more information about how to create an access token and service account id attribute description authorization required use bearer <your-access-token> where <your-access-token> is the access token you requested from the galaxy store authentication server service-account-id required the service account id used to create the jwt associated with the access token can be found in the assistance > api service area of seller portal content-type required must be application/json the following example shows the header used with the iap apis curl -x <iap_publish-or-iap_order-or-iap_subscription_api_request> \ -h "content-type application/json" \ -h "authorization bearer <your-access-token>" \ -h "service-account-id <your-service-account-id>" url path parameters the url path for every iap publish and subscription api request must contain the package name for the iap orders api, the package name may be required in the body parameter for the iap subscription api, the in-app product purchase transaction identifier is also required attribute description packagename required for iap order and subscription apis the app's package name purchaseid required for iap subscription api unique identifier of the in-app product purchase transaction the following example shows the url path for creating an in-app product using the iap publish api https //devapi samsungapps com/iap/v6/applications/<packagename>/items the following example shows the url path for canceling, refunding, or revoking a subscription using the iap subscription api https //devapi samsungapps com/iap/seller/v6/applications/<packagename>/items/purchases/subscriptions/<purchaseid>
tutorials game, mobile
bloggalaxy store is one of the top app stores to sell your android games in many different countries. you can also sell various in-app purchase (iap) items inside your games using the samsung iap sdk. as many of you now use the unity engine to develop your games, samsung has introduced a unity plugin for the samsung iap sdk that enables you to implement iap features. follow the steps outlined in this blog to easily implement the unity plugin into your project and utilize the samsung iap functionalities. prerequisites it is assumed you are already familiar with the samsung iap procedure. if not, please read the iap sdk programming guide carefully before proceeding further. after that, download the samsung iap unity plugin package and go through its documentation. to avoid compatibility issues, make sure you meet the system requirements. there are three types of iap items: consumable: can be used only one time and re-purchasable non-consumable: can be used any number of times and not re-purchasable subscription: can be used any number of times while it is active for this example, we have developed a basic coin collecting game in unity for android and added ui buttons that allow users to buy iap items (consumable and non-consumable) and a subscription. the “buy super jump” button initiates purchasing a super jump item from galaxy store using the samsung iap sdk. super jump is a consumable item which enables the player to jump higher than normal. similarly, the “upgrade player” button initiates purchasing a player upgrade, which is a non-consumable item. this blog only covers consumable and non-consumable purchases, we’ll discuss subscriptions in a future blog. figure 1: preview of the sample game developed in unity. note: you are required to develop your game/application in unity beforehand to integrate the iap unity plugin into it. integrate the samsung iap unity plugin after creating the game in unity, you need to enable samsung iap functionalities in your project. follow the steps below: import the samsung iap unity plugin package into the project. in unity, click assets -> import package -> custom package and select the downloaded plugin package. you can now see the plugins folder under your assets folder and the “samsungiap.cs” script at assets/plugins/script. copy or move the “samsungiap.cs” script into the default scripts folder of your project (where all the scripts are kept together) so that other scripts can access it easily. if you don’t already have a scripts folder, create a new one and keep all your project scripts together along with “samsungiap.cs.” create an empty game object in the hierarchy tab and drag-and-drop the “samsungiap.cs” script onto it. in our sample project, we have renamed the game object as “samsungiap.” click on the “samsungiap” game object and check if the iap functionality is enabled in the inspector, as shown below: figure 2: samsung iap is enabled for the project. set the iap operation mode iap supports three operational modes. the production mode is for enabling billing for item purchases and the other two are for testing iap functions without billing the game users for item purchases. the default operation mode is set to operation_mode_test with the return value as success, but you can set the return value to failure instead, or switch to operation_mode_production by checking (√) the production build checkbox in the inspector as shown in figure 2. you can learn more about the iap operation modes and how they work from here. register the game and iap items in seller portal to process/test the samsung iap operations, both your game and any iap items need to be registered in seller portal. follow the steps below: ensure you have switched the platform of your game to android and the package name is different from the apps registered in other app stores. you can rename the package name of your project from player settings -> other settings. save your unity project and build the apk file. in unity, go to file -> build settings and then click the build button. follow the steps listed in register an app and in-app items in seller portal and complete the registration of your game and iap items accordingly. for our sample game, we have registered a consumable and a non-consumable item with the ids “buysuperjump” and “buyupgradedplayer” respectively. keep the item ids in mind as they will be required when initiating the purchases. you can add testers (non-licensed and licensed) in the binary tab of seller portal while registering your game in the manner covered in the previous step. licensed testers are not charged for purchasing any iap items. you can register the licensed testers in your seller portal profile. see iap testing for more information. get previously purchased items make sure to retrieve any previously purchased non-consumable and unconsumed items every time the user starts the game. use the getownedlist() method of the iap plugin to get information about the items the user has already purchased. however, please note there is a script called “player.cs” in our project which is added to the main player game object as a component. from now on we will be editing the code in “player.cs” to enable all the samsung iap functions for this project. follow the steps below: add the following line at the beginning to access the samsung iap libraries in this script. using samsung; call the getownedlist() method whenever the game launches by adding the following line at the beginning of the start() method. learn more about the getownedlist() method here. samsungiap.instance.getownedlist(itemtype.all, ongetownedlist); after the processing of the getownedlist() method is completed, the ongetownedlist callback is triggered, which receives information about the specified purchased items and api call processing. we need to implement this callback method under the same class as in the following; void ongetownedlist(ownedproductlist _ownedproductlist){ if(_ownedproductlist.errorinfo != null){ if(_ownedproductlist.errorinfo.errorcode == 0){// 0 means no error if(_ownedproductlist.results != null){ foreach(ownedproductvo item in _ownedproductlist.results){ if(item.mconsumableyn == "y"){ //consume the consumable items and onconsume callback is triggered afterwards samsungiap.instance.consumepurchaseditems(item.mpurchaseid, onconsume); } if(item.mitemid == "buysuperjump"){ superjump++; } else if(item.mitemid == "buyupgradedplayer"){ playermaterial = resources.load<material>("playermaterial"); meshrenderer meshrenderer = getcomponent<meshrenderer>(); meshrenderer.material = playermaterial; } } } } } as you can see, some actions have been taken inside the game depending on the respective item ids. for example, the super jump counter has been increased and the material of the player gets changed. if there is any consumable item which has not been reported as consumed, then the consumepurchaseditems() method is invoked. we describe this method in the next section. consume purchased consumable items use the consumepurchaseditems() method to report the purchased consumable item as consumed, which enables the item to be purchased again. see acknowledge a purchased consumable item to understand this process better. when the process of the consumepurchaseditems() method in the previous section is finished, the item data and processing results are returned to the onconsume callback method. we need to implement this method in the same way under the same class as we implemented the ongetownedlist method earlier. void onconsume(consumedlist _consumedlist){ if(_consumedlist.errorinfo != null){ if(_consumedlist.errorinfo.errorcode == 0){ if(_consumedlist.results != null){ foreach(consumevo item in _consumedlist.results){ if(item.mstatuscode == 0){ //successfully consumed and ready to be purchased again. } } } } } } get purchasable iap items the users may want to see details of the available iap items in the store for the game. the getproductsdetails() method helps to retrieve detailed information (for example, item name, price, or id) about the iap items registered in your game that are available for users to purchase. there is a ui button “available items” in our sample game for querying the purchasable items. after clicking this button, brief information for each item is presented in a simple dropdown list next to the button (see figure 3). to get the list of available items: declare a button variable and a dropdown variable in the beginning of the “player.cs” script. public button getproductsbutton; public dropdown itemlist; add a listener method for the “available items” button at the end of the start() method. getproductsbutton.onclick.addlistener(ongetproductsbutton); to initiate the getproductsdetails() method, we need to implement the listener ongetproductsbutton() method. void ongetproductsbutton(){ //get all the product details samsungiap.instance.getproductsdetails("", ongetproductsdetails); } after the processing is completed on the server side, the ongetproductsdetails callback is triggered, which contains information about the available iap items. implement this callback method and add information of each item to the dropdown method so that the users can see them easily. in the example, we show only the item name and price. void ongetproductsdetails(productinfolist _productlist){ if (_productlist.errorinfo != null){ if (_productlist.errorinfo.errorcode == 0){// 0 means no error if (_productlist.results != null){ itemlist.clearoptions(); list<string> optionitems = new list<string>(); int i = 1; foreach (productvo item in _productlist.results){ string temp = i+ ". " + item.mitemname + ": $ " + item.mitemprice; optionitems.add(temp); i++; } itemlist.addoptions(optionitems); } } } } figure 3: showing the available iap items in the game. the information about all iap items is shown in the dropdown menu as a list. you can show only one specific item or more items by specifying their ids in the getproductsdetails() method if you want. learn more about the method here. purchase iap items there are two ui buttons (see figures 1 and 3) in our sample game, namely “buy super jump” and “upgrade player,” for purchasing consumable and non-consumable items, respectively. the variables for these two buttons are declared in the beginning of the start() method and two listener methods: onbuysuperjumpbutton() and onupgradeplayerbutton() are added at the end of the start() method of “player.cs” script. consequently, tapping on these buttons invokes the corresponding methods in the script. follow the steps below to complete in-app purchasing: to enable the “buy super jump” and the “upgrade player” buttons purchasing a super jump and a player upgrade, we need to instantiate the startpayment() method inside the button listeners with the corresponding item ids.void onbuysuperjumpbutton(){ //purchase a consumable item samsungiap.instance.startpayment("buysuperjump", "", onpayment); } void onupgradeplayerbutton(){ //purchase a non-consumable item samsungiap.instance.startpayment("buyupgradedplayer", "", onpayment); } after the payment processing is completed, the onpayment callback is triggered, which contains information about the purchased item, the transaction, and api call processing. we need to implement this callback method and act according to the item ids as in the following:void onpayment(purchasedinfo _purchaseinfo){ if(_purchaseinfo.errorinfo != null){ if(_purchaseinfo.errorinfo.errorcode == 0){ if(_purchaseinfo.results != null){ //your purchase is successful if(_purchaseinfo.results.mconsumableyn == "y"){ //consume the consumable items samsungiap.instance.consumepurchaseditems(_purchaseinfo.results.mpurchaseid, onconsume); } if(_purchaseinfo.results.mitemid == "buysuperjump"){ superjump++; } else if(_purchaseinfo.results.mitemid == "buyupgradedplayer"){ playermaterial = resources.load<material>("playermaterial"); meshrenderer meshrenderer = getcomponent<meshrenderer>(); meshrenderer.material = playermaterial; } } } } } for the consumepurchaseditems() method, we have already implemented the onconsume listener method. in this way, in-app purchasing is fully implemented for both consumable and non-consumable items. next, build the project, run it on your galaxy device, and check that the iap works flawlessly. in addition, you may update the apk of your game in seller portal and submit a beta version for more iap testing. see the test guide to learn more about testing. do not forget to switch the iap operation mode to operation_mode_production before submitting the game to be published. conclusion this tutorial explains the entire procedure of integrating the samsung iap unity plugin and using the iap functionalities for a sample game. therefore, we hope that you can make use of this tutorial and develop an in-app purchase enabled game for galaxy store using unity and sell your game items successfully to generate revenue. follow up this site has many resources for developers looking to build for and integrate with samsung devices and services. stay in touch with the latest news by creating a free account or by subscribing to our monthly newsletter. visit the marketing resources page for information on promoting and distributing your apps. finally, our developer forum is an excellent way to stay up-to-date on all things related to the galaxy ecosystem.
Md. Abulkalam Azad
Learn Code Lab
codelabimplement in-app subscriptions using samsung iap objective learn how to integrate the samsung in-app purchase sdk into your application so that users can purchase and upgrade subscriptions directly within the app overview the samsung in-app purchase iap service provides developers with a reliable solution for managing digital purchases within mobile applications it guarantees a smooth and secure experience for users when buying digital goods, managing subscriptions, or processing refunds and consumed products the iap sdk enables easy integration of the iap functionality into your app, such as configuring iap, retrieving product details, offering and selling products, and managing purchased products to successfully sell in-app products, follow these four basic steps download and integrate the samsung iap sdk into your application request for commercial seller status in the samsung galaxy store seller portal upload your application's binary file in the seller portal add in-app products to your app by integrating in-app purchases iap , your apps can sell in-app products, including subscriptions a subscription is a specific type of in-app product available for purchase through your app in the galaxy store when a user buys a subscription, it grants access for a set duration known as the subscription period or payment cycle at the end of this period, the subscription automatically renews, allowing the user to continue using the product for another subscription period and to be automatically billed with the subscription price for more information, go to samsung iap set up your environment you will need the following android studio latest version recommended samsung iap sdk latest version samsung galaxy device android 6 0 or higher samsung galaxy store seller portal commercial seller account sample code here is a sample code for you to start coding in this code lab download it and start your learning experience! in-app subscription bookspot sample code 1 2 mb start your project in android studio, click open to open an existing project locate the downloaded android project bookspot_blank_code from the directory and click ok register the app and its associated subscriptions in the seller portal to register the sample app along with the in-app products in the samsung galaxy store seller portal, follow these steps sign in using your commercial seller account in android studio, modify the package name of the sample app navigate to app > kotlin + java > com example bookspot view, and in the mainactivity java file, refactor the application name bookspot from the package name com example bookspot for all directories notethe package name com example bookspot is already registered in the seller portal to avoid any conflicts, rename it with a different package name next, open the app > manifests > androidmanifest xml file and check that all necessary permissions are present com samsung android iap permission billing to connect to iap and enable in-app product registration in the seller portal android permission internet because iap uses the internet <uses-permission android name="com samsung android iap permission billing" /> <uses-permission android name="android permission internet" /> build the apk from android studio and upload the binary to the seller portal once the testing process is complete and the app functions smoothly as intended, return to this step and upload the final apk file in the in app purchase tab, add the subscriptions with item ids as basic and standard these are the item ids of the subscriptions created in the sample app select subscription as the item type click the price setting button to set the subscription price noteto learn more about pricing, see manage subscription pricing provide the details for the payment cycle, free trial period, and free trial/tiered pricing limit as shown below noteincluding a free trial promotion for your app is optional to test the functionality of the getpromotioneligibility api, you can add a free trial select all subscriptions you added and click activate lastly, add a license tester to enable purchasing within the app edit your seller portal profile and include your samsung account in the license test field on the test device, sign in with the same samsung account initialize the samsung iap sdk before using the samsung iap sdk library samsung-iap-6 4 0 aar , ensure that it is added to the app > libs folder and included as a dependency in the module-level build gradle file dependencies { implementation filetree dir 'libs', include ['* aar'] } next, open the mainactivity java file in the oncreate function, create an instance of iaphelper and set the operation mode to operation_mode_test this mode enables only license testers to test the application without incurring charges iaphelper = iaphelper getinstance getapplicationcontext ; iaphelper setoperationmode helperdefine operationmode operation_mode_test ; notebefore submitting the app for beta testing or release, change the operation mode to operation_mode_production get product details and check the promotion eligibility to obtain information about subscriptions registered in the store related to your app, use the getproductsdetails api you can retrieve details about a specific subscription by providing the argument named itemid with values such as basic or standard you can use an empty string "" as the argument to obtain all product details iaphelper getproductsdetails itemid, new ongetproductsdetailslistener { @override public void ongetproducts @nonnull errorvo errorvo, @nonnull arraylist<productvo> productlist { if errorvo geterrorcode == iaphelper iap_error_none { for productvo item productlist { itemname settext item getitemname +" level course" ; itemtype settext "item type "+item gettype ; itemprice settext "item price "+item getitemprice +item getcurrencyunit ; itemduration settext "item duration "+item getsubscriptiondurationunit ; subscriptiondialogbutton setonclicklistener dialogbtnlistener ; getpromotioneligibility item getitemid ; } } else { log e "ongetproducts error ", errorvo geterrorstring ; } } } ; after getting the product details, check the promotion eligibility use the getpromotioneligibility api to return the pricing options for a subscription, including free trials and introductory prices that may apply to the user iaphelper getpromotioneligibility itemid, new ongetpromotioneligibilitylistener { @override public void ongetpromotioneligibility @nonnull errorvo errorvo, @nonnull arraylist<promotioneligibilityvo> pricinglist { if errorvo geterrorcode == iaphelper iap_error_none { for promotioneligibilityvo pricing pricinglist { itempricing settext "promotion eligibility "+pricing getpricing ; } } else { log e "ongetpromotioneligibility error ", errorvo geterrorstring ; } } } ; initiate the payment process and acknowledge the subscription to initiate a purchase and complete the payment transaction process, use the startpayment api the result of the purchase is specified through the onpaymentlistener interface, which provides detailed purchase information in the event of a successful transaction once the app has granted entitlement to the user, notify samsung iap of the successful transaction using the acknowledgepurchases api additionally, call the handlechangeplan function to make the change plan button visible and to set the onclicklistener iaphelper startpayment itemid, new onpaymentlistener { @override public void onpayment @nonnull errorvo errorvo, @nullable purchasevo purchasevo { if errorvo geterrorcode == iaphelper iap_error_none && purchasevo != null { acknowledgepurchases purchasevo getpurchaseid ; handlechangeplan itemid ; } else { log e "onpayment error ", errorvo geterrorstring ; } } } ; use the acknowledgepurchases api as below iaphelper acknowledgepurchases purchaseid, errorvo, acknowledgedlist -> { if errorvo geterrorcode == iaphelper iap_error_none { for acknowledgevo item acknowledgedlist { log e "onacknowledgepurchases ", item getstatusstring ; } } else { log e "onacknowledgepurchases error ", errorvo geterrorstring ; } } ; manage changes to subscription plans the changesubscriptionplan api allows users to switch between different tiers of the same subscription changes can be categorized as follows upgrade - moving from a lower-priced tier to a higher-priced tier, or switching between tiers of equal value downgrade - transitioning from a higher-priced tier to a lower-priced tier you can use proration modes to set the payment and current subscription period settings there are four proration modes available instant_prorated_date, instant_prorated_charge, instant_no_proration, and deferred in this code lab, use instant_prorated_date so that the current subscription is changed instantly, allowing the user to start using the new subscription tier right away iaphelper changesubscriptionplan itemid, newitemid, helperdefine prorationmode instant_prorated_date, new onchangesubscriptionplanlistener { @override public void onchangesubscriptionplan @nonnull errorvo errorvo, @nullable purchasevo purchasevo { if errorvo geterrorcode == iaphelper iap_error_none && purchasevo != null { handlechangeplan newitemid ; updatechangeplanview newitemid ; } else { log e "onchangesubscriptionplan error ", errorvo geterrorstring ; } } } ; notefor more details on handling changes to subscription plans, see manage subscription plan changes retrieve and process the list of subscriptions the getownedlist api retrieves a list of in-app products that the user has previously purchased, including active subscriptions and free trials call the getownedlist api from the iaphelper class and obtain the results through the ongetownedlistlistener interface utilize the helperdefine product_type_subscription parameter to fetch only subscription data after acquiring the subscription list, check the acknowledgment status of each subscription using the getacknowledgedstatus function and check whether all of the subscriptions are being acknowledged by samsung iap if any of the subscription status is not acknowledged, then call the acknowledgepurchases function to notify the acknowledgement to samsung iap if the subscription price has changed in the seller portal, it may be necessary for existing subscribers to consent to the price increase before the next subscription period, depending on certain conditions to determine if consent is required from the subscriber, use the getpricechangemode and isconsented functions if consent is needed, call the handleconsent function to make the consent button visible, and set the onclicklistener for the button accordingly iaphelper getownedlist helperdefine product_type_subscription, new ongetownedlistlistener { @override public void ongetownedproducts @nonnull errorvo errorvo, @nonnull arraylist<ownedproductvo> ownedlist { if errorvo geterrorcode == iaphelper iap_error_none { for ownedproductvo item ownedlist { // check the acknowledgedstatus helperdefine acknowledgedstatus acknowledgedstatus = item getacknowledgedstatus ; if acknowledgedstatus equals helperdefine acknowledgedstatus not_acknowledged { acknowledgepurchases item getpurchaseid ; } // handle the price change if item getitemid equals item1 || item getitemid equals item2 { handlechangeplan item getitemid ; subscriptionpricechangevo subscriptionpricechangevo = item getsubscriptionpricechange ; if subscriptionpricechangevo != null && subscriptionpricechangevo getpricechangemode equals helperdefine pricechangemode price_increase_user_agreement_required && !subscriptionpricechangevo isconsented { handleconsent item getitemid , item getpurchaseid ; } } } } else { log e "getownlist error ", errorvo geterrorstring ; } } } ; to create a deep link to the consent page when needed, use the following code uri deeplinkuri = uri parse "samsungapps //subscriptiondetail?purchaseid="+purchasedid ; intent intent = new intent intent action_view, deeplinkuri ; startactivity intent ; run the app after building the apk, install the app on a samsung galaxy device to test the app, click on view details in the basic tab this displays the purchase details, including promotion eligibility, item type, duration, and price then, click on continue to subscribe in the samsung checkout pop-up, select your payment method and click the subscribe button a payment confirmation screen appears upon successful completion of the transaction when the change plan button appears, click on it a pop-up shows the changes in your subscription plan click next and then subscribe using your payment method a payment confirmation screen appears, and the view changes to the standard tab, where you can see the details of your new subscription noteto test and display the consent button, you must increase the price of any subscription in the seller portal the price update will be applied in the galaxy store after a waiting period of 7 days the subscription renews every 10 minutes and will expire in operation_mode_test mode to test the change in the subscription price, set the operation mode to operation_mode_production you're done congratulations! you have successfully achieved the goal of this code lab now, you can implement in-app subscriptions using samsung iap into your application by yourself! if you are having trouble, you may download this file in-app subscription bookspot complete code 1 3 mb to learn more about developing apps with samsung iap sdk, visit developer samsung com/iap
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.