### STARTING Event Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/index.md This JSON object illustrates the data for a STARTING event. It provides the lobby state, owner, settings, and member details, indicating that the lobby is transitioning to a starting state. ```json { "service": "lobby", "operation": "STARTING", "data": { "lobbyId": "22819:unranked:406", "lobby": { "state": "starting", "owner": "f6fa3e0e-6aac-497a-84e1-c8db6f545c12", "settings": {}, "version": 1, "numMembers": 1, "members": [ { "profileId": "48844593-6e01-464f-bc13-565ee536a46b", "name": "", "pic": "", "rating": 0, "team": "all", "isReady": true, "extra": {}, "ipAddress": "174.112.74.185", "cxId": "13469:48844593-6e01-464f-bc13-565ee536a46b:1kslkorpivpa68bhf21q1avi9q" } ] } } } ``` -------------------------------- ### Lobby Event Sequence Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/index.md An example demonstrating the sequence of lobby events, including STARTING, ROOM_PROGRESS, and ROOM_ASSIGNED, as sent to lobby members. ```json {"service":"lobby","operation":"STARTING","data":{"lobbyId":"23649:CursorPartyV2:4186","lobby":{"state":"starting","settings":{},"version":1,"cRegions":[],"round":1,"isRoomReady":false,"keepAliveRateSeconds":72,"isAvailable":true,"ownerCxId":"23649:37e60799-468d-4440-8fce-5d8eabade18d:4s26gha7bhmiottrn3v38d8l0o","legacyLobbyOwnerEnabled":false,"numMembers":1,"members":[{"profileId":"37e60799-468d-4440-8fce-5d8eabade18d","name":"greg@bitheads.com","pic":"","rating":0,"team":"all","isReady":true,"extra":{"colorIndex":6,"presentSinceStart":false},"ipAddress":"184.148.127.43","cxId":"23649:37e60799-468d-4440-8fce-5d8eabade18d:4s26gha7bhmiottrn3v38d8l0o"}]}}} {"service":"lobby","operation":"ROOM_PROGRESS","data":{"lobbyId":"23649:CursorPartyV2:4186","curStep":1,"ofStep":5,"msg":"Host lookup","variation":"no-host-found"}} {"service":"lobby","operation":"ROOM_PROGRESS","data":{"lobbyId":"23649:CursorPartyV2:4186","curStep":2,"ofStep":5,"msg":"New host started"}} {"service":"lobby","operation":"ROOM_PROGRESS","data":{"lobbyId":"23649:CursorPartyV2:4186","curStep":3,"ofStep":5,"msg":"Host docker init"}} {"service":"lobby","operation":"ROOM_ASSIGNED","data":{"lobbyId":"23649:CursorPartyV2:4186","connectData":{"address":"3.96.222.126","ports":{"udp":9000,"tcp":9000,"ws":9001}},"passcode":"fda606"}} ``` -------------------------------- ### StartStream JSON Response Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/playbackstream/startstream.md Example JSON response received after successfully starting a stream, including stream details and player IDs. ```json { "status": 200, "data": { "playbackStreamId": "b8da4619-2ddc-4184-b654-cd11d12a3275", "initiatingPlayerId": "198bcafcd-6e84-4c30-9f6e-3f9f016440c6", "targetPlayerId": "a6943c74-6655-4245-8b2b-13bb908d3f88", "status": "STARTED", "summary": {}, "initialSharedData": { "entities": [], "statistics": {} }, "events": [], "createdAt": 1425481184200, "updatedAt": 1425481184200 } } ``` -------------------------------- ### Get Items on Promotion (C++) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/useritems/getitemsonpromotion.md This C++ example demonstrates how to get items on promotion. It takes shop ID, flags for including definitions and promotion details, and JSON options as input. The call is made directly on the UseritemsService. ```cpp const char *shopId = "None"; bool includeDef = True; bool includePromotionDetails = True; const char *optionsJson = "{\"category\": \"Equipment\"}"; <%= data.branding.codePrefix %>.getUseritemsService().getItemsOnPromotion(shopId, includeDef, includePromotionDetails, optionsJson, this); ``` -------------------------------- ### Find Users by Name Starting With (Objective-C) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/friend/findusersbynamestartingwith.md Objective-C example for finding users by name prefix. Ensure BCCompletionBlock and BCErrorCompletionBlock are defined. ```objectivec NSString *searchText = @"someText"; int maxResults = 5; BCCompletionBlock successBlock; // define callback BCErrorCompletionBlock failureBlock; // define callback [[<%= data.branding.codePrefix %> friendService] findUsersByNameStartingWith:searchText maxResults:maxResults completionBlock:successBlock errorCompletionBlock:failureBlock cbObject:nil]; ``` -------------------------------- ### Get Lobby Instances Response Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/getlobbyinstances.md This snippet shows an example of the JSON response when retrieving lobby instances. It includes details about the lobby's ID, member count, and public settings. ```json { "data": { "lobbyInstances": [ { "lobbyId": "23782:10b6d6fa-0aa6-43b0-a7b3-48aff2d13312:52kc0h19k0pnnjhnrp8pug7udd", "numMembers": 1, "maxMembers": 8, "publicSettings": { "name": "myLobbyName", "pwd": "mySecretCode" } } ] }, "status": 200 } ``` -------------------------------- ### Get Lobby Data in C++ Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/getlobbydata.md This C++ example shows how to fetch lobby data. It requires a lobby ID and a callback object. ```cpp const char *lobbyId = "13229:Relay_lobbyT_v2:20"; <%= data.branding.codePrefix %>->getLobbyService()->getLobbyData(lobbyId, this); ``` -------------------------------- ### SmartSwitchAuthenticateAdvanced in Java Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/smartswitchauthenticateadvanced.md Example of using SmartSwitchAuthenticateAdvanced in Java. This snippet includes the necessary setup for authentication and defines callback methods for success and error. ```java AuthenticationType authenticationType = AuthenticationType.Universal; AuthenticationIds ids = new AuthenticationIds ("authAdvancedUser", "authAdvancedPass", ""); boolean forceCreate = true; string extraJson = "{\"key\":\"value\"}"; this; // implements IServerCallback <%= data.branding.codePrefix %>.smartSwitchAuthenticateAdvanced(authenticationType, ids, forceCreate, extraJson, this); public void serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, JSONObject jsonData) { System.out.print(String.format("Success | %s", jsonData.toString())); } public void serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, String jsonError) { System.out.print(String.format("Failed | %d %d %s", statusCode, reasonCode, jsonError.toString())); } ``` -------------------------------- ### Get Sales Inventory By Category (Objective-C) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/appstore/getsalesinventorybycategory.md Objective-C example for fetching sales inventory. Define BCCompletionBlock and BCErrorCompletionBlock for callbacks. ```objectivec NSString *storeId = @"itunes"; NSString *userCurrency = @"{\"userCurrency\":\"USD\"}"; NSString *category = @"subscriptions"; BCCompletionBlock successBlock; // define callback BCErrorCompletionBlock failureBlock; // define callback [[<%= data.branding.codePrefix %> appStoreService] getSalesInventoryByCategory:storeId userCurrency:userCurrency category:category completionBlock:successBlock errorCompletionBlock:failureBlock cbObject:nil]; ``` -------------------------------- ### Initialize Billing Client and Query Products Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/learn/5_portal-tutorials/store-integration-google/index.md This snippet demonstrates how to initialize the BillingClient, query SKU details for in-app products, and launch the billing flow upon successful setup. It also includes logic for querying existing purchases. ```java @Override public void onBillingSetupFinished(BillingResult billingResult) { // [start querySku] if (billingResult.getResponseCode() == BillingClient.BillingResponseCode.OK) { // The BillingClient is ready. You can query purchases here. List skuList = new ArrayList<>(); skuList.add("2012testproduct01"); skuList.add("2012testproduct02"); Log.e(TAG, "buy product...billingResult2"); SkuDetailsParams.Builder params = SkuDetailsParams.newBuilder(); params.setSkusList(skuList).setType(BillingClient.SkuType.INAPP); billingClient.querySkuDetailsAsync(params.build(), new SkuDetailsResponseListener() { @Override public void onSkuDetailsResponse(BillingResult billingResult, List skuDetailsList) { // Process the result. if (billingResult == null) { Log.wtf(TAG, "onSkuDetailsResponse: null BillingResult"); return; } int responseCode = billingResult.getResponseCode(); String debugMessage = billingResult.getDebugMessage(); switch (responseCode) { case BillingClient.BillingResponseCode.OK: Log.i(TAG, "onSkuDetailsResponse: " + responseCode + " " + debugMessage); if (skuDetailsList == null) { Log.w(TAG, "onSkuDetailsResponse: null SkuDetails list"); skusWithSkuDetails.postValue(Collections.emptyMap()); } else { Map newSkusDetailList = new HashMap(); for (SkuDetails skuDetails : skuDetailsList) { newSkusDetailList.put(skuDetails.getSku(), skuDetails); BillingFlowParams billingFlowParams = BillingFlowParams.newBuilder() .setSkuDetails(skuDetails) .build(); int responseCodeF = billingClient.launchBillingFlow(MainActivity.this, billingFlowParams).getResponseCode(); } skusWithSkuDetails.postValue(newSkusDetailList); Log.i(TAG, "onSkuDetailsResponse: count " + newSkusDetailList.size()); } break; case BillingClient.BillingResponseCode.SERVICE_DISCONNECTED: case BillingClient.BillingResponseCode.SERVICE_UNAVAILABLE: case BillingClient.BillingResponseCode.BILLING_UNAVAILABLE: case BillingClient.BillingResponseCode.ITEM_UNAVAILABLE: case BillingClient.BillingResponseCode.DEVELOPER_ERROR: case BillingClient.BillingResponseCode.ERROR: Log.e(TAG, "onSkuDetailsResponse: " + responseCode + " " + debugMessage); break; case BillingClient.BillingResponseCode.USER_CANCELED: Log.i(TAG, "onSkuDetailsResponse: " + responseCode + " " + debugMessage); break; // These response codes are not expected. case BillingClient.BillingResponseCode.FEATURE_NOT_SUPPORTED: case BillingClient.BillingResponseCode.ITEM_ALREADY_OWNED: case BillingClient.BillingResponseCode.ITEM_NOT_OWNED: default: Log.wtf(TAG, "onSkuDetailsResponse: " + responseCode + " " + debugMessage); } } }); } // [Start query purchase] if (!billingClient.isReady()) { Log.e(TAG, "queryPurchases: BillingClient is not ready"); } Log.d(TAG, "queryPurchases: INAPP"); Purchase.PurchasesResult result = billingClient.queryPurchases(BillingClient.SkuType.INAPP); if (result == null) { Log.i(TAG, "queryPurchases: null purchase result"); processPurchases(null); } else { if (result.getPurchasesList() == null) { Log.i(TAG, "queryPurchases: null purchase list"); processPurchases(null); } else { processPurchases(result.getPurchasesList()); } } } ``` -------------------------------- ### GenerateAnonymousId Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/authentication/generateanonymousid.md Generates a GUID for use as an anonymous installation ID. This method is normally called only once when the application starts for the first time. ```APIDOC ## GenerateAnonymousId ### Description Generates a GUID for use as an anonymous installation ID. This method is normally called only once when the application starts for the first time. The generated ID is used in conjunction with [InitializeIdentity](/api/capi/client/initializeidentity). ### Method Signature ```csharp string GenerateAnonymousId(); ``` ### Parameters This method does not take any parameters. ### Returns - **string**: A unique GUID string representing the anonymous installation ID. ### Usage Examples #### C# ```csharp string anonId = BrainCloud.AuthenticationService.GenerateAnonymousId(); ``` #### C++ ```cpp std::string anonId = BrainCloud->getAuthenticationService()->generateAnonymousId(); ``` #### Objective-C ```objectivec NSString * anonId = [[BrainCloud authenticationService] generateAnonymousId]; ``` #### Java ```java String anonId = BrainCloud.getAuthenticationService().generateAnonymousId(); ``` #### JavaScript ```javascript var anonId = BrainCloud.authentication.generateAnonymousId(); ``` #### Dart ```dart var anonId = BrainCloud.authentication.generateAnonymousId(); ``` ``` -------------------------------- ### GetPage C# Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/globalentity/getpage.md Demonstrates how to call the GetPage API in C# with success and failure callbacks. Ensure you have the necessary BrainCloud SDK setup. ```csharp string context = "{\"pagination\":{\"rowsPerPage\":50,\"pageNumber\":1},\"searchCriteria\":{\"entityType\":\"address\"},\"sortCriteria\":{\"createdAt\":1,\"updatedAt\":-1}}"; SuccessCallback successCallback = (response, cbObject) => { Debug.Log(string.Format("Success | {0}", response)); }; FailureCallback failureCallback = (status, code, error, cbObject) => { Debug.Log(string.Format("Failed | {0} {1} {2}", status, code, error)); }; <%= data.branding.codePrefix %>.GlobalEntityService.GetPage(context, successCallback, failureCallback); ``` -------------------------------- ### Get Global Leaderboard Versions API Response Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/4_s2s/leaderboard/getgloballeaderboardversions.md Example JSON response from the GetGlobalLeaderboardVersions API, detailing leaderboard ID, type, rotation, retained count, and version history with start and end times. ```json { "data": { "leaderboardId": "L1", "leaderboardType": "HIGH_VALUE", "rotationType": "WEEKLY", "retainedCount": 2, "versions": [ { "versionId": 27, "startingAt": 1434499200000, "endingAt": 1435104000000 }, { "versionId": 26, "startingAt": 1433894400000, "endingAt": 1434499200000 } ] }, "status": 200 } ``` -------------------------------- ### Initialize Wrapper with Apps (C++) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/initializewithapps.md Initializes the wrapper with server URL, default app ID, a map of secrets, app version, company name, and app name. ```cpp const char* serverUrl = "<%= data.branding.serverUrl %>"; std::string secret = <%= data.example.appSecret %>; std::string appId = <%= data.example.appId %>; std::string childSecret = <%= data.example.appChildSecret %>; std::string childAppId = <%= data.example.appChildId %>; std::map secretMap; secretMap[appId] = secret; secretMap[childAppId] = childSecret; const char* version = <%= data.example.appVersion %>; const char* company = <%= data.example.companyName %>; const char* appName = <%= data.example.appName %>; <%= data.branding.codePrefix %>->initializeWithApps(serverUrl, appId.c_str(), secretMap, version, company, appName); ``` -------------------------------- ### Example JSON Response for GUID Generation Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/3_cc/bridge/generateGuid.md This is an example of the JSON response structure received after successfully generating a GUID. ```json { "data": { "response": { "guid": "81a2c41d-ab0d-4057-adb8-d79bc819ee01" }, "success": true }, "status": 200 } ``` -------------------------------- ### JSON Response Example for Get Presence of Group Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/presence/getpresenceofgroup.md This is an example of the JSON response received when calling the Get Presence of Group API. It includes a list of users with their online status and presence details. ```json { "data": { "presence": [ { "user": { "id": "a50a9aae-65fc-4171-b3f9-c0054b7e2d6b", "name": "", "pic": null, "cxs": [ "13229:a50a9aae-65fc-4171-b3f9-c0054b7e2d6b:84uedu4cof8gvlj3r009cejcik" ] }, "online": true, "summaryFriendData": {}, "activity": {} }, { "user": { "id": "07ba7ab2-3505-4342-b91f-6500fa8f5585", "name": "", "pic": null }, "online": false, "summaryFriendData": {}, "activity": {} } ] }, "status": 200 } ``` -------------------------------- ### JSON Response Example for Get Player Scores Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/leaderboard/getplayerscores.md An example of the JSON response structure when successfully retrieving player scores. ```json { "data": { "versionId": 1, "scores": [ { "score": 10101, "data": { "nickname": "batman" }, "createdAt": 1613678944374, "updatedAt": 1613678944374 }, { "score": 101, "data": { "nickname": "batman" }, "createdAt": 1613678939147, "updatedAt": 1613678939147 }, { "score": 10, "data": { "nickname": "batman" }, "createdAt": 1613678933679, "updatedAt": 1613678933679 } ], "leaderboardId": "anArcadeLeaderboardId" }, "status": 200 } ``` -------------------------------- ### SysRoomReady Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/index.md The room experience is ready to launch. ```APIDOC ## SysRoomReady ### Description The room experience is ready to launch. ### Method Not specified (assumed to be a C++ SDK method call) ### Endpoint /api/capi/lobby/sysroomready ### Parameters Not specified in source text. ### Request Example Not specified in source text. ### Response Not specified in source text. ``` -------------------------------- ### Read Promotion Configuration (Raw API) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/promotions/sysreadpromotion.md This example shows how to make a raw API call to read promotion configuration. It specifies the service, operation, and the promotion ID in the data payload. ```r { "service": "promotions", "operation": "SYS_READ_PROMOTION", "data": { "promotionId": 1 } } ``` -------------------------------- ### Initialize Wrapper with Apps (Java) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/initializewithapps.md Initializes the wrapper with server URL, default app ID, a map of secrets, and app version. ```java String serverUrl = "<%= data.branding.serverUrl %>"; String secret = <%= data.example.appSecret %>; String appId = <%= data.example.appId %>; String childSecret = <%= data.example.appChildSecret %>; String childAppId = <%= data.example.appChildId %>; Map secretMap = new HashMap(); secretMap.put(appId, secret); secretMap.put(childAppId, childSecret); String version = <%= data.example.appVersion %>; <%= data.branding.codePrefix %>.initializeWithApps(serverUrl, appId, secretMap, version); ``` -------------------------------- ### Get Random Entities Matching in JavaScript Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/customentity/getrandomentitiesmatching.md JavaScript example to get random entities. The 'whereJson' can be an object or a string. Results are handled in a callback. ```javascript var entityType = "athletes"; var whereJson = { "data.position": "forward" }; var maxReturn = 2; <%= data.branding.codePrefix %>.customEntity.getRandomEntitiesMatching(entityType, whereJson, maxReturn, result => { var status = result.status; console.log(status + " : " + JSON.stringify(result, null, 2)); }); ``` -------------------------------- ### GetEntityPageOffset Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/customentity/getentitypageoffset.md Retrieves a paginated list of entities. This example demonstrates how to call the API to get entities with a specific page size and offset. ```javascript var pageOffset = 0; var pageSize = 10; // Get the first page of entities brainCloud.getGlobalEntity().getEntityPageOffset(pageOffset, pageSize, // Success callback function (response) { // Handle success response console.log("Success: " + JSON.stringify(response)); }, // Failure callback function (error) { // Handle error response console.log("Error: " + error); } ); ``` -------------------------------- ### Initialize Wrapper with Apps (C#) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/initializewithapps.md Initializes the wrapper with server URL, default app ID, a map of secrets, and app version. ```csharp // C# string serverUrl = "<%= data.branding.serverUrl %>"; string secret = <%= data.example.appSecret %>; string appId = <%= data.example.appId %>; string childSecret = <%= data.example.appChildSecret %>; string childAppId = <%= data.example.appChildId %>; Dictionary secretMap = new Dictionary(); secretMap.Add(appId, secret); secretMap.Add(childAppId, childSecret); string version = <%= data.example.appVersion %>; <%= data.branding.codePrefix %> = new <%= data.branding.codeWrapper %>(); <%= data.branding.codePrefix %>.InitWithApps(serverUrl, appId, secretMap, version); ``` -------------------------------- ### Get Player Scores from Leaderboards in Java Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/leaderboard/getplayerscoresfromleaderboards.md Java code to get player scores from leaderboards. This example implements the IServerCallback interface for handling asynchronous responses. ```java String[] leaderboardIds = { "leaderboardId1", "leaderboardId2" }; this; // implements IServerCallback <%= data.branding.codePrefix %>.getLeaderboardService().getPlayerScoresFromLeaderboards(leaderboardIds, this); public void serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, JSONObject jsonData) { System.out.print(String.format("Success | %s", jsonData.toString())); } public void serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, String jsonError) { System.out.print(String.format("Failed | %d %d %s", statusCode, reasonCode, jsonError.toString())); } ``` -------------------------------- ### Example Promotion JSON Response Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/4_s2s/promotions/syscreatepromotion.md This is an example of the JSON response received after successfully creating a promotion. ```json { "data": { "gameId": "23783", "promotionId": 3, "type": "SCHEDULED", "name": "Independence Day Sale", "message": { "en": "Happy 4th of July!" }, "enabled": false, "segments": [], "prices": [ { "itemId": "coinbundle10", "priceId": 0 } ], "notifications": [ { "trigger": "ACTIVATED", "notificationTemplateId": 1 } ], "customJson": { "key": "value" }, "startAt": 1593781259911, "endAt": 1594126859911, "createdAt": 1592544049481, "updatedAt": 1592544049481, "version": 1 }, "status": 200 } ``` -------------------------------- ### Get Player Score in Java Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/leaderboard/getplayerscore.md This Java example shows how to get a player's score from a leaderboard. The class must implement IServerCallback to handle responses. ```java String leaderboardId = "default"; int versionId = -1; this; // implements IServerCallback <%= data.branding.codePrefix %>.getLeaderboardService().getPlayerScore(leaderboardId, versionId, this); public void serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, JSONObject jsonData) { System.out.print(String.format("Success | %s", jsonData.toString())); } public void serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, String jsonError) { System.out.print(String.format("Failed | %d %d %s", statusCode, reasonCode, jsonError.toString())); } ``` -------------------------------- ### SysLaunchServer Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/roomserver/index.md Launches a hosted server directly, bypassing brainCloud lobby matchmaking. ```APIDOC ## SysLaunchServer ### Description Launch a hosted server directly. Allows for the bypassing of brainCloud lobby matchmaking. ### Method POST ### Endpoint /api/capi/roomserver/syslaunchserver ``` -------------------------------- ### Product Pricing Structure Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/productmanagement/syssetdefaultproductprice.md Illustrates the JSON structure for defining product prices, including currency and price values for different platforms. ```json { "priceOptions": [ { "currency": "USD", "price": 0.99 }, { "currency": "CAD", "price": 1.29 } ], "googlePlay": { "id": "googleiapid" } } ``` -------------------------------- ### Get Group Leaderboard View in Java Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/leaderboard/getgroupleaderboardview.md Java code to get a group leaderboard. This example includes the necessary serverCallback and serverError methods for handling responses. ```java String leaderboardId = "default"; String groupId = "actual_group_id"; SortOrder sort = SocialLeaderboardService.SortOrder.HIGH_TO_LOW; int beforeCount = 3; int afterCount = 4; this; // implements IServerCallback <%= data.branding.codePrefix %>.getLeaderboardService().getGroupLeaderboardView(leaderboardId, groupId, sort, beforeCount, afterCount, this); public void serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, JSONObject jsonData) { System.out.print(String.format("Success | %s", jsonData.toString())); } public void serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, String jsonError) { System.out.print(String.format("Failed | %d %d %s", statusCode, reasonCode, jsonError.toString())); } ``` -------------------------------- ### Get File Info Simple in Dart Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/globalfilev3/getfileinfosimple.md Use the Dart client to get file information. This example demonstrates checking the status code for success or failure. ```dart var folderPath = "/root1/sub11/sub12/"; var filename = "sub12file1"; ServerResponse result = await <%= data.branding.codePrefix %>.globalFileV3Service.getFileInfoSimple(folderPath:folderPath, filename:filename); if (result.statusCode == 200) { print("Success"); } else { print("Failed ${result.error['status_message'] ?? result.error}"); } ``` -------------------------------- ### Purchase User Item in Java Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/useritems/purchaseuseritem.md This Java example shows how to purchase a user item. It requires the item definition ID, quantity, shop ID, and implementation of server callback methods for success and error handling. ```java String defId = "sword001"; int quantity = 1; String shopId = ""; boolean includeDef = true; this; // implements IServerCallback <%= data.branding.codePrefix %>.getUserItemsService().purchaseUserItem(defId, quantity, shopId, includeDef, this); public void serverCallback(ServiceName serviceName, ServiceOperation serviceOperation, JSONObject jsonData) { System.out.print(String.format("Success | %s", jsonData.toString())); } public void serverError(ServiceName serviceName, ServiceOperation serviceOperation, int statusCode, int reasonCode, String jsonError) { System.out.print(String.format("Failed | %d %d %s", statusCode, reasonCode, jsonError.toString())); } ``` -------------------------------- ### Get Upload Total Bytes to Transfer in Dart Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/file/getuploadtotalbytestotransfer.md Example of how to get the total upload bytes in Dart. It includes basic error handling for the server response. ```dart var uploadId = "1234-1234-1234-1234"; ServerResponse result = await <%= data.branding.codePrefix %>.fileService.getUploadTotalBytesToTransfer(uploadId:uploadId); if (result.statusCode == 200) { print("Success"); } else { print("Failed ${result.error['status_message'] ?? result.error}"); } ``` -------------------------------- ### Initialize Google Sign-In and Authenticate Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/learn/5_portal-tutorials/authentication-google-playgame/index.md This C# code snippet demonstrates how to configure Google Sign-In for Unity, enabling game sign-in, and initiating the sign-in process. It handles the callback to retrieve the server auth code. ```csharp public void RegisterDeviceToken() { GoogleSignIn.Configuration = configuration; GoogleSignIn.Configuration.UseGameSignIn = true; GoogleSignIn.DefaultInstance.SignIn().ContinueWith(GoogleSinInCallback); } public void GoogleSinInCallback(Task task) { if (task.IsFaulted) { bcreturn.GetComponent().text = "Failed to call GoogleSignIn()"; } else { serverAuthCode = task.Result.AuthCode; } } ``` -------------------------------- ### Get Subscribed Channels in JavaScript Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/chat/getsubscribedchannels.md JavaScript example to get subscribed channels. The callback function receives a result object containing the status and channel data. ```javascript var channelType = "all"; <%= data.branding.codePrefix %>.chat.getSubscribedChannels(channelType, result => { var status = result.status; console.log(status + " : " + JSON.stringify(result, null, 2)); }); ``` -------------------------------- ### Initialize Wrapper with Apps (Objective-C) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/initializewithapps.md Initializes the wrapper with server URL, default app ID, a map of secrets, and app version. ```objectivec NSString* serverUrl = @"<%= data.branding.serverUrl %>"; NSString* secret = @<%= data.example.appSecret %>; NSString* appId = @<%= data.example.appId %>; NSString* childSecret = @<%= data.example.appChildSecret %>; NSString* childAppId = @<%= data.example.appChildId %>; NSDictionary* secretMap = @{ appId : secret, childAppId : childSecret, }; NSString* version = @<%= data.example.appVersion %>; [<%= data.branding.codePrefix %> initializeWithApps:serverUrl defaultAppId:appId secretMap:secretMap appVersion:version]; ``` -------------------------------- ### Get File List in C++ Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/groupfile/getfilelist.md This C++ example demonstrates how to fetch a file list from a group. It takes the group ID, folder path, and a recursion flag as parameters. The method signature implies a callback mechanism handled by the 'this' object. ```cpp const char *groupId = "dfsfsffsd"; const char *folderPath = ""; bool recurse = true; <%= data.branding.codePrefix에요>->getGroupFileService()->getFileList(groupId, folderPath, recurse, this); ``` -------------------------------- ### Get Sales Inventory By Category (JavaScript) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/appstore/getsalesinventorybycategory.md JavaScript example to get sales inventory. The callback function receives the result object containing status and data. ```javascript var storeId = "itunes"; var userCurrency = { "userCurrency": "USD" }; var category = "subscriptions"; <%= data.branding.codePrefix %>.appStore.getSalesInventoryByCategory(storeId, userCurrency, category, result => { var status = result.status; console.log(status + " : " + JSON.stringify(result, null, 2)); }); ``` -------------------------------- ### Objective-C SmartSwitchAuthenticateFacebook Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/1_wrapper/smartswitchauthenticatefacebook.md Example of authenticating a user with Facebook credentials in Objective-C. Requires defining completion and error completion blocks. ```objectivec NSString* externalID = @"userFacebookId"; NSString* authToken = @"tokenFromFacebook"; BCCompletionBlock successBlock; // define callback BCErrorCompletionBlock failureBlock; // define callback [<%= data.branding.codePrefix %> smartSwitchAuthenticateExternal:externalID authenticationToken:authToken forceCreate:true completionBlock:successBlock errorCompletionBlock:failureBlock cbObject:nil]; ``` -------------------------------- ### Get Lobby Data JSON Response Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/4_s2s/lobby/getlobbydata.md This is an example of a successful JSON response when retrieving lobby data. It contains detailed information about the lobby and its members. ```json { "data": { "id": "13229:Relay_lobbyT_v2:20", "lobbyType": "Relay_lobbyT_v2", "state": "setup", "rating": 0, "lobbyTypeDef": { "lobbyTypeId": "Relay_lobbyT_v2", "teams": { "all": { "minUsers": 1, "maxUsers": 8, "autoAssign": true, "code": "all" } }, "rules": { "allowEarlyStartWithoutMax": true, "forceOnTimeStartWithoutReady": true, "allowJoinInProgress": false, "onTimeStartSecs": 600, "disbandOnStart": true, "everyReadyMinPercent": 15, "everyReadyMinNum": 1, "earliestStartSecs": 1, "tooLateSecs": 600 }, "desc": "starts when 1 player is ready" }, "settings": {}, "version": 1, "connectData": {}, "timetable": { "createdAt": 1631050042177, "early": 1631050043177, "onTime": 1631050642177, "tooLate": 1631050642177 }, "cRegions": [], "round": 1, "ownerCxId": "13229:db4be46d-1e99-41fe-9402-a0e8f7cd7cb5:p57kebat767ogdtesnp5cmd46p", "legacyLobbyOwnerEnabled": true, "owner": "db4be46d-1e99-41fe-9402-a0e8f7cd7cb5", "numMembers": 1, "members": [ { "profileId": "db4be46d-1e99-41fe-9402-a0e8f7cd7cb5", "name": "", "pic": "", "rating": 1200, "team": "all", "isReady": true, "extra": {}, "cxId": "13229:db4be46d-1e99-41fe-9402-a0e8f7cd7cb5:p57kebat767ogdtesnp5cmd46p" } ] }, "status": 200 } ``` -------------------------------- ### JSON Response Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/productmanagement/syssetdefaultproductprice.md Example JSON response when retrieving product details, including default price information. ```json { "data": { "gameId": "23783", "itemId": "gold_bars_10", "type": "Consumable", "iTunesSubscriptionType": null, "category": "bars", "title": "Bars (10)", "description": "Bundle of 10 Bars.", "imageUrl": "", "currency": { "bar": 10 }, "parentCurrency": {}, "peerCurrency": { "deploypeer": { "gems": 11 } }, "defaultPriceId": 2, "prices": [ { "priceId": 0, "referencePrice": 99, "storeData": { "amazon": { "id": "amazoniapid" }, "itunes": { "ids": [ { "appId": "iphone", "itunesId": "appleiapid" } ] }, "facebook": { "currencyList": [ { "currency": "USD", "price": 0.99 }, { "currency": "CAD", "price": 1.29 } ] }, "googlePlay": { "id": "googleiapid" } } }, { "priceId": 1, "referencePrice": 999, "storeData": { "amazon": { "id": "amazoniapid" }, "itunes": { "ids": [ { "appId": "iphone", "itunesId": "appleiapid" } ] }, "facebook": { "currencyList": [ { "currency": "USD", "price": 0.99 }, { "currency": "CAD", "price": 1.29 } ] }, "googlePlay": { "id": "googleiapid" } } }, { "priceId": 2, "referencePrice": 699, "storeData": { "amazon": { "id": "amazoniapid" }, "itunes": { "ids": [ { "appId": "iphone", "itunesId": "appleiapid" } ] }, "facebook": { "currencyList": [ { "currency": "USD", ``` -------------------------------- ### Get Item Catalog Service Proxy in Cloud Code Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/3_cc/bridge/getitemcatalogserviceproxy.md Use this snippet in Cloud Code to get the ItemCatalogServiceProxy. Ensure you are in the Cloud Code tab to view this example. ```cfscript var proxy = bridge.getItemCatalogServiceProxy(); ``` ```cfscript var proxy = bridge.getItemCatalogServiceProxy(); ``` -------------------------------- ### Get Mail Service Proxy in Cloud Code Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/3_cc/bridge/getmailserviceproxy.md Use this snippet in Cloud Code to get a proxy for the MailService. Ensure you are in the Cloud Code tab to view this example. ```cfscript var proxy = bridge.getMailServiceProxy(); ``` ```cfscript var proxy = bridge.getMailServiceProxy(); ``` -------------------------------- ### Create Promotion using Raw JSON Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/promotions/syscreatepromotion.md This example shows how to structure the request payload for creating a promotion using raw JSON. It includes all necessary fields for the promotion. ```json { "service": "promotions", "operation": "SYS_CREATE_PROMOTION", "data": { "promotionJson": { "name": "Independence Day Sale", "type": "SCHEDULED", "startAt": 1593781259911, "endAt": 1594126859911, "message": { "en": "Happy 4th of July!" }, "enabled": false, "segments": [], "prices": [ { "itemId": "coinbundle10", "priceId": 0 } ], "notifications": [ { "trigger" : "ACTIVATED", "notificationTemplateId" : 1 } ], "customJson": { "key": "value" } } } } ``` -------------------------------- ### SysCreateFolder JSON Response Example Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/groupfile/syscreatefolder.md This is an example JSON response after successfully creating a folder. It includes the groupId, details of the updated groupFileTree with the newly created folder, and the createdTreeId. ```json { "data": { "groupId": "2bf538d1-19ea-4e14-9862-f979215e09b7", "groupFileTree": { "treeVersion": 3, "tree": [ { "treeId": "59533e64-abc0-4f04-976b-8f395073ea2e", "children": [ { "treeId": "d9e937cc-750f-4414-962c-838f1af3f34a", "children": null, "name": "gpath", "acl": { "member": 2, "other": 0 }, "type": "Folder", "ownerId": null, "desc": "desc" } ], "name": "gpath", "acl": { "member": 2, "other": 0 }, "type": "Folder", "ownerId": null, "desc": "" }, { "treeId": "40479c72-b46b-4c05-902c-239ada116acd", "children": [ { "treeId": "fb3431cd-6e2f-47f1-8100-8941abf6bb4f", "children": null, "name": "gpathcopy", "acl": { "member": 2, "other": 0 }, "type": "Folder", "ownerId": null, "desc": "desc" } ], "name": "gpathcopy", "acl": { "member": 2, "other": 0 }, "type": "Folder", "ownerId": null, "desc": "" } ], "acl": { "member": 2, "other": 0 } }, "createdTreeId": "fb3431cd-6e2f-47f1-8100-8941abf6bb4f" }, "status": 200 } ``` -------------------------------- ### Get Updated Files in Cloud Code (CFScript) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/s3handling/getupdatedfiles.md Cloud Code example using CFScript to get updated S3 files. It utilizes a bridge to access the S3HandlingServiceProxy. ```cfscript var category = "Tuning"; var fileDetails = [ { "fileId": "hjvfsghguhuhrtghgh", "shortName": "short", "fileName": "fname", "relativeUrl": "http://", "absoluteUrl": "http://", "category": "Tuning", "date": 100000000000, "md5Hash": "njf8ehg8tr7htgheguhh" } ]; var s3HandlingProxy = bridge.getS3HandlingServiceProxy(); var postResult = s3HandlingProxy.getUpdatedFiles(category, fileDetails); if (postResult.status == 200) { // Success! } ``` -------------------------------- ### Get Recent Streams for Target Player (Cloud Code) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/playbackstream/getrecentstreamsfortargetplayer.md Cloud Code (CFScript) example to get recent playback streams for a target player using the bridge object. ```cfscript var targetPlayerId = "player"; var maxNumStreams = 5; var playbackStreamProxy = bridge.getPlaybackStreamServiceProxy(); var postResult = playbackStreamProxy.getRecentStreamsForTargetPlayer(targetPlayerId, maxNumStreams); if (postResult.status == 200) { // Success! } ``` -------------------------------- ### Join Lobby in C++ Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/lobby/joinlobby.md This C++ example demonstrates joining a lobby. It requires a vector of user IDs and boolean flags for readiness. ```cpp const char *lobbyId = "55555:4v4:3"; std::vector otherUserCxIds; otherUserCxIds.push_back("55555:aaa-bbb-ccc-ddd:asdfjkl"); bool isReady = false; const char *extraJson = "{}"; const char *teamCode = "blue"; <%= data.branding.codePrefix %>->getLobbyService()->joinLobby(lobbyId, otherUserCxIds, isReady, extraJson, teamCode, this); ``` -------------------------------- ### Start Purchase in C# Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/appstore/startpurchase.md Initiates a purchase transaction using the Steam store. Requires success and failure callbacks for handling the response. ```csharp string storeId = "steam"; string purchaseData = "{\"itemId\":\"3555\",\"language\":\"en\"}"; SuccessCallback successCallback = (response, cbObject) => { Debug.Log(string.Format("Success | {0}", response)); }; FailureCallback failureCallback = (status, code, error, cbObject) => { Debug.Log(string.Format("Failed | {0} {1} {2}", status, code, error)); }; <%= data.branding.codePrefix %>.AppStoreService.StartPurchase(storeId, purchaseData, successCallback, failureCallback); ``` -------------------------------- ### Get Entity Count with Hint (Cloud Code) Source: https://github.com/getbraincloud/braincloud-docs/blob/main/docs/api/2_capi/globalentity/getlistcountwithhint.md Cloud Code (CFScript) example for getting an entity count with 'where' and 'hintJson' filters. It uses a bridge to access the GlobalEntityServiceProxy. ```cfscript var where = { "data.team": "Red", "data.position": "Forward" }; var hintJson = { "data.team": 1, "data.position": 1 }; var globalEntityProxy = bridge.getGlobalentityServiceProxy(); var postResult = globalEntityProxy.GetListCountWithHint(where, hintJson); ```