Update Samsung Wallet Card Templates Using the Server API
M. A. Hasan Molla
Engineer, Samsung Developer Program
Card template management is a crucial task for partners in the Samsung Wallet ecosystem that is typically handled through the Wallet Partners Portal. Manually altering numerous existing templates via the web interface can be inefficient and challenging. Samsung provides a set of server-side APIs to address this, allowing partners to programmatically manage and modify their card templates for greater operational agility.
Using these APIs enables partners to integrate update capabilities directly into their own ecosystems. This automation facilitates the seamless maintenance of card offerings, helping partners keep their content dynamic and up-to-date.
As a partner, this article walks you through the implementation of the Update Wallet Card Template API specifically using Python. If you are a Java developer or want to implement the Add Wallet Card Template API, you can follow the previous content on creating Samsung Wallet card templates.
API overview
This section details the REST API designed for modifying a pre-existing wallet card template, enabling direct updates from a partner's server.
Endpoint URL: Direct requests to modify a card template to the following URL. It is imperative to substitute {cardId} with the identifier of the specific card template you intend to alter.
https://tsapi-card.walletsvc.samsung.com/partner/v1/card/template/{cardId}
Request headers: Secure interaction with this API is restricted to authenticated partners. The headers detailed below are vital for establishing a secure and validated communication channel with the Samsung server.
- Authorization: This field must contain the Bearer token. For comprehensive information, consult the JSON web token documentation.
- X-smcs-partner-id: This field must be populated with your unique partner identifier.
- X-request-id: A universally unique identifier (UUID) is required here, freshly generated for each request.
Request body: The payload of the request needs to be structured as a JSON object. This object must include a key named ctemplate, with its value being a JWT token. This specific JWT securely contains the complete data for the revised card template.
For a deeper dive into the API specifications, check the official documentation.
Implementing the API to create a card template
The Update Wallet Card Template API enables partners to modify existing card templates in the Wallet Partners Portal. In this section, we implement Python code to update a coupon card template, for example, by changing its title.
Extracting the keys from certificates
Extract the public and private keys from the certificate files obtained during the onboarding process.
def getPublicKey(crt_path):
"""
Extract publick key from a .crt file.
"""
try:
with open(crt_path, "rb") as f:
crt_data = f.read()
certificate = x509.load_pem_x509_certificate(crt_data, default_backend())
public_key = certificate.public_key()
public_key_pem = public_key.public_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PublicFormat.SubjectPublicKeyInfo
)
return jwk.JWK.from_pem(public_key_pem)
except Exception as error:
print(f"Error reading public key from {crt_path}: {error}")
return None
def getPrivateKey(pem_path):
'''
Extract private key from a .pem file.
'''
try:
with open(pem_path, "rb") as pem_data:
private_key = serialization.load_pem_private_key(
pem_data.read(),
password = None,
backend = default_backend()
)
return private_key.private_bytes(
encoding=serialization.Encoding.PEM,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption()
)
except Exception as error:
print(f"Error reading private key from {pem_path}: {error}")
return None
Generating the authorization token
The Samsung server uses a JWT format token to verify if the request is from an authorized partner. Follow these steps to create an authorization token.
- Create an authorization token header. Set the payload content type to ‘AUTH’ since this is an authorization token.
- Create the payload using the authorization token header.
- Generate the authorization token.
The following code snippet demonstrates these steps.
def generateAuthToken(partnerId, certificateId, utcTimestamp, privateKey, cardId):
auth_header = {
"cty": "AUTH",
"ver": 3,
"certificateId": certificateId,
"partnerId": partnerId,
"utc": utcTimestamp,
"alg": "RS256"
}
auth_payload = {
"API": {
"method": "POST",
"path": f"/partner/v1/card/template/{cardId}"
},
}
auth_token = jwt.encode(
payload=auth_payload,
key=privateKey,
algorithm='RS256',
headers=auth_header
)
return auth_token
Generating a payload object token
The request body includes a parameter named ctemplate, which is also a JWT token. Create the JWT token using the following code snippet.
def generateCDataToken(partnerId, samsungPublicKey, partnerPrivateKey, certificateId, utcTimestamp, data):
jwe_header = {
"alg": "RSA1_5",
"enc": "A128GCM"
}
jwe_token = jwe.encrypt(
data,
samsungPublicKey,
encryption=jwe_header["enc"],
algorithm=jwe_header["alg"]
)
print(f"jwe_token: \n{jwe_token}\n")
jws_header = {
"alg": "RS256",
"cty": "CARD",
"ver": 3,
"certificateId": certificateId,
"partnerId": partnerId,
"utc": utcTimestamp,
}
jws_token = jws.sign(
jwe_token,
key=partnerPrivateKey,
algorithm='RS256',
headers=jws_header
)
print(f"jws_token: \n{jws_token}\n")
return jws_token
Building and executing the request
Build and send the HTTP request to the specified update endpoint. Add all fields that you want to modify in the ’cDataPayload’ object. Refer to the documentation to identify the fields that you can modify.
def main(partnerId, cardId, certificateId, utcTimestamp, requestId, endpoint):
partnerPublicKey = getPublicKey("../cert/partner.crt")
print(f"partnerPublicKey {partnerPublicKey}")
samsungPublicKey = getPublicKey("../cert/samsung.crt")
print(f"samsungPublicKey {samsungPublicKey}\n")
partnerPrivateKey = getPrivateKey("../cert/private_key.pem")
print(f"partnerPrivateKey {partnerPrivateKey}\n")
authToken = generateAuthToken(partnerId, certificateId, utcTimestamp, partnerPrivateKey, cardId)
print(f"authToken {authToken}\n")
cDataPayload = {}
# --- Add data here that you want to update.
cDataPayload["cardTemplate"] = {
"title": "Update Card tile",
"countryCode": "KR",
"saveInServerYn": "Y"
}
data = json.dumps(cDataPayload).encode('utf-8')
cDataToken = generateCDataToken(partnerId, samsungPublicKey, partnerPrivateKey, certificateId, utcTimestamp, data)
print(f"cDataToken: \n{cDataToken}\n")
# --- Prepare JSON body (Python dictionary) ---
c_data_json_body = {
"ctemplate": cDataToken
}
# --- Build HTTP Request ---
headers = {
"Authorization": "Bearer " + authToken,
"x-smcs-partner-id": partnerId,
"x-request-id": requestId,
"x-smcs-cc2": "KR",
"Content-Type": "application/json"
}
# --- Execute HTTP Request ---
try:
response = requests.post(endpoint, json=c_data_json_body, headers=headers)
response.raise_for_status()
print("Wallet Card Template updated successfully: " + json.dumps(response.json()))
except requests.exceptions.RequestException as e:
print("Failed to update Wallet Card Template:")
print(f"Error: {e}")
if response:
print("Response body:", response.text)
Running the application
Download the sample project and open it with any IDE, then follow this process.
-
Configure: Update ‘PARTNER_ID’, ‘CERTIFICATE_ID’, and, crucially, ‘CARD_ID_TO_UPDATE’ in src/main.py with your actual credentials and the ID of the card you need to modify.
-
Place certificates: Ensure your partner.crt, samsung.crt and private_key.pem files are in the cert/ directory.
-
Install dependencies: Install all the required dependencies from the requirements.txt file.
pip install -r requirements.txt
- Execute: Run the main script from the terminal.
python src/main.py
If the request is successful, the specified card template in the Wallet Partners Portal is updated. The API returns the updated card ID with a success status, otherwise it returns an error. Find all the status codes in the '[Result]' section of the documentation.
Wallet Card Template updated successfully:
{
"cardId": "cardId",
"resultCode": "0",
"resultMessage": "UPDATE_SUCCESS"
}
Conclusion
By implementing the API to update an existing Samsung Wallet card template through this article, you can now automate and streamline the management of your card templates, ensuring that they always reflect the latest information.
References
For additional information on this topic, refer to the resources below.