Implementing "Add to Wallet" in an Android Application
samsung wallet is a fast and secure digital wallet application bundled with millions of samsung galaxy devices worldwide. its streamlined functionality allows users to add and store various passes, tickets, and credentials all in one place. you can design custom wallet cards, such as for boarding passes, tickets, coupons, gift cards and loyalty cards, for your service and issue them to users who can add them to the samsung wallet application on their device. samsung wallet cards are signed with the rs256 asymmetric algorithm. the rs256 signing algorithm requires a private key, which is a personal credential that must never be shared in the application. consequently, a separate server application is needed to store the key and sign the wallet card data (cdata). when the user taps the "add to samsung wallet" button in the application, the server application creates and signs the wallet card data, then returns a jwt token that is used to add the wallet card to the user's samsung wallet application. figure 1: "add to wallet" flow this tutorial uses kotlin to demonstrate how to implement the "add to wallet" feature in an android mobile application that adds movie tickets to samsung wallet. it also shows how to generate the wallet cards using a spring boot server. you can follow along with the tutorial by downloading the sample code files. develop the mobile application to implement the "add to wallet" button in the mobile application, you must configure the application, implement the application ui, and define the application logic for the button. configuring the mobile application project create an application project and configure it to connect to and communicate with the server through rest api requests: in android studio, create a new project. to implement rest api support in the application, add the following retrofit library dependencies to the application's "build.gradle" file: 'com.squareup.retrofit2:retrofit:2.11.0' 'com.squareup.retrofit2:converter-gson: 2.11.0' to enable communication with the server, add the following permissions to the "androidmanifest.xml" file: <uses-permission android:name="android.permission.internet"/> <uses-permission android:name="android.permission.access_network_state"/> <uses-permission android:name="android.permission.access_wifi_state"/> to enable testing with a local non-https server, add the following attribute to the "application" element in the "androidmanifest.xml" file: android:usescleartexttraffic="true" implementing the application ui the application ui consists of two screens: the movie tickets list and a ticket detail page. in the application code, define a movie data class that contains details for the movie tickets that can be added to samsung wallet. data class movie( val name:string, val studio:string, val ticketnumber:string, ) create a recyclerview that displays the list of movie tickets as buttons on the main screen. each button has a listener that opens the detail page for the ticket. you can study the implementation details in the sample code. to check whether the device supports samsung wallet, send an http get request to the following endpoint, where build.model is the model of the device: https://api-us3.mpay.samsung.com/wallet/cmn/v2.0/device/available?servicetype=wallet&modelname=${build.model} create the ticket detail page layout in the "activity_movie_detail.xml" file. the "add to wallet" button is implemented on this page. figure 2: detail page layout implement the ticket detail page functionality in the moviedetailactivity activity class in the application code. for this demonstration, the movie ticket data is predefined in the application code. in a real application, the data is usually retrieved in real time from an external database. val movielists = listof<movie>( movie("the wallet", "samsung studios", "a-01"), movie("crying sea", "laplace studio","h-07"), movie("canoe", "terra productions", "r-03") ) val position:int = intent.getintextra("movieposition", 0) val movie:movie = movielists[position] binding.mvnametext.text = movie.name binding.mvstudiotext.text = movie.studio binding.mvticketnumber.text = "ticket: ${movie.ticketnumber}" binding.addtowalletbutton.setonclicklistener { // request server to generate card data // retrieve signed card data from server // add card to samsung wallet application } when the user taps the "add to wallet" button, onclicklistener() is triggered. its functionality is defined later in this tutorial. connecting to the server to communicate with the server: in the tokenresponse class, define the structure of the json response to be received from the server. the status field indicates whether the token generation request was successful, and the jwt field contains the generated cdata in the form of a jwt token. data class tokenresponse( val status: string, val jwt:string ) in the "apiclient.kt" file, define a retrofitclient object that is used to establish the connection with the server. define the apiinterface interface, which defines the api request and response: the api endpoint url is base_url/movie/{id}, where {id} is the movie ticket id to be added the expected response from the endpoint is a tokenresponse object. define an apiclient object that extends apiinterface and creates a retrofitclient instance to establish the server connection. object retrofitclient { private const val base_url = "http://192.xxx.xxx.xxx:8080" // define your server url val retrofit: retrofit by lazy { retrofit.builder() .baseurl(base_url) .addconverterfactory(gsonconverterfactory.create()) .build() } } interface apiinterface { @get("/movie/{id}") suspend fun getmovie(@path("id") movieid:int): response<tokenresponse> } object apiclient { val apiservice: apiinterface by lazy { retrofitclient.retrofit.create(apiinterface::class.java) } } adding card data to samsung wallet to request cdata generation from the server and add the wallet card to samsung wallet: in the addtowalletbutton.setonclicklistener() method within the moviedetailactivity class, send a request to the server to generate cdata for the selected movie ticket. if cdata generation is successful, to add the movie ticket to samsung wallet, send an http request containing the cdata token to the following endpoint url: https://a.swallet.link/atw/v1/{card id}#clip?cdata={cdata token} for more information about this endpoint, see data transmit link. binding.addtowalletbutton.setonclicklistener { coroutinescope(dispatchers.main).launch { val response = apiclient.apiservice.getmovie(position) if(response.issuccessful && response.body()!=null){ startactivity(intent( intent.action_view, uri.parse("http://a.swallet.link/atw/v1/3aabbccddee00#clip?cdata=${response.body()!!.jwt}"))) // replace '3aabbccddee00' part with your card id } } } notethe generated cdata is valid for 30 seconds, so it is recommended to generate the cdata only when the "add to samsung wallet" button is clicked. if the cdata has expired by the time the token is sent to samsung wallet, the user can receive a "request timed out" error. generate signed wallet card data the server application must be configured to receive the card data request from the mobile application and return a signed jwt token. this part of the tutorial uses the spring boot framework. configuring the server project to create and configure a server application to generate and sign wallet card data: in the spring initializr tool or any supported java ide, create a spring boot project and open the sample code. to configure the server to receive rest api requests from the mobile application, add the "spring web" dependency to the project. define a token data class. make sure it has the same attributes as the tokenresponse data class defined in the mobile application. data class token(val status:string, val jwt:string initialize a tokencontroller class that receives the incoming requests and returns a token object in response. @restcontroller @requestmapping("movie") class tokencontroller { @getmapping(path = ["/{movieid}"]) fun getmovie(@pathvariable movieid:int): token { return token("success", "{dummy_cdata}") // cdata generation logic } } the cdata generation and signing logic is described in the next section. implementing card data signing logic for easier understanding, this section describes a simplified implementation of the cdata generation sample code. in the server application project, copy the following credential files to the "sample/securities/" directory. samsung public key from the samsung certificate ("samsung.crt") partner public key from your partner certificate ("partner.crt") partner private key from the private key file ("partner.key") to handle the certificate files and signing algorithms, add the following dependencies to the server application's "build.gradle" file: implementation 'com.nimbusds:nimbus-jose-jwt:9.37.3' implementation 'org.bouncycastle:bcprov-jdk18on:1.77' in a new "jwtgen.kt" file, define a readcertificate() method that reads the public keys from the certificates and a readprivatekey() method that reads the private key from the key file. private val partner_id = "4048012345678912345" // replace with your partner id private val samsungpublickey = readcertificate(getstringfromfile("sample/securities/samsung.crt")) private val partnerpublickey = readcertificate(getstringfromfile("sample/securities/partner.crt")) private val partnerprivatekey = readprivatekey(getstringfromfile("sample/securities/partner.key")) fun readprivatekey(key: string): privatekey { val keybyte = readkeybyte(key) lateinit var privatekey: privatekey val pkcs8spec = pkcs8encodedkeyspec(keybyte) try { val kf = keyfactory.getinstance("rsa") privatekey = kf.generateprivate(pkcs8spec) } catch (e: invalidkeyspecexception) { e.printstacktrace() } catch (e: nosuchalgorithmexception) { e.printstacktrace() } return privatekey } fun readcertificate(cert: string): publickey { lateinit var certificate: certificate val keybyte = readkeybyte(cert) val `is`: inputstream = bytearrayinputstream(keybyte) try { val cf = certificatefactory.getinstance("x.509") certificate = cf.generatecertificate(`is`) } catch (e: certificateexception) { e.printstacktrace() } return certificate.publickey } private fun readkeybyte(key: string): bytearray { val keybyte: bytearray val bais = bytearrayinputstream(key.tobytearray(standardcharsets.utf_8)) val reader: reader = inputstreamreader(bais, standardcharsets.utf_8) val pemreader = pemreader(reader) var pemobject: pemobject? = null try { pemobject = pemreader.readpemobject() } catch (e: ioexception) { e.printstacktrace() } keybyte = if (pemobject == null) { base64.getdecoder().decode(key) } else { pemobject.content } return keybyte } fun getstringfromfile(path: string?): string { try { val file = file(objects.requirenonnull(classloader.getsystemclassloader().getresource(path)).file) return string(files.readallbytes(file.topath())) } catch (e: ioexception) { throw runtimeexception(e) } } generating card data cdata token generation is implemented in the "jwtgen.kt" file: read the file containing raw json data that defines the ticket data structure. for this demonstration, use the "ticket.json" file in the "sample/payload/" directory of the cdata generation sample code. generate or fill in the required ticket details. for example, the "{title}" and "{seatnumber}" fields are replaced with the movie title and seat number. for information about the complete json structure, see wallet cards. convert the json data to a jwe object. encrypt the jwe object with the samsung public key. build the custom jws header for samsung wallet cards. sign and validate the complete jws object with your partner private and public key using the rs256 asymmetric algorithm. this is the cdata token. private val currenttimemillis = system.currenttimemillis() private val plaindata:string = getstringfromfile("sample/payload/ticket.json") .replace("{refid}", uuid.randomuuid().tostring()) .replace("{language}", "en") .replace("{createdat}", currenttimemillis.tostring()) .replace("{updatedat}", currenttimemillis.tostring()) .replace("{issuedate}", currenttimemillis.tostring()) .replace("{startdate}", (currenttimemillis + timeunit.days.tomillis(1)).tostring()) .replace("{enddate}", (currenttimemillis + timeunit.days.tomillis(1) + +timeunit.hours.tomillis(2)).tostring()) fun generatecdata(moviename: string, movieticktno:string): string{ // modify data as needed val data = plaindata.replace("{title}", "\"$moviename\"") .replace("{seatnumber}","\"$movieticktno\"") //print(data) return generate(partner_id, samsungpublickey, partnerpublickey, partnerprivatekey, data) } private fun generate(partnerid: string, samsungpublickey: publickey, partnerpublickey: publickey, partnerprivatekey: privatekey, data: string): string { val jweenc = encryptionmethod.a128gcm val jwealg = jwealgorithm.rsa1_5 val jweheader = jweheader.builder(jwealg, jweenc).build() val encryptor = rsaencrypter(samsungpublickey as rsapublickey) val jwe = jweobject(jweheader, payload(data)) try { jwe.encrypt(encryptor) } catch (e: joseexception) { e.printstacktrace() } val payload = jwe.serialize() val jwsalg = jwsalgorithm.rs256 val utc = system.currenttimemillis() val jwsheader = jwsheader.builder(jwsalg) .contenttype("card") .customparam("partnerid", partnerid) .customparam("ver", "2") .customparam("utc", utc) .build() val jwsobj = jwsobject(jwsheader, payload(payload)) val rsajwk = rsakey.builder(partnerpublickey as rsapublickey) .privatekey(partnerprivatekey) .build() val signer: jwssigner try { signer = rsassasigner(rsajwk) jwsobj.sign(signer) } catch (e: joseexception) { e.printstacktrace() } return jwsobj.serialize() } returning the signed token in the server application code, when the server receives a request at the movie/{movieid} endpoint, the tokencontroller class calls the jwtgen.generatecdata() method with the movie id, which generates and returns the cdata jwt token in the api response. in this tutorial, since the movie ticket list was predefined in the mobile application project, make sure the same movie data class and list are defined here too. @restcontroller @requestmapping("movie") class tokencontroller { @getmapping(path = ["/{movieid}"]) fun getmovie(@pathvariable movieid:int): token { val movielists = listof<movie>( movie("the wallet", "samsung studios", "a-01"), movie("crying sea", "laplace studio","h-07"), movie("canoe", "terra productions", "r-03") ) if( movieid>2){ // implement your verification logic return token("failure", "") } else{ val cdata = jwtgen.generatecdata(movielists[movieid].name, movielists[movieid].ticketnumber) return token("success", cdata) } } } testing the application to test your "add to wallet" integration: connect the server and the mobile device to the same network. launch the server and mobile applications. in the mobile application, tap a movie ticket in the list. its detail page opens. tap add to samsung wallet. the server generates and returns the cdata token. the samsung wallet application launches on the device and the movie ticket information is added to it. figure 3: ticket added to samsung wallet summary implementing the "add to wallet" feature enables your users to add your digital content, such as tickets, passes, and loyalty cards, to the samsung wallet application on their mobile device as wallet cards. in addition to implementing the "add to samsung wallet" button in your mobile application, you must also create a server application that securely generates and signs the wallet card data and returns it to the mobile application for transmitting to samsung wallet. for more information about adding "add to wallet" to your application, see implementing atw button. you can also study the extended sample application (clicking this link downloads the sample code) and the api reference. if you have questions about or need help with the information presented in this article, you can share your queries on the samsung developers forum. you can also contact us directly for more specialized support through the samsung developer support portal. resources click the links below to download the sample code. android app sample code extended android app sample code cdata generation server sample code