Skip to main content

Red Packet Use Case Implementation

Scenario Description

Users send red packets (real currency, virtual currency, points, etc.) to specified friends in one-to-one chat/group chat conversations. Senders and receivers can clearly perceive whether the red packet has been claimed (unclaimed, claimed).

Effect Example

Red Packet Message Flow

1. Preparation

Before getting started, please ensure you have created an application and completed client SDK integration.

2. Define Red Packet Message

2.1 Define Red Packet Message Type

You can create red packet type messages (such as RedPacketMessage) through IMLib SDK's custom messages. Message content structure should be defined according to business requirements, ensuring consistency across platforms (Android / iOS / Web).

Android / iOS custom message class references:

Web Sample Code:

// 1. RongIMLib.registerMessageType must be called before connect, otherwise may cause abnormal message receiving behavior.
// 2. Try to register all custom messages in your application uniformly at once, and only call registration once for the same type of message for easier management.

const messageType = 'app:red_packet' // Message type
const isPersited = true // Whether to store
const isCounted = true // Whether to count
const searchProps = [] // Search fields, no need to set for Web, search field values should be in range (-Math.pow(2, 64), Math.pow(2, 64)) and integers when set to numbers
const isStatusMessage = false // Whether it's a status message. Status messages are not stored, not counted, and can only be received when receiver is online.
const PersonMessage = RongIMLib.registerMessageType(messageType, isPersited, isCounted, searchProps, isStatusMessage)

2.2 Define Red Packet Message Display Template

If you're using IMKit SDK, you must create corresponding message display templates, otherwise SDK cannot properly display this type of message.

Android / iOS custom red packet message display template reference classes:

Web IMKit Custom Message Style Sample Code

// Construct IMKit initialization parameters
const customMessage = {
// Regular message display
userMessage: {
// key is the messageType of custom message, returned elements currently don't support setting class, you can set inline styles if needed.
'app:red_packet': (message) => {
const content = message.content;
return `<div style='padding: 0.5em 0.8333em;'>Red packet from ${content.name}</div>`;
}
},
// Notification message display
notifyMessage: {
// key is the messageType of custom message, returned elements currently don't support setting class, you can set inline styles if needed.
'app:red_packet': (message) => {
const content = message.content
const string = `<div>Red packet from ${content.name}</div>`
return string;
}
},
// Last message display in conversation
lastMessage:{
// key is the messageType of custom message, returned elements currently don't support setting class, you can set inline styles if needed.
'app:red_packet': (message) => {
const content = message.content;
return `[Red Packet]`;
},
}
};

// Special note: This init is only for demonstrating custom message settings, applications don't need to initialize multiple times
imkit.init({
customMessage:customMessage
});

3. Register and Receive Red Packet Messages

// Register custom message type, register after SDK initialization
ArrayList<Class<? extends MessageContent>> myMessages = new ArrayList<>();
myMessages.add(CustomRedPacketMessage.class);
RongCoreClient.registerMessageType(myMessages);

// Receive message example: Set receive message listener, automatically callback when receiving messages. If you're using IMLib SDK, please call RongCoreClient's addOnReceiveMessageListener method
IMCenter.addOnReceiveMessageListener(
new io.rong.imlib.listener.OnReceiveMessageWrapperListener() {
@Override
public boolean onReceivedMessage(Message message, ReceivedProfile profile) {
int left = profile.getLeft();
boolean isOffline = profile.isOffline();
boolean hasPackage = profile.hasPackage();
}
});

// Returned `Message` entity reference information below, can use `objectName` or `content` to distinguish message types:

{
"conversationType": "PRIVATE",
"targetId": "userid3453",
"messageId": 70,
"channelId": "",
"messageDirection": "RECEIVE",
"senderUserId": "userid3453",
"receivedStatus": "io.rong.imlib.model.Message$ReceivedStatus @560f848",
"sentStatus": "SENT",
"receivedTime": 1739428279001,
"sentTime": 1739428279158,
"objectName": "app:red_packet",
"content": {
"content": "Red packet message"
},
"extra": "",
"readReceiptInfo": "io.rong.imlib.model.ReadReceiptInfo @b8d3c06",
"messageConfig": {
"disablePushTitle": false,
"pushTitle": "",
"pushContent": "",
"pushData": "null",
"templateId": "",
"forceShowDetailContent": false,
"iOSConfig": null,
"androidConfig": null,
"harmonyConfig": null
},
"canIncludeExpansion": false,
"expansionDic": null,
"expansionDicEx": null,
"mayHasMoreMessagesBefore": false,
"UId": "CKVO-0J6T-GM26-D3E6",
"disableUpdateLastMessage": "false",
"directedUsers": "0"
}

4. Extension Area Display (Send Red Packet Entry)

4.1 Set Red Packet Extension Panel Plugin

If you're using IMLib SDK, you need to implement the send red packet entry yourself. If you're using IMKit SDK, you can add custom plugins to IMKit's extension panel.

Android Implementation Process

Custom plugins need to implement the IPluginModule interface class. You can refer to IPluginModule.java in IMKit source code and specific implementation classes. Here we use implementing custom plugin RedPacketPlugin example class as an example.

iOS Implementation Process

Insert corresponding red packet extension plugin icon in chat page's viewDidLoad method

[self.chatSessionInputBarControl.pluginBoardView insertItem:[UIImage imageNamed:@"redPacket"] highlightedImage:[UIImage imageNamed:@"redPacket"] title:@"Send Red Packet" tag:20080];

Web IMKit doesn't have extension panel concept

4.2 Configure Extension Panel Plugin

Sample Code

// 1. Inherit `DefaultExtensionConfig`, create custom extension panel configuration class `MyExtensionConfig`, override `getPluginModules()` method.

public class MyExtensionConfig extends DefaultExtensionConfig {
@Override
public List<IPluginModule> getPluginModules(Conversation.ConversationType conversationType, String targetId) {
List<IPluginModule> pluginModules = super.getPluginModules(conversationType,targetId);
// Add red packet extension item
pluginModules.add(new RedPacketPlugin());
return pluginModules;
}
}

// 2. After SDK initialization, call `setExtensionConfig` method to set custom input configuration. SDK will display extension panel according to this configuration.

RongExtensionManager.getInstance().setExtensionConfig(new MyExtensionConfig());

5. Send Red Packet Message After Successful Payment

After user payment succeeds, you need to call RongCloud's send message method to send red packet message and set message as extensible. Choose which platform to send this type of message from according to business logic.

// Build red packet message
CustomRedPacketMessage redPacketMessage = CustomRedPacketMessage.obtain("0.01");
io.rong.imlib.model.Message message =
io.rong.imlib.model.Message.obtain(targetId, conversationType, redPacketMessage);
// Set message as extensible
message.setCanIncludeExpansion(true);
HashMap<String, String> redInfo = new HashMap<>();
redInfo.put("open","false");
redInfo.put("count","1");
redInfo.put("amount","0.01");
message.setExpansion(redInfo);
// Send message, if you're using IMLib SDK, please use RongCoreClient's sendMessage method
IMCenter.getInstance().sendMessage(message, null, null, null);

Server Sample Code

 /**
* Send group gray bar message - targeted users (up to 1000 users per request)
*/
String[] targetIds = {"groupId"};
RedPacketMessage redPacketMessage =new RedPacketMessage("Red packet message");
HashMap<String, String> hashMap = new HashMap<>();
hashMap.put("open", "false");
hashMap.put("count", "1");
hashMap.put("amount", "2");
GroupMessage groupMessage = new GroupMessage()
.setSenderId("fromId")
.setIsIncludeSender(1)
.setTargetId(targetIds) // Group ID
.setContent(redPacketMessage)
.setObjectName(txtMessage.getType())
.setExpansion(true)
.setExtraContent(hashMap);

ResponseResult redPackeReslut = group.send(groupMessage);
System.out.println("group info Notify message result: " + redPackeReslut.toString());

6. Open Red Packet and Update Red Packet Extension

After user clicks to open red packet, red packet message status needs to change to "opened". At this time, you can update this message's extension information through Message Extension Listener updateMessageExpansion, set opening user ID and mark as opened status in extension, and change local display message style.

// messageUid is the original red packet message unique ID.

RongIMClient.getInstance()
.updateMessageExpansion(
redInfo,
messageUid,
new RongIMClient.OperationCallback() {
@Override
public void onSuccess() {
// Update sender handles UI data refresh after updating extension here
IMCenter.getInstance().refreshMessage(currentMessage);
}

@Override
public void onError(RongIMClient.ErrorCode errorCode) {
Toast.makeText(
getApplicationContext(),
"Setting failed, ErrorCode : " + errorCode.getValue(),
Toast.LENGTH_LONG)
.show();
}
});

Server Sample Code

/**
*
* Set Message Extension
*
*/
ExpansionModel msg = new ExpansionModel();
msg.setMsgUID("BS45-NPH4-HV87-10LM");
msg.setUserId("WNYZbMqpH");
msg.setTargetId("tjw3zbMrU");
msg.setConversationType(1);
HashMap<String, String> kv = new HashMap<String, String>();
kv.put("type1", "1");
kv.put("type2", "2");
kv.put("type3", "3");
kv.put("type4", "4");
msg.setExtraKeyVal(kv);
msg.setIsSyncSender(1);
ResponseResult result = expansion.set(msg);
System.out.println("set expansion: " + result.toString());

7. Sender Updates Red Packet Message Extension

Red packet message senders can globally set message extension listeners and handle corresponding processing when receiving message extension update callbacks. It's recommended to call client service API to get latest red packet claim information.

// Receiver Android sample code
RongIMClient.getInstance().setMessageExpansionListener(new RongIMClient.MessageExpansionListener() {
@Override
public void onMessageExpansionUpdate(Map<String, String> expansion, Message message) {
if (message.getContent() instanceof CustomRedPacketMessage){
IMCenter.getInstance().refreshMessage(message); // Refresh original message
// Other custom processing
}
}
});

8. Post Red Packet Claim Operations

After opening red packet, if you need to display "XX claimed the red packet", the server can send a group targeted message to red packet sender and claimer, or monitor message extension information to display corresponding user information and claim status. Red packet sender can monitor message extension information, and after receiving monitoring, actively get latest claim status from business client.

// Insert gray bar message
InformationNotificationMessage informationNotificationMessage = InformationNotificationMessage.obtain("You claimed the red packet sent by xxx");

ConversationType conversationType = ConversationType.PRIVATE;
String targetId = "user1";
String senderUserId = "Simulated sender ID";
ReceivedStatus receivedStatus = new ReceivedStatus(0x1);
String sentTime = System.currentTimeMillis();

IMCenter.getInstance().insertIncomingMessage(conversationType, targetId, senderUserId, receivedStatus, informationNotificationMessage, sentTime, new RongIMClient.ResultCallback<Message>() {
/**
* Success callback
* @param message Inserted message
*/
@Override
public void onSuccess(Message message) {

}

/**
* Failure callback
* @param errorCode Error code
*/
@Override
public void onError(RongIMClient.ErrorCode errorCode) {

}
});