Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Recommendations
Filter
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. 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 application called book spot, which offers users the option to subscribe to their favorite books and consumable items, such as text fonts, for purchase. after purchase, users can consume the item. finally, developers can view all their payment and refund history on specific dates by calling the samsung iap orders api from the back-end server. prerequisites before implementing in-app purchases in your app, do the following to enable a smooth and effective execution of the process while developing your own application: integrate the samsung iap sdk into your application. for more information about the iap sdk integration, you can follow the integration of samsung iap services in android apps article. upload the application for beta testing on samsung galaxy store. a step-by-step guide with screenshots has been provided in the documentation. for more details, see the section “production closed beta test” on the test guide. finally, create items on the seller portal so that users can purchase or subscribe to them while using the application. for more details about the available items that the seller portal supports, see the programming guide. for the sample application, we have already completed these steps. some example items were already created in seller portal, such as books and fonts so that you can consume and subscribe to them while using this sample application. implementation of item purchase now that the application and items are ready, you can implement the purchase functionality in your application like in the sample below: when clicking "buy," the startpayment() method is called, specifying parameters for item id and the onpaymentlistener interface, which handles the results of the payment transaction. the onpayment() callback returns whether the purchase has succeeded or failed. the purchasevo object is instantiated and in case it is not null, it holds the purchase results. if the purchase is successful, then it validates the purchase showing its id. if the purchase is not successful, a purchaseerror message is shown. for more information, check the purchase an in-app item section. iaphelper.startpayment(itemid, string.valueof(1), new onpaymentlistener() { @override public void onpayment(@nonnull errorvo errorvo, @nullable purchasevo purchasevo) { if (purchasevo != null) { // purchase successful log.d("purchaseid" , purchasevo.getpurchaseid().tostring()); toast.maketext(getapplicationcontext() ,"purchase successfully", toast.length_short).show(); } else { log.d("purchaseerror" , errorvo.tostring()); toast.maketext(getapplicationcontext() ,"purchase failed", toast.length_short).show(); } } }); implementation of item consumption after successfully purchasing an item, the user can then consume it. in the sample code below, when "consumed" is selected, the consumepurchaseitems() triggers the consume functionality. this is necessary as items must be marked as consumed so they can be purchased again: the consumepurchaseitems() method is called specifying the parameters for purchaseid and the onconsumepurchaseditemslistener() interface, which handles the item data and results. this code also checks if consuming the purchased items succeeded or failed: if the errorvo parameter is not null and there is no error with the purchase, which can be verified with the iap_error_none response code, then the “purchase acknowledged” message is displayed. however, if there is an error, the errorvo parameter returns an error description with the geterrorstring() getter, along with the “acknowledgment failed” message. iaphelper.consumepurchaseditems(purchaseid, new onconsumepurchaseditemslistener() { @override public void onconsumepurchaseditems(@nonnull errorvo errorvo, @nonnull arraylist<consumevo>arraylist) { if (errorvo != null && errorvo.geterrorcode() == iaphelper.iap_error_none) { toast.maketext(getapplicationcontext() ,"purchase acknowledged", toast.length_short).show(); } else { toast.maketext(getapplicationcontext(), "acknowledgment failed: " + errorvo.geterrorstring(), toast.length_short).show(); } } }); implementation of item subscription besides purchasing and consuming items, you can also subscribe to them in your applications. similar to the validation done for the consumable item purchase, you validate the subscription with a purchase id if the purchase is successful. use the same code snippet specified for “item purchase.” for more information, check the implementation of item purchase section. implementation of the samsung iap orders api the samsung iap orders api is used to view all payments and refunds on a specific date. it does this by fetching the payments and refunds history within the date you specified. let’s implement the samsung iap orders api and create a server to listen to its notifications. through server-to-server communication, the api returns all orders data for the application. configuring the server you can develop a spring boot server for this purpose. here are the guidelines on how to set up this server: set up a spring boot project. for more information, follow the steps on 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. get payment and refund history 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 for this date is returned. otherwise, it only returns all the data from the day before the current date. api endpoint: https://devapi.samsungapps.com/iap/seller/orders method: post headers: add the following fields to the request header. for more information, see the create an access token page, which helps you understand how to create the access token in detail. the token is used for authorization. you can also get the service account id by clicking the assistance > api service tabs on seller portal. for more details, read the section create a service account and visit seller portal. header name description required/optional values content-type format of the request body required application/json authorization authorization security header required bearer: access_token service account id this id can be created in seller portal and is used to generate the json web token (jwt) required service-account-id parameters: the following parameters can be used to build your post request. name type required/optional description sellerseq string required your seller deeplink, which is found in your profile in seller portal and consists of a 12-digit number. packagename string optional used to view payment and refund data. you can provide the application package name. when a package name is not specified, the data for all applications is shown. requestdate string optional specify a date from which to view the payment and refund data. if the date is not specified, the data from a day before your current date is returned. continuationtoken string optional use this if you want to check if there is a continuation for the data on the next page. if there is no more data, the response is null. to implement rest api support, add the following okhttp library dependencies to your application's build.gradle file: implementation 'com.squareup.okhttp3:okhttp: version' implementation 'com.google.code.gson:gson: version' a detailed description of the request items can be found in the request section of the samsung iap orders api documentation. for more information on the server communication, see samsung iap server api. here is a brief summary of the code below: a post request is mapped to the /orders url, which logs the request. the previously described parameters containing the data you specified are formatted in a json body using the string.format() method. the outgoing request is logged in a json body format. a requestbody is instantiated containing the json data, formatted for an http request to be sent to the server with the specified token and service account id. this code also handles multiple results your request can return: the onfailure() method is called when the network request fails for some reason, providing any error details using the ioexception exception. if the request succeeds, the onresponse() method returns the response body or any response exception found. @restcontroller @requestmapping(value = "/iap", method = requestmethod.post) public class orderscontroller { private final okhttpclient client = new okhttpclient(); @getmapping("/orders") public void sendtoserver() { system.out.println("post request received"); // log the request // define parameters values, use according to your requirement // string packagename = "com.example.app_name "; // string requestdate = "20240615"; // string continuationtoken = "xxxxxxxxxxx…….xxxxxx"; string sellerseq = "0000000xxxxx"; // create the json body, use packagename, requestdate, continuationtoken according to your requirement string jsonbody = string.format( "{\"sellerseq\":\"%s\"}", sellerseq ); // create the request body requestbody body = requestbody.create(jsonbody, mediatype.parse("application/json; charset=utf-8")); // access token string token = "0djt9yzryukdogbvulxxxxxx"; // build the request request request = new request.builder() .url("https://devapi.samsungapps.com/iap/seller/orders") .post(body) .addheader("authorization","bearer " + token) .addheader("service-account-id", "85412253-21b2-4d84-8ff5-xxxxxxxxxxxx") .addheader("content-type", "application/json") .build(); client.newcall(request).enqueue(new callback() { @override public void onfailure(@notnull call call, @notnull ioexception e) { system.err.println("request failed: " + e.getmessage()); } @override public void onresponse(@notnull call call, @notnull response response) throws ioexception { if (response.issuccessful()) { string responsebody = response.body().string(); system.out.println("response: " + responsebody); } else { system.err.println("unexpected response code: " + response.code()); system.err.println("response body: " + response.body().string()); } response.close(); // close the response body } }); } } congratulations! you have just built the spring boot server to handle api post requests using the okhttpclient to manage http requests and responses for your sample application. example response as previously mentioned, a json-formatted response is returned to your request. for detailed descriptions of each response body element, see the “response” section of the samsung iap orders api documentation. the following output format is a sample in which only some of the response-body data is presented. in this case, the continuationtoken parameter key returns null because there is no continuation for the data on the next page. the orderitemlist parameter key lists all the orders with specific details, such as orderid, countryid, packagename, among others. { "continuationtoken": null, "orderitemlist": [ { "orderid": "s20230210kr019xxxxx", "purchaseid": "a778b928b32ed0871958e8bcfb757e54f0bc894fa8df7dd8dbb553cxxxxxxxx", "contentid": "000005059xxx", "countryid": "usa", "packagename": "com.abc.xyz" }, { "orderid": "s20230210kr019xxxxx", "purchaseid": "90a5df78f7815623eb34f567eb0413fb0209bb04dad1367d7877edxxxxxxxx", "contentid": "000005059xxx", "countryid": "usa", "packagename": "com.abc.xyz" }, ] } usually, the responses contain all the relevant information about user purchases, such as the in-app item title, price, and payment status. therefore, you can use the information and create views for an easier order management. 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 item purchase, consumption, and registration, as well as how to integrate the samsung iap orders api and configure a server to fetch all the payment and refund history within specific dates. integrating the samsung iap orders api functionality into your server is an essential step in managing your application payments history to ensure a seamless experience to users. now, you can implement the samsung iap orders api into your application to track all payments, refunds and make your business more manageable. related resources for additional information on this topic, see the resources below: download the android sample 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
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
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 items 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 an item 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 item list get /iap/v6/applications/ packagename/items request a list of item information within a scope appropriate for the page and size view individual item get /iap/v6/applications/ packagename/items/ id request detailed information on one item create item post /iap/v6/applications/ packagename/items register an in-app item modify item put /iap/v6/applications/ packagename/items modify an in-app item partial item modification patch /iap/v6/applications/ packagename/items modify the specified parameters of an in-app item remove item delete /iap/v6/applications/ packagename/items/ id remove an in-app item see in-app purchase for more information about iap functionality in seller portal view item list request a list of item 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 items 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 item registered in seller portal title string title of the in-app item registered in seller portal description string brief explanation of the in-app item registered in seller portal type string in-app item type consumable an item that can be purchased one or more times and remains effective or available in the app until it is used one time for example, coins, special powers, or gems 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 unspecified an unknown item type status string item distribution status in seller portal published item is for sale in galaxy store unpublished item is not available in galaxy store removed item has been removed from galaxy store unspecified item status is not known itempaymentmethod phonebillstatus boolean whether or not the item is paid with an automatic payment on a phone bill true the item is paid by an automatic payment on a phone bill false the item 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 item the price can be set between 0 and 400 prices[] countryid string three-character country code iso 3166 of the country where the item 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 item in the specified country's currency totalcount number number of items listed in the response success status 200 success { "itemlist" [ { "id" "one_gallon_gas", "title" "1 gallon gas", "description" "fuel for driving game", "type" "consumable", "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 item request detailed information about one item request get /iap/v6/applications/ packagename/items/ id name type description id string required unique identifier of the in-app item 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 item 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" "consumable", "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 item register an in-app item request post /iap/v6/applications/com package name/items name type description id string required unique identifier of the in-app item registered in seller portal title string required title of the in-app item registered in seller portal description string required brief explanation of the in-app item registered in seller portal type string required in-app item type consumable an item that can be purchased one or more times and remains effective or available in the app until it is used one time for example, coins, special powers, or gems 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 unspecified an unknown item type status string required item distribution status in seller portal published item is for sale in galaxy store unpublished item is not available in galaxy store removed item has been removed from galaxy store unspecified item status is not known itempaymentmethod phonebillstatus boolean required whether or not the item is paid with an automatic payment on a phone bill true the item is paid by an automatic payment on a phone bill false the item 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 item the price can be set between 0 and 400 prices[] countryid string required three-character country code iso 3166 of the country where the item 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 item 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" "consumable","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" "consumable", "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 item modify an in-app item the request replaces all existing information, except the content id, of the item tipto modify an app, use the response from view individual item to create the input required for this request request put /iap/v6/applications/ packagename/items see create item 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" "consumable","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" "consumable", "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 item modification modify the title, countryid, or localprice of an in-app item 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 item registered in seller portal title string title of the in-app item registered in seller portal prices[] countryid string three-character country code iso 3166 of the country where the item is sold prices[] localprice string price of the item 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" "consumable", "status" "published" } see failure response codes for a list of possible response codes when a request fails remove item remove an in-app item request delete /iap/v6/applications/ packagename/items/ id name type in description id string path required unique identifier of the in-app item 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 01400 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 item does not exist 409conflict 105 the item 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 0 unitypackage 225kb mar 19, 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 items 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 items purchased in operation_mode_production mode are considered owned items operation_mode_test startpayment requests are processed as specified, except financial transactions do not occur licensed testers are not billed for item 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 items purchased in operation_mode_test mode are considered owned items in order to purchase in-app items, 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 items for free all other users see an error message if they try to purchase an in-app item 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 items 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 items 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 subscription items all returns all purchased non-consumable items, consumable items that have not been consumed and active subscription items noteboth purchased consumable items that were previously reported as consumed and expired subscription items 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 items and api call processing get in-app item details use the getproductsdetails method to get detailed information for example, item id, price, and description about some or all of the in-app items 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 items specify an empty string "" to get information about all registered items code snippet // get information about 3 in-app items samsungiap instance getproductsdetails "com mygame product1, com mygame product2, com mygame product3", ongetproductsdetails ; // get information about all in-app items samsungiap instance getproductsdetails "", ongetproductsdetails ; after processing is complete, the ongetproductsdetails callback is triggered, which contains information about the specified items and api call processing purchase an in-app item use the startpayment method to initiate a purchase and payment transaction for a specified in-app item 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 item, 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 item, 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 item 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 item, 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 items 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 item 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 items 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 item information orderid string unique identifier assigned to the purchase receipt purchaseid string unique identifier of the in-app item 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 item is sold packagename string package name of the application registered in seller portal itemid string unique identifier of the in-app item registered in seller portal itemtitle string title of the in-app item 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 item was purchased for example, $ localcurrencycode string three-character currency code iso 4217 of the country's currency where the item was purchased for example, eur, gbp, usd localprice string price of the item in the country where the item 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 item is a subscription, the origin order id of the subscription freetrialyn string if the item is purchased during a free trial period y the item was purchased during a free trial period n the item was not purchased during a free trial period tieredsubscriptionyn string if the item is purchased as a lower-tier/introductory or regular-tier/regular subscription y the item was purchased as a lower-tier or introductory subscription n the item 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 items subscription - cancel, refund, revoke or check the status of iap subscription items 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 items 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 item 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 item purchase transaction the following example shows the url path for creating an item 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
tutorials mobile, game
blogselling digital content is a popular business all over the world. if you are interested in selling your digital items in the samsung ecosystem, then you need to learn about the samsung in-app purchase (iap) sdk. you can implement samsung iap in your android, unity, and unreal applications. since server to server communication is more secure and reliable, payment transaction should be verified from the iap server. this is the second of two blogs on this topic. in the first part, we discussed how to integrate samsung’s iap server api into your app’s server. in this blog, we will learn how to communicate with your server through an android app. please go through the documentation of samsung iap sdk to integrate samsung iap sdk in your app. then build your own app server for server verification which is covered in the first part of this blog. to know about server api, read samsung iap server api. get started let’s learn through a simple android game. this game has an item which can only be used for a certain period of time. so, it is a subscription type item. if a user buys this item, then the item will be available after purchase verification. when the app is launched, the app checks if this item is already subscribed or not. there can be one of two results: the item is not subscribed, then the app offers to subscribe this item. the item is subscribed then the app gets the current status of this subscription through getsubscriptionstatus server api. the subscription status can be active or cancel. subscription can be canceled for various reasons. if the iap server returns the subscription status as ‘cancel’ then the app notifies it to the user. implementation of these two cases are discussed in the next sections. implement android iap at first, integrate samsung iap sdk in your android app and register it in the seller office to test in-app items. when the app is launched, call getownedlist() api. it returns a list of in-app items that the app user currently has from previous purchases. if the item is not in this list, then the app offers to purchase the item. to purchase any item, call startpayment(). this api notifies the end user if the purchase succeeded or failed. if the purchase is successful, then do the server verification. if your app’s server validates the purchase, then make the item available to the user, otherwise request user to purchase it again. public void onpayment(errorvo _errorvo, purchasevo _purchasevo) { if (_errorvo != null) { if (_errorvo.geterrorcode() == iaphelper.iap_error_none) { if (_purchasevo != null) { if (mpassthroughparam != null && _purchasevo.getpassthroughparam() != null) { if (mpassthroughparam.equals(_purchasevo.getpassthroughparam())) { if (_purchasevo.getitemid().equals(item_id_subscription)) { mmainactivity.setbackgroundpurchaseid(_purchasevo.getpurchaseid()); new purchaseverification(mmainactivity).execute(_purchasevo.getpurchaseid()); } } } } } } } if the item is available in this list, then detailed information of this item such as purchase id will be available in the ownedproductvo type arraylist. to call getsubscriptionstatus server api, we need the purchase id of the item. so, send this id to your app’s server to get the status of the subscribed item. public void ongetownedproducts(errorvo _errorvo, arraylist<ownedproductvo> _ownedlist) { if (_errorvo != null) { if (_errorvo.geterrorcode() == iaphelper.iap_error_none) { if (_ownedlist != null) { for (ownedproductvo item : _ownedlist) { if (item.getitemid().compareto(itemname.item_id_subscription) == 0) { // check whether subscription is canceled or not. new subscriptiondetails(mmainactivity).execute(item.getpurchaseid()); } } } } else { log.e(tag, "ongetownedproducts errorcode [" + _errorvo.geterrorcode() +"]"); } } } connect your app with your app server create an asynchronous task for communicating with the server. this task has two parts. one is to send purchase id to your app server and the other is to receive the result from the app server. use doinbackground() method for these two tasks. return this result to your main ui through onpostexecute() method. create a class which extends asynctask<string,void,string> for server verification. then write the following code in doinbackground() method to send the purchase id: cookiehandler.setdefault( new cookiemanager( null, cookiepolicy.accept_all ) ); try{ url url = new url("http:// "); //url of your app’ server urlconnection connection = url.openconnection(); connection.setdooutput(true); connection.setdoinput(true); outputstreamwriter out = new outputstreamwriter(connection.getoutputstream(); string y = ""; for(int i = 0;i < x.length;i++) { y = y + x[i]; } out.write(y); out.close(); }catch(exception e){ } receive to the server verification result using the following code: string output = ""; bufferedreader in = new bufferedreader(new inputstreamreader(connection.getinputstream())); string s = ""; while((s = in.readline())!= null) { output = output + s; in.close(); } return output; now, create an interface called serverresponse and implement it in an activity where you want to show the result from your app’s server. public interface serverresponse { void processfinish(string output); } after receiving the result from the server, return the result to your main ui through onpostexecute() method. protected void onpostexecute(string result) { serverresponse.processfinish(result); } test your app let’s test the app. upload your web app onto a server. then use that url in your app to check server verification in doinbackground() method. keep in mind that samsung in-app purchase can’t be tested in an emulator of android studio. so use a samsung device to test your app. read the test guide before starting to test your app. a simple android game is attached at the end of this article where app to server communication is implemented. this game has a blue background image which can be subscribed. if this item is not in an active subscription period, then the app offers to subscribe the background. if the user purchases the item, then the game verifies the purchase through the server. if the purchase is verified, then it shows that the subscription status is activated and the app makes the item available. if the user unsubscribes the item from the galaxy store, subscription status becomes ‘cancel’. however, as the active subscription period has not ended yet, the item is still available in the app. wrapping up in these two blogs, we have covered the full communication between your app, server and iap server. now you will be able to implement purchase verification through your server. if your app is free but has some premium contents, then you can monetize your app. samsung in-app purchase provides many ways to earn money from your app. go to galaxy store games to find out more details about it. download the simple android game from galaxy store download the simple android game from here follow up this site has many resources for developers looking to build for and integrate with samsung devices and services. stay in touch with the latest news by creating a free account or by subscribing to our monthly newsletter. visit the marketing resources page for information on promoting and distributing your apps. finally, our developer forum is an excellent way to stay up-to-date on all things related to the galaxy ecosystem.
Jakia Sultana
product_updates mobile, game
newsdownload the latest samsung in-app purchase (iap) sdk and start selling in-app items from your app in galaxy store. samsung in-app purchase sdk v6.1.1 (7 mb) 3/15/2024 samsung iap sdk v6.1.1 includes enhancements for payment security, distributes the aar library instead of the project file, and updates the minsdkversion and targetsdkversion. use the plugins to integrate with unity and unreal engines. see samsung in-app purchase for more information about using the sdk.
tutorials game, mobile
bloggalaxy store, a default app store bundled with millions of samsung galaxy devices, is a top destination for gamers. it has a highly customizable iap (in-app purchase) system that supports three types of iap items: consumables, which are used once and must be repurchased to use again non-consumables, which has unlimited uses after purchase subscriptions, which allows unlimited uses for a fixed duration the samsung iap plugin supports unreal engine, an advanced 3d game engine with next-generation graphics and features, popular among professional game developers. unreal engine 5 is officially supported since samsung iap plugin version 6.1.4, enabling you to integrate samsung iap into your unreal engine games. this article demonstrates how you can integrate the samsung iap plugin into unreal engine games to enable users to purchase iap items. prerequisites the samsung iap plugin version 6.1.4 supports unreal engine versions 4.18 and higher. basically, if your tools can build and run an unreal engine 5 game for android devices, you can implement the samsung iap plugin features in your game. the demonstration in this article uses the following recommended development environment: unreal engine 5.1 visual studio 2022 android sdk: android sdk api level 32 or higher android ndk r25b cmake 3.10.2 build tools 33 setting up the development environment to set up your unreal engine game project to implement the samsung iap plugin: in the unreal engine global settings, check that you have defined the target sdk version, minimum sdk version, android sdk location, android ndk location, java location, sdk api level, and ndk api level for your project. open an existing unreal engine project or create a new project. the code examples in this article assume an unreal engine c++ project. go to edit > project settings > platforms > android and set the following properties: android package name: define the package name for your project. minimum sdk version: the version must be 26 or higher. target sdk version: the version must be 32 or higher. package game data inside apk: fill the checkbox. this is required because samsung galaxy store seller portal only supports uploading single apk files. figure 1: android project settings in unreal engine download the unreal iap plugin from the samsung developers website. extract the content of the downloaded file to an empty folder inside the plugins* folder of your project directory. if the <project folder>/plugins/ folder does not exist, you must create it. figure 2: create the "plugins” folder in the <project folder>/source/<project name>/ folder, open the <project name>.build.cs file. to add the samsung iap plugin to the project dependencies, in the publicdependencymodulenames.addrange() section, add samsungiap to the list: publicdependencymodulenames.addrange(new string[] { "core", "coreuobject", "engine", "inputcore", "enhancedinput", "samsungiap" }); to enable the plugin within unreal engine, relaunch unreal engine. go to edit > plugins > installed > service and fill the checkbox next to samsung iap plugin. relaunch unreal engine to ensure the plugin is enabled and ready to use in your project. figure 3: enable samsung iap plugin in unreal engine registering the game and iap items before samsung iap functionalities can be integrated into your game, the game and its iap items must be registered in samsung galaxy store seller portal: in unreal engine, go to edit > project settings > platforms > android and make sure you have defined the android package name for the project and that package game data inside .apk is enabled. to build the .apk file, in the unreal engine toolbar, select platforms > android > package project. register your game application in samsung galaxy store seller portal, filling in the required information. in the binary tab of seller portal, upload your game’s apk file. to enable testing the iap functionalities while developing the game, create a closed beta test. in the binary tab, select add beta test and register your testers and feedback channel for the closed beta test. for more information, see beta test. in the in-app purchase tab, create your iap items and activate them. for demonstration purposes, the game in this tutorial has two consumable items: "buysuperspeed" and "buysuperjump." to save your game and iap item details, select save. for more information about registering applications and in-app items, see register an app and in-app items in seller portal. integrating in-app purchases now that the game application and its iap items have been registered, you can begin implementing the samsung iap features in your code. step 1: include the header file to access the samsung iap functions in your project, you must add the header file to the project code: in unreal engine, select tools > refresh visual studio project. to open and edit the project code in visual studio, select tools > open visual studio. open the c++ code file where you want to implement the iap functions. include the samsung iap plugin header file in your code. #include "iap.h" step 2: set the iap operation mode the samsung iap plugin has three operation modes: iap_mode_test: for development and testing. iap_mode_production: for public beta and production releases. iap_mode_test_failure: for testing failure cases. in this mode, all requests return failure responses. set the operation mode using the setoperationmode(<iap mode>) function. since the game is in development, use "iap_mode_test." the #if platform_android directive ensures multi-platform compatibility by compiling and executing the code block for the android platform only, avoiding errors that can be caused when compiling for other platforms. #if platform_android samsung::iap::setoperationmode(iap_mode_test); #endif step 3: create and set a listener class the samsung iap library has four main api functions: getproductdetails() retrieves a list of products and their details. getownedlist() retrieves a list of the user’s owned items. startpayment() initiates a purchase. consumepurchaseditems() consumes a purchased item. each of these functions requires a listener or callback function that handles the data returned from the iap library function: ongetproducts() is the listener for getproductdetails(). ongetownedproducts() is the listener for getownedlist(). onpayment() is the listener for startpayment(). onconsumepurchaseditems() is the listener for consumepurchaseditems(). create a skeleton listener class with these callback functions. in the following examples, a c++ class named samsungiaplistener has been created in unreal engine, generating the samsungiaplistener.cpp and samsungiaplistener.h files in the project source directory. in the samsungiaplistener.h file, define the class: #pragma once #include "coreminimal.h" #include "iap.h" class samsungiaplistener : public samsung::iaplistener { public: void ongetproducts(int result, const fstring& msg, const std::vector<samsung::productvo>& data); void ongetownedproducts(int result, const fstring& msg, const std::vector<samsung::ownedproductvo>& data); void onpayment(int result, const fstring& msg, const samsung::purchasevo& data); void onconsumepurchaseditems(int result, const fstring& msg, const std::vector<samsung::consumevo>& data); }; in the samsungiaplistener.cpp file, create skeleton code for the callback functions: #include "samsungiaplistener.h" using namespace std; using namespace samsung; #if platform_android void samsungiaplistener::ongetproducts(int result, const fstring& msg, const vector<productvo>& data) { } void samsungiaplistener::ongetownedproducts(int result, const fstring& msg, const vector<ownedproductvo>& data) { } void samsungiaplistener::onpayment(int result, const fstring& msg, const purchasevo& data) { } void samsungiaplistener::onconsumepurchaseditems(int result, const fstring& msg, const vector<consumevo>& data) { } #endif in the main code file, to set the samsungiaplistener listener class that was just created as the iap listener class for the project, use the setlistener() function. #include "samsungiaplistener.h" #if platform_android samsung::iap::setoperationmode(iap_mode_test); samsung::iap::setlistener(new samsungiaplistener); #endif step 4: retrieve purchasable items to retrieve the list of available iap items, use the getproductdetails() function: samsung::iap::getproductdetails(""); the iap library returns the available items list in the parameters of the ongetproducts() callback function. the data variable contains the list, from which you can extract its member variables and handle them in unreal engine as needed. for instance, you can use the ongetproducts() callback function to display the list of available items and their prices in the game: void samsungiaplistener::ongetproducts(int result, const fstring& msg, const vector<productvo>& data) { for (auto& i : data) { printmessage(fstring::printf(text("%s price = %s"), *i.mitemname, *i.mitempricestring)); } } figure 4: list of available items retrieved you can also retrieve the details for a specific item by placing its item id in the string parameter of the getproductdetails() function. for example, getproductdetails("buysuperjump") retrieves only the details for the buysuperjump item. step 5: retrieve owned items to ensure that the user’s previously purchased iap items are available in the game, when the game is launched, retrieve the list of items that they own, using the getownedlist() function: samsung::iap::getownedlist(product_type_all); the ongetownedproducts() callback function receives the owned item list. you can use it to perform tasks such as restoring the purchased items’ functionalities in the game, and checking for and consuming any consumable items in the user’s account that have not been consumed yet. it is important to consume the consumable items as soon as possible, because they cannot be repurchased until they are consumed. void samsungiaplistener::ongetownedproducts(int result, const fstring& msg, const vector<ownedproductvo>& data) { if (data.size() == 0) { printmessage(fstring::printf(text("no previously owned items"))); } else { for (auto& i : data) { samsung::iap::consumepurchaseditems(*i.mpurchaseid); printmessage(fstring::printf(text("consuming owned item: %s"), *i.mitemname)); } } } step 6: purchase items initiate purchasing an item with the startpayment() function. in this example, the user wants to purchase the item with the item id “buysuperjump:” samsung::iap::startpayment("buysuperjump", "pass_through_value", true); when the function is called, the screen switches to portrait mode and displays the checkout ui. the user selects their payment method and confirms the payment. when galaxy store successfully processes the payment, the item is added to the user’s owned item list. to check whether the item has been added to the user’s owned item list, you can use the getownedlist() function. figure 5: samsung iap checkout ui remember that consumable items remain on the user’s owned item list and cannot be repurchased until the item is consumed. ideally, apply the item’s game effect and consume the item as soon as it is purchased. since the result of the startpayment() function is returned to the onpayment() callback function, you can extend this callback function to do tasks with the item after completing the payment. in our example game, the variable jumpheight is set to 500. when the user buys the “buysuperjump” item, the jump height is doubled. this game effect can be implemented within the onpayment() callback function. void samsungiaplistener::onpayment(int result, const fstring& msg, const purchasevo& data) { fstring sjump = text("buysuperjump"); if(sjump.equals(*data.mitemid)){ jumpheight = 1000; superjumpsavailable++; samsung::iap::consumepurchaseditems(*data.mpurchaseid); printmessage(fstring::printf(text("super jump purchased"))); } } step 7: consume purchased items to consume a previously purchased item, you must first retrieve its purchase id. the purchase id can be found within the data variable in the callback function for the startpayment() and getownedlist() functions. you can implement consuming the item directly from the callback function with the consumepurchaseditems() function, in the same way as previously demonstrated. samsung::iap::consumepurchaseditems(*data.mpurchaseid); when an item is consumed through the consumepurchaseditems() function, the onconsumepurchaseditems() callback function is triggered. in this callback function, make sure that the result of the purchase has been stored locally before the iap item is consumed and removed from the user’s owned item list. void samsungiaplistener::onconsumepurchaseditems(int result, const fstring& msg, const vector<consumevo>& data) { for (auto& i : data) { printmessage(fstring::printf(text("item successfully consumed"))); } } results and summary with the samsung iap feature fully integrated into our example unreal engine game, we can test the iap functionality within the game. purchasing the “buysuperjump” item triggers a chain of iap library functions that acquires the item and consumes the item to implement its game effect: startpayment() function initiates the payment process. onpayment() callback function reacts to the successful payment: a. changes the user’s jump height in the game to 1000. b. displays the message “super jump purchased.” c. calls the consumepurchaseditems() function. consumepurchaseditems() function consumes the purchased item, removing it from the user’s owned items. onconsumepurchaseditems() callback function reacts to consuming the item, displaying the message “item successfully consumed.” figure 6: “buysuperjump” item successfully purchased and consumed this demonstration has shown how easy it is to integrate samsung iap in an unreal engine 5 game. with only a few library functions, you can implement any samsung iap functionalities that you want in games made with unreal engine. to learn more about how samsung iap works, see our previous article integration of samsung iap services in android apps. if you have questions about or need help with the information in this article, you can share your queries on the samsung developers forum.
Mobassir Ahsan
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.