{"id":37660246,"url":"https://github.com/frejun-tech/react-native-softphone-sdk","last_synced_at":"2026-01-20T16:51:40.361Z","repository":{"id":327004330,"uuid":"1090134426","full_name":"frejun-tech/react-native-softphone-sdk","owner":"frejun-tech","description":null,"archived":false,"fork":false,"pushed_at":"2025-12-11T12:02:43.000Z","size":2028,"stargazers_count":0,"open_issues_count":1,"forks_count":0,"subscribers_count":0,"default_branch":"main","last_synced_at":"2025-12-12T03:29:07.601Z","etag":null,"topics":[],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/frejun-tech.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":"CODE_OF_CONDUCT.md","threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null,"notice":null,"maintainers":null,"copyright":null,"agents":null,"dco":null,"cla":null}},"created_at":"2025-11-05T09:12:03.000Z","updated_at":"2025-12-11T12:02:48.000Z","dependencies_parsed_at":null,"dependency_job_id":null,"html_url":"https://github.com/frejun-tech/react-native-softphone-sdk","commit_stats":null,"previous_names":["frejun-tech/react-native-softphone-sdk"],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/frejun-tech/react-native-softphone-sdk","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/frejun-tech%2Freact-native-softphone-sdk","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/frejun-tech%2Freact-native-softphone-sdk/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/frejun-tech%2Freact-native-softphone-sdk/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/frejun-tech%2Freact-native-softphone-sdk/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/frejun-tech","download_url":"https://codeload.github.com/frejun-tech/react-native-softphone-sdk/tar.gz/refs/heads/main","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/frejun-tech%2Freact-native-softphone-sdk/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":28478376,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-01-16T06:30:42.265Z","status":"ssl_error","status_checked_at":"2026-01-16T06:30:16.248Z","response_time":107,"last_error":"SSL_read: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":[],"created_at":"2026-01-16T11:47:52.628Z","updated_at":"2026-01-16T11:47:52.683Z","avatar_url":"https://github.com/frejun-tech.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# React Native Softphone SDK\n\nA robust TypeScript SDK for integrating FreJun VoIP softphone capabilities into React Native applications.\n\n## 🌟 Features\n\n*   **VoIP Calling**: Built on `sip.js` and `react-native-webrtc` for high-quality audio calls.\n*   **Flexible Auth**: Support for **Standard Browser OAuth** and **Direct Code Exchange**.\n*   **Secure Auth**: OAuth2 flow with **Automatic Token Refresh** (handles 401 Unauthorized automatically).\n*   **Resilience**: Auto-reconnection logic when the app comes to the foreground.\n*   **Call Forking Support**: Intelligently handles duplicate SIP invites to prevent \"Ghost Hangups\".\n*   **Multiple Caller IDs**: Fetch and switch between available Virtual Numbers from the user profile.\n*   **Encrypted Storage**: Securely persists session tokens.\n\n---\n\n## 📦 Installation\n\n1.  **Install the SDK**:\n    ```bash\n    npm install react-native-softphone-sdk\n    # or\n    yarn add react-native-softphone-sdk\n    ```\n\n2.  **Install Peer Dependencies**:\n    You must install these native modules in your project:\n    ```bash\n    npm install react-native-webrtc react-native-encrypted-storage google-libphonenumber jwt-decode sip.js buffer events\n    ```\n\n3.  **iOS Installation**:\n    ```bash\n    cd ios \u0026\u0026 pod install \u0026\u0026 cd ..\n    ```\n\n---\n\n## ⚙️ Platform Configuration\n\n### Android Setup\n\n1.  **Permissions (`AndroidManifest.xml`)**:\n    Add the following permissions. Note the Bluetooth permissions required for Android 12+ (API 31).\n\n    ```xml\n    \u003cuses-permission android:name=\"android.permission.INTERNET\" /\u003e\n    \u003cuses-permission android:name=\"android.permission.RECORD_AUDIO\" /\u003e\n    \u003cuses-permission android:name=\"android.permission.MODIFY_AUDIO_SETTINGS\" /\u003e\n    \u003cuses-permission android:name=\"android.permission.ACCESS_NETWORK_STATE\" /\u003e\n    \u003cuses-permission android:name=\"android.permission.FOREGROUND_SERVICE\" /\u003e\n    \n    \u003c!-- Android 12+ Bluetooth Requirements --\u003e\n    \u003cuses-permission android:name=\"android.permission.BLUETOOTH_CONNECT\" /\u003e\n    ```\n\n2.  **Deep Linking (OAuth Redirect)**:\n    Required only if using **Standard Browser Login**. Add this intent filter inside your `\u003cactivity\u003e` tag.\n\n    ```xml\n    \u003cintent-filter\u003e\n        \u003caction android:name=\"android.intent.action.VIEW\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.DEFAULT\" /\u003e\n        \u003ccategory android:name=\"android.intent.category.BROWSABLE\" /\u003e\n        \u003c!-- Replace 'frejun' with your specific scheme --\u003e\n        \u003cdata android:scheme=\"frejun\" /\u003e \n    \u003c/intent-filter\u003e\n    ```\n\n### iOS Setup\n\n1.  **Info.plist**:\n    Add the Microphone usage description.\n    ```xml\n    \u003ckey\u003eNSMicrophoneUsageDescription\u003c/key\u003e\n    \u003cstring\u003eWe need access to your microphone to make VoIP calls.\u003c/string\u003e\n    ```\n\n2.  **Background Modes**:\n    Enable **\"Audio, AirPlay, and Picture in Picture\"** and **\"Voice over IP\"** in Xcode Project Capabilities.\n\n---\n\n## 🚀 Usage Guide\n\n### 1. Initialization\nInitialize the SDK once, preferably in your App's root component.\n\n```typescript\nimport { Softphone } from 'react-native-softphone-sdk';\n\nconst CREDENTIALS = {\n    clientId: 'YOUR_CLIENT_ID',\n    clientSecret: 'YOUR_CLIENT_SECRET',\n};\n\n// ... inside useEffect\nconst init = async () =\u003e {\n    // Restore session from storage\n    const restoredSoftphone = await Softphone.initialize(CREDENTIALS);\n    if (restoredSoftphone) {\n        setSoftphone(restoredSoftphone); \n    }\n};\ninit();\n```\n\n### 2. Authentication (Login)\n\nYou have two options for logging in users.\n\n#### Option A: Standard Browser Flow\nUse this if you want the SDK to open the system browser for FreJun login.\n\n```typescript\nimport { Linking } from 'react-native';\n\nconst handleLogin = async () =\u003e {\n    // 1. Opens Browser\n    await Softphone.login(); \n};\n\n// 2. Handle Redirect (Deep Link)\nuseEffect(() =\u003e {\n    const sub = Linking.addEventListener('url', async (event) =\u003e {\n        if (event.url.includes('?code=')) {\n            try {\n                // Exchange code for token\n                const softphoneInstance = await Softphone.handleRedirect(event.url);\n                setSoftphone(softphoneInstance);\n            } catch (e) {\n                console.error(\"Login failed\", e);\n            }\n        }\n    });\n    return () =\u003e sub.remove();\n}, []);\n```\n\n#### Option B: Direct Login (Custom Integration)\nUse this if you have already obtained an **Authorization Code** or tokens via your own API or WebView and want to initialize the SDK directly.\n\n```typescript\nconst handleDirectLogin = async () =\u003e {\n    try {\n        // Pass credentials (accessToken, email, refreshToken) directly\n        // Note: refreshToken is mandatory to ensure session continuity\n        const softphoneInstance = await Softphone.login({ \n            accessToken: \"YOUR_ACCESS_TOKEN\", \n            email: \"user@example.com\",\n            refreshToken: \"YOUR_REFRESH_TOKEN\",\n            // Optional: Provide these to enable auto-refresh if the accessToken is already expired\n            clientId: \"YOUR_CLIENT_ID\",\n            clientSecret: \"YOUR_CLIENT_SECRET\"\n        });\n\n        if (softphoneInstance) {\n            setSoftphone(softphoneInstance);\n            console.log(\"Logged in successfully!\");\n        }\n    } catch (e) {\n        console.error(\"Direct login failed\", e);\n    }\n};\n```\n\n### 3. Starting the Engine \u0026 Event Listeners\nYou must call `start()` to connect the WebSocket and register for events.\n\n```typescript\nuseEffect(() =\u003e {\n    if (!softphone) return;\n\n    const listeners = {\n        onConnectionStateChange: (type, state, isError) =\u003e {\n            console.log(`Status: ${state}`); // e.g., Registered, Connected, Disconnected\n        },\n\n        // ARGS: Type ('Incoming'/'Outgoing'), Session Object, Details\n        onCallCreated: (type, session, details) =\u003e {\n            console.log(`Call: ${type}, Candidate: ${details.candidate}`);\n            activeSession.current = session; // IMPORTANT: Store session ref\n            \n            if (type === 'Incoming') {\n                // Show incoming call UI\n            }\n        },\n\n        onCallAnswered: (session) =\u003e { /* Call is live */ },\n\n        onCallHangup: (session) =\u003e {\n            // IGNORE \"Ghost Hangups\" from call forking\n            if (activeSession.current \u0026\u0026 activeSession.current !== session) return;\n            activeSession.current = null;\n        },\n        \n        onSessionRefresh: (payload) =\u003e {\n            console.log(\"Session was refreshed automatically. New tokens:\", payload);\n            // Optionally, save these new tokens to your app's state management or storage\n        }\n    };\n\n    softphone.start(listeners).then(() =\u003e {\n        console.log(\"SDK started and ready to make calls!\");\n    });\n}, [softphone]);\n```\n\n### 4. Managing Calls\n\n```typescript\n// --- OUTGOING ---\n// Option 1: Use default caller ID from user profile\nawait softphone.makeCall('+919876543210');\n\n// Option 2: Use a specific Virtual Number (Caller ID)\nawait softphone.makeCall('+919876543210', '+918012345678');\n\n// --- INCOMING ---\n// Answer an incoming call\nawait activeSession.current.answer();\n\n// Hangup or Reject a call\nawait activeSession.current.hangup();\n```\n\n### 5. Using Virtual Numbers\nFetch the list of numbers assigned to the user to build a \"Select Caller ID\" UI.\n\n```typescript\nconst numbers = softphone.getVirtualNumbers();\n// Returns: [{ name: \"Office\", country_code: \"+91\", number: \"...\", default_calling_number: true }, ...]\n```\n\n### 6. Manual Reconnect\nIf the connection drops, you can provide a manual reconnection trigger.\n\n```typescript\ntry {\n    await softphone.connect();\n} catch (e) {\n    Alert.alert(\"Reconnection failed\", \"Please check your network connection.\");\n}\n```\n\n---\n\n## 📡 Handling Background/Killed State\n\nStandard WebSockets are terminated when an app is killed. To receive calls in this state, you must implement a native VoIP push notification solution.\n\n1.  **Background (App Minimized):** The SDK listens to `AppState` changes and automatically attempts to reconnect the socket when the app is brought to the foreground.\n2.  **Killed (App Closed):**\n    *   **Android:** Requires a solution using FCM Data Messages, `react-native-callkeep`, and a Foreground Service.\n    *   **iOS:** Requires APNs PushKit (VoIP Push) integrated with `react-native-callkeep` and Apple's `CallKit` framework.\n\n---\n\n## 📚 API Reference\n\n### `Softphone` Class\n\n| Method | Returns | Description |\n| :--- | :--- | :--- |\n| `static initialize(creds)` | `Promise\u003cSoftphone \\| null\u003e` | Configures SDK with credentials, restores a previous session from storage, and checks permissions. |\n| `static login(params?)` | `Promise\u003cSoftphone \\| void\u003e` | If params `{accessToken, email, refreshToken, clientId?, clientSecret?}` are provided, logs in directly. `refreshToken` is required. \u003cbr\u003e **Note:** `clientId` and `clientSecret` are only used to refresh the token if the provided `accessToken` is already expired. If no params are given, it initiates the standard browser OAuth flow. |\n| `static handleRedirect(url)` | `Promise\u003cSoftphone\u003e` | Exchanges the authorization code from a deep link URL for session tokens and completes the browser login flow. |\n| `start(listeners)` | `Promise\u003cvoid\u003e` | Connects the WebSocket, registers the SIP user agent, fetches the user profile, and attaches event listeners. Includes `onSessionRefresh` listener. |\n| `connect()` | `Promise\u003cvoid\u003e` | Manually attempts to reconnect the transport and re-register the SIP user agent. |\n| `makeCall(to, [from])` | `Promise\u003cboolean\u003e` | Initiates an outbound call. Updates the user's primary virtual number if `from` differs from the current default. |\n| `getVirtualNumbers()` | `VirtualNumber[]` | Returns an array of available caller IDs (virtual numbers) for the authenticated user. |\n| `getTokens()` | `TokenPayload \\| null` | Returns the current session tokens (`accessToken`, `refreshToken`, `email`). |\n| `logout()` | `Promise\u003cvoid\u003e` | Destroys the current session, unregisters the SIP user agent, and clears all credentials from secure storage. |\n\n### `Session` Class\n\n| Method | Description |\n| :--- | :--- |\n| `answer()` | Accepts an incoming call. |\n| `hangup()` | Ends the current call (can be used to cancel, reject, or terminate). |\n\n---\n\n## ⚠️ Troubleshooting\n\n**Q: `TypeError: answer is not a function`**\n*   **Fix:** Ensure your `onCallCreated` listener receives **3 arguments**: `(type, session, details)`. You are likely trying to call `.answer()` on the `details` object instead of the `session` object.\n\n**Q: Calls drop immediately with \"Ghost Hangup\"**\n*   **Fix:** This is caused by SIP Call Forking. To prevent this, your `onCallHangup` listener must check if the session being hung up is the currently active one: `if (activeSession.current !== session) return;`.\n\n**Q: 401 Unauthorized Errors**\n*   **Fix:** The SDK handles this automatically with its **Auto-Refresh** mechanism. It will detect the error, refresh the session tokens using the stored refresh token, and retry the failed request. No action is required from you.\n*   **Note**: If you need to be notified when tokens are refreshed (e.g., to update your own app's state or storage), use the `onSessionRefresh` event listener passed to the `start()` method.\n\n---\n\n**License:** MIT","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffrejun-tech%2Freact-native-softphone-sdk","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Ffrejun-tech%2Freact-native-softphone-sdk","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Ffrejun-tech%2Freact-native-softphone-sdk/lists"}