### Install zmp-sdk Source: https://miniapp.zaloplatforms.com/documents/api Install the Zalo Mini App SDK using npm. This is the first step to integrate Zalo APIs into your project. ```bash npm install zmp-sdk ``` -------------------------------- ### setupAd Source: https://miniapp.zaloplatforms.com/documents/api/setupAd Initializes advertising configurations for the Mini App. This API needs to be called when the application starts. ```APIDOC ## setupAd() ### Description Configures the information used for running advertisements. This API should be called when initializing the application. ### Method Signature ```typescript setupAd(): void ``` ### Usage Import the function from `zmp-sdk/apis` and call it during your application's setup. ### Example ```typescript import { setupAd } from "zmp-sdk/apis"; // Call setupAd during application initialization setupAd(); ``` ### Notes - This feature is currently in a beta phase and is only available to specific partners. - Refer to the error handling guide for details on error codes. ``` -------------------------------- ### Get File Info with Async/Await Source: https://miniapp.zaloplatforms.com/documents/api/getFileInfo This snippet demonstrates how to get file information using async/await for cleaner asynchronous code. Make sure to import 'zmp-sdk/apis'. ```javascript import { LFSStorage } from 'zmp-sdk/apis'; const getFileInfo = async () => { try { const { size, digest, type } = await LFSStorage.getFileInfo({ filePath: "[Đường dẫn tới file]", digestAlgorithm: "md5", }); } catch (error) { // xử lý khi gọi api thất bại console.log(error); } }; ``` -------------------------------- ### OnStartCallback Source: https://miniapp.zaloplatforms.com/documents/api/CameraEvents Event that signals the start of streaming from the camera. ```APIDOC ## OnStartCallback ### Description This event is triggered when the camera streaming process begins. ### Method `camera.on(CameraEvents.OnStartCallback, callback)` ### Parameters This event does not provide any specific parameters to the callback. ### Request Example ```javascript import api, { CameraEvents } from "zmp-sdk"; const camera = api.createCameraContext({ videoElement }); camera.on(CameraEvents.OnStartCallback, () => { console.log("START STREAMING"); }); // ...camera.start ``` ``` -------------------------------- ### Choose Image from Camera (Front) Source: https://miniapp.zaloplatforms.com/documents/api/chooseImage This example demonstrates how to use the chooseImage API to capture an image using the front-facing camera. ```APIDOC ## chooseImage (Camera - Front) ### Description Allows users to capture an image using the front-facing camera. ### Method chooseImage ### Parameters #### Request Body - **sourceType** (("album" | "camera")[]) - Required - Source of the image selection. Must include "camera". - **cameraType** ("back" | "front") - Optional - Specifies the camera to use. Set to "front" for the front camera. ### Request Example ```javascript const { filePaths } = await chooseImage({ sourceType: ["camera"], cameraType: "front", }); ``` ### Response #### Success Response (Promise) - **filePaths** (string[]) - An array of paths to the selected image files. ### Response Example ```json { "filePaths": ["path/to/image.jpg"] } ``` ``` -------------------------------- ### Get File Info with Callback Source: https://miniapp.zaloplatforms.com/documents/api/getFileInfo Use this snippet to get file information using a callback function. Ensure the 'zmp-sdk/apis' is imported. ```javascript import { LFSStorage } from 'zmp-sdk/apis'; LFSStorage.getFileInfo({ filePath: "[Đường dẫn tới file]", digestAlgorithm: "md5", success: (data) => { // xử lý khi gọi api thành công const { size, digest, type } = data; }, fail: (error) => { // xử lý khi gọi api thất bại console.log(error); }, }); ``` -------------------------------- ### Choose Image from Camera (Back) Source: https://miniapp.zaloplatforms.com/documents/api/chooseImage This example shows how to use the chooseImage API to capture an image using the back-facing camera. ```APIDOC ## chooseImage (Camera - Back) ### Description Allows users to capture an image using the back-facing camera. ### Method chooseImage ### Parameters #### Request Body - **sourceType** (("album" | "camera")[]) - Required - Source of the image selection. Must include "camera". - **cameraType** ("back" | "front") - Optional - Specifies the camera to use. Set to "back" for the back camera. ### Request Example ```javascript const { filePaths } = await chooseImage({ sourceType: ["camera"], cameraType: "back", }); ``` ### Response #### Success Response (Promise) - **filePaths** (string[]) - An array of paths to the selected image files. ### Response Example ```json { "filePaths": ["path/to/image.jpg"] } ``` ``` -------------------------------- ### Choose Multiple Images from Album or Camera Source: https://miniapp.zaloplatforms.com/documents/api/chooseImage This example demonstrates how to select multiple images from either the photo album or by capturing new ones with the camera. ```APIDOC ## chooseImage (Multiple Images) ### Description Allows users to select multiple images from their photo album or capture new ones using the camera. ### Method chooseImage ### Parameters #### Request Body - **sourceType** (("album" | "camera")[]) - Required - Source of the image selection. Can include "album", "camera", or both. - **count** (number) - Optional - The maximum number of images that can be selected. ### Request Example ```javascript const { filePaths } = await chooseImage({ sourceType: ["album", "camera"], count: 5, }); ``` ### Response #### Success Response (Promise) - **filePaths** (string[]) - An array of paths to the selected image files. ### Response Example ```json { "filePaths": ["path/to/image1.jpg", "path/to/image2.jpg"] } ``` ``` -------------------------------- ### Display ZMA_Middle Ad Source: https://miniapp.zaloplatforms.com/documents/api/displayAd This example demonstrates how to set up, load, and display the ZMA_Middle ad. Ensure the ad ID is present in the HTML structure. ```javascript import React from "react"; import { createRoot } from "react-dom/client"; import { setupAd, loadAd, displayAd } from "zmp-sdk/apis"; function App() { useEffect(() => { displayAd({ id: "ZMA_Middle" }); }, []); return ( <> ...
... ); } setupAd(); loadAd({ ids: ["ZMA_Middle"], config: { display: false } }); const root = createRoot(document.getElementById("app")); root.render(React.createElement(App)); ``` -------------------------------- ### Get System Version Information Source: https://miniapp.zaloplatforms.com/documents/api/getSystemInfo Call getSystemInfo to retrieve version details such as the SDK version, API version, and Zalo app version. This API returns a Promise object. ```javascript const { version, apiVersion, zaloVersion } = getSystemInfo(); ``` -------------------------------- ### Example Server Response for Location Source: https://miniapp.zaloplatforms.com/documents/api/getLocation This is an example of the JSON response structure you might receive from your server after converting the location token into user location information. ```json { "data": { "provider": "gps", "latitude": "10.758341", "longitude": "106.745863", "timestamp": "1666249171003" }, "error": 0, "message": "Success" } ``` -------------------------------- ### Open Biometric Authentication with Async/Await Source: https://miniapp.zaloplatforms.com/documents/api/openBioAuthentication This example demonstrates how to use the openBioAuthentication API with async/await for a more modern asynchronous flow. It handles potential errors using a try-catch block. Ensure your app has the required permissions. ```javascript import { openBioAuthentication } from "zmp-sdk/apis"; const openBioAuthenUI = async () => { try { const data = await openBioAuthentication({ secretData: "", ui: { title: "Biometric login for my app", subTitle: "Log in using your biometric credential", negativeButtonText: "Cancel", }, }); } catch (error) { const { code } = error; } }; ``` -------------------------------- ### Detect Camera Streaming Start with OnStartCallback Source: https://miniapp.zaloplatforms.com/documents/api/CameraEvents This event is triggered when the camera streaming begins. It's useful for initiating actions or UI updates when the camera feed becomes active. Requires the camera to be started. ```javascript import api, { CameraEvents } from "zmp-sdk"; const camera = api.createCameraContext({ videoElement }); camera.on(CameraEvents.OnStartCallback, () => { console.log("START STREAMING"); }); //...camera.start ``` -------------------------------- ### Import setNavigationBarTitle API Source: https://miniapp.zaloplatforms.com/documents/api/setNavigationBarTitle Import the setNavigationBarTitle API from the zmp-sdk. This is a required setup step before using the API. ```javascript import { setNavigationBarTitle } from "zmp-sdk/apis"; ``` -------------------------------- ### Server Upload Success Response Source: https://miniapp.zaloplatforms.com/documents/api/openMediaPicker Example JSON response indicating a successful media upload to the server. ```json { "error": 0, "message": "Success", "data": { "urls": [...] } } ``` -------------------------------- ### Advertising APIs Source: https://miniapp.zaloplatforms.com/documents/api APIs for managing advertising within the mini app, including setup, loading, displaying, and refreshing ads. ```APIDOC ## Advertising APIs ### setupAd - **Description**: Configure information for running advertisements. ### loadAd - **Description**: API to load an advertisement. ### displayAd - **Description**: API to display an advertisement after it has been loaded. ### refreshAd - **Description**: API to remove the ad from the current session. ``` -------------------------------- ### Request Camera Permission Source: https://miniapp.zaloplatforms.com/documents/api/requestCameraPermission This snippet demonstrates how to use the requestCameraPermission API to ask the user for camera access. It includes examples for both callback-based and async/await usage. ```APIDOC ## requestCameraPermission ### Description Allows the application to request camera access from the device. Note that for iOS, permission is only granted the first time the Zalo app is installed. If the user does not grant permission on the first display or revokes it during use, subsequent calls will not display the permission prompt. The user must go to device settings to grant permission again. ### Parameters #### Object `object` | Property | Type | Default | Required | Description | Minimum Version | |---|---|---|---|---|---| | success | function | | | Callback function when the API call is successful | | | fail | function | | | Callback function when the API call fails | | ### Return Values #### Promise `` | Property | Type | Description | Minimum Version | |---|---|---|---| | userAllow | boolean | Indicates whether the user has granted permission: * `true`: user grants permission * `false`: user does not grant permission | | | message | string | Description of the status | | ``` -------------------------------- ### Get Product List from Cache with Error Handling Source: https://miniapp.zaloplatforms.com/documents/api/getItem Fetch a product list from the cache. It's crucial to wrap JSON parsing in a try-catch block to handle potential errors, such as invalid JSON format, which could otherwise crash the app. ```javascript try { const data: Product[] = JSON.parse(getItem("cache.productList")); } catch (error) { // Không tìm thấy dữ liệu trong cache, hoặc dữ liệu không phải chuỗi JSON hợp lệ } ``` -------------------------------- ### Handle Errors when Following Official Account Source: https://miniapp.zaloplatforms.com/documents/api/followOA Implement error handling for the followOA API call. This example specifically checks for the user's refusal to follow (-201 error code) and other potential errors. ```javascript try { \n await followOA({ \n id: "xxxx", \n }); \n console.log("Theo dõi thành công"); \n} catch (error) { \n const code = (error as AppError).code; \n if (code === -201) { \n console.log("Người dùng đã từ chối theo dõi"); \n } else { \n console.log("Lỗi khác"); \n } \n} ``` -------------------------------- ### Handle Real-time Camera Frames with OnFrameCallback Source: https://miniapp.zaloplatforms.com/documents/api/CameraEvents Use this event to receive camera frames in real-time. Ensure the camera is started before listening for frames. The callback provides frame data, width, and height. ```javascript import api, { CameraEvents, PhotoFrame } from "zmp-sdk"; const camera = api.createCameraContext({ videoElement }); camera.on(CameraEvents.OnFrameCallback, (data: PhotoFrame) => { const { data, width, height } = data; }); //...camera.start ``` -------------------------------- ### Get Storage Information Source: https://miniapp.zaloplatforms.com/documents/api/getNativeStorageInfo Call nativeStorage.getStorageInfo() to retrieve the current and limit sizes of the cache. This API is supported starting from SDK version 2.43.0. ```javascript const { currentSize, limitSize } = nativeStorage.getStorageInfo(); ``` -------------------------------- ### Server-side Token Conversion Source: https://miniapp.zaloplatforms.com/documents/api/getPhoneNumber This example demonstrates how your server can convert the received token into the user's phone number using Zalo Open API. Ensure you include the access_token, code (the token from the Mini App), and your app's secret_key. ```javascript { "data": { "number": "849123456789" }, "error": 0, "message": "Success" } ``` -------------------------------- ### getAccessToken Source: https://miniapp.zaloplatforms.com/documents/api/getAccessToken API used to get user authentication information. Starting from SDK version 2.35.0, apps can access access tokens by default without user confirmation. This token only allows exporting the user ID. For Name and Avatar, use the authorize API to request user permission for the userInfo scope. ```APIDOC ## getAccessToken ### Description API used to get user authentication information. Starting from SDK version 2.35.0, apps can access access tokens by default without user confirmation. This token only allows exporting the user ID. For Name and Avatar, use the authorize API to request user permission for the userInfo scope. ### Method Signature `getAccessToken()` ### Returns - `Promise`: A Promise that resolves with the access token string. ``` -------------------------------- ### Import setupAd API Source: https://miniapp.zaloplatforms.com/documents/api/setupAd Import the setupAd function from the zmp-sdk/apis module. ```typescript import { setupAd } from "zmp-sdk/apis"; ``` -------------------------------- ### Initialize Application with setupAd Source: https://miniapp.zaloplatforms.com/documents/api/setupAd Call setupAd() during application initialization in app.ts. This API configures advertising information and is required for ad functionality. ```typescript import React from "react"; import { createRoot } from "react-dom/client"; import { setupAd } from "zmp-sdk/apis"; import "zmp-ui/zaui.css"; import "./css/app.scss"; import App from "./components/app"; // Setup advertising setupAd(); const root = createRoot(document.getElementById("app")); root.render(React.createElement(App)); ``` -------------------------------- ### Create a shortcut with parameters Source: https://miniapp.zaloplatforms.com/documents/api/createShortcut Create a shortcut with custom parameters. The `params` object allows you to pass additional information, such as UTM sources, which will be appended when the Mini App is opened via the shortcut. Requires SDK version 2.16.3 or later. ```javascript await createShortcut({\n params: {\n utm_source: "shortcut", \n },\n}); ``` -------------------------------- ### getSetting Source: https://miniapp.zaloplatforms.com/documents/api/getSetting Retrieves the user's current setting information, including authorization status for various scopes. ```APIDOC ## getSetting ### Description API to retrieve the user's current setting information. ### Method `getSetting` ### Parameters This method does not take any parameters. ### Request Example ```javascript import { getSetting } from "zmp-sdk/apis"; const { authSetting } = await getSetting(); ``` ### Response #### Success Response (`Promise`) - **authSetting** (`AuthorizeType`) - Description: Information about authorization scopes. `true` indicates the user has granted permission for the corresponding API. #### Response Example ```json { "authSetting": { "scope.userInfo": true, "scope.userLocation": false, "scope.userPhonenumber": true, "scope.camera": false, "scope.micro": false } } ``` ### Scopes - **scope.userInfo**: Corresponds to `getUserInfo` API. Provides user information (name, avatar, etc.). - **scope.userLocation**: Corresponds to `getLocation` API. Provides user location information. - **scope.userPhonenumber**: Corresponds to `getPhoneNumber` API. Provides the user's phone number. - **scope.camera**: Corresponds to `createCameraContext` API. Access to the camera. - **scope.micro**: Corresponds to `createCameraContext` API. Access to the microphone. ``` -------------------------------- ### Get Product ID from Route Parameters Source: https://miniapp.zaloplatforms.com/documents/api/getRouteParams Call getRouteParams to retrieve all route parameters. Destructure the 'id' property to get the product ID, assuming it's passed in the URL. The API returns a Record. ```javascript const { id } = getRouteParams(); ``` -------------------------------- ### Import getSetting API Source: https://miniapp.zaloplatforms.com/documents/api/getSetting Import the getSetting API from the zmp-sdk. This is required before calling the API. ```javascript import { getSetting } from "zmp-sdk/apis"; ``` -------------------------------- ### hideKeyboard Source: https://miniapp.zaloplatforms.com/documents/api/hideKeyboard API to hide the virtual keyboard. Supported starting from SDK version 2.5.3. ```APIDOC ## hideKeyboard ### Description API to hide the virtual keyboard. ### Method Signature ```javascript import { hideKeyboard } from "zmp-sdk/apis"; hideKeyboard(); ``` ### Example ```javascript hideKeyboard(); ``` ### Version Support * SDK: 2.5.3+ ``` -------------------------------- ### showToast Source: https://miniapp.zaloplatforms.com/documents/api/showToast Displays a short toast message on the screen. Supported starting from SDK version 2.5.3. ```APIDOC ## showToast ### Description Displays a short toast message on the screen. ### Method Signature ```javascript showToast({ message: string }): Promise ``` ### Parameters #### Object Parameters - **message** (string) - Required - The content of the message to display. ### Request Example ```javascript showToast({ message: "Đặt hàng thành công!", }); ``` ### Response This API does not return a value upon success. ``` -------------------------------- ### Get Recent Search Keyword Source: https://miniapp.zaloplatforms.com/documents/api/getItem Retrieve a previously stored search keyword from the cache using its key. ```javascript const keyword = getItem("recentSearch"); ``` -------------------------------- ### Import configAppView API Source: https://miniapp.zaloplatforms.com/documents/api/configAppView Import the necessary function from the zmp-sdk/apis. ```javascript import { configAppView } from "zmp-sdk/apis"; ``` -------------------------------- ### Server Upload Failure Response Source: https://miniapp.zaloplatforms.com/documents/api/openMediaPicker Example JSON response indicating a failed media upload to the server. ```json { "error": -1, "message": "Fail" } ``` -------------------------------- ### Create a simple shortcut Source: https://miniapp.zaloplatforms.com/documents/api/createShortcut Use this snippet to create a basic shortcut on the user's home screen. No additional parameters are needed for a simple shortcut. ```javascript await createShortcut(); ``` -------------------------------- ### Remove ZMA_Middle Ad Source: https://miniapp.zaloplatforms.com/documents/api/refreshAd Call the refreshAd API with the ID of the ad to be removed. This example shows how to remove the ZMA_Middle ad. ```javascript refreshAd({ id: "ZMA_Middle" }); ``` -------------------------------- ### Open Media Picker for Photo with Compression Source: https://miniapp.zaloplatforms.com/documents/api/openMediaPicker Opens the media picker to select a photo with a compression level of 2. The result is a temporary local file path. ```javascript const { data } = await openMediaPicker({ type: "photo", compressLevel: 2, }); console.log(data); ``` -------------------------------- ### Import openMediaPicker API Source: https://miniapp.zaloplatforms.com/documents/api/openMediaPicker Import the openMediaPicker function from the zmp-sdk/apis module. ```javascript import { openMediaPicker } from "zmp-sdk/apis"; ``` -------------------------------- ### Open a Zalo Mini App with tracking parameters Source: https://miniapp.zaloplatforms.com/documents/api/openMiniApp Attach additional parameters, like utm_campaign, to the Mini App URL for tracking purposes. These parameters are available in the 'params' object. ```javascript openMiniApp({\n appId: "194839900003483517", \n params: { \n utm_campaign: "spring_promo", \n }, \n}); ``` -------------------------------- ### Clear Native Storage Cache Source: https://miniapp.zaloplatforms.com/documents/api/clear Clears all data from the native storage cache. Supported starting from SDK version 2.43.0. ```APIDOC ## nativeStorage.clear() ### Description Clears all data from the native storage cache. ### Method `nativeStorage.clear()` ### Parameters This method does not take any parameters. ### Request Example ```javascript nativeStorage.clear(); ``` ### Response This method does not return any specific value upon successful execution. Refer to the error handling guide for potential issues. ``` -------------------------------- ### Get Device ID with Async/Await Source: https://miniapp.zaloplatforms.com/documents/api/getDeviceIdAsync Use the getDeviceIdAsync function with await to retrieve the device ID. Ensure this is called within an async function. ```javascript const deviceId = await getDeviceIdAsync(); ``` -------------------------------- ### Fetch User Info and Orders with Async/Await Source: https://miniapp.zaloplatforms.com/documents/api/errorCode Use async/await for linear asynchronous logic. Ensure 'await' is called within an 'async' function. ```javascript const { userInfo } = await getUserInfo({ autoRequestPermission: true, }); const { orders } = await fetchOrders({ userId: userInfo.id, }); console.log("Các đơn hàng của người dùng: ", orders); ``` -------------------------------- ### createCameraContext Source: https://miniapp.zaloplatforms.com/documents/api/createCameraContext Initializes a camera context to access and control camera and microphone streams. It returns a ZMACamera object with various methods for stream management and interaction. ```APIDOC ## createCameraContext ### Description Initializes a camera context to access and control camera and microphone streams. It returns a ZMACamera object with various methods for stream management and interaction. ### Parameters #### Object `object` | Property | Type | Default | Required | Description | |--------------------|------------------|---------|----------|--------------------------------------------------| | videoElement | HTMLVideoElement | | true | The main video element to render the camera stream | | mediaConstraints | MediaConstraints | | | Initial streaming configuration | ### MediaConstraints Object | Property | Type | Default | Required | Description | |--------------|---------|---------|----------|--------------------------------------------------| | width | number | | | Video width | | height | number | | | Video height | | facingMode | FacingMode | | | Camera direction (FRONT or BACK) | | deviceId | string | | | Specific camera device ID to use | | video | boolean | | | Enable/disable video stream | | audio | boolean | | | Enable/disable microphone stream | | mirrored | boolean | | | Mirror mode for the image | ### FacingMode Enum - **FRONT**: Front camera - **BACK**: Back camera ### Return Values #### ZMACamera Object | Property | Type | Description | |--------------------|----------|--------------------------------------------------| | start | function | Start camera streaming | | stop | function | End camera streaming | | pause | function | Pause streaming | | resume | function | Resume streaming | | isUsing | function | Check streaming status | | updateMediaConstraints | function | Update streaming configuration | | takePhoto | function | Take a photo from the camera | | flip | function | Switch between front and back cameras | | setMirror | function | Enable/disable mirror mode for the image | | getCameraList | function | Get the list of active cameras on the device | | getSelectedDeviceId| function | Get the device ID of the active camera | | setDeviceId | function | Switch active camera using device ID | | on | function | Listen for CameraEvents events | | off | function | Stop listening for CameraEvents events | ``` -------------------------------- ### Get Context Information Source: https://miniapp.zaloplatforms.com/documents/api/getContextAsync Call getContextAsync to retrieve context and check if it's valid. The context includes an ID and type (USER_CHAT or GROUP_CHAT). ```javascript const contextInfo = await getContextAsync(); if (contextInfo) { // Ngữ cảnh hợp lệ const { id, type } = contextInfo; } ``` -------------------------------- ### Import downloadFile API Source: https://miniapp.zaloplatforms.com/documents/api/downloadFile Import the downloadFile API from the zmp-sdk/apis module. Ensure you have SDK version 2.44.0 or later. ```javascript import { downloadFile } from "zmp-sdk/apis"; ``` -------------------------------- ### Verify Reward Token Response Source: https://miniapp.zaloplatforms.com/documents/api/loadAd Example JSON response structure for verifying a reward token. The 'data.result' field indicates the success of the verification. ```json { "msg": "Success", "err": 0, "data": { "result": true } } ``` -------------------------------- ### Import displayAd API Source: https://miniapp.zaloplatforms.com/documents/api/displayAd Import the displayAd API from the zmp-sdk. This is the first step before using any ad-related functionalities. ```javascript import { displayAd } from "zmp-sdk/apis"; ``` -------------------------------- ### Import sendDataToPreviousMiniApp API Source: https://miniapp.zaloplatforms.com/documents/api/sendDataToPreviousMiniApp Import the necessary function from the zmp-sdk/apis. ```javascript import { sendDataToPreviousMiniApp } from "zmp-sdk/apis"; ``` -------------------------------- ### saveFile Source: https://miniapp.zaloplatforms.com/documents/api/saveFile Saves a file from a network path or temporary storage to the local data directory. This function is available starting from SDK version 2.51.0. ```APIDOC ## saveFile ### Description Saves a file from a network path or temporary storage to the local data directory. Supports downloading files in formats listed [here](link_to_supported_formats). This function is available starting from SDK version 2.51.0. ### Method `LFSStorage.saveFile(options)` ### Parameters #### Object `options` - **filePath** (string) - Required - The path to the file on the **network** or **temporary storage** (returned after calling the `openMediaPicker` API of the mini app). - **success** (function) - Optional - Callback function when the API call is successful. - **fail** (function) - Optional - Callback function when the API call fails. ### Return Values Returns a Promise that resolves with an object containing the saved file path. #### Promise `` - **savedPath** (string) - The path to the file saved locally. ### Sample Code ```javascript import { LFSStorage } from 'zmp-sdk/apis'; LFSStorage.saveFile({ filePath: "[Path to file]", success: (data) => { // Handle successful API call const { savedPath } = data; }, fail: (error) => { // Handle API call failure console.log(error); }, }); ``` // Or using async/await: ```javascript import { LFSStorage } from 'zmp-sdk/apis'; const saveFile = async () => { try { const { savedPath } = await LFSStorage.saveFile({ filePath: "[Path to file]", }); } catch (error) { // Handle API call failure console.log(error); } }; ``` ### Errors - **-300**: Your max 10MB of local storage data is reached. (Local storage is limited to 10MB. Delete unnecessary old files to save more. Refer to [Delete saved local files](link_to_delete_files).) - **-301**: Your device run out of storage. - **-302**: File cannot be found. Please check your param again. (Possible reasons: Path uses http (only https is supported), or the file does not exist.) - **-303**: Please wait... We're still downloading the file. - **-304**: No Internet connection. Please check your network settings. - **-305**: Download failed. Please check your network or file path again. ``` -------------------------------- ### Get Current Network Type Source: https://miniapp.zaloplatforms.com/documents/api/getNetworkType Call the getNetworkType API to retrieve the current network connection type. The result is destructured to access the networkType property. ```javascript const { networkType } = await getNetworkType(); ``` -------------------------------- ### Import showOAWidget API Source: https://miniapp.zaloplatforms.com/documents/api/showOAWidget Import the showOAWidget function from the zmp-sdk/apis module. This is required before using the API. ```javascript import { showOAWidget } from "zmp-sdk/apis"; ``` -------------------------------- ### Import getContextAsync Source: https://miniapp.zaloplatforms.com/documents/api/getContextAsync Import the getContextAsync API from the zmp-sdk. ```javascript import { getContextAsync } from "zmp-sdk/apis"; ``` -------------------------------- ### Import saveVideoToGallery API Source: https://miniapp.zaloplatforms.com/documents/api/saveVideoToGallery Import the necessary function from the zmp-sdk. Ensure you have the correct SDK version (2.44.0 or later). ```javascript import { saveVideoToGallery } from "zmp-sdk/apis"; ``` -------------------------------- ### Get Access Token Source: https://miniapp.zaloplatforms.com/documents/api/getAccessToken Call the getAccessToken API to retrieve the user's access token. This API returns a Promise that resolves with the access token string. ```javascript const accessToken = await getAccessToken(); ``` -------------------------------- ### Import openShareSheet API Source: https://miniapp.zaloplatforms.com/documents/api/openShareSheet Import the openShareSheet API from the zmp-sdk. ```javascript import { openShareSheet } from "zmp-sdk/apis"; ``` -------------------------------- ### Display OA QR Code Source: https://miniapp.zaloplatforms.com/documents/api/viewOAQr This example demonstrates how to use the viewOAQr API to display a QR code for a specific Official Account (OA) with its display name. ```APIDOC ## viewOAQr API ### Description This API allows the application to display the OA's QR code. ### Method Signature `viewOAQr({ id: string, displayName: string })` ### Parameters #### Parameters Object - **id** (string) - Required - The ID of the OA. - **displayName** (string) - Required - The display name for the QR code. ### Request Example ```javascript await viewOAQr({ id: "765465772305886642", displayName: "Galaxy Cinema", }); ``` ### Version Support - SDK: 2.5.3 and later ``` -------------------------------- ### Import followOA API Source: https://miniapp.zaloplatforms.com/documents/api/followOA Import the followOA API from the zmp-sdk/apis module. This is required before using the API. ```javascript import { followOA } from "zmp-sdk/apis"; ``` -------------------------------- ### Call requestUpdateZalo API Source: https://miniapp.zaloplatforms.com/documents/api/requestUpdateZalo Call the requestUpdateZalo API to prompt users to update their Zalo app. Refer to the error handling guide for details on error codes. ```javascript await requestUpdateZalo(); ``` -------------------------------- ### getSystemInfo Source: https://miniapp.zaloplatforms.com/documents/api/getSystemInfo Retrieves system and device information, including version numbers, language, platform, and theme. ```APIDOC ## getSystemInfo ### Description API to retrieve system and device information, including version numbers, language, platform, and theme. ### Method `getSystemInfo()` ### Parameters This method does not accept any parameters. ### Response Returns a `Promise` object containing system details. #### SystemInfo Object | Field | Type | Default | Description | Minimum Version | |---|---|---|---|---| | `apiVersion` | `string` | | The current ZMP SDK version. | | | `language` | `string` | | The device's display language. | | | `platform` | `"android" | "iOS" | "wp" | "unknown" | ""` | | Information about the device's operating system. | | | `version` | `string` | | The version of the current Zalo Mini App. | | | `zaloLanguage` | `string` | | The display language of the Zalo app on the device. | Zalo iOS: 22.03.01.r2, Zalo Android: 21.09.01, ZMP SDK: 2.17.3 | | `zaloTheme` | `string` | | The current theme of the Zalo app on the device. | Zalo iOS: 22.03.01.r2, Zalo Android: 21.09.01, ZMP SDK: 2.17.3 | | `zaloVersion` | `string` | | The version of the Zalo app on the device. | | ### Request Example ```javascript import { getSystemInfo } from "zmp-sdk/apis"; const { version, apiVersion, zaloVersion } = getSystemInfo(); ``` ### Response Example ```json { "apiVersion": "2.4.0", "language": "vi", "platform": "android", "version": "1.0.0", "zaloLanguage": "21.09.01", "zaloTheme": "dark", "zaloVersion": "21.09.01" } ``` ``` -------------------------------- ### Open Media Picker for Video Source: https://miniapp.zaloplatforms.com/documents/api/openMediaPicker Opens the media picker to select a video. The result is a temporary local file path. ```javascript const { data } = await openMediaPicker({ type: "video", }); console.log(data); ``` -------------------------------- ### Retrieve User ID Source: https://miniapp.zaloplatforms.com/documents/api/getUserID Call the getUserID API to get the unique identifier for the current user. The API returns a Promise that resolves to a string representing the user ID. ```javascript const userID = await getUserID({}); ``` -------------------------------- ### Get User Settings Source: https://miniapp.zaloplatforms.com/documents/api/getSetting Call the getSetting API to retrieve the user's current authorization settings. The response contains the authSetting object, which details the granted permissions. ```javascript const { authSetting } = await getSetting(); ``` -------------------------------- ### Import getUserInfo API Source: https://miniapp.zaloplatforms.com/documents/api/getUserInfo Import the getUserInfo API from the zmp-sdk. ```javascript import { getUserInfo } from "zmp-sdk/apis"; ``` -------------------------------- ### Import showFunctionButtonWidget API Source: https://miniapp.zaloplatforms.com/documents/api/showFunctionButtonWidget Import the showFunctionButtonWidget API from the zmp-sdk/apis module. ```javascript import { showFunctionButtonWidget } from "zmp-sdk/apis"; ``` -------------------------------- ### Add App to Favorites Source: https://miniapp.zaloplatforms.com/documents/api/favoriteApp This API adds the current application to the user's favorite list in the Zalo Mini Apps Store. It is supported starting from SDK version 2.27.1. ```APIDOC ## Add App to Favorites ### Description Adds the current application to the user's favorite list in the Zalo Mini Apps Store. ### Method ```javascript await favoriteApp(); ``` ### Parameters This method does not take any parameters. ### Request Example ```javascript await favoriteApp(); ``` ### Response This method does not return a value upon success. Error handling should be managed separately. Refer to the error handling guide and error code descriptions for details. ``` -------------------------------- ### Import setNavigationBarColor API Source: https://miniapp.zaloplatforms.com/documents/api/setNavigationBarColor Import the necessary function from the zmp-sdk/apis. ```javascript import { setNavigationBarColor } from "zmp-sdk/apis"; ``` -------------------------------- ### Get User's Location Token Source: https://miniapp.zaloplatforms.com/documents/api/getLocation Call the getLocation API to obtain a location token. This action will prompt the user for location permission. The token expires after 2 minutes and can only be used once. ```javascript const { token } = await getLocation(); ``` -------------------------------- ### openWebview Source: https://miniapp.zaloplatforms.com/documents/api/openWebview Loads a web page using a Webview. Listen for the WebviewClosed event to know when the Webview is dismissed. ```APIDOC ## openWebview ### Description Loads a web page using a Webview. Listen for the `WebviewClosed` event to know when the Webview is dismissed. ### Method Signature ```javascript openWebview({ url: string, config?: { style?: "bottomSheet" | "normal", leftButton?: "back" | "none" } }): void ``` ### Parameters #### url (string) - Required The URL of the web page to load. #### config (object) - Optional Configuration options for the Webview. ##### style (string) - Optional, Default: "bottomSheet" The display style of the Webview. Can be `"bottomSheet"` or `"normal"`. Minimum Version: 2.30.0 ##### leftButton (string) - Optional, Default: "back" The left button in the header. Only supported for `style: "bottomSheet"`. Can be `"back"` or `"none"`. Minimum Version: 2.30.0 ### Request Example Open the Zalo Mini App homepage: ```javascript openWebview({ url: "https://mini.zalo.me", }); ``` Open the Zalo Mini App homepage in full screen: ```javascript openWebview({ url: "https://mini.zalo.me", config: { style: "normal", }, }); ``` ``` -------------------------------- ### createShortcut Source: https://miniapp.zaloplatforms.com/documents/api/createShortcut This API allows your application to create a shortcut on the home screen. It supports creating a simple shortcut or one with additional parameters. ```APIDOC ## createShortcut ### Description Allows the application to create a shortcut on the home screen. ### Method Signature `createShortcut(options?: { params?: Record }): Promise` ### Parameters #### Optional Parameters - **params** (`Record`) - Optional - Parameters to be added to the Zalo Mini App when opened. Minimum Version: 2.16.3 ### Request Example #### Simple Shortcut ```javascript await createShortcut(); ``` #### Shortcut with Parameters ```javascript await createShortcut({ params: { utm_source: "shortcut", }, }); ``` ### Notes - Different parameters will create different shortcuts. - Refer to the documentation for error handling and detailed error codes. ``` -------------------------------- ### Load ZMA_Middle Ad Source: https://miniapp.zaloplatforms.com/documents/api/loadAd Example of loading a 'ZMA_Middle' ad using the loadAd API within a React component's useEffect hook. Ensure the corresponding HTML element exists. ```javascript import React, { useEffect } from "react"; import { loadAd } from "zmp-sdk/apis"; function HomePage() { useEffect(() => { loadAd({ ids: ["ZMA_Middle"] }); }, []); return ( <> ...
); } export default HomePage; ``` -------------------------------- ### showOAWidget Source: https://miniapp.zaloplatforms.com/documents/api/showOAWidget Displays an OA Widget that allows users to follow an OA directly. The OA information is retrieved from the authenticated Mini App. This feature is supported starting from SDK version 2.38.0. ```APIDOC ## showOAWidget ### Description Displays an OA Widget that allows users to follow an OA directly. The OA information is retrieved from the authenticated Mini App. This feature is supported starting from SDK version 2.38.0. ### Method showOAWidget ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **id** (string) - Required - The ID of the element where the widget should be displayed. - **guidingText** (string) - Optional - Text to guide the user. Defaults to "Nhận thông báo khuyến mãi mới nhất từ cửa hàng". - **color** (string) - Optional - The primary color of the widget. Must be a hex string. Defaults to "#0068FF". - **onStatusChange** (function) - Optional - A callback function that is called when the user follows the OA. It receives the new follow status (boolean) as an argument. ### Request Example ```javascript import { showOAWidget } from "zmp-sdk/apis"; showOAWidget({ id: "oaWidget", guidingText: "Nhận thông báo khuyến mãi mới nhất từ cửa hàng", color: "#0068FF", onStatusChange: (status) => { console.log(status); }, }); ``` ### Response #### Success Response (200) This method does not return a value directly, but triggers the `onStatusChange` callback with the follow status. ``` -------------------------------- ### Import getDeviceIdAsync Source: https://miniapp.zaloplatforms.com/documents/api/getDeviceIdAsync Import the getDeviceIdAsync function from the zmp-sdk/apis module. ```javascript import { getDeviceIdAsync } from "zmp-sdk/apis"; ``` -------------------------------- ### Import openProfile API Source: https://miniapp.zaloplatforms.com/documents/api/openProfile Import the `openProfile` function from the `zmp-sdk/apis` module. ```javascript import { openProfile } from "zmp-sdk/apis"; ``` -------------------------------- ### Get Live App Name and Version Source: https://miniapp.zaloplatforms.com/documents/api/getAppInfo Call the getAppInfo API to retrieve the current live name and version of the Zalo Mini App. Ensure error handling is implemented for production applications. ```javascript const { name, version } = await getAppInfo({}); ``` -------------------------------- ### Import getSystemInfo API Source: https://miniapp.zaloplatforms.com/documents/api/getSystemInfo Import the getSystemInfo function from the zmp-sdk/apis module. ```javascript import { getSystemInfo } from "zmp-sdk/apis"; ``` -------------------------------- ### Save Video to Gallery Example Source: https://miniapp.zaloplatforms.com/documents/api/saveVideoToGallery Save a video to the device's media gallery. The video URL must be provided. File size limits apply: 100MB for iOS, no limit for Android. ```javascript await saveVideoToGallery({ videoUrl: "https://test-videos.co.uk/vids/bigbuckbunny/mp4/h264/360/Big_Buck_Bunny_360_10s_1MB.mp4", }); console.log("Lưu video thành công!"); ``` -------------------------------- ### Import createShortcut API Source: https://miniapp.zaloplatforms.com/documents/api/createShortcut Import the createShortcut API from the zmp-sdk. This is required before using the API. ```javascript import { createShortcut } from "zmp-sdk/apis"; ``` -------------------------------- ### Open Zalo Mini App Homepage in Fullscreen Webview Source: https://miniapp.zaloplatforms.com/documents/api/openWebview Configure the webview to display in 'normal' style for a fullscreen experience. This option is available from SDK version 2.30.0. ```javascript openWebview({ url: "https://mini.zalo.me", config: { style: "normal", }, }); ``` -------------------------------- ### Get Saved File List with Promises Source: https://miniapp.zaloplatforms.com/documents/api/getSavedFileList This asynchronous method retrieves the list of saved files using Promises. It simplifies error handling with try-catch blocks. The resolved value contains the file list. ```javascript import { LFSStorage } from 'zmp-sdk/apis'; const getSavedFileList = async () => { try { const { list } = await LFSStorage.getSavedFileList({}); } catch (error) { // xử lý khi gọi api thất bại console.log(error); } }; ``` -------------------------------- ### Request Camera Permission with Callbacks Source: https://miniapp.zaloplatforms.com/documents/api/requestCameraPermission Use this method to request camera permission and handle the response using success and fail callbacks. Ensure the `zmp-sdk/apis` module is imported. ```javascript import { requestCameraPermission } from "zmp-sdk/apis"; requestCameraPermission({ success: ({ userAllow, message }) => { if (userAllow) { // được phép sử dụng camera } }, fail: (err) => { // xử lý khi gọi api thất bại console.log(err); } }); ``` -------------------------------- ### Get Saved File List with Callbacks Source: https://miniapp.zaloplatforms.com/documents/api/getSavedFileList Use this method to retrieve the list of saved files using a callback function. The success callback receives the file list, while the fail callback handles errors. ```javascript import { LFSStorage } from 'zmp-sdk/apis'; LFSStorage.getSavedFileList({ success: (data) => { // xử lý khi gọi api thành công const { list } = data; }, fail: (error) => { // xử lý khi gọi api thất bại console.log(error); }, }); ``` -------------------------------- ### Import chooseImage API Source: https://miniapp.zaloplatforms.com/documents/api/chooseImage Import the chooseImage API from the zmp-sdk. This is required before using the API. ```javascript import { chooseImage } from "zmp-sdk/apis"; ``` -------------------------------- ### Open Zalo Mini App Homepage in Webview Source: https://miniapp.zaloplatforms.com/documents/api/openWebview Use openWebview to load the Zalo Mini App homepage. Ensure the WebviewClosed event is handled to detect when the webview is closed. ```javascript openWebview({ url: "https://mini.zalo.me", }); ``` -------------------------------- ### Import favoriteApp API Source: https://miniapp.zaloplatforms.com/documents/api/favoriteApp Import the favoriteApp API from the zmp-sdk. This is required before using the API. ```javascript import { favoriteApp } from "zmp-sdk/apis"; ``` -------------------------------- ### sendDataToPreviousMiniApp Source: https://miniapp.zaloplatforms.com/documents/api/sendDataToPreviousMiniApp Sends data to the previously opened Zalo Mini App. The receiving Mini App needs to listen for the OnDataCallback event to get the data. If the API is called multiple times, the last data will be sent. ```APIDOC ## sendDataToPreviousMiniApp ### Description Sends data to the previously opened Zalo Mini App. The receiving Mini App needs to listen for the OnDataCallback event to get the data. If the API is called multiple times, the last data will be sent. ### Method ```javascript sendDataToPreviousMiniApp ``` ### Parameters #### Request Body - **data** (any) - Required - The data to be sent. ### Request Example ```json { "data": "Success" } ``` ``` -------------------------------- ### Import Native Storage API Source: https://miniapp.zaloplatforms.com/documents/api/clear Import the `nativeStorage` API from the zmp-sdk. This is required before you can use any of its methods. ```javascript import { nativeStorage } from "zmp-sdk/apis"; ``` -------------------------------- ### Get User Location Source: https://miniapp.zaloplatforms.com/documents/api/getLocation This API retrieves the user's current location. A permission request will be displayed when the API is called. The Mini App can only obtain location information if the user agrees to grant location sharing permission. ```APIDOC ## getLocation ### Description API to retrieve the user's current location. A permission request will be displayed when the API is called. The Mini App can only obtain location information if the user agrees to grant location sharing permission. ### Method ```javascript getLocation() ``` ### Parameters None ### Response #### Success Response (`Promise`) - **token** (`string`) - A string used to retrieve location information via the server. Each provided token can be used to retrieve information once and expires after 2 minutes. ### Request Example ```javascript const { token } = await getLocation(); ``` ### Response Example ```json { "token": "USER_LOCATION_TOKEN" } ``` ### Notes - Requires permission granted via the 'App Management' page. - The obtained token must be sent to your server to convert it into location information. - Refer to the Zalo Open API documentation for server-side conversion. ```