Filter
-
Content Type
-
Category
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Mobile/Wearable
Visual Display
Digital Appliance
Platform
Filter
Learn Code Lab
codelabintegrate samsung pay web checkout with merchant sites objective learn how to integrate the samsung pay payment system into your merchant sites using the samsung pay web checkout sdk partnership request to use the samsung pay web checkout sdk, you must become an official samsung pay partner once done, you can fully utilize this code lab you can learn more about the partnership process by visiting the samsung pay page here in samsung developers notein accordance with the applicable samsung pay partners agreements, this code lab covers the setup and use of the samsung pay web checkout sdk for purposes of integrating samsung pay with merchant sites the use cases and corresponding code samples included are representative examples only and should not be considered as either recommended or required overview the samsung pay web checkout service enables users to pay for purchases on your website with payment cards saved in the samsung wallet app on their mobile device it supports browser-based payments on both computers and mobile devices a mobile device with samsung wallet installed is required to make purchases through samsung pay web checkout when the user chooses to pay with samsung pay, they must provide their samsung account id email id or scan the qr code on the screen with their mobile device the user then authorizes the purchase within the samsung wallet application, which generates the payment credential on the device and transmits it to your website through the web checkout for more information, see samsung pay web checkout set up your environment you will need the following access to samsung pay developers site samsung wallet test app from samsung pay developers site samsung galaxy device that supports samsung wallet app internet browser, such as google chrome codesandbox account notein this code lab, you can use the samsung wallet test app to try the functionality of the samsung pay web checkout service in a staging environment you can use the official samsung wallet app from the galaxy store once your service is in the production environment start your project and register your service in your browser, open the link below to access the project file of the sample merchant site codesandbox io/s/virtual-store-sample-fnydk5 click the fork button to create an editable copy of the project next, follow the steps below to register your sample merchant site in the samsung pay developers site go to my projects > service management click create new service select web online payment as your service type enter your service name and select your service country select your payment gateway from the list of supported payment gateways pg if your pg uses the network token mode, upload the certificate signing request csr or privacy enhanced mail pem file you obtained from your pg contact your pg for details enter the payment domain name s for your website in the service domain field and click add for example, if your domain is mywebstore com, but the checkout page is hosted on the subdomain payments mywebstore com, you will need to enter payments mywebstore com as the service domain for each additional domain url, click add in this code lab, the generated preview url of the forked project is your service domain click the name of the newly created service to see its details, such as the generated service id that you can use for all the registered service domains include the samsung pay web checkout javascript sdk the samsung pay web checkout sdk uses javascript to integrate the samsung pay payment system to your website this sdk allows users to purchase items via web browser in the <head> section of the index html file of the project, include the samsung pay web checkout javascript sdk file <script src="https //img mpay samsung com/gsmpi/sdk/samsungpay_web_sdk js"></script> initialize the samsung pay client to initiate payments using the samsung pay api, create a new instance of the paymentclient class and pass an argument specifying that the environment as stage write the code below in the <script> tag of the <body> section const samsungpayclient = new samsungpay paymentclient { environment "stage" } ; when the service is still in debug or test mode, you can only use the staging environment to test payment functionality without processing live transactions noteby default, the service is initially set to debug or test mode during creation to switch the service status to release mode, a request must be made through the samsung pay developers site after successfully transitioning to release mode, change the environment to production next, define the service id, security protocol, and card brands that the merchant can support as payment methods the service id is the unique id assigned to your service upon creation in the samsung pay developers site let paymentmethods = { version "2", serviceid "", //input your service id here protocol "protocol_3ds", allowedbrands ["visa", "mastercard"] }; check whether the samsung pay client is ready to pay using the given payment method call the createandaddbutton function if the response indicates that the client is ready samsungpayclient isreadytopay paymentmethods then function response { if response result { createandaddbutton ; } } catch function err { console error err ; } ; create and implement the samsung pay button go to the <body> section and, inside the page-container div, create a container for the samsung pay button <div align="center" id="samsungpay-container"></div> next, go back to the <script> tag and write the createandaddbutton function inside this function, generate the samsung pay button by calling the createbutton method ensure that the button appears on the page by appending it to the container you created function createandaddbutton { const samsungpaybutton = samsungpayclient createbutton { onclick onsamsungpaybuttonclicked, buttonstyle "black"} ; document getelementbyid "samsungpay-container" appendchild samsungpaybutton ; } function onsamsungpaybuttonclicked { // create the transaction information //launch the payment sheet } from the createandaddbutton function, call the onsamsungpaybuttonclicked function when the user clicks the generated button create the transaction information in the onsamsungpaybuttonclicked function, create the transactiondetail object for the user’s purchase input your service domain in the url key let transactiondetail = { ordernumber "sample0n1y123", merchant { name "virtual shop", url "", //input your service domain countrycode "us" }, amount { option "format_total_estimated_amount", currency "usd", total 2019 99 } }; below are the descriptions of the keys included in the transactiondetail object key type description ordernumber string order number of the transaction allowed characters [a-z][a-z][0-9,-] merchant object data structure containing the merchant information merchant name string merchant name merchant url string merchant domain url e g , samsung com the maximum length is 100 characters merchant countrycode string merchant country code e g , us for united states iso-3166-1 alpha-2 amount object data structure containing the payment amount amount option string display format for the total amount on the payment sheet format_total_estimated_amount = displays "total estimated amount " with the total amountformat_total_price_only = displays the total amount only amount currency string currency code e g , usd for us dollar the maximum length is 3 character amount total string total payment amount in the currency specified by amount currencythe amount must be an integer e g , 300 or in a format valid for the currency, such as 2 decimal places after a separator e g , 300 50 notefor the complete list of specifications for the transactiondetail object, see samsung pay web checkout api reference launch the payment sheet after creating the transaction information, call the loadpaymentsheet method to display the web checkout ui the user can either input their email address or scan the generated qr code a timer screen in the web checkout ui is displayed after the user input, while a payment sheet is launched in the user's samsung wallet app the payment sheet contains the payment card option s and the transaction details when the user confirms their payment on their mobile device, you will receive the paymentcredential object generated by the device then, inform the samsung server of the payment result using the notify method the paymentresult object contains the payment result information during transaction processing and after the payment is processed with the pg network notefor real transactions, you need to extract the payment credential information from the 3ds data key within the paymentcredential object and process it through your payment provider however, in this code lab, you only need to print the paymentcredential to the console samsungpayclient loadpaymentsheet paymentmethods, transactiondetail then function paymentcredential { console log "paymentcredential ", paymentcredential ; const paymentresult = { status "charged", provider "test pg" }; samsungpayclient notify paymentresult ; } catch function error { console log "error ", error ; } ; other possible values of the status key are charged - payment was charged successfully canceled - payment was canceled by either the user, merchant, or the acquiring bank rejected - payment was rejected by the acquiring bank erred - an error occurred during the payment process test the samsung pay button after integrating the samsung pay web checkout service into your sample merchant site, follow the steps below to test the functionality of the integrated service open your sample merchant site in a new tab then, click the pay with samsung pay button in the web checkout ui, enter the email address of your samsung account to send a payment request to samsung pay tap the push notification sent to the samsung wallet app installed on your mobile device then, click accept when the payment sheet is loaded, tap on pin and enter your pin to proceed a verified message will display in both the samsung wallet app and web checkout ui to indicate that the payment was processed successfully you're done! congratulations! you have successfully achieved the goal of this code lab topic now, you can integrate the samsung pay web checkout service into your website by yourself if you're having trouble, you may check the complete code below codesandbox io/s/virtual-store-complete-dkhzfx to learn more about developing apps for samsung pay devices, visit developer samsung com/pay
Develop Samsung Blockchain
dockey management in this section, we will cover general terms – public key, private key, and an address, and how samsung blockchain keystore generates and manages these keys samsung blockchain keystore is a hierarchical deterministic hd wallet and follow the industry standards of bip-32, bip-39 and bip-44 bip stands for bitcoin improvement proposal by implementing these standards, samsung blockchain keystore aim to provide better user experience to back up the wallet, since the user only needs to keep the root seed of the private and public keys safe it is just the 12 words generated from samsung blockchain keystore that user needs to remember or write down we will look into how this is achieved by implementing hierarchical deterministic wallet in samsung blockchain keystore public key, private key, and address the key pair is mandatory to participate in the blockchain network this key pair is composed of a public key and a private key public key is used to derive an address that is used like a user’s account in blockchain it is safe to share the public key or the address with others on the other hand, a private key is used to sign transactions and must be kept secret anyone who has access to the private key can sign transactions and spend cryptocurrency or use crypto-assets without user’s permission simply put, the private key is a random number based on the private key, there are algorithms, like elliptic curve digital signature algorithm ecdsa that derives the public key this algorithm may differ depending on the blockchain platform but one interesting characteristic of a public key is that it is derived from a private key, but the other way around is not possible – public key cannot derive nor predict the private key the same relationship applies to the public key and the address address, which is used like a user’s account, cannot derive any public keys since a private key is a random number, this implies that the randomness of a private key generation must be guaranteed yet, software random number generators, also known as pseudo random number generators, are known to have security vulnerabilities because the public key and address format differs by blockchain platforms, user needs to have one key pair for ethereum, another key pair for bitcoin, and etc if a user wants several accounts for ethereum, then that many number of key pairs will be required moreover, bitcoin uses countless number of accounts, because after a transaction has been made, any bitcoin changes after the transaction is returned to a different account of the user’s in other words, it becomes very complex and inconvenient if a user would have to save a key pair for every blockchain account that the user holds samsung blockchain keystore aims to reduce this by implementing hierarchical deterministic wallet hierarchical deterministic wallet hd wallet hierarchical deterministic wallet allows these multiple key pairs to be derived from a single root seed called, “root seed ” root seed is the root of a large tree of public and private keys this root seed is the only thing that user needs to store and back up this is the key to access all of your crypto secrets, so how it is generated and stored should be kept in a secure environment root seed is between 128 and 256 bits and because the physical look of root seed is not very user friendly, and is a combination of “0” and “1”, there is an industry standard, to replace them with mnemonic words, or a group of words for example, if the root seed is 128 bits, then with the checksum of 4 bits, a total of 132 bits is split into a group of 11 bits each group falls into a group number between 0 and 2047, which is an index to a wordlist of 2048 words these index numbers are then converted into the corresponding words and the combination of 12 words make up “recovery phrase” in samsung blockchain keystore generating root seed and mnemonic words in samsung blockchain keystore samsung blockchain keystore generates the root seed by trusted app in trusted execution environment, by the steps below ① true random number generator trng , also known as hardware random number generator, that is embedded into samsung device chipsets, generates an initial entropy length ent of 128 random bits elaborating more on ent, industry standard allows 128 to 256 bits, in multiple of 32 bits depending on the length of the initial entropy length, the number of words that this will be converted into will differ, from 12 to 24, in multiple of 3 ② samsung blockchain keystore takes the first 4 bits of the sha-256 hash of the 128 bits to generate something called, “checksum ” theoretically, it is ent/32 that is taken to generate the checksum so for samsung blockchain keystore, ent is 128 bits, resulting in 4 bits of checksum for other wallets that generate 24 words with the ent of 256 bits, 8 bits are used as a checksum ③ samsung blockchain keystore appends the previously generated 4 bits of checksum to the initial entropy length, resulting in 132 bits ④ 132 bits combination of initial entropy length and checksum are divided into 11 bits, resulting in 12 words, “mnemonic codes” these 12 words are industry standard, and is one of the 2048 words on the bip-39 english wordlist ⑤ because the 12 words follow bip-39 standard used in the industry, user can back up wallet on a different samsung device that supports samsung blockchain keystore, or other wallets that are bip-39-compatible importing a wallet when a user imports a wallet in samsung blockchain keystore, the user will enter the 12, 18 or 24 words into the trusted user interface tui that will protect user’s input this time, samsung blockchain keystore will convert the mnemonic words entered in order to the original root seed the root seed is the one and only source that samsung blockchain keystore will save in a secure area likewise, this will become the source to generate countless number of public keys and sign transactions with the private keys when a request is made randomly entering mnemonic words to guess recovery phrase some may raise a question on the feasibility of guessing the words among 2048 words on the mnemonic words list and somehow, getting access to the private key that corresponds to the recovery phrase but it’s not just the words of 12 to 24 in multiple of 3, that have to correctly chosen, but the order of these words have to be correct as well this is because if you are using 12 words, then 128 bits must be correctly guessed, and 266 bits for 24 words choice between 0 and 1 on 128 bits give us 2 x 2 x 2 x … 2 = 2128 of the possible root seeds, and 2^256 cases for 24 words moreover, the checksum of 4 bits for 12 words, and 8 bits for 24 words, protects randomly making a combination of words when importing a wallet in samsung blockchain keystore, there is a checksum check after user has entered 12, 18 or 24 words, and it will throw an error that the combination of words entered isn’t a valid recovery phrase the user will receive absolutely no information on which words make the checksum invalid, making it even more difficult to randomly guess the recovery phrase hd path the hd wallet is a tree of theoretically infinite number of private and public keys one interesting fact is that it allows derivation of a child keys from the root seed via a function defined in bip-32 standard, “child key derivation ckd functions ” this means with the root seed and the location of the tree, key derivation is feasible more details on the key derivations can be found in the appendix the location in the tree is called a “path” and bip-44 standard defines the standard to unify rules for wallet’s compatibility of these hd key generation hence developers just need to specify the path to derive the address from, and whoever keeps the root seed will be able to calculate and return the actual key value for that specified location each depth is represented by “/” in the hd path and the apostrophe ‘ implies that the depth is hardened the following is hd path level standard defined in bip-44 ![] /sd2_images/services/blockchain/hd_path _level_standard png purpose’ is “44” here, with the implication that it is the following bip-44 standard coin_type’ tells if it is ethereum, bitcoin, or other coins the algorithms to derive the public key from the private key can differ by the coin type, though both ethereum and bitcoin use ecdsa algorithm the number is constant and set for each crypto, and it can be registered in slip-0044 slip satoshilabs improvement proposals , managed by satoshilabs for example, it is “0” for bitcoin, and “60” for ethereum account‘ represents multiple accounts number and is usually ‘0’ change is usually used in bitcoin, using “1” for the account to receive all the changes after sending bitcoins to other accounts normally, “0” is used address_index is the last depth, and usually starts with 0, and increases by one, when you “add” an account in a wallet for example, hd path for the first account of ethereum is m/44’/60’/0’/0/0 and for the second account of bitcoin is m/44’/0’ /0’/0/1 use of hd path in samsung blockchain keystore samsung blockchain keystore can be used to 1 derive an address or extended public key and 2 sign a transaction to consume these two features, developers of dapps or wallets will need to define, where in the hd tree, they would like to derive the public key from, and use the corresponding private key to sign the transaction hd path is a required parameter for apis related to the two features below get address from samsung blockchain keystore if you are a dapp or wallet developer, you can use samsung blockchain keystore to first get the user’s address or extended public key public key and the chain code , and search on the blockchain ledger, transaction history and records of the user, so that user can know how much cryptocurrency or crypto-asset is remaining here’s a brief flow of getting the address ① wallet or dapps will make a request to samsung blockchain keystore to derive an address or extended public key for hd path “m/44’/60’/ 0’/0/0” ethereum account ② using samsung blockchain keystore sdk, wallet/dapp’s request will be passed to samsung blockchain keystore ③ once samsung blockchain keystore will receives the request to get the address or extended public key, it will pass onto the controller to communicate with trusted app to derive the public key ④ root seed is stored safely in a secure area, and the derivation of the extended public key public key and the chain code of the hd path, is executed by trusted application in trusted execution environment ⑤ derived public key will be then passed to samsung blockchain keystore app to derive the address, where one more algorithm function will be executed ⑥ after the calculation, the address that corresponds to the requested hd path will be returned to wallet or dapp via samsung blockchain keystore sdk sign a transaction by samsung blockchain keystore the user will now want to make a transaction, such as sending cryptocurrencies, that will require the user to “write” on the ledger this change needs to be signed by the private key that corresponds to the user’s address, derived from user’s public key below is a diagram and explanation for each step ① wallet or dapps will make a request to samsung blockchain keystore to sign a transaction a correctly formatted transaction without the signature part, and hd path to derive the private key to sign the transaction will be needed ② using samsung blockchain keystore sdk, wallet/dapp’s request will be passed to samsung blockchain keystore ③ once samsung blockchain keystore will receives the request to get the public key, it will pass onto the controller to communicate with trusted app ④ trusted app parses the transaction at first and then blockchain keystore displays the detailed information, including the recipient's address, amount, and fees, on the its screen once the user reviews the transaction details, they can confirm it using either pin verification or fingerprint authentication ⑤ after the user’s confirmation, the safely stored root seed will now be used to derive the private key that corresponds to the hd path that was passed with the transaction request then the trusted application will sign the transaction with the derived private key likewise, these are all executed in trusted execution environment ⑥ the signed transaction will be returned to samsung blockchain keystore app ⑦ samsung blockchain keystore app will return the signed transaction to wallet/dapp via samsung blockchain keystore sdk and wallet/dapps can now submit the signed transaction to the blockchain network more details on the bip-32, bip-39 and bip-44 can be found in the following links **bip-32 ** hierarchical deterministic wallets [https //github com/bitcoin/bips/blob/master/bip-0032 mediawiki] https //github com/bitcoin/bips/blob/master/bip-0032 mediawiki bip-39 mnemonic code for generating deterministic keys https //github com/bitcoin/bips/blob/master/bip-0039 mediawiki#wordlists bip-44 multi-account hierarchy for deterministic wallets https //github com/bitcoin/bips/blob/master/bip-0044 mediawiki slip-44 registered coin types for bip-0044 https //github com/satoshilabs/slips/blob/master/slip-0044 md
Develop Samsung Blockchain
api apipackage class tree deprecated index help com samsung android sdk coldwallet class scwservice java lang object com samsung android sdk coldwallet scwservice public class scwservice extends java lang object class for the proxy to use the samsung blockchain keystore service the keystore's hd wallet seed is bip-39 compatible see also https //github com/bitcoin/bips/blob/master/bip-0039 mediawiki nested class summary nested classes modifier and type class and description static class scwservice scwcheckformandatoryappupdatecallback callback for checkformandatoryappupdate api static class scwservice scwgetaddresslistcallback callback for getaddresslist api static class scwservice scwgetextendedpublickeylistcallback callback for getextendedpublickeylist api static class scwservice scwsignbtctransactioncallback callback for signbtctransaction api static class scwservice scwsignethpersonalmessagecallback callback for signethpersonalmessage api static class scwservice scwsignethtransactioncallback callback for signethtransaction api static class scwservice scwsignklaytransactioncallback callback for signklaytransaction api method summary all methods static methods instance methods concrete methods modifier and type method and description void checkformandatoryappupdate scwservice scwcheckformandatoryappupdatecallback callback checks whether a mandatory update of samsung blockchain keystore is needed or not void getaddresslist scwservice scwgetaddresslistcallback callback, java util arraylist<java lang string> hdpath request to get a list of addresses that corresponds to a list of hd paths void getextendedpublickeylist scwservice scwgetextendedpublickeylistcallback callback, java util arraylist<java lang string> hdpath request to get a list of extended public keys that corresponds to a list of hd paths static scwservice getinstance return the instance of the keystore proxy object int getkeystoreapilevel get api level which the keystore in the device supports java lang string getseedhash get the pseudo seed hash which is randomly generated when the hd wallet created whenever the seed for the wallet is changed, this key shall be changed int[] getsupportedcoins get coin types supported by samsung blockchain keystore void signbtctransaction scwservice scwsignbtctransactioncallback callback, byte[] transaction, java util list<java lang string> hdpathlist, java util list<byte[]> utxotxlist, java lang string changehdpath request to sign bitcoin transaction void signethpersonalmessage scwservice scwsignethpersonalmessagecallback callback, byte[] msg, java lang string hdpath request to sign ethereum typed structured data void signethtransaction scwservice scwsignethtransactioncallback callback, byte[] transaction, java lang string hdpath request to sign ethereum transaction void signklaytransaction scwservice scwsignklaytransactioncallback callback, byte[] transaction, java lang string hdpath, int networkid request to sign klay transaction methods inherited from class java lang object equals, getclass, hashcode, notify, notifyall, tostring, wait, wait, wait method detail getinstance public static scwservice getinstance return the instance of the keystore proxy object returns the instance, or null if samsung blockchain keystore is not available on the device getkeystoreapilevel public int getkeystoreapilevel get api level which the keystore in the device supports caution you should check the api level before invoking any apis otherwise, it will return scwapilevelexception if keystore api level is lower than the required level, update the keystore app first via scwdeeplink galaxy_store returns api level since api level 1 getseedhash public java lang string getseedhash get the pseudo seed hash which is randomly generated when the hd wallet created whenever the seed for the wallet is changed, this key shall be changed returns null if keystore does not support wallet key, zero-length string if the wallet is not created otherwise, wallet is created since api level 1 getsupportedcoins public int[] getsupportedcoins get coin types supported by samsung blockchain keystore returns array of coin types, scwcointype throws scwapilevelexception - api level exception since api level 1 see also https //github com/satoshilabs/slips/blob/master/slip-0044 md checkformandatoryappupdate public void checkformandatoryappupdate @nonnull scwservice scwcheckformandatoryappupdatecallback callback checks whether a mandatory update of samsung blockchain keystore is needed or not do not call this method in the background thread if there is a mandatory update, you need to open the app update link, scwdeeplink galaxy_store parameters callback - result callback since api level 1 getextendedpublickeylist public void getextendedpublickeylist @nonnull scwservice scwgetextendedpublickeylistcallback callback, @nonnull java util arraylist<java lang string> hdpath request to get a list of extended public keys that corresponds to a list of hd paths parameters callback - result callback hdpath - the hd path list to bring the public keys the depth of a path should be between 3 and 6 for example, "m/44'/60'", "m/44'/60'/0'/0/0" since api level 1 see also https //github com/bitcoin/bips/blob/master/bip-0032 mediawiki getaddresslist public void getaddresslist @nonnull scwservice scwgetaddresslistcallback callback, @nonnull java util arraylist<java lang string> hdpath request to get a list of addresses that corresponds to a list of hd paths parameters callback - result callback hdpath - the hd path list to bring the addresses the depth of a path should be between 3 and 6 for example, "m/44'/60'", "m/44'/60'/0'/0/0" since api level 1 see also https //github com/bitcoin/bips/blob/master/bip-0032 mediawiki signethtransaction public void signethtransaction @nonnull scwservice scwsignethtransactioncallback callback, @nonnull byte[] transaction, @nonnull java lang string hdpath request to sign ethereum transaction parameters callback - result callback transaction - a byte array of a rlp-encoded unsigned ethereum transaction hdpath - hd path that corresponds to public key needed for signing since api level 1 signethpersonalmessage public void signethpersonalmessage @nonnull scwservice scwsignethpersonalmessagecallback callback, @nonnull byte[] msg, @nonnull java lang string hdpath request to sign ethereum typed structured data parameters callback - result callback msg - a byte array of raw message to be signed the keystore will add "ethereum signed message \n" prefix, so it should not be included in msg hdpath - hd path that corresponds to public key needed for signing since api level 1 see also https //github com/ethereum/eips/blob/master/eips/eip-712 md signklaytransaction public void signklaytransaction @nonnull scwservice scwsignklaytransactioncallback callback, @nonnull byte[] transaction, @nonnull java lang string hdpath, @nonnull int networkid request to sign klay transaction parameters callback - result callback transaction - a byte array of a raw transaction to be signed by samsung blockchain keystore the transaction is same as the sigrlp value mentioned in klaytn's official document hdpath - hd path that corresponds to public key needed for signing networkid - the klaytn network id, or the integer to identify the network "8217" is klaytn cypress mainnet and "1001" is klaytn baobab testnet since api level 2 see also https //docs klaytn com/node/en/installation/config signbtctransaction public void signbtctransaction @nonnull scwservice scwsignbtctransactioncallback callback, @nonnull byte[] transaction, @nonnull java util list<java lang string> hdpathlist, @nonnull java util list<byte[]> utxotxlist, @nonnull java lang string changehdpath request to sign bitcoin transaction parameters callback - result callback transaction - a byte array of a serialized unsigned bitcoin transaction to be signed by samsung blockchain keystore hdpathlist - a list of hd paths that corresponds to utxo's public key utxotxlist - a list of byte array of the serialized transaction which contain the utxo used in this transaction changehdpath - hd path that corresponds to the change address since api level 2 see also https //github com/bitcoin/bips/blob/master/bip-0044 mediawiki, https //github com/bitcoin/bips/blob/master/bip-0049 mediawiki, https //github com/bitcoin/bips/blob/master/bip-0084 mediawiki
Develop Samsung Blockchain
docgetting started the following steps should be followed before integrating the samsung blockchain platform sdk prepare samsung galaxy device to run your apk check your development environment android minimum api level for samsung blockchain platform sdk 24 noteminimum build level for samsung blockchain platform sdk is 21, but will properly work from level 24 configure your ide to integrate samsung blockchain platform sdk with your android app create an “aar” directory if you don’t have one, and add the blockchainplatformsdk_1 2 03 aar to ”aar” directory in your android project go to gradle scripts > build gradle and enter the following dependencies dependencies { repositories { flatdir{ dirs 'aar' } } implementation name 'blockchainplatformsdk_1 2 03', ext 'aar' // network implementation 'com squareup retrofit2 retrofit 2 6 0' implementation 'com squareup retrofit2 converter-gson 2 6 0' implementation 'com squareup okhttp3 logging-interceptor 3 8 0' implementation 'com google code gson gson 2 8 5' // web3j implementation 'org web3j core 4 8 8-android' // for check developer mode implementation 'org ini4j ini4j 0 5 4' // dagger implementation 'com google dagger dagger 2 21' annotationprocessor 'com google dagger dagger-compiler 2 21' implementation "io reactivex rxjava2 rxjava 2 2 8" implementation "io reactivex rxjava2 rxandroid 2 1 1" // protobuf implementation 'com google protobuf protobuf-java 3 9 1' implementation 'com google protobuf protobuf-gradle-plugin 0 8 10' } import the package into your code import com samsung android sdk blockchain *; samsung blockchain platform sdk supports 2 kinds of hardware wallet samsung blockchain keystore ledger's devices like nano x, nano s notetransactions on evm-compatible networks binance smart chain, klaytn, polygon, avalanche c-chain and fantom are signed from the hardware wallets using the same pathway as that of ethereum for these transactions, currency unit displayed on hardwarewallet, such as samsung keystore or ledger, will show eth as currency unit instead of bnb, klay, matic, avax and ftm development setting guide for each environment is as follows integration with samsung blockchain keystore samsung blockchain keystore is compatible with selected samsung devices only you need to have one of selected samsung devices to run your app with samsung blockchain keystore please refer to the restrictions check your development environment android minimum api level for samsung blockchain keystore 28 notesamsung blockchain platform sdk requires samsung blockchain keystore that is higher than 1 5 1 download the samsung blockchain keystore sdk set 'developer mode' to test your app without app id verification you can find more information about app id scw_app_id , here add "blockchainkeystoresdk_v1 6 0 aar" to "aar" directory in your android project go to gradle script > build gradle and add below dependency dependencies { // keystore sdk implementation name 'blockchainkeystoresdk_v1 6 0', ext 'aar' } integration with nano x or nano s by ledger there is no restrictions to link with ledger device so any samsung galaxy mobile is ok to test your app which is integrated with samsung blockchain platform sdk when you sign with ledger device check your development environment ledger nano x 1 2 4-1 or higher ledger nano s 1 6 or higher ledger ethereum app 1 9 8 or higher you can refer ledger's guide page to get started go to gradle > build gradle and add below dependency dependencies { // ledger implementation 'com ledger lib ledger-android-library 1 2 2' }
Develop Samsung Pay
api apioverview package class tree index help package com samsung android sdk samsungpay v2 class samsungpay java lang object samsungpaybase com samsung android sdk samsungpay v2 samsungpay public final class samsungpay extends samsungpaybase this class provides apis to get the samsung pay status on the device also, this class provides apis to activate samsung pay on the device partner apps must check the samsung pay status on the device before performing any card management or payment operation since api level 1 1 constructor summary constructors constructor description samsungpay android content context context, partnerinfo partnerinfo constructor to get the samsungpay instance the caller should set the valid serviceid in partnerinfo method summary all methodsinstance methodsconcrete methods modifier and type method description void activatesamsungpay api to bring the samsung pay app to a state in which cards can be added samsung pay might be either in stub only state or samsung account is not signed in state partner app checks the samsung pay status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_setup_not_completed, partner app can call this api to launch samsung pay and user can sign in to the app void getsamsungpaystatus statuslistener listener api to get the samsung pay status on the device partner issuers, merchants, and so on applications must call this api to check the current state of samsung pay before doing any operation void getwalletinfo list<string> keys, statuslistener listener api to get the requested wallet information from samsung pay partner app can use this information to uniquely identify the user and samsung pay app on a particular device void gotoupdatepage api to go to samsung pay update page partner app checks the samsung pay status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_app_need_to_update, partner app can call this api to go to update samsung pay app if samsung pay app version is same or bigger than 2 1 00, it goes to "about samsungpay" menu if samsung pay app version is lower than 2 1 00 or kr device, it launches samsung pay app main screen methods inherited from class java lang object equals, getclass, hashcode, notify, notifyall, tostring, wait, wait, wait constructor details samsungpay public samsungpay android content context context, partnerinfo partnerinfo constructor to get the samsungpay instance the caller should set the valid serviceid in partnerinfo partnerinfo is passed to samsung pay for partner verification context ct = activity; // or context ct = service; // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring samsungpay partner_service_type, samsungpay servicetype inapp_payment tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; samsungpay samsungpay = new samsungpay ct, pinfo ; parameters context - activity context or service context partnerinfo - partner information throws nullpointerexception - thrown if parameters are null since api level 1 1 method details getsamsungpaystatus public void getsamsungpaystatus statuslistener listener api to get the samsung pay status on the device partner issuers, merchants, and so on applications must call this api to check the current state of samsung pay before doing any operation // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring samsungpay partner_service_type, samsungpay servicetype inapp_payment tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; samsungpay samsungpay = new samsungpay context, pinfo ; samsungpay getsamsungpaystatus new statuslistener { @override public void onsuccess int status, bundle data { // success case if status == spay_ready { log d tag, "samsung pay is ready on the device" ; // perform your operation } else if status == spay_not_ready { // samsung pay is supported but not fully ready // if extra_error_reason is error_spay_app_need_to_update, // call gotoupdatepage // if extra_error_reason is error_spay_setup_not_completed, // call activatesamsungpay } else if status == spay_not_allowed_temporally { log d tag, "samsung pay is not allowed temporally" ; // if extra_error_reason is error_spay_connected_with_external_display, // guide user to disconnect it } else { // samsung pay is not supported on this device log d tag, "device does not support samsung pay" ; } } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle such as samsungpay extra_error_reason if provided } } ; parameters listener - callback through which the result is provided on success, samsung pay status code is provided via statuslistener onsuccess int status, bundle data if samsung pay is ready to be used, samsungpay#spay_ready will be returned otherwise, samsungpay#spay_not_ready or samsungpay#spay_not_supported or samsungpay#spay_not_allowed_temporally can be returned with samsungpay#extra_error_reason from bundle also, partner can get extra information from bundle data bundle keys if provided bundle values #extra_country_code device country code iso 3166-1 alpha-2 #extra_member_id string memberid for korean issuers only on any failure, the failure code is provided via statuslistener onfail int errorcode, bundle errordata note please refer spaysdk common_status_table in detail throws nullpointerexception - thrown if the callback passed is null since api level 1 1 gotoupdatepage public void gotoupdatepage api to go to samsung pay update page partner app checks the samsung pay status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_app_need_to_update, partner app can call this api to go to update samsung pay app if samsung pay app version is same or bigger than 2 1 00, it goes to "about samsungpay" menu if samsung pay app version is lower than 2 1 00 or kr device, it launches samsung pay app main screen // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring samsungpay partner_service_type, samsungpay servicetype inapp_payment tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; samsungpay samsungpay = new samsungpay context, pinfo ; samsungpay gotoupdatepage ; since api level 1 2 activatesamsungpay public void activatesamsungpay api to bring the samsung pay app to a state in which cards can be added samsung pay might be either in stub only state or samsung account is not signed in state partner app checks the samsung pay status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_setup_not_completed, partner app can call this api to launch samsung pay and user can sign in to the app // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring samsungpay partner_service_type, samsungpay servicetype inapp_payment tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; samsungpay samsungpay = new samsungpay context, pinfo ; samsungpay activatesamsungpay ; since api level 1 1 getwalletinfo public void getwalletinfo list<string> keys, statuslistener listener api to get the requested wallet information from samsung pay partner app can use this information to uniquely identify the user and samsung pay app on a particular device // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring samsungpay extra_issuer_name, "issuer name" ; bundle putstring samsungpay partner_service_type, samsungpay servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; samsungpay samsungpay = new samsungpay context, pinfo ; // bundle keys added to get wallet information from samsung pay // this information can be delivered to the partner server for eligibility check arraylist<string> keys = new arraylist<> ; keys add samsungpay wallet_user_id ; keys add samsungpay device_id ; samsungpay getwalletinfo keys, new statuslistener { @override public void onsuccess int status, bundle walletdata { // log d tag, "dowalletinfo onsuccess callback is called" ; // for visa, deviceid can be set to "clientdeviceid" as defined by visa string deviceid = walletdata get samsungpay device_id ; // for visa, walletuserid can be set to "clientwalletaccountid" as defined by visa string walletuserid = walletdata get samsungpay wallet_user_id ; } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle such as samsungpay extra_error_reason if provided } } parameters keys - key list to get wallet information if the list is empty, all possible key values are returned the possible keys are #wallet_dm_id #device_id #wallet_user_id listener - callback through which the result is provided on success, statuslistener onsuccess int status, bundle data is invoked with wallet information the success code can be one of the following codes with bundle data status bundle keys bundle values usage vts mdes #error_none samsungpay#wallet_dm_id string device management id n/a paymentappinstanceid = device_id + padding "00" + wallet_dm_id *if you need 'paymentappinstanceid', you can generate it as above samsungpay#device_id string device id clientdeviceid samsungpay#wallet_user_id string wallet user id clientwalletaccountid on any failure, the error code is provided via statuslistener onfail int errorcode, bundle errordata note please refer spaysdk common_status_table in detail throws nullpointerexception - thrown if parameters are null since api level 1 2 samsung electronics samsung pay sdk 2 22 00 - nov 19 2024
Develop Samsung Wallet
docapi guidelines app2app sdk integration specs description & use rp sdk is an app2app sdk for samsung wallet driver's license service online scenarios this sdk provides an implementation for direct communication between the samsung wallet and partner applications build the settings rpsdk requires additional dependencies with dependencies { implementation "rp-sdk-1 0-release aar" implementation "androidx core core-ktx 1 3 2" implementation "androidx lifecycle lifecycle-runtime-ktx 2 7 0" implementation "androidx lifecycle lifecycle-livedata-core-ktx 2 7 0" implementation "io reactivex rxjava2 rxjava 2 2 21" implementation "io reactivex rxjava2 rxkotlin 2 4 0" implementation "io reactivex rxjava2 rxandroid 2 1 1" implementation "com squareup okhttp3 okhttp 4 11 0" implementation "com google code gson gson 2 10 1" implementation "org bouncycastle bcprov-jdk15to18 1 66" implementation "com nimbusds nimbus-jose-jwt 9 37 3" } androidmanifest xml <manifest xmlns android="http //schemas android com/apk/res/android"> <uses-permission android name="android permission internet" /> <queries> <package android name="com samsung android spay" /> </queries> </manifest> r8 / proguard the specific rules are already bundled into the aar which can be interpreted by r8 automatically sdk method app2app sdk supports one method request signature & parameters of the request method fun request targetpackagename string, requestid string, applink string, onresponselistener onresponselistener? = null parameter name description targetpackagename the pakcage name to connect to requestid a random string to identify each request applink the applink built by samsung mcs server guidehttps //developer samsung com/wallet/api_new/verifywith/button html#data-transmit-link onresponselistener a listener to receive each events or request [sample code] https //developer samsung com/wallet/api_new/references/coderesources html#rpclient-sample-code binding button setonclicklistener { rpclientapis request "com samsung android spay", uuid randomuuid tostring , applink, object rpclientapis onresponselistener { override fun ongetmdocrequestdata deviceengagementbytes bytearray bytearray? { log i tag, "ongetmdocrequestdata $deviceengagementbytes " /** * 1 prepare mdoc request data iso-18013-5 * 2 build sessionestablishmentbytes iso-18013-5 * 3 encrypt it with hkdf iso-18013-5, 9 1 1 5 cryptographic operations **/ return "encryptedsessionestablishmentbytes" } override fun onmdocresponse encryptedresponse bytearray { log i tag, "onmdocresponse $encryptedresponse " /** * 1 decrypt it with hkdf iso-18013-5, 9 1 1 5 cryptographic operations * 2 cbor decode it **/ } override fun onmdocresponsefailed exception exception { log i tag, "onmdocresponsefailed $exception " } } } error code explanation the below exceptions might occur through the onmdocresponsefailed callback exceptions name description rpcommunicationexception this error occurs when the data requested by the listener is incorrect rpconnectionfailedexception this occurs when the app 2 app communication between apps is not working this usually occurs when the target package name is written incorrectly web2app api integration specs the api specifications that need to be implemented by the rp partner are described below called by samsung to the rp partner send key send the wallet application key info and return the data field types requested to the client for authentication of the mdl [request] type value description method post url {partner server url}/rp/v1 0/{cardid}/{refid}/key headers authorization string 1024 required credential token the token can have the prefix "bearer" as an authorization type, e g , bearer <credentials> * refer to authorization token for more details path parameters cardidstring 32 required wallet card identifier issued from partner portal when the partner manager signs up for partner services and registers the wallet card they want to service refid string 32 required unique content identifier defined by the content provider query parameter n/a payload data string 3000 required jwt data encrypted with the public key information and card type if decrypted this data is decoded, and it has the following format information { “data” “xxxxxxxxxxx”, “card” {"type" "relyingparty", "subtype" "others", "designtype" "us-01" }} [example] post {partner server url}/rp/v1 0/{cardid}/{refid}/key content-type application/json { “data” “eyjjdhkioijbvvriiiwidmvyijoimiisinbhcnruzxjjzci6inrlc3qilcj1dgmioje3mtyymdyznjaxmtasimfszyi6iljtmju2in0 zxlkbgjttwlpaupctvrjnfiwtk5jaxdpwvd4bklqb2lvbe5ctfu5qljwqxrnaluysw4wllz5afaxs0fnmvjhbzbdn2nix2pydgtfoddqbnhrrmpfwkppcnnsuus4mnn0owvxtjeyvzvmoejax1d5ngvzmze3vdnad0pncmpwzwdzoek3avlcwwrlogj5lxfimjblu3ruc3jsszlpslfnn1fam2xzauxscxltb0vlbervd0fpatrmry1jukzwdvlrbxrintg3utd1zwnuq1lwwgzwalvecg01yxbfbdv3szm1ugz3d0dkrem2tmowz1awbtz3nk1kdl9mddbvzwc2mwzjagdbyny0emxmzju2cvyzm0t6zjdjbwvpbkjrnnpmsgutymfwyxhvzk5ld2htzwvjuzftv3larm1nvlj6mefsmnbxa0dqlvjkt1iza3vzavo0vjfidy1aq2iyvwvwyvdzru9nuedrvw1mbtfuowjwt1zmz1nuv1f0se5pvtfjyvrhtg1dwlpvqs5pmzzrd1g4wmjnq21wd3o2ll9kzehfvxnnbm13b1drddrmcu4xmuncauntsnutbwpyv2zrckxos0zvenbss085ckdxbudpz0pqukf1ntfsotryc2vivwdfwu9ns2rgr1vomwjhmhb3y0tfngtjmet2dkfowhprodn0azbjqzrot2f6vzlmovntt0rhmu9imefoavfzqzddevfqnndnlwflvk8waejwsejkmeduruh1z3exc21vvmxrbjblsnjqwhm4x3fwcnplekwtadfpcfk1aes1zug5q3nisms0aehcngnmwulkrujfz09bcgzxcgfumgfsvgfmodhhdxlqsgzhdgrma0tlwdv0q0rtajixse5tt0fhwtjvwlzrr0hxu0wzngjabtu5aezmnvdha0ljce9bmhlwue9tqznwtflkv2jsmm85lkfoedbvytvgetzudkxkvxvketazshc e07yyl7ior3885vykss5_q1icpx750uu2ge5sujsedx3dr_u0x4tse9_0nxm46dywnfuxruagfjdnjhibc707li9vi3xtyihwnweifydgv1qb9oddkyyzuahxqmjhvuqncdt6df2caqzf5qgmvqfmgse_t7ipu8vqfxe34do-skzj8ftduss2ecdanbqokchih3m39noubpfhcx68plpcw50dixlupxwegniu2t3co24yliaklgac669accxdqr34utvuqhtjt_ftxkahalzoa34_hj_s82fivixh1itd74uojzse7ibwya_kvysozavnmztz2th9cbwycvx8wa” } [response] type value description http status code 200 ok payload data string 3000 required jwt data encrypted with the data field types requested to the client for authentication of the mdl [result] http status code description 200 ok success 400 bad request requests cannot or will not be processed due to something that is perceived to be a client error 401 unauthorized authorization token is invalid or expired 500 internal server error the server encountered an unexpected condition that prevented it from fulfilling the request 503 service unavailable the server is not ready to handle the request send authentication data the data is encrypted according to the requested data and then transmitted along with the data card information [request] type value description method post url {partner server url}/rp/v1 0/{cardid}/{refid}/auth headers authorization string 1024 required credential token the token can have the prefix "bearer" as an authorization type, e g , bearer <credentials> * refer to authorization token for more details pathparameters cardid string 32 required wallet card identifier issued from partner portal when the partner manager signs up for partner services and registers the wallet card they want to service refid string 32 required unique content identifier defined by the content provider queryparameter n/a payload data string 3000 required jwt data encrypted with the public key information and card type if decrypted this data is decoded, it has the following format information { “data” “xxxxxxxxxxx”, “card” {"type" "idcard","subtype" "drivers","designtype" "us-01" }} [example] post {partner server url}/rp/v1 0/{cardid}/{refid}/auth content-type application/json { “data” “eyjjdhkioijbvvriiiwidmvyijoimiisinbhcnruzxjjzci6inrlc3qilcj1dgmioje3mtyymdyznjaxmtasimfszyi6iljtmju2in0 zxlkbgjttwlpaupctvrjnfiwtk5jaxdpwvd4bklqb2lvbe5ctfu5qljwqxrnaluysw4wllz5afaxs0fnmvjhbzbdn2nix2pydgtfoddqbnhrrmpfwkppcnnsuus4mnn0owvxtjeyvzvmoejax1d5ngvzmze3vdnad0pncmpwzwdzoek3avlcwwrlogj5lxfimjblu3ruc3jsszlpslfnn1fam2xzauxscxltb0vlbervd0fpatrmry1jukzwdvlrbxrintg3utd1zwnuq1lwwgzwalvecg01yxbfbdv3szm1ugz3d0dkrem2tmowz1awbtz3nk1kdl9mddbvzwc2mwzjagdbyny0emxmzju2cvyzm0t6zjdjbwvpbkjrnnpmsgutymfwyxhvzk5ld2htzwvjuzftv3larm1nvlj6mefsmnbxa0dqlvjkt1iza3vzavo0vjfidy1aq2iyvwvwyvdzru9nuedrvw1mbtfuowjwt1zmz1nuv1f0se5pvtfjyvrhtg1dwlpvqs5pmzzrd1g4wmjnq21wd3o2ll9kzehfvxnnbm13b1drddrmcu4xmuncauntsnutbwpyv2zrckxos0zvenbss085ckdxbudpz0pqukf1ntfsotryc2vivwdfwu9ns2rgr1vomwjhmhb3y0tfngtjmet2dkfowhprodn0azbjqzrot2f6vzlmovntt0rhmu9imefoavfzqzddevfqnndnlwflvk8waejwsejkmeduruh1z3exc21vvmxrbjblsnjqwhm4x3fwcnplekwtadfpcfk1aes1zug5q3nisms0aehcngnmwulkrujfz09bcgzxcgfumgfsvgfmodhhdxlqsgzhdgrma0tlwdv0q0rtajixse5tt0fhwtjvwlzrr0hxu0wzngjabtu5aezmnvdha0ljce9bmhlwue9tqznwtflkv2jsmm85lkfoedbvytvgetzudkxkvxvketazshc e07yyl7ior3885vykss5_q1icpx750uu2ge5sujsedx3dr_u0x4tse9_0nxm46dywnfuxruagfjdnjhibc707li9vi3xtyihwnweifydgv1qb9oddkyyzuahxqmjhvuqncdt6df2caqzf5qgmvqfmgse_t7ipu8vqfxe34do-skzj8ftduss2ecdanbqokchih3m39noubpfhcx68plpcw50dixlupxwegniu2t3co24yliaklgac669accxdqr34utvuqhtjt_ftxkahalzoa34_hj_s82fivixh1itd74uojzse7ibwya_kvysozavnmztz2th9cbwycvx8wa” } [response] type value description http status code 200 ok400 bad request [result] http status code description 200 ok success 400 bad request requests cannot or will not be processed due to something that is perceived to be a client error 401 unauthorized authorization token is invalid or expired 500 internal server error the server encountered an unexpected condition that prevented it from fulfilling the request 503 service unavailable the server is not ready to handle the request code explanation based on the sample code jwt jws + jwe decryption between the wallet backed server and partner server 1 verify by generating a jws using the body data // generate jws by the body data private static signedjwt parsejwt final string data { try { return signedjwt parse data ; } catch parseexception e { log error "parserjwt error class {}, error message {}", e getclass , e getmessage ; throw new customexception httpstatus internal_server_error, "parserjwt error" ; } } // verify jws using samsung public key public requestbody getrequestbody final keyring keyring { final signedjwt signedjwt = jwtutils verify keyring gettargetpublickey , encrypteddata, 60 * 10000 ; // verify and generate jws try { final string strbody = jwtutils getdecryptedpayloadfrom keyring getsourceprivatekey , jweobject parse signedjwt getpayload tostring ; // decryption jwe by the jws return objectmapper readvalue strbody, requestbody class ; // convert to data format requested by client } catch parseexception | jsonprocessingexception e { log error "getrequestbody {}", e getmessage ; throw new customexception httpstatus internal_server_error, "data body parse error" ; } } 2 decrypt the jwe using the jws jweobject parse signedjwt getpayload tostring public static string getdecryptedpayloadfrom final key privatekey, final jweobject data { try { data decrypt new rsadecrypter privatekey privatekey ; // decryption jwe using partner private key return data getpayload tostring ; } catch joseexception e { log error "joseexception message {}", e getmessage ; throw new customexception httpstatus internal_server_error, "getdecryptedpayloadfrom error" ; } } 3 convert to the format send by the client public requestbody getrequestbody final keyring keyring { final signedjwt signedjwt = jwtutils verify keyring gettargetpublickey , encrypteddata, 60 * 10000 ; // verify and generate jws try { final string strbody = jwtutils getdecryptedpayloadfrom keyring getsourceprivatekey , jweobject parse signedjwt getpayload tostring ; // decryption jwe by the jws return objectmapper readvalue strbody, requestbody class ; // convert to data format requested by client } catch parseexception | jsonprocessingexception e { log error "getrequestbody {}", e getmessage ; throw new customexception httpstatus internal_server_error, "data body parse error" ; } } generate mdocestablishment 1 generate rsa key per refid public class transactioncontext { private final keypair keypair; // rsa key private final byte[] clientengagement; // body data received through key api, base64url decoded value @equalsandhashcode exclude private int encryptmessagecounter = 0; // count value when encrypted @equalsandhashcode exclude private int decryptmessagecounter = 0; // count value when decrypted } private cache<string, transactioncontext> contextcache; // rsa key management per refid with memory cache // generate and store rsa key per refid only once upon first request public transactioncontext settransactioncontext final string key, final string base64encodedclientengagement { log info "base64encodedclientpublickey {}", base64encodedclientengagement ; this contextcache put key, new transactioncontext keyutils generatekeypair , base64utils decode base64encodedclientengagement getbytes ; return this gettransactioncontextby key ; } // part of retrieving ras key based on refid public transactioncontext gettransactioncontextby final string key { return optional ofnullable this contextcache getifpresent key orelsethrow -> { log info "{} is empty", key ; return new customexception httpstatus bad_request, "no key matching the refid" ; } ; } 2 create request field values @override public mono<list<string>> createrequest final partnerinputdto inputdto { final string mockdata = "{ \"doctype\" \"org iso 18013 5 1 mdl\", \"namespaces\" { \"org iso 18013 5 1\" { \"sex\" false, \"portrait\" false, \"given_name\" false, \"issue_date\" false, \"expiry_date\" false, \"family_name\" false, \"document_number\" false, \"issuing_authority\" false }, \"org iso 18013 5 1 aamva\" { \"dhs_compliance\" false, \"edl_credential\" false } } }"; return mono just collections singletonlist mockdata ; } 3 generate establishment @allargsconstructor public class establishment { private final transactioncontext context; // info of client public key , partner private key, public key private final list<string> strreqs; // data field information required for authentication to the client private final keyring keyring; // rsa key information for jwt jws + jwe encryption and decryption between wallet backed server and partner server } protected cborobject generate { final cborobject sessionestablishment = cborobject newmap ; sessionestablishment set e_reader_key, cborobject fromobjectandtag keyutils getereaderkey context , tag_size ; // generate onekey by public key in transactioncontext sessionestablishment set data, cborobject fromobject cipherutils encrypt context, generaterequestformat getrequestcborobjectsfrom strreqs ; // add request data field information for authentication return sessionestablishment; } ``` generate the response value jwt jws + jwe 1 generate establishment with jwe public static string encryptedstringjwe final key publickey, final string data { // please enter samsung public key and establishment data final jweobject jwe = new jweobject new jweheader builder jwealgorithm rsa_oaep_256, encryptionmethod a128gcm build , new payload data ; try { jwe encrypt new rsaencrypter rsapublickey publickey ; return jwe serialize ; } catch joseexception e { log error "encryptedstringjwe exception message {}", e getmessage ; throw new customexception httpstatus internal_server_error, "encryptedstringjwe error" ; } } 2 generate jws by jwe public static string generatesignedstringjws final key privatekey, final key publickey, final string payload { // enter your partner’s public key, private key, and jwe data try { final jwsobject jwsobj = new jwsobject getdefaultjwsheader , new payload payload ; jwssigner signer = new rsassasigner new rsakey builder rsapublickey publickey privatekey rsaprivatekey privatekey build ; jwsobj sign signer ; return jwsobj serialize ; } catch joseexception e { log error "encryptedstringjws exception message {}", e getmessage ; throw new customexception httpstatus internal_server_error, "generatesignedstringjws error" ; } } 3 generate jwt jws + jwe public partneroutputdto topartneroutputdto { final cborobject generate = this generate ; final string establishment = base64 geturlencoder encodetostring generate encodetobytes ; final string strjwe = jwtutils encryptedstringjwe keyring gettargetpublickey , establishment ; final jwsheader jwsheader = jwtutils getdefaultjwsheader keyring getversion , keyring getcertificateid , "partnerid" ; return new partneroutputdto jwtutils generatesignedstringjws jwsheader, keyring getsourceprivatekey , keyring getsourcepublickey ,strjwe ; } authentication processing for values in data fields requested for authentication 1 retrieve transactioncontext value stored in cache using refid value @override public mono<transactioncontext> getcontext final partnerinputdto inputdto { return mono just this transactioncontextmanager gettransactioncontextby inputdto getrefid ; } 2 processes the decryption process of the request body data like jwt jws + jwe decryption between wallet backed server and partner server 3 generate mdocresponse public class mdocresponse { private final transactioncontext context; // managed tranactioncontext by refid private final byte[] data; // base64url decoded data after decrypting jwt jws + jwe data public mdocresponse final transactioncontext context, final string inputdto { this context = context; this data = base64utils decode inputdto getbytes standardcharsets utf_8 ; } } 4 get the field values requested for authentication from the data in mdocresponse public string getdata { // sessiondata = { // ? "data" bstr ; encrypted mdoc response or mdoc request // ? "status" uint ; status code // } final cborobject response = cborobject decodefrombytes data ; checktype response, cbortype map ; final cborobject data = response get data ; checktype data, cbortype bytestring ; return cborobject decodefrombytes isencryptedmode ? cipherutils decrypt this context, data getbytestring data getbytestring tojsonstring ; } 5 create a session value using the transactioncontext value managed by refid and then decrypt it private static byte[] processcipher final ciphermode ciphermode, final transactioncontext context, final byte[] bytes { // ciphermode encrypt or decrypt, bytes data passed by the client try { cipher cipher = cipher getinstance "aes/gcm/nopadding" ; final int counter = ciphermode encrypt == ciphermode ? context getencryptmessagecounter context getdecryptmessagecounter ; gcmparameterspec parameterspec = new gcmparameterspec 128, getsessionkeyiv ciphermode identifier, counter ; cipher init ciphermode ciphermode , getsecretkeyspec context, ciphermode info , parameterspec ; return cipher dofinal bytes ; } catch invalidalgorithmparameterexception | nosuchpaddingexception | illegalblocksizeexception | nosuchalgorithmexception | badpaddingexception | invalidkeyexception e { log error "error type {}, message {}", e getclass , e getmessage ; throw new customexception httpstatus internal_server_error, "processcipher error" ; } } 6 examining data received from the client @override public mono<void> authentication final string response { log info "response info {}", response ; return mono empty ; }
Develop Samsung Pay
doc3 3 web checkout sdk 3 3 1 overview samsung pay web checkout enables seamless, secure payments on your website using cards stored in the samsung wallet app this javascript-based sdk makes it easy to integrate samsung pay into your desktop or mobile web checkout experience key features cross-device supportusers can complete purchases on both desktop and mobile browsers samsung wallet integrationpayments are authorized using cards saved in the samsung wallet mobile app secure credential transmissionpayment credentials are securely generated on the mobile device and transmitted to your website multiple authentication optionsusers can bind their device by either entering their samsung account email scanning a qr code displayed on your checkout page user scenario with the service flow the following figures describe the user scenario for making a purchase through samsung pay web checkout payment initiation & device binding the user selects samsung pay as the payment method at checkout a web checkout ui launches, prompting the user to link their device by either enter samsung account email scan a qr code using their mobile device a push notification is sent to their samsung wallet app for mobile devices the user selects samsung pay as the payment method at checkout a payment request pop-up is displayed and prompts the user to select the “pay” button the samsung wallet app automatically opens on the current device user confirmation on mobile device the user taps the notification on their device the samsung wallet app opens a payment sheet showing order details the user selects a payment card and authorizes the purchase payment completion a "verified" screen is shown in the browser as the transaction is confirmed your website receives a secure payment credential from samsung pay you forward this credential to your payment processor to complete the purchase 3 3 2 web checkout integration samsung pay web checkout enables seamless online payments using samsung wallet on supported mobile devices let’s us look how to integrate the web checkout sdk into your website and process secure, tokenized transactions prerequisites before integrating samsung pay web checkout, ensure the following samsung pay merchant id you must complete the partner onboarding process to obtain a valid merchant id tokenization support your acquirer and issuer must support tokenized in-app transactions per card network standards web checkout integration steps to integrate the samsung pay web checkout solution to your website include the samsung pay sdk add the sdk to your website's frontend <script src="https //img mpay samsung com/gsmpi/sdk/samsungpay_web_sdk js"></script> configure payment methods define the supported card brands, protocol, api version, and your service merchant id const paymentmethods = { "version" "2", "serviceid" "dcc1cbb25d6a470bb42926", "protocol" "protocol_3ds", "allowedbrands" ["visa","mastercard"] } initialize the samsung pay client set the environment "stage" – testing with device "stage_without_apk" – testing without device simulated "production" – live environment const samsungpayclient = new samsungpay paymentclient {environment "stage"} ; note if your project has a content-security-policy csp applied, please ensure that you add a nonce to the css to maintain compliance this can be done by updating your sdk configuration as follows const samsungpayclient = new samsungpay paymentclient {environment "stage", nonce "your-nonce"} ; check availability verify samsung pay availability in the user’s browser/device samsungpayclient isreadytopay paymentmethods then function response { if response result { // add a payment button } } catch function err { console error err ; } ; add samsung pay button use the official samsung pay button asset and adhere to branding guidelines <div id="samsungpay-container"> <button id="samsung-pay-btn"> <img src="/your/path /samsung-pay-button png" alt="samsung pay" style="{follow the samsung's official branding guideline}" /> </button> </div> note download the official samsung pay button image and branding guideline from download page and use it directly in your html as shown here download attach click handler add your event handler to the button document getelementbyid "samsung-pay-btn" addeventlistener "click", onsamsungpaybuttonclicked ; create the transaction detail define transaction metadata such as order info, merchant details, and total amount const transactiondetail = { "ordernumber" "dstrf345789dsgty", "merchant" { "name" "virtual shop", "url" "virtualshop com", "id" "xn7qfnd", "countrycode" "us" }, "amount" { "option" "format_total_estimated_amount", "currency" "usd", "total" 300 } } launch payment flow trigger the web checkout interface when the user clicks the payment button when the onclick event is triggered, your event handler must call the loadpaymentsheet method, which initiates the web checkout ui flow when the user confirms the payment from their mobile device, you receive the paymentcredential object generated by the device note extract the payment credential information from the 3ds data key within the paymentcredential object and process it through your payment provider inform the samsung server of the payment result using the notify method within the paymentresult object samsungpayclient loadpaymentsheet paymentmethods, transactiondetail then paymentcredential => { // forward paymentcredential to your payment provider const paymentresult = { const paymentresult = { "status" "charged", "provider" "pg name" } samsungpayclient notify paymentresult ; } catch error => { payment credential sample the paymentcredential is the resulting output of the loadpaymentsheet method sample paymentcredential json output using jwe-only { "method" "3ds", "recurring_payment" false, "card_brand" "visa", "card_last4digits" "8226", "3ds" { "type" "s", "version" "100", "data" "eyjhbgcioijsu0exxzuilcjrawqioiixzhlsbkfvrvjttk53z0j0mmvzcevwu1poswrzzghqbvi3bzhqcdvkagvbpsisinr5cci6ikppu0uilcjjagfubmvsu2vjdxjpdhldb250zxh0ijoiulnbx1blssisimvuyyi6ikexmjhhq00ifq jykxn2h9pk1uj-4knpuij1r49ykw7-3aelznhadzsztclvjlhoyjomujfl1h21yq_5rmdwz9lj6o67j8m6kn_1dnkvnqaugi203ol5tegf-j15n_pcinj1nycfyivohazidbg9fq2nzts_muu9cvykiz-ifsuz6rfl9aiuoakjpctzpn8lwlddzxzme3j86sd45i-ahxwbujfvy9d2zrt1sddgoxgorjrzy3o5s29pybkaytjmcpc_jicu-sdsx3s1snm_cvhaqiccoxyidih6hfwo35fsswysvxu8yfpgtwbcdai9ujkptvr7npnp1ch85ja3dvw3mi87v-pwiqmw hdzesnbxu0d0t68e pcv1csibw7jgtlgfoovmebm-wggpw9rhonbkdb_qwwfl_cuf7_0nj_knuozq4pudk0_vzktbhi3kv0gt2ybmqs6zfpnxd3cdpgk_lyio8z8xciasoz5vltamjg7n5maadxxpvqwtcpk_tbksve2ke8w7r3u4kapfjl2ene06j3e4rkae367x8_aoxy2l3lhoeqzl4lfsntfs71xfc-s9h5-bgi2clkba-9hlrtpbxtumwa830rwywm7m fs5-tfbxq73l7icrrwkbla" } } the decrypted output will be similar to this { "amount" "100", "currency_code" "usd", "utc" "1719388643614", "eci_indicator" "5", "tokenpan" "5185731679991253", "tokenpanexpiration" "0127", "cryptogram" "akkeavcvwhfmammud6r3aoacfa==" } note for information about the content of the paymentmethods, transactiondetail, and paymentcredential data structures, see the api reference 3 3 3 decrypting payment credentials for security, samsung pay encrypts the payment credential using json web encryption jwe you must decrypt this payload to extract the payment token and process the transaction to decrypt the payment credentials, generate a der file from your private key $ openssl pkcs8 -topk8 -in merchant key -outform der -nocrypt -out rsapriv der decrypt the jwe encrypted data sample implementation in java import java nio file files; import java nio file paths; import java security keyfactory; import java security interfaces rsaprivatekey; import java security spec pkcs8encodedkeyspec; import java util base64; import javax crypto cipher; import javax crypto spec gcmparameterspec; import javax crypto spec secretkeyspec; import com fasterxml jackson databind jsonnode; import com fasterxml jackson databind objectmapper; public class developerportalsample { public static void main string[] args throws exception { // example jwe string replace with your actual jwe and private key path string encryptedtext = {{encryptedpayload}}; string privatekeypath = " /rsapriv der"; string private_key = base64 getencoder encodetostring files readallbytes paths get privatekeypath ; string result = decryptjwe encryptedtext, private_key ; system out println result ; } public static string decryptjwe string encryptedtext, string privatekeytext throws exception { // split jwe parts by ' ' string delims = "[ ]"; string[] tokens = encryptedtext split delims ; if tokens length < 5 { throw new illegalargumentexception "invalid jwe format" ; } // decode and parse jwe header byte[] headerbytes = base64 geturldecoder decode tokens[0] ; string headerjson = new string headerbytes ; objectmapper mapper = new objectmapper ; jsonnode header = mapper readtree headerjson ; // extract algorithm information from header string alg = header has "alg" ? header get "alg" astext "rsa1_5"; string enc = header has "enc" ? header get "enc" astext "a128gcm"; // convert private key byte[] privatekeybytes = base64 getdecoder decode privatekeytext ; pkcs8encodedkeyspec privatekeyspec = new pkcs8encodedkeyspec privatekeybytes ; keyfactory keyfactory = keyfactory getinstance "rsa" ; rsaprivatekey privatekey = rsaprivatekey keyfactory generateprivate privatekeyspec ; // decode encrypted key, iv, ciphertext, and authentication tag byte[] enckey = base64 geturldecoder decode tokens[1] ; byte[] iv = base64 geturldecoder decode tokens[2] ; byte[] ciphertext = base64 geturldecoder decode tokens[3] ; byte[] tag = base64 geturldecoder decode tokens[4] ; // create cipher instance based on key management algorithm string keymanagementalgorithm; boolean useaad = false; if "rsa-oaep" equals alg { keymanagementalgorithm = "rsa/ecb/oaeppadding"; // at samsung, oaep uses aad additional authenticated data useaad = true; } else if "rsa1_5" equals alg { keymanagementalgorithm = "rsa/ecb/pkcs1padding"; // while rsa1_5 does not use aad useaad = false; } else { throw new illegalargumentexception "unsupported key management algorithm " + alg ; } // decrypt the cek content encryption key cipher decryptcipher = cipher getinstance keymanagementalgorithm ; decryptcipher init cipher decrypt_mode, privatekey ; byte[] plainenckey = decryptcipher dofinal enckey ; // create cipher instance based on content encryption algorithm string contentencryptionalgorithm; int gcmtaglength; if "a128gcm" equals enc || "a256gcm" equals enc { contentencryptionalgorithm = "aes/gcm/nopadding"; gcmtaglength = 128; } else { throw new illegalargumentexception "unsupported content encryption algorithm " + enc ; } // decrypt the content cipher contentcipher = cipher getinstance contentencryptionalgorithm ; gcmparameterspec gcmparameterspec = new gcmparameterspec gcmtaglength, iv ; secretkeyspec keyspec = new secretkeyspec plainenckey, "aes" ; contentcipher init cipher decrypt_mode, keyspec, gcmparameterspec ; // aad handling use base64url-encoded header bytes as aad if useaad { byte[] encodedheader = base64 geturlencoder withoutpadding encode headerbytes ; contentcipher updateaad encodedheader ; } // concatenate ciphertext and tag, then pass to dofinal byte[] cipherdata = new byte[ciphertext length + tag length]; system arraycopy ciphertext, 0, cipherdata, 0, ciphertext length ; system arraycopy tag, 0, cipherdata, ciphertext length, tag length ; byte[] plaintext = contentcipher dofinal cipherdata ; return new string plaintext, java nio charset standardcharsets utf_8 ; } sample implementation in c# using system; using system io; using system text; using system text json nodes; using system security cryptography; public static void main string[] args { // example jwe string replace with your actual jwe and private key path string encryptedtext = {{encryptedpayload}}; string privatekeypath = /rsapriv der"; // read the private key file der format byte[] privatekeybytes = file readallbytes privatekeypath ; // decrypt the jwe string result = decryptjwe encryptedtext, privatekeybytes ; // print the result console writeline result ; } public static string decryptjwe string encryptedtext, byte[] privatekeybytes { // split jwe parts by ' ' var parts = encryptedtext split ' ' ; if parts length < 5 throw new argumentexception "invalid jwe format" ; // decode and parse jwe header var headerbytes = base64urldecode parts[0] ; var headerjson = encoding utf8 getstring headerbytes ; var header = jsonnode parse headerjson ; // extract algorithm information from header string alg = header?["alg"]? tostring ?? "rsa1_5"; string enc = header?["enc"]? tostring ?? "a128gcm"; // convert private key assume pkcs8 der using var rsa = rsa create ; rsa importpkcs8privatekey privatekeybytes, out _ ; // decode encrypted key, iv, ciphertext, and authentication tag var enckey = base64urldecode parts[1] ; var iv = base64urldecode parts[2] ; var ciphertext = base64urldecode parts[3] ; var tag = base64urldecode parts[4] ; // create cipher instance based on key management algorithm bool useaad = false; if alg == "rsa-oaep" { // at samsung, oaep uses aad additional authenticated data useaad = true; } else if alg == "rsa1_5" { // while rsa1_5 does not use aad useaad = false; } else { throw new argumentexception $"unsupported key management algorithm {alg}" ; } // decrypt the cek content encryption key byte[] plainenckey = alg == "rsa-oaep" ? rsa decrypt enckey, rsaencryptionpadding oaepsha1 rsa decrypt enckey, rsaencryptionpadding pkcs1 ; // decrypt the content using var aes = new aesgcm plainenckey, 16 ; var plaintext = new byte[ciphertext length]; if useaad { // aad handling use base64url-encoded header bytes as aad var encodedheader = encoding ascii getbytes base64urlencode headerbytes ; aes decrypt iv, ciphertext, tag, plaintext, encodedheader ; } else { aes decrypt iv, ciphertext, tag, plaintext ; } return encoding utf8 getstring plaintext trimend '\0' ; } private static byte[] base64urldecode string input { string s = input replace '-', '+' replace '_', '/' ; switch s length % 4 { case 2 s += "=="; break; case 3 s += "="; break; } return convert frombase64string s ; } private static string base64urlencode byte[] input { return convert tobase64string input trimend '=' replace '+', '-' replace '/', '_' ; } 3 3 4 integration on webview configure webview enablements to invoke samsung pay application in webview, you should override the shouldoverrideurlloading method javascript and dom storage are disabled in a webview by default you can enable through the websettings attached to your webview websettings allows any website to use javascript and dom storage for more information, visit websettings sample code kotlin import android webkit webview import android webkit webviewclient import android content intent import android content activitynotfoundexception companion object { private const val samsung_pay_url_prefix string = "samsungpay" private const val samsung_app_store_url string = "samsungapps //productdetail/com samsung android spay" } private lateinit var webview webview webview settings run { javascriptenabled = true domstorageenabled = true } webview webviewclient = object webviewclient { override fun shouldoverrideurlloading view webview, request webresourcerequest boolean { // get url from webresourcerequest val url = request url tostring // add below if statement to check if url is samsung pay or samsung app store deep link if url startswith samsung_pay_url_prefix || url startswith samsung_app_store_url , ignorecase = false { try { val intent = intent parseuri url, intent uri_intent_scheme startactivity intent } catch e activitynotfoundexception { // exception would be occured if the samsung wallet app is not installed // go to install samsung wallet app from market val installintent = intent parseuri "samsungapps //productdetail/com samsung android spay", intent uri_intent_scheme installintent addflags intent flag_activity_new_task startactivity installintent } // return true will cause that the url will not be loaded in webview return true } // the remaining part of the shouldoverrideurlloading method code // return false when you want to load url automatically by webview return false } } 3 3 5 sample implementation the following sample code implements the samsung pay web checkout button on a merchant site the implementation steps are described in web checkout integration for information about the content of the paymentmethods, transactiondetail, and paymentcredential data structures, see the api reference <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <script src="https //img mpay samsung com/gsmpi/sdk/samsungpay_web_sdk js"></script> </head> <body> <div id="samsungpay-container"></div> <script> const samsungpayclient = new samsungpay paymentclient {environment "stage"} ; let paymentmethods = { version "2", serviceid "dcc1cbb25d6a470bb42926", protocol "protocol_3ds", allowedbrands ["visa","mastercard"] } samsungpayclient isreadytopay paymentmethods then function response { if response result { createandaddbutton ; } } catch function err { console error err ; } ; function createandaddbutton { const samsungpaybutton = samsungpayclient createbutton { onclick onsamsungpaybuttonclicked, buttonstyle "black", type "buy" } ; document getelementbyid "samsungpay-container" appendchild samsungpaybutton ; } function onsamsungpaybuttonclicked { let transactiondetail = { ordernumber "dstrf345789dsgty", merchant { name "virtual shop", url "virtualshop com", id "xn7qfnd", countrycode "us" }, amount { option "format_total_estimated_amount", currency "usd", total 300 } } samsungpayclient loadpaymentsheet paymentmethods, transactiondetail then function paymentcredential { console log "paymentcredential ", paymentcredential ; const paymentresult = { "status" "charged", "provider" "pg name" } samsungpayclient notify paymentresult ; } catch function error { console log "error ", error ; } ; } </script> </body> </html> 3 3 6 api reference let us learn the description of data structures used in the samsung pay web checkout api integration paymentmethods the paymentmethods object defines the payment methods that the merchant supports "paymentmethods" data structure elements key type required description version string required samsung pay api versionthe supported value is 2 serviceid string required merchant id that is assigned after onboarding protocol string required payment protocol typethe supported value is protocol_3ds allowedbrands list<string> required list of supported card brandsthe possible values are visamastercardamexdiscoverelomadacbjaywan tbd isrecurring boolean optional value if payment is recurringthe default value is false isbillingaddressrequired boolean optional value if billing address must be included in the payment credentials the default value is false iscardholdernamerequired boolean optional value if cardholder name must be included in the payment credentials the default value is false iscpfcardrequired boolean optional value if cpf must be included in the payment credentials the default value is false merchantchoicebrands object optional data structure containing configuration information for a co-badged card merchantchoicebrands type string required co-badged card display option for the payment sheetthe possible values are mandatory = only the brand defined in merchantchoicebrands brands is enabledpreference = the brand defined in merchantchoicebrands brands is selected by default but the user can change it merchantchoicebrands brands list<string> required list of supported brands for the co-badged cardthe possible values are madacb extrapaymentinfo object optional data structure containing additional supported features extrapaymentinfo id string required feature id for the additional featurethe possible values are combocard = combo carddsrp = digital secure remote payment extrapaymentinfo type string optional feature type, if the value of extrapaymentinfo id is dsrpthe possible values are ucaf = universal cardholder authentication fieldicc = integrated circuit cardthe default value is ucaf transactiondetail the transactiondetail object contains the transaction information for the user's purchase "transactiondetail" data structure elements key type required description ordernumber string required order number of the transactionthe following characters are allowed [a-z][a-z][0-9,-] merchant object required data structure containing merchant information merchant name string required merchant name merchant url string required merchant domain urlthe maximum length is 100 characters merchant id string conditional a unique identifier, known as the merchant unique id, is assigned by either merchant or the payment gateway pg or payment orchestrator po when a merchant is onboarded into their system this id is required in specific scenarios, namely when onboarding as a pg or po with samsung, or if the token brand is "mada" or the merchantchoicebrands brands includes "mada" the character limit for this id varies 15 characters for "mada" token brands and 45 characters for all other cases merchant countrycode string required merchant country codeiso-3166-1 alpha-2 amount object required data structure containing the payment amount amount option string required display format for the total amount on the payment sheetthe possible values are format_total_estimated_amount = display "total estimated amount " and total amountformat_total_price_only = display the total amount only amount currency string required currency codethe maximum length is 3 characters amount total string required total payment amount in the currency specified by amount currencythe amount must be an integer for example, 300 or in a format valid for the currency such as 2 decimal places after a separator, for example, 300 50 type string optional transaction typethis value is specifically supported for mada tokens and will not apply to other token types the possible values are purchasepreauthorizationthe default value is purchase paymentcredential the paymentcredential object contains the payment credential information generated by the samsung wallet application on the user's mobile device paymentcredential data structure elements key type required description card_brand string required brand of the payment card card_last4digit object required last 4 digits of the card number 3ds object required data structure containing the generated 3ds data 3ds type string optional 3ds typethe value is s for samsung pay 3ds version string required 3ds versionthe value for the current version is 100 3ds data string required encrypted payment credential data recurring_payment boolean required value if credential is enabled for recurringthe default value is false encryptedmessage string conditional encrypted string jwe that contains billing address, cardholder name and cpf when required by partner it can be decrypted in the same way as payment credentials encryptedmessage the decrypted encryptedmessage object in paymentcredential object contains billing address, cardholder name and cpf when required by partner "encryptedmessage" data structure elements key type required description billingaddress object conditional billing address billingaddress addressline1 string required address line 1 billingaddress addressline2 string optional address line 2 billingaddress city string required city billingaddress state string conditional state billingaddress countrycode string required country code iso 3166-1 alpha-3 billingaddress postalcode string required postal code cardholdername string conditional cardholder name cpf object conditional brazilian cpf cpf name string required the full name of the individual associated with the cpf cpf number string required the brazilian taxpayer number cpf , consisting of exactly 11 digits, without hyphens or dots paymentresult the paymentresult object contains the payment result information during transaction processing, and after the payment is processed with pg network paymentresult data structure elements key type required description status string required payment statusthe possible values are charged = payment was charge successfullycanceled = payment was canceled by either user, merchant, or acquirerrejected = payment was rejected by acquirererred = an error occurred during the payment process provider string optional payment provider pg name 3 3 7 partner checklist checklist for samsung pay web checkout on the merchant website, verify if the following functions works as expected samsung pay is available in the payment options section of the website samsung pay logo is displayed correctly in the payment options section after the samsung pay payment option is selected, the account/scan qr and email input options are displayed, and redirects the user to the samsung wallet app on their mobile device for the account option, “request to pay” and “cancel” buttons are displayed for the email option, “next” and “cancel” buttons, and a way to reset id are displayed for the scan qr option, the request automatically times out if you wait for more than 5 minutes, and you are redirected to the checkout screen once redirected to the samsung wallet app, “pay” and “cancel” buttons are displayed on a mobile browser, after the samsung pay payment option is selected, “continue with samsung pay” button is displayed samsung checkout screen is displayed the merchant domain name is displayed the order summary which contains the amount due, and product name is displayed the payment method selected is “samsung wallet” the contact information displays the customer’s name, phone, and email you should be able to modify this information, if needed “continue” and “cancel” buttons are displayed note these are relevant if you are executing an end-to-end test you can skip these tests if you are using a test transaction setup on the samsung wallet app via your test device, verify if the following functions works as expected a default card is displayed on the payment sheet the card name and last 4 digits of the card is displayed on the payment sheet you are able to change the card when multiple cards are enrolled in samsung pay if you requested for the transaction using billingaddress parameter, the billing address is displayed on the payment sheet the billing address can be filled and modified depending on the amount option parameter, the payment amount is displayed as “total” or “total estimated amount ” the merchant name is displayed on the payment sheet the pin/biometric authentication option is displayed to proceed with payment confirmation the “verified” checkmark is displayed in blue upon payment confirmation if you are testing with actual cards, and samsung wallet is in production environment, confirm the transaction notification on the mobile phone is displayed once the purchase is made on transaction completion, verify the following on the merchant website the payment completion screen is displayed on the mobile or non-mobile device, depending where the transaction is initiated you are able to initiate a payment using samsung pay with a card already added for the merchant’s website basic card
Develop Samsung Pay
api apioverview package class tree index help package com samsung android sdk samsungpay v2 class watchmanager java lang object samsungpaybase com samsung android sdk samsungpay v2 watchmanager all implemented interfaces apptoappconstants public final class watchmanager extends samsungpaybase implements apptoappconstants this class provides apis for watch management partner apps must check the samsung pay watch status on the device before performing any card management also, this class provides apis getting cards information, adding new card to samsung pay on watch, and so on since api level 2 5 field summary fields modifier and type field description static final string device_serial_num key to represent device serial number to generate the paymentappinstanceid static final int error_invalid_parameter this error indicates that the given parameter is invalid this is returned as spaysdk extra_error_reason for spaysdk error_registration_fail error static final int error_spay_pin_lock_setup_canceled this error indicates that user canceled the pin lock setup partner app should ask user to setup pin for samsung pay gear static final int error_spay_watch_connection this error indicates that samsung pay watch plug-in can not connect with samsung pay watch partner app should ask user to check bluetooth connection or pairing static final int error_spay_watch_pay_progress this error indicates that samsung pay watch is in a process of payment static final int error_spay_watch_pin_lock_setup_canceled this error indicates that user canceled the pin lock setup partner app should ask user to setup pin for samsung pay watch static final int spay_watch_taking_log_for_report this error indicates that samsung pay watch is taking log for error report static final int spay_watch_update_is_ongoing this error indicates that samsung pay watch being updated fields inherited from interface com samsung android sdk samsungpay v2 apptoappconstants error_auth_code_expired, error_auth_code_invalid, error_auth_code_max_try_reached, error_auth_code_type_invalid, error_authentication_closed, error_authentication_failed, error_authentication_not_ready, error_authentication_timed_out, error_card_already_registered, error_card_idv_not_supported, error_card_not_supported, error_framework_internal, error_invalid_card, error_invalid_cardinput, error_max_card_num_reached, error_max_pan_provision_num_reached, error_server_reject, error_tsm_fail, error_verify_card, error_wallet_id_mismatch, extra_app2app_intent, extra_app2app_payload, extra_card_balance, extra_card_status_reason, extra_issuer_app_card_linked constructor summary constructors constructor description watchmanager android content context context, partnerinfo partnerinfo api to get the watchmanager instance the caller should set valid serviceid method summary all methodsinstance methodsconcrete methods modifier and type method description void activatesamsungpay api to bring the samsung pay on watch app to a state in which cards can be added samsung pay on watch might be samsung account is not signed in state partner app checks the samsung pay on watch status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_setup_not_completed, partner app can call this api to launch samsung pay on watch and user can sign in to the app void addcard addcardinfo addcardinfo, addcardlistener listener api to add a card from partner app example issuer/bank app to samsung pay on watch partner app uses this api to add card to samsung pay on watch by providing the required card details void getallcards android os bundle cardfilter, getcardlistener listener api to get all the cards from samsung pay on watch for the given filter void getsamsungpaystatus statuslistener listener api to get the samsung pay on watch status on the device partner issuers applications must call this api to check the current state of samsung pay on watch before doing any operation void getwalletinfo list<string> keys, statuslistener listener api to get the requested wallet information from samsung pay on watch partner app can use this information to uniquely identify the user and samsung pay on watch app on a particular device void gotoupdatepage api to go to samsung pay on watch update page partner app checks the samsung pay on watch status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_app_need_to_update, partner app can call this api to go to update samsung pay on watch app methods inherited from class java lang object equals, getclass, hashcode, notify, notifyall, tostring, wait, wait, wait field details device_serial_num public static final string device_serial_num key to represent device serial number to generate the paymentappinstanceid since api level 2 5 see also constant field values error_spay_pin_lock_setup_canceled public static final int error_spay_pin_lock_setup_canceled this error indicates that user canceled the pin lock setup partner app should ask user to setup pin for samsung pay gear since api level 2 5 see also constant field values error_invalid_parameter public static final int error_invalid_parameter this error indicates that the given parameter is invalid this is returned as spaysdk extra_error_reason for spaysdk error_registration_fail error since api level 2 5 see also constant field values error_spay_watch_pin_lock_setup_canceled public static final int error_spay_watch_pin_lock_setup_canceled this error indicates that user canceled the pin lock setup partner app should ask user to setup pin for samsung pay watch since api level 2 5 see also constant field values spay_watch_update_is_ongoing public static final int spay_watch_update_is_ongoing this error indicates that samsung pay watch being updated since api level 2 5 see also constant field values spay_watch_taking_log_for_report public static final int spay_watch_taking_log_for_report this error indicates that samsung pay watch is taking log for error report since api level 2 5 see also constant field values error_spay_watch_pay_progress public static final int error_spay_watch_pay_progress this error indicates that samsung pay watch is in a process of payment since api level 2 5 see also constant field values error_spay_watch_connection public static final int error_spay_watch_connection this error indicates that samsung pay watch plug-in can not connect with samsung pay watch partner app should ask user to check bluetooth connection or pairing since api level 2 5 see also constant field values constructor details watchmanager public watchmanager android content context context, partnerinfo partnerinfo api to get the watchmanager instance the caller should set valid serviceid partnerinfo is passed to samsung pay on watch for caller verification context ct = activity; // or context ct = service; string issuername = "mybank"; // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring watchmanager extra_issuer_name, issuername ; bundle putstring watchmanager partner_service_type, watchmanager servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; watchmanager watchmanager = new watchmanager ct, pinfo ; parameters context - activity context or service context partnerinfo - partner information throws nullpointerexception - thrown if parameters are null since api level 2 5 method details getsamsungpaystatus public void getsamsungpaystatus @nonnull statuslistener listener api to get the samsung pay on watch status on the device partner issuers applications must call this api to check the current state of samsung pay on watch before doing any operation // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring watchmanager partner_service_type, watchmanager servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; watchmanager watchmanager = new watchmanager context, pinfo ; watchmanager getsamsungpaystatus new statuslistener { @override public void onsuccess int status, bundle data { // success case if status == spay_ready { log d tag, "samsung pay on watch is ready on the device" ; // perform your operation } else if status == spay_not_ready { // samsung pay on watch is supported but not fully ready // if extra_error_reason is error_spay_app_need_to_update, // call gotoupdatepage // if extra_error_reason is error_spay_setup_not_completed, // call activatesamsungpay } else { // samsung pay on watch is not supported on this device log d tag, "device does not support samsung pay on watch" ; } } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle such as watchmanager extra_error_reason if provided } } ; parameters listener - callback through which the result is provided on success, samsung pay on watch status code is provided via statuslistener onsuccess int status, bundle data if samsung pay on watch is ready to be used, #spay_ready will be returned otherwise, #spay_not_ready or #spay_not_supported can be returned with #extra_error_reason from bundle also, partner can get extra information from bundle data bundle keys if provided bundle values spaysdk extra_country_code device country code iso 3166-1 alpha-2 on any failure, the failure code is provided via statuslistener onfail int errorcode, bundle errordata note please refer spaysdk common_status_table in detail throws nullpointerexception - thrown if the callback passed is null since api level 2 5 gotoupdatepage public void gotoupdatepage api to go to samsung pay on watch update page partner app checks the samsung pay on watch status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_app_need_to_update, partner app can call this api to go to update samsung pay on watch app // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring watchmanager partner_service_type, watchmanager servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; watchmanager watchmanager = new watchmanager context, pinfo ; watchmanager gotoupdatepage ; since api level 2 5 activatesamsungpay public void activatesamsungpay api to bring the samsung pay on watch app to a state in which cards can be added samsung pay on watch might be samsung account is not signed in state partner app checks the samsung pay on watch status with getsamsungpaystatus statuslistener api if the status is #spay_not_ready and #extra_error_reason is #error_spay_setup_not_completed, partner app can call this api to launch samsung pay on watch and user can sign in to the app // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring watchmanager partner_service_type, watchmanager servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; watchmanager watchmanager = new watchmanager context, pinfo ; watchmanager activatesamsungpay ; since api level 2 5 getwalletinfo public void getwalletinfo list<string> keys, @nonnull statuslistener listener api to get the requested wallet information from samsung pay on watch partner app can use this information to uniquely identify the user and samsung pay on watch app on a particular device // set the serviceid which is assigned by the samsung pay developer during on boarding string serviceid = "sampleserviceid"; bundle bundle = new bundle ; bundle putstring watchmanager extra_issuer_name, "issuer name" ; bundle putstring watchmanager partner_service_type, watchmanager servicetype app2app tostring ; partnerinfo pinfo = new partnerinfo serviceid, bundle ; watchmanager watchmanager = new watchmanager context, pinfo ; // bundle keys added to get wallet information from samsung pay on watch // this information can be delivered to the partner server for eligibility check arraylist<string> keys = new arraylist<> ; keys add watchmanager wallet_user_id ; keys add watchmanager device_id ; watchmanager getwalletinfo keys, new statuslistener { @override public void onsuccess int status, bundle walletdata { // log d tag, "dowalletinfo onsuccess callback is called" ; // for visa, deviceid can be set to "clientdeviceid" as defined by visa string deviceid = walletdata get watchmanager device_id ; // for visa, walletuserid can be set to "clientwalletaccountid" as defined by visa string walletuserid = walletdata get watchmanager wallet_user_id ; } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle such as watchmanager extra_error_reason if provided } } parameters keys - key list to get wallet information if the list is empty, all possible key values are returned the possible keys are #wallet_dm_id #device_id #wallet_user_id device_serial_num listener - callback through which the result is provided on success, statuslistener onsuccess int status, bundle data is invoked with wallet information the success code can be one of the following codes with bundle data status bundle keys bundle values usage vts mdes #error_none #wallet_dm_id string device management id n/a paymentappinstanceid = device_serial_num + wallet_dm_id *if you need 'paymentappinstanceid', you can generate it as above #device_id string device id clientdeviceid #wallet_user_id string wallet user id clientwalletaccountid device_serial_num string device serial number n/a on any failure, the error code is provided via statuslistener onfail int errorcode, bundle errordata note please refer spaysdk common_status_table in detail throws nullpointerexception - thrown if parameters are null since api level 2 5 addcard public void addcard @nonnull addcardinfo addcardinfo, @nonnull addcardlistener listener api to add a card from partner app example issuer/bank app to samsung pay on watch partner app uses this api to add card to samsung pay on watch by providing the required card details this helps user to add their cards to samsung pay on watch directly from partner app watchmanager watchmanager = new watchmanager ct, pinfo ; string cardtype = card card_type_credit; string tokenizationprovider = addcardinfo provider_abcd; // get it from issuer app // samsung pay on watch does not provide detailed payload information // generate provisioning payload in accordance with your card network specifications string testpayload = "thisistestpayloadcardinfo1234567890"; bundle carddetail = new bundle ; carddetail putstring addcardinfo extra_provision_payload, testpayload ; addcardinfo addcardinfo = new addcardinfo cardtype, tokenizationprovider, carddetail ; watchmanager addcard addcardinfo, new addcardlistener { @override public void onsuccess int status, card card { log d tag, "onsuccess callback is called" ; } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle // such as watchmanager extra_error_reason or watchmanager extra_request_id if provided } @override public void onprogress int currentcount, int totalcount, bundle bundledata { log d tag,"onprogress callback is called " + currentcount + " / " + totalcount ; } } ; parameters addcardinfo - detail card information to add listener - callback through which the result is provided on success, addcardlistener onsuccess int, card is invoked with #error_none status code with added card information on any failure, the error code is provided via addcardlistener onfail int errorcode, bundle errordata the failure code can be one of the following codes with bundle data status bundle keys bundle values #error_registration_fail -104 #extra_error_reason apptoappconstants error_card_already_registered -500 apptoappconstants error_framework_internal -501 apptoappconstants error_invalid_card -502 apptoappconstants error_invalid_cardinput -503 error_invalid_parameter -504 apptoappconstants error_server_reject -505 apptoappconstants error_max_card_num_reached -506 apptoappconstants error_card_not_supported -514 apptoappconstants error_max_pan_provision_num_reached -515 apptoappconstants error_wallet_id_mismatch -516 error_spay_watch_pin_lock_setup_canceled -701 spay_watch_update_is_ongoing -702 spay_watch_taking_log_for_report -703 error_spay_watch_pay_progress -704 error_spay_watch_connection -705 #extra_request_id string value returned from server note please refer spaysdk common_status_table for other error status throws nullpointerexception - thrown if parameters are null since api level 2 17 getallcards public void getallcards @nullable android os bundle cardfilter, @nonnull getcardlistener listener api to get all the cards from samsung pay on watch for the given filter since api level 2 5, partner must define issuer names as a card filter on samsung pay developers while on-boarding bundle cardfilter = new bundle ; watchmanager getallcards cardfilter, new getcardlistener { @override public void onsuccess list<card> cards { // getting card status is success if cards == null || cards isempty { log e tag,"no card is found" ; return; } else { // perform operation with card data for card s cards { log d tag, "cardid " + s getcardid + "cardstatus" + s getcardstatus ; // get extra card data if s getcardinfo != null { string last4fpan = s getcardinfo getstring watchmanager extra_last4_fpan ; string last4dpan = s getcardinfo getstring watchmanager extra_last4_dpan ; string cardtype = s getcardinfo getstring watchmanager extra_card_type ; string cardissuername = s getcardinfo getstring watchmanager extra_issuer_name ; log d tag, "last4fpan " + last4fpan + "last4dpan" + last4dpan + "app2apppayload " + app2apppayload ; } } } } @override public void onfail int errorcode, bundle errordata { log e tag, "onfail callback is called, errorcode " + errorcode ; // to get more reason of the failure, // check some extra error codes in the errordata bundle such as watchmanager extra_error_reason if provided } } ; parameters listener - callback through which the result is provided on success, getcardlistener onsuccess list is invoked with list of cards on any failure, the error code is provided via getcardlistener onfail int, bundle note please refer spaysdk common_status_table in detail throws nullpointerexception - thrown if listener is null since api level 2 13 samsung electronics samsung pay sdk 2 22 00 - nov 19 2024
Develop Samsung Pay
doc3 4 save to pay 3 4 1 overview save to pay s2p is a secure integration service by samsung pay that enables partners to store and access user payment credentials for future transactions the communication between the partner’s backend and the save to pay server is protected by mutual ssl two-way ssl authentication, ensuring that both the client and server validate each other's identities key highlights uses a custom certificate authority ca managed by samsung pay techops requires ip allowlisting for both staging and production environments communication is secured over tls 1 2 involves both inbound partner → s2p and outbound s2p → partner api communications, secured via ssl and authenticated with client certificates and headers 3 4 2 endpoints there are 2 endpoints available - staging & production staging will be used for development and integration testing access to these endpoints is restricted to allowlisted ip addresses partner should provide the external ip addresses during the onboarding process supported protocols - tlsv1 2 staging https //s2p-api stg mpay samsung com production https //s2p-api mpay samsung com 3 4 3 onboarding steps to begin integration, follow these onboarding steps step 1 submit a certificate signing request csr partners must generate and send a csr to samsung, along with the following details common name cn for the client certificate partner server base url for receiving outbound notifications from the s2p server external ip address to be added to the access allowlist step 2 receive certificate and partner id samsung will sign the csr using its internal ca and return the client certificate a unique partner id will be issued for each environment this partner id must be included in the headers of every request made to the s2p server 3 4 4 authentication overview mutual ssl is used for both inbound and outbound communication between the partner and the save to pay system inbound partner → save to pay server all requests must be secured with mutual ssl partners connect using the client certificate issued by samsung every request must include the partner id in the header partner ids are environment-specific different for staging and production outbound save to pay server → partner s2p communicates with partner servers over mutual ssl samsung will use a client certificate signed by the partner’s ca partner must be able to validate s2p’s certificate for inbound requests 3 4 5 security protocols protocol tls v1 2 authentication mutual ssl two-way tls certificates partner-to-s2p samsung issues the client certificate s2p-to-partner partner issues the client certificate to samsung 3 4 6 best practices the best practices are keep your client certificate secure and monitor expiration dates log and monitor all inbound/outbound requests for verification and debugging maintain a staging environment for ongoing testing 3 4 7 external api specification the external api specification in the context of samsung's save to pay s2p service refers to the structured guidelines and protocols that define how external partner systems can securely interact with the s2p platform this specification encompasses authentication methods, data formats, api endpoints, and integration workflows to ensure seamless and secure provisioning of payment cards into the samsung wallet app 3 4 8 integration workflow the integration involves several key steps initialization & ui setup step 1–2 register session the partner server initiates the flow by registering with the s2p server on success, it receives regid a unique session identifier must be cached for session tracking welcomeurl a hosted ui url that guides the user through the card addition process step 3 display welcome ui the partner's frontend embeds the welcomeurl ui typically in an <iframe> the ui shows a qr code and clear instructions for the user to continue user interaction step 4 user launches samsung wallet spay wa the user opens the samsung wallet app and scans the qr code shown on the welcome ui if the app is not installed, the ui directs the user to download the samsung wallet app sign in with their samsung account session linking & device validation step 5–6 initiate request & device association spay wa scans the qr code and triggers an initiate request to the s2p server s2p validates the payload and links the device info with the regid the server also forwards the device metadata to the partner server device id wallet id user id the welcome ui updates to show that linking was successful card pre-provisioning step 7–8 partner pre-provisions card the partner server contacts the issuer to pre-provision the card retrieve the encrypted issuerblob which contains secure card/token information step 9 return issuerblob the partner server includes the issuerblob in its notify response back to the s2p server this blob is encrypted only the issuer can decrypt it is device- and wallet-specific only usable by the original device format depends on the issuer step 10 deliver to device the s2p server includes the issuerblob and any other metadata in the initiate response back to the spay wa tokenization steps 11–16 add token in samsung pay spay wa initiates the standard tokenization process using the issuerblob the token is securely added to the samsung wallet for use in nfc or online transactions completion & confirmation step 17 notify s2p server after successful provisioning, spay wa notifies the s2p server that the card/token was added successfully for the given regid step 18 notify partner the s2p server sends a final callback to the partner server confirming the process is completed for the regid 3 4 9 data types type json type format description string string size 2048 boolean boolean object object enum string pattern [a-za-z0-9_]{1,256 values from a limited set are only allowed each field of type enum will define the values allowed phonenumber string pattern [0-9+ -]+ uuid string pattern [a-za-z0-9-_]{26,128} unique identifier url string size 2048 must be an absolute url defined by rfc 2396 uniform resource identifiers uri generic syntax supported schemes - http, https timestamp number int64 - signed 64 bits unix epoch time in milliseconds countrycode string size 2 unique identifier 3 4 10 inbound api specification – save2pay the inbound api specification for save2pay defines the protocols and requirements for partner servers to interact with the save2pay system this specification ensures secure and standardized communication during the push provisioning process general contract base url https //s2p-api mpay samsung com/ext/v1 security mutual ssl is required common headers header name type validation description request-id uuid required unique identifier for the request partner-id uuid required unique identifier that is provided to partner during onboarding partner-id uuid required request-id echoed back in the response headers common http error codes http code description application code message 400 bad request 400 1 invalid data 500 internal server error 500 1 internal server error 503 service not available 503 1 service temporarily unavailable retry-after header is required 503 service not available 503 2 api temporarily unavailable retry-after header is required 3 4 11 registration partner server registers a session for the user as a result, a unique registration id will be generated partner server should make sure that this is called only once for one card a welcomeurl will also be returned partner server can display the welcomeurl in browser or email upon rendering, a qr code will be displayed and users can use their spay wa to scan the qr code welcomeurl has an expiration date, partner server should check if it's still valid before rendering if it's expired, a get call will return the new url request post /registrations body key type validation description example registration email string optional user email address registration enforceemailmatching boolean default is false optional enforce only spay wa with the same email address can provision enforcement is only against the email address that's provided by the partner true registration hideemail boolean default is false optional hide email field registration phone phonenumber optional user phone number registration enforcephonematching boolean optional default is false enforce only spay wa with the same phone number can provision enforcement is only against the phone number that's provided by the partner true registration hidephone boolean optional default is false hide phone field registration welcomecallbackurl url optional callback url that the welcome ui will redirect to once the user successfully linked a spay wa account registration allowofflinecommunication boolean optional default is false if true, s2p will communicate to the user via email and/or phone number to facilitate the provisioning process registration data object optional arbitrary data blob that'll be passed to the device when an account is linked registration custom cardname string required card name that'll show on the welcome page registration custom cardarturl url required cardart url that'll show on the welcome page registration custom partnername string required partner name that'll show on the welcome page registration custom partnerlogourl url required partner logo url that'll show on the welcome page registration custom partnertncurl url optional partner tnc url that'll show on the welcome page registration id uuid required registration id that identifies this session registration status enum - pending, linked required registration status pending registration welcomeurlexpiration timestamp required welcomeurl expiration timestamp in milliseconds response status http/1 1 201 created header name value content-type application/json example post /ext/v1/registrations { "email" "user@gmail com", "enforceemailmatching" true, "phone" "14089998888", "enforcephonematching" true, "custom" { "cardname" "xyz bank credit card", "cardarturl" "https //xyz com/cardart png", "partnername" "xyz bank", "partnerlogourl" "https //xyz com/logo png" } } http/1 1 201 created { "id" "395ce2e29485442cbd9bacdc77105126", "welcomeurl" "https //s2p stg mpay samsung com/v1/welcome/eyjlbmmioijbmju2r0nniiw iywxnijoizglyin0 s0dnxrskdkjw8sbh kg4uqhfwkkdnqrviihkaqshq_jayb99ct tizdzrwrn-qlhuzj4imuyv1sagehavyxluamarwa tlekqcerr0jklc-fnqkcva", "status" "pending", "welcomeurlexpiration" 1505953396844 } get registration check existing registration status and/or get new welcomeurl request get /registrations/{regid} headers name value validation partner-id partner id value assigned by samsung wallet required response status http/1 1 200 ok status name value content-type application/json body key type validation description example registration id uuid required registration id that identify this session registration status enum - pending, linked required registration status pending registration welcomeurl url required this is the url that partner can show to the user as an iframe a separate page it shows the qrcode and optionally user can enter email and phone number registration welcomeurlexpiration timestamp required welcomeurl expiration timestamp in milliseconds example http/1 1 200 ok { "id" "395ce2e29485442cbd9bacdc77105126", "welcomeurl" "https //s2p stg mpay samsung com/v1/welcome/eyjlbmmioijbmju2r0nniiw iywxnijoizglyin0 s0dnxrskdkjw8sbh kg4uqhfwkkdnqrviihkaqshq_jayb99ct tizdzrwrn-qlhuzj4imuyv1sagehavyxluamarwa tlekqcerr0jklc-fnqkcva", "status" "pending", "welcomeurlexpiration" 1505953396844 } errors common http error codes http code description application code message 400 bad request 400 1 invalid data 500 internal server error 500 1 internal server error 503 service not available 503 1 service temporarily unavailable retry-after header is required 503 service not available 503 2 api temporarily unavailable retry-after header is required 3 4 12 outbound to partner the outbound api specification for save2pay defines how the save2pay server communicates with partner servers during the push provisioning process this specification ensures secure and standardized communication between save2pay and its partners general contract base url base url for outbound apis to be provided by the partner during the onboarding process security mutual ssl is required common headers header name type validation description request-id uuid required unique identifier for the request partner-id uuid required unique identifier that is provided to partner during onboarding response-id uuid required request-id echoed back in the response headers 3 4 13 event notification notify partner for events request post /notifications body key description type validation example event regid registration id uuid required event type event type enum refer to event types and errors for details required event error more information about the failure enum refer to event types and errors for details event desc additional description of the event string optional user container for user information object conditional will be present for payment cards user id samsung account id string required emailmatches is true if the email provided in the registration request matches with samsung account email boolean conditional it is present only if an email was provided in the registration request phonematches is true if the phone number provided in the registration request matches with device phone number boolean conditional it is present only if a phone number was provided in the registration request device container for device information object conditional will be present for payment cards device id device id string required device imeilast4 last 4 of device imei string size 4 optional device seriallast4 last 4 of device serial number string size 4 optional device locale country device country code countrycode optional wallet container for wallet information object conditional will be present for payment cards wallet id wallet id string required event types and errors type error description wa_ready wallet app is ready for provisioning wa_provisioned indicates card was successfully provisioned into the wallet wa_provision_failure indicates provisioning failed for some unknown reason wa_provision_failure card_already_present indicates card is already present response status http/1 1 200 ok header name value content-type application/json body card data encrypteddata description encrypted pan data that will be returned to the device to provision the card type string size 65536 validation conditional required if card data was not provided in the registration request example example post /notifications { "event" { "regid" "395ce2e29485442cbd9bacdc77105126", "type" "wa_ready" }, "emailmatches" true, "phonematches" true, "user" { "id" "rcsm3gwjt9mxgfwy5sg123" }, "wallet" { "id" "gpccugejs9giih8zch1111" }, "device" { "id" "mtuxmte5mdawmjawmdm1n999", "imeilast4" "6166", "locale" { "country" "us" }, "seriallast4" "4934" } } http/1 1 200 ok { "card" { "data" { "encrypteddata" "*****" } } } 3 4 14 save to pay javascript library javascript library interface savetopayui { /** * shows the welcome ui redirects to welcomecallbackurl if it was provided in the registration request when the page reaches one of the final states */ static void showwelcomemodal s2prequest r ; /** * shows the welcome ui resolves the promise with the status and optionally details after the welcome ui is closed */ static promise <s2presponse> showwelcomemodalpromise s2prequest r ; /** * api to close the modal */ static void closewelcomemodal ; }; dictionary s2prequest { /** * welcomeurl provided by save2pay server in the registration response */ required domstring welcomeurl; }; dictionary s2presponse { required status status, /** * true if triggered by iframe closing by user or parent page * false if the status is one of the final statuses, not triggered by iframe closing this can only happen in mobile android case */ required boolean isiframeclosed, /** * optional error information if the status is 'failure' */ details details }; dictionary details { required errorcode errorcode; domstring message; }; enum status { "success", "failure", "device_not_supported", "default_pending" }; enum errorcode { "invalid_input", "provision_failure", "network_error", "unknown_error", "card_already_present", "canceled" }; usage code block -1 html <script src="https //spay samsung com/s2p/libs/js/0 0 4/s2p min js"></script> code block -2 javascript - redirect var input = { "welcomeurl" 'https //s2p mpay samsung com/v1/welcome/eyjlbmmioijbmju2r0nniiwiywx nijoizglyin0 eltgw8qp56ciezo2 mh34gjebgyp_m7- gw0sbdl3ckaplp7rtvmc8fe-tmq2ipmp2rcc1a39qodbvw2schiarbooahbe77lpvl8nhkkapi6mhynl-yz6gqx0sjw xfrtyjpdzxrnmlq8ffe6pg' } window spay savetopayui showwelcomemodal input code block- 3 javascript - promise var request = { "welcomeurl" 'https //s2p mpay samsung com/v1/welcome/eyjlbmmioijbmju2r0nniiwiywx nijoizglyin0 eltgw8qp56ciezo2 mh34gjebgyp_m7- gw0sbdl3ckaplp7rtvmc8fe-tmq2ipmp2rcc1a39qodbvw2schiarbooahbe77lpvl8nhkkapi6mhynl-yz6gqx0sjw xfrtyjpdzxrnmlq8ffe6pg' } function successcallback response { console log response status } function failurecallback error { console log error } window spay savetopayui showwelcomemodalpromise request then succes scallback, failurecallback promise resolution device type description desktop, tablet & mobile - ios js library will resolve the promise - 1 when the iframe is closed by the user 2 closewelcomemodal function is invoked mobile - android js library will resolve the promise as soon as the provisioning session ends or closewelcomemodal function is invoked provisioning session ends when one of the following has happened - 1 the card was successfully added 2 there was some failure and card provisioning flow cannot continue further 3 timeout has happened 4 user canceled the provisioning process mobile flows
Develop Samsung Blockchain
docapi implementation samsung blockchain keystore api level get instance get seedhash check for mandatory app update is root seed backed up get supported coins get hd path get a list of addresses get a list of extended public keys sign a transaction is reboot authentication required go to samsung blockchain keystore settings handle error codes deeplinks samsung blockchain keystore api level samsung blockchain keystore api level plays a key role to ensure that the required api level of samsung blockchain keystore on a user’s device is properly installed to support the api that your android app tries to call for example, if your android app is trying to implement a new samsung blockchain keystore api that requires “api level 2”, your android app will need to check whether samsung blockchain keystore app installed on user’s device also supports api level 2 if a user’s app supports api level 1, then your app will need to guide users to update samsung blockchain keystore app to the latest version users can be directed to the update page in galaxy store otherwise, there will be a runtime exception due to api level exception when calling apis with level higher than the level supported by the user’s version the api level for each api will be mentioned in the javadoc, under “since” title, and developers can call “getkeystoreapilevel api” to check the current api level on the user’s device your android app will need to check the api level whenever needed – it may be at the beginning of running samsung blockchain keystore app or every time your app calls an api public void getkeystoreapilevel { int keystoreapilevel = scwservice getinstance getkeystoreapilevel ; boolean iskeystoreapisupported = keystoreapilevel > 0; } get instance scwservice getinstance will need to be used to call any of the apis provided by samsung blockchain keystore if samsung blockchain keystore is supported on the device, an instance will be returned if it is not available on the device, then null will be returned if null is returned, it means samsung blockchain keystore is not supported on the user’s device a different keystore or a wallet needs to be used scwservice scwserviceinstance = scwservice getinstance ; get seed hash getseedhash api aims to help developers distinguish two things 1 check whether user has set up samsung blockchain keystore 2 check whether root seed recovery phrase has been changed or not every time a new root seed or a wallet is created or restored, the seed hash in a string value will be changed actually, this is not the preimage of the real seed, but a pseudo hash value so, it is not possible to calculate the real seed with the pseudo one it is strongly recommended for the application to cache the returned hash value to reduce the number of times to check the derived address’s validity if the returned value is same as cached, the derived addresses are still valid, so the application keeps using these addresses otherwise, the application should refresh the addresses from new seed with getaddresslist or getextendedpublickeylist api whenever the application starts, it needs to call getseedhash in case that the returned value is a zero-length string, it means that there is no wallet in the samsung blockchain keystore so, the application ui needs to guide users to jump to samsung blockchain keystore to create a wallet with scwdeeplink main deeplink public void getseedhash { string seedhash = scwservice getinstance getseedhash ; boolean initialized = seedhash != null && seedhash length > 0 ; } check mandatory app update checkformandatoryappupdate api is to help developers check if a user must update samsung blockchain keystore because samsung blockchain keystore handles only one task at a time, make sure to not call the checkformandatoryappupdate api in the background as it may cause other api calls or requests to be cancelled if a mandatory app update is needed, users can be directed to the galaxy store using a deeplink, scwdeeplink galaxy_store otherwise, users will see the mandatory app update popups during an operation process, such as signing a transaction, and will need to update samsung blockchain keystore before proceeding note scwservice scwcheckformandatoryappupdatecallback will need to be implemented correspondingly scwservice scwcheckformandatoryappupdatecallback callback = new scwservice scwcheckformandatoryappupdatecallback { @override public void onmandatoryappupdateneeded boolean needed { if needed { startdeeplink scwdeeplink galaxy_store ; } } }; scwservice getinstance checkformandatoryappupdate callback ; how to handle the returned value a boolean needed value of whether a mandatory update is needed or not will be returned if needed, developers will need to guide users to go to samsung blockchain keystore app page in galaxy store to update is root seed backed up isrootseedbackedup api helps developers check if there is a backup of root seed since a user can create a wallet without a backup of root seed, developers can advise the user to make root seed backup if a backup of root seed is needed, the users will be directed to the page which backs up the mnemonic phrases in the samsung blockchain keystore using a deep link, scwdeeplink backup_wallet boolean isbackedup = scwservice getinstance isrootseedbackedup ; if !isbackedup { startdeeplink scwdeeplink backup_wallet ; } how to handle the returned value the result of root seed backup will be returned in a boolean type get supported coins getsupportedcoins api is used to find out which type of cryptocurrencies are supported, in case there is a different logic that developers must implement for different cryptocurrencies it is returned in an int array of standard coin types according to bip standard – for example, 60 for ethereum int[] supportedcoins = scwservice getinstance getsupportedcoins ; stringbuilder sb = new stringbuilder ; sb append "supported coins" append '\n' ; for int i = 0; i < supportedcoins length; i++ { sb append '[' append i append "] " append supportedcoins[i] append '\n' ; } string s = sb tostring ; get hd path gethdpath api helps developers derive hd path for a specified coin type this api can be used as a parameter when deriving an address and requesting to sign a transaction note that utxo-based cryptocurrency, such as bitcoin will not be supported for this api no callback will be needed for this api as hd path in string type will be returned immediately //derive hd path for the cryptocurrency that your app supports string ethereumhdpath = scwservice gethdpath scwcointype eth, 0 ; string klaytnhdpath = scwservice gethdpath scwcointype klay, 0 ; string tronhdpath = scwservice gethdpath scwcointype tron, 0 ; string stellarhdpath = scwservice gethdpath scwcointype xlm, 0 ; there are two parameters needed coin type and address index coin type use scwcointype class to specify the cryptocurrency that your app uses address index address index is like an account number it is recommended to use 0 as the default address index increasing the address index will generate a different account for example, if you need another ethereum account, then you can increase this address index to 1 if you need just one address for your service, then make sure to use the same coin type and same address index throughout your service so that user does not get confused with multiple addresses examples the returned value will be hd path in a string format this hd path will be needed for getaddresslist api and signing cryptocurrency apis scwservice gethdpath scwcointype eth, 0 will return “m/44’/60’/0’/0/0” scwservice gethdpath scwcointype eth, 1 will return “m/44’/60’/0’/0/1” scwservice gethdpath scwcointype klay, 0 will return “m/44’/8217’/0’/0/0” scwservice gethdpath scwcointype tron, 0 will return “m/44’/195’/0’/0/0” scwservice gethdpath scwcointype xlm, 0 will return “m/44’/148’/0’” for more details on hd path refer to key management section in understanding keystore you can find how hd path is used in samsung blockchain keystore get a list of addresses getaddresslist api allows developers to request to get a list of addresses that correspond to a list of hd paths a list of the hd path, compatible with bip-44 needs to be passed on to bring the addresses the depth of hd path should be between 3 and 6 also, scwservice scwgetaddresslistcallback will need to be implemented correspondingly scwservice scwgetaddresslistcallback callback = new scwservice scwgetaddresslistcallback { @override public void onsuccess list<string> addresslist { } @override public void onfailure int errorcode, string errormessage { //handle errors } }; string hdpath = scwservice gethdpath scwcointype eth, 0 ; arraylist<string> hdpathlist = new arraylist<> ; hdpathlist add hdpath ; scwservice getinstance getaddresslist callback, hdpathlist ; hierarchical deterministic path hd path examples hdpath for ethereum m/44'/60'/0'/0/0 hdpath for bitcoin m/44'/0'/0'/0/0 if you are unsure about what hd path is, then you can generate hd path with gethdpath api except for bitcoin how to handle the returned value the returned value will be a list of addresses in a list** format each address will correspond to the hd path in the arraylist minimize calling getaddresslist api by checking seed hash value to avoid calling getaddresslist api as much as possible, please utilize getseedhash api to check whether the root seed has been changed or not, since different seed hash value implies that the corresponding address has also been updated get a list of extended public keys getextendedpublickeylist api allows developers to request to get a list of extended public keys that correspond to a list of hd paths a list of the hd path, compatible with bip-44 needs to be passed on to bring the public key the depth of path should be between 3 and 6 take note that the scwservice scwgetextendedpublickeylistcallback will need to be implemented correspondingly scwservice scwgetextendedpublickeylistcallback callback = new scwservice scwgetextendedpublickeylistcallback { @override public void onsuccess list<byte[]> extendedpublickeylist { } @override public void onfailure int errorcode, string errormessage { //handle errors } }; string hdpath = scwservice gethdpath scwcointype eth, 0 ; arraylist<string> hdpathlist = new arraylist<> ; hdpathlist add hdpath ; scwservice getinstance getextendedpublickeylist callback, hdpathlist ; hierarchical deterministic path hd path examples hdpath for ethereum m/44'/60'/0'/0/0 hdpath for bitcoin m/44'/0'/0'/0/0 how to handle the returned value the returned value will be list <byte[]> that corresponds to each hd path requested in the arraylist each byte array is composed of 33 bytes of compressed public key and 32 bytes of chain code you can derive the child public key based on this data note that you need to derive the address of the compressed public key or call getaddresslist api to get the address minimize calling getextendedpublickeylist api by checking seed hash value use getseedhash api to check whether the root seed has been changed or not, since different seed hash value implies that corresponding public keys have also been updated sign a transaction there are seven apis that support signing cryptocurrency transactions ethereum, personal sign message in ethereum, bitcoin, klaytn, tron, personal sign message in tron, and stellar note only signing a transaction is included in the samsung blockchain keystore scope 1 signethtransaction api signethtransaction api as the name implies, sends a request to samsung blockchain keystore to sign an ethereum transaction likewise, scwservice scwsignethtransactioncallback will need to be implemented scwservice scwsignethtransactioncallback callback = new scwservice scwsignethtransactioncallback { @override public void onsuccess byte[] signedethtransaction { } @override public void onfailure int errorcode, string errormessage { //handle error } }; string toaddress = "0xe7425ee1bc64ab7c51ce3617cb83e76fd545f1a9"; string ethamount = "123 456789"; string ethgasprice = "12000000000"; string ethgaslimit = "21000"; string data = ""; long chainid = 1; string hdpath = scwservice gethdpath scwcointype eth, 0 ; byte[] encodedunsignedethtx = createrawtransaction toaddress, ethamount, ethgasprice, ethgaslimit, data ; private byte[] createrawtransaction param1, param2, … { //implement your code here } scwservice getinstance signethtransaction callback, encodedunsignedethtx, hdpath, chainid ; the parameters to take note are as follows encodedunsignedethtx a byte array of an rlp-encoded unsigned ethereum raw transaction hdpath hd path that corresponds to the address linked to your android app that also corresponds to the private key which is used for signing chainid chain id to prevent replay attacks between different chain for eip1559 transaction, chainid should be null how to handle the returned value the signed transaction will be returned in a byte array type in a rlp-encoded format 2 signethpersonalmessage api signethpersonalmessage api can be used to request to samsung blockchain keystore to sign a message in ethereum scwservice scwsignethpersonalmessagecallback will need to be implemented scwservice scwsignethpersonalmessagecallback callback = new scwservice scwsignethpersonalmessagecallback { @override public void onsuccess byte[] signedpersonalmessage { } @override public void onfailure int errorcode, string errormessage { //handle error } }; string hdpath = scwservice gethdpath scwcointype eth, 0 ; byte[] unsignedmsg = "to sign up, please sign this message " getbytes ; scwservice getinstance signethpersonalmessage callback, unsignedmsg, hdpath ; the parameters to take note are as follows unsignedmsg – a byte array of raw message to be signed by samsung blockchain keystore the "\u0019ethereum signed message \n" prefix will be added by samsung blockchain keystore, so your android app should not include the prefix in the message hdpath hd path that corresponds to the address linked to your android app that also corresponds to the private key which is used for signing how to handle the returned value the type of return is a byte array of signed message based on r, s, v values for a transaction’s signature respectively 3 signbtctransaction api signbtctransaction api can be used to create a request to samsung blockchain keystore to sign a bitcoin transaction the scwservice scwsignbtctransactioncallback will need to be implemented scwservice scwsignbtctransactioncallback callback = new scwservice scwsignbtctransactioncallback { @override public void onsuccess byte[] signedbtctransaction { } @override public void onfailure int errorcode, string errormessage { //handle error } }; list<utxo> utxos = new arraylist<> ; arraylist<string> inputhdpathlist = new arraylist<> ; string changehdpath = "m/44'/0'/0'/0/0"; string inputhdpath1 = "m/44'/0'/0'/0/0"; string inputhdpath2 = "m/44'/0'/0'/0/1"; utxos add getunspentoutputs inputhdpath1 ; utxos add getunspentoutputs inputhdpath2 ; transactionextended unsignedtx = makeunsignedtransaction networkparams, utxos, to, value, fee ; for int i = 0; i < unsignedtx getinputs size ; i++ { string inputhdpath = unsignedtx getinputs gethdpath i ; inputhdpathlist add inputhdpath ; } private transaction makeunsignedtransaction networkparameters networkparams, list<utxo> utxos, string to, long value, long fee { //make unsigned transaction among unspent outputs to spend value with fee //implement your code here } scwservice getinstance signbtctransaction callback, transaction, inputhdpathlist, changehdpath ; the parameters to take note are as follows transaction a byte array of a serialized unsigned bitcoin transaction to be signed by samsung blockchain keystore inputhdpathlist a list of hd path that corresponds to the addresses linked to the transaction inputs in transaction this list also corresponds to the private key which is used for signing bip-44, 49, 84 are supported and coin type “1” in hd path can be used for bitcoin test network parameter check samsung blockchain keystore will verify the requested transaction using transactioninput in transaction and inputhdpathlist each transactioninput should correspond to an hd path in inputhdpathlist if there are multiple transactioninput, then corresponding inputhdpathlist and transactioninputs should be listed in the same order changehdpath if there is a return change, then include the hd path that corresponds to the change address if the change address is not needed, then this value should be null how to handle the returned value the signed transaction will be returned in a byte array type 4 signklaytransaction api signklaytransaction api can be used to request to samsung blockchain keystore to sign a klaytn transaction scwservice scwsignklaytransactioncallback will need to be implemented scwservice scwsignklaytransactioncallback callback = new scwservice scwsignklaytransactioncallback { @override public void onsuccess byte[] signedklaytransaction { } @override public void onfailure int errorcode, string errormessage { //handle error } }; string hdpath = scwservice gethdpath scwcointype klay, 0 ; byte[] unsignedtransaction = getunsignedtx ; int klaytnchainid = 1001; scwservice getinstance signklaytransaction callback, unsignedtransaction, hdpath, klaytnchainid ; the parameters to take note are as follows unsignedtransaction a byte array of raw transaction to be signed by samsung blockchain keystore it is same as the sigrlp value mentioned in klaytn official document hdpath - hd path that corresponds to the public key linked to your android app that also corresponds to the private key which is used for signing klaytnchainid – the klaytn network id or the integer to identify the network "8217" is klaytn cypress mainnet and "1001" is klaytn baobab testnet how to handle the returned value the signed transaction will be returned in a byte array type in a rlp-encoded format 5 signtrxtransaction api signtrxtransaction api can be used to request to samsung blockchain keystore to sign a tron transaction scwservice scwsigntrxtransactioncallback will need to be implemented scwservice scwsigntrxtransactioncallback callback = new scwservice scwsigntrxtransactioncallback { @override public void onsuccess byte[] signedtrxtransaction { //handle signed tron transaction } @override public void onfailure int errorcode, string errormessage { //handle error } }; string hdpath = scwservice gethdpath scwcointype tron, 0 ; string from = “tdcmwosbafcegqqnuarnjghy4tabdcmdwi” string to = “tq6pm81jdc2ghruonytzgvpc7svyqcemeu”; int amount = 2; byte[] unsignedtransaction = createunsignedtransaction hdpath from, to, amount ; private byte[] createunsignedtransaction param1, param2, … { //implement your code here } scwservice getinstance signtrxtransaction callback, unsignedtransaction, hdpath ; the parameters to take note are as follows unsignedtransaction a byte array of raw tron transaction to be signed by samsung blockchain keystore hdpath - hd path that corresponds to the public key linked to your android app that also corresponds to the private key which is used for signing how to handle the returned value signed transaction will be returned in a byte array 6 signtrxpersonalmessage api signtrxpersonalmessage api can be used to request to the samsung blockchain keystore to sign a message in tron the scwservice scwsigntrxpersonalmessagecallback will need to be implemented scwservice scwsigntrxpersonalmessagecallback callback = new scwservice scwsigntrxpersonalmessagecallback { @override public void onsuccess byte[] signedpersonalmessage { } @override public void onfailure int errorcode, string errormessage { //handle error } }; string hdpath = scwservice gethdpath scwcointype tron, 0 ; byte[] unsignedmsg = "to sign up, please sign this message " getbytes ; scwservice getinstance signtrxpersonalmessage callback, unsignedmsg, hdpath ; the parameters to take note are as follows unsignedmsg a byte array of raw message to be signed by samsung blockchain keystore a "\u0019tron signed message \n32" prefix will be added by samsung blockchain keystore, so your android app should not include the prefix in the message hdpath hd path that corresponds to the address linked to your android app that also corresponds to the private key which is used for signing how to handle the returned value the type of return is a byte array of signed message based on values for a transaction’s signature - r, s, v respectively 7 signxlmtransaction api signxlmtransaction api can be used to request to the samsung blockchain keystore to sign a stellar transaction the scwservice scwsignxlmtransactioncallback will be needed to be implemented scwservice scwsignxlmtransactioncallback callback = new scwservice scwsignxlmtransactioncallback { @override public void onsuccess byte[] signedxlmtransaction { //handle signed stellar transaction } @override public void onfailure int errorcode, string errormessage { //handle error } }; string recipientaccount = “gay5dorarbd5l3fbbwuhxkciv7vcmqicsllj7gyr4664av4mxtx2fh4o”; string amount = “100”; paymentoperation operation = new paymentoperation builder recipientaccount, asset, amount build ; string hdpath = scwservice gethdpath scwcointype xlm, 0 ; arraylist<string> hdpathlist = new arraylist<> ; hdpathlist add hdpath ; string sourceaccount = “gb7zviydvsww3ctfj2v3oproahgbuomebwib55xieii3aq6523pg4lm5”; string memo = "hello12347"; byte[] unsignedtransaction = createunsignedtransaction sourceaccount, operation, memo, networkid ; private byte[] createunsignedtransaction param1, param2, … { //implement your code here // include networkid, envelopetype envelopte_type_tx , and xdr-encoded transaction } scwservice getinstance signxlmtransaction callback, unsignedtransaction, hdpathlist ; the parameters to take note are as follows unsignedtransaction – a byte array of raw transaction to be signed by samsung blockchain keystore it is the same as the signature base, which includes networkid, envelopetype, and xdr-encoded transaction hdpathlist a list of hd path that corresponds to the addresses linked to your android app that also corresponds to the private key which is used for signing how to handle the returned value the signed transaction will be returned in a byte array developers can use base64 encoding to implement this result into envelopexdr, which can derive the transaction that can be submitted to the network is reboot authentication required the isrebootauthenticationrequired api allows you to check whether pin authentication is required after reboot some keystore api calls can require pin authentication after device reboot these calls are successful only after the user enters their blockchain keystore pin at the prompt the isrebootauthenticationrequired method allows you to determine whether accessing the keystore api requires pin authentication boolean isrebootauthenticationrequired = scwservice getinstance isrebootauthenticationrequired ; if isrebootauthenticationrequired { // user prompted for pin authentication } else { // user not prompted for pin authentication } • handling the returned value the isrebootauthenticationrequired method returns a boolean value go to samsung blockchain keystore settings samsung blockchain keystore provides a user-friendly setup page for the first time users and a settings page for existing users developers can easily jump to samsung blockchain keystore settings by using a deeplink, scwdeeplink main there are two purposes of calling the samsung blockchain keystore main activity setup samsung blockchain keystore for first time users after calling getseedhash api, if the wallet is not created, a zero length value will be returned this is when your android app should call samsung blockchain keystore settings via a deep link as shown below samsung blockchain keystore will check if a user needs to set up a new wallet and if needed, will lead to a setup page after the activity is finished, your android app should call the getseedhash api, once more, to make sure that the wallet has been created and the corresponding seed hash value is returned samsung blockchain keystore settings for existing users for existing users, when samsung blockchain keystore settings is called, a user will see a list of menu related to samsung blockchain keystore management features include changing the pin, removing the wallet, checking a recovery phrase to back up the wallet, enabling/disabling fingerprint as an authentication method, or managing notification preferences more information about the samsung blockchain keystore, such as notices, terms and conditions, and app information can be also found here a sample code for calling samsung blockchain keystore via a deeplink is as follows uri uri = uri parse scwdeeplink main ; intent intent = new intent intent action_view ; intent setdata uri ; intent setflags intent flag_activity_new_task ; mcontext startactivity intent ; *do not call startactivityforresult intent as no results will be returned make sure to use startactivity intent instead handling error codes in addition to general error codes, the following are some special cases that developers may want to look out for mandatory update is needed samsung blockchain keystore was removed due to user entering wrong pin more than n times api key is invalid the popups above will be shown from samsung blockchain keystore app, though the samsung blockchain keystore will still return corresponding error codes in the mandatory update error case, the user will see a popup with a link to galaxy apps store page to update samsung blockchain keystore if it was reset, due to entering a wrong pin more than n times, then the user will need to create or import the wallet via samsung blockchain keystore service again it is recommended that developers call checkformandatoryappupdate api before calling other apis, to check whether a mandatory app update is needed for this api, no ui or popup will be shown from samsung blockchain keystore upon integration, developers may receive an “error_package_signature_verification_failed” error in this case, developers can turn on developer mode to skip the app verification stage yet, developers will need to implement proper app id, officially issued by the samsung blockchain keystore team before launching your android app in the market public interface scwerrorcode { int error_mandatory_app_update_needed = -8; int error_package_signature_verification_failed = -11; int error_wallet_reset = -12; int error_check_app_version_failed = -15; int error_tnc_not_agreed = -6; } please refer to the scwerrorcode class in javadoc for more details on error codes samsung blockchain keystore deeplinks deep links to samsung blockchain keystore and deep link to update samsung blockchain keystore app in galaxy store are provided developers can implement the links below to direct users to go to the main page and back up root seed page in samsung blockchain keystore settings directly deep link to galaxy store can be used when user needs to update samsung blockchain keystore app features deeplink main page scwdeeplink main galaxy apps store scwdeeplink galaxy_store backup wallet scwdeeplink backup_wallet
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.