Sending Virtual Gifts - Android
Virtual gifting is a powerful monetization and engagement feature that allows viewers to support hosts or speakers during a livestream by sending them digital tokens or "gifts." These gifts can be visually animated and even linked to leaderboards or reward systems.
This guide explains how to implement a secure and real-time virtual gifting experience using your backend server in combination with VideoSDK PubSub.
How It Works
-
User Action: A viewer taps on a gift button to send a virtual gift to the host.
-
Server Verification:
- A request is made to your business backend to process the gift.
- The server authenticates the user, checks their wallet balance, deducts the gift value, and returns a success response.
-
Event Broadcast: Upon success, the client publishes a PubSub message to inform everyone in the meeting (host + other viewers) that a gift has been sent. Clients can then visually show an animation or notification.
Backend Responsibility
Your backend plays a central role in verifying, validating, and processing gift transactions. It should:
- Authenticate the request (token/session)
- Verify if the user has sufficient balance
- Deduct the gift cost
- Store the transaction in a database (optional but recommended)
- Respond with success or failure
Frontend Implementation
- Sending a Gift (Client to Backend + PubSub)
- Kotlin
- Java
// Data class for request body
data class GiftRequest(val senderId: String, val hostId: String, val giftType: String)
// Retrofit API interface
interface ApiService {
@POST("send-gift")
suspend fun sendGift(@Body request: GiftRequest): Response<GiftResponse>
}
// Gift sending logic with PubSub
fun sendGift(giftType: String, senderId: String, hostId: String, pubSub: PubSub) {
CoroutineScope(Dispatchers.IO).launch {
try {
val response = api.sendGift(GiftRequest(senderId, hostId, giftType))
if (response.isSuccessful && response.body()?.success == true) {
pubSub.publish(mapOf("giftType" to giftType, "from" to senderId, "to" to hostId))
} else {
Log.e("Gift", "Failed: ${response.body()?.message}")
}
} catch (e: Exception) {
Log.e("Gift", "Error: ${e.message}")
}
}
}
// Request model
public class GiftRequest {
public String senderId;
public String hostId;
public String giftType;
public GiftRequest(String senderId, String hostId, String giftType) {
this.senderId = senderId;
this.hostId = hostId;
this.giftType = giftType;
}
}
// Response model
public class GiftResponse {
public boolean success;
public String message;
}
// Retrofit interface
public interface ApiService {
@POST("send-gift")
Call<GiftResponse> sendGift(@Body GiftRequest request);
}
// Gift sending method
public void sendGift(String giftType, String senderId, String hostId, PubSub pubSub) {
GiftRequest request = new GiftRequest(senderId, hostId, giftType);
Retrofit retrofit = new Retrofit.Builder()
.baseUrl("https://your-api.com/")
.addConverterFactory(GsonConverterFactory.create())
.build();
ApiService api = retrofit.create(ApiService.class);
api.sendGift(request).enqueue(new Callback<GiftResponse>() {
@Override
public void onResponse(Call<GiftResponse> call, Response<GiftResponse> response) {
if (response.isSuccessful() && response.body().success) {
Map<String, String> payload = new HashMap<>();
payload.put("giftType", giftType);
payload.put("from", senderId);
payload.put("to", hostId);
pubSub.publish(payload);
} else {
Log.e("Gift", "Failed: " + (response.body() != null ? response.body().message : "Unknown error"));
}
}
@Override
public void onFailure(Call<GiftResponse> call, Throwable t) {
Log.e("Gift", "Error sending gift", t);
}
});
}
- Displaying the Gift (All Clients)
- Kotlin
- Java
// In your Activity or Fragment
val gifts = mutableListOf<Gift>()
pubSub.onMessage("GIFT") { message ->
val from = message["from"] ?: "Unknown"
val to = message["to"] ?: "Unknown"
val type = message["giftType"] ?: "gift"
val gift = Gift(from = from, to = to, type = type)
gifts.add(gift)
runOnUiThread {
Toast.makeText(
this,
"🎁 $from sent a $type to $to",
Toast.LENGTH_SHORT
).show()
}
}
// In your Activity or Fragment
List<Gift> gifts = new ArrayList<>();
pubSub.onMessage("GIFT", message -> {
String from = message.get("from");
String to = message.get("to");
String type = message.get("giftType");
Gift gift = new Gift(from, to, type);
gifts.add(gift);
runOnUiThread(() -> {
Toast.makeText(
context,
"🎁 " + from + " sent a " + type + " to " + to,
Toast.LENGTH_SHORT
).show();
});
});
API Reference
The API references for all the methods and events utilized in this guide are provided below.
Got a Question? Ask us on discord