@dhana-cs/react-native-truecaller
v1.0.3
Published
React Native wrapper for Truecaller Android SDK with OAuth authentication support
Maintainers
Readme
@dhana-cs/react-native-truecaller
A React Native wrapper for the Truecaller Android SDK with OAuth authentication support. This package provides easy-to-use methods for integrating Truecaller authentication into your React Native applications.
Features
- ✅ Android Support: Full integration with Truecaller Android SDK
- ✅ OAuth Authentication: Complete OAuth 2.0 flow implementation
- ✅ TypeScript Support: Full TypeScript definitions included
- ✅ Easy Integration: Simple API for authentication flows
- ✅ Error Handling: Comprehensive error handling and logging
- ✅ Customizable UI: Support for custom button colors and text
- ✅ Locale Support: Multi-language support
Installation
1. Install the package
npm install @dhana-cs/react-native-truecaller
# or
yarn add @dhana-cs/react-native-truecaller2. Android Setup
Add Truecaller SDK dependency
The package automatically includes the Truecaller SDK dependency, but you need to configure your app.
Configure AndroidManifest.xml
Add the following to your android/app/src/main/AndroidManifest.xml:
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
<!-- Required permissions -->
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<!-- Truecaller SDK configuration -->
<uses-sdk tools:overrideLibrary="com.truecaller.android.sdk" />
<application>
<!-- Add your Truecaller Client ID -->
<meta-data
android:name="com.truecaller.android.sdk.ClientId"
android:value="YOUR_TRUECALLER_CLIENT_ID" />
</application>
</manifest>Get Truecaller Client ID
- Visit Truecaller Developer Portal
- Create a new app or use an existing one
- Get your Client ID from the dashboard
- Add it to your
AndroidManifest.xmlas shown above
Configure strings.xml
Add your Client ID to android/app/src/main/res/values/strings.xml:
<resources>
<string name="clientID">YOUR_TRUECALLER_CLIENT_ID</string>
</resources>3. iOS Setup
iOS is not supported by Truecaller SDK, but the package includes placeholder implementations that will throw appropriate errors.
4. Link the package
For React Native 0.60+, the package will be auto-linked. For older versions, you may need to manually link:
react-native link @dhana-cs/react-native-truecallerExpo Configuration
Option 1: Expo Development Build (Recommended)
Install the package:
npx expo install @dhana-cs/react-native-truecallerCreate a development build:
npx expo install expo-dev-client npx expo run:androidConfigure AndroidManifest.xml in your Expo project:
- Navigate to
android/app/src/main/AndroidManifest.xml - Add the Truecaller Client ID:
<application> <!-- Your existing meta-data --> <meta-data android:name="com.truecaller.android.sdk.ClientId" android:value="YOUR_TRUECALLER_CLIENT_ID" /> </application>- Navigate to
Add to strings.xml:
- Navigate to
android/app/src/main/res/values/strings.xml - Add your Client ID:
<resources> <string name="clientID">YOUR_TRUECALLER_CLIENT_ID</string> </resources>- Navigate to
Option 2: Built-in Expo Config Plugin (Recommended)
The package includes a built-in Expo config plugin that automatically configures the AndroidManifest.xml:
Update
app.config.js:export default { expo: { // ... other config plugins: [ // ... other plugins ["@dhana-cs/react-native-truecaller", { clientId: "YOUR_TRUECALLER_CLIENT_ID" }] ] } };Build with EAS:
eas build --platform android
The built-in config plugin will automatically:
- Add the Truecaller Client ID to AndroidManifest.xml
- Configure the necessary meta-data for the SDK
- Handle all Android configuration automatically
Important Notes for Expo
- Cannot use Expo Go: Truecaller SDK requires native modules, so you must use Development Build or EAS Build
- Test on Real Device: Truecaller SDK doesn't work well with emulators
- Install Truecaller App: Must be installed on the test device
- Development Build: Use
npx expo run:androidinstead ofexpo start
Usage
Basic Usage
import { trueCallerService } from '@dhana-cs/react-native-truecaller';
// Check if Truecaller is available
const isUsable = await trueCallerService.isUsable();
if (isUsable) {
// Initialize the SDK
await trueCallerService.initialize();
// Authenticate user
const result = await trueCallerService.authenticate(['profile', 'phone']);
console.log('Authorization Code:', result.authorizationCode);
console.log('Phone Number:', result.phoneNumber);
}Advanced Usage with Custom Configuration
import { trueCallerService } from '@dhana-cs/react-native-truecaller';
// Initialize with custom configuration
await trueCallerService.initialize({
buttonColor: '#FF6B35',
buttonTextColor: '#FFFFFF',
scopes: ['profile', 'phone']
});
// Authenticate
const authResult = await trueCallerService.authenticate();Using the Enhanced Auth Service
import { trueCallerAuthService } from '@dhana-cs/react-native-truecaller';
// Check availability
const isAvailable = await trueCallerAuthService.isAvailable();
if (isAvailable) {
// Perform complete authentication flow
const response = await trueCallerAuthService.authenticateAndLogin();
if (response.success) {
console.log('Authentication successful!');
console.log('Phone Number:', response.phoneNumber);
} else {
console.error('Authentication failed:', response.error);
}
}Direct Native Module Usage
import { TrueCallerSDK } from '@dhana-cs/react-native-truecaller';
// Initialize SDK
await TrueCallerSDK.initializeSdkWithDefaults();
// Setup OAuth
const oauthSetup = await TrueCallerSDK.setupCompleteOAuth(['profile', 'phone']);
// Request verification
const result = await TrueCallerSDK.requestVerification();API Reference
TrueCallerService
Methods
initialize(config?: TrueCallerConfig): Promise<boolean>- Initialize the SDKisTrueCallerInstalled(): Promise<boolean>- Check if Truecaller app is installedisUsable(): Promise<boolean>- Check if OAuth flow is usableauthenticate(scopes?: string[]): Promise<TrueCallerAuthResult>- Authenticate usersetLocale(locale: string): Promise<boolean>- Set localereset(): void- Reset initialization state
TrueCallerAuthService
Methods
isAvailable(): Promise<boolean>- Check if authentication is availableauthenticateAndLogin(): Promise<TrueCallerAuthResponse>- Complete authentication flow
TrueCallerSDK (Native Module)
Methods
initializeSdk(...): Promise<boolean>- Initialize with custom optionsinitializeSdkWithDefaults(): Promise<boolean>- Initialize with defaultssetupOAuthState(): Promise<{state: string}>- Setup OAuth statesetOAuthScopes(scopes: string[]): Promise<string[]>- Set OAuth scopessetupCodeChallenge(): Promise<{codeVerifier: string, codeChallenge: string}>- Setup PKCEsetupCompleteOAuth(scopes?: string[]): Promise<OAuthSetup>- Complete OAuth setupisUsable(): Promise<boolean>- Check if usablerequestVerification(): Promise<TrueCallerOAuthData>- Request verificationsetLocale(locale: string): Promise<boolean>- Set locale
Types
TrueCallerConfig
interface TrueCallerConfig {
scopes?: string[];
buttonColor?: string;
buttonTextColor?: string;
loginTextPrefix?: string;
ctaText?: string;
buttonShapeOptions?: string;
footerType?: string;
consentTitleOption?: string;
sdkOptions?: string;
}TrueCallerAuthResult
interface TrueCallerAuthResult {
authorizationCode: string;
state: string;
codeVerifier: string;
scopesGranted: string[];
}TrueCallerAuthResponse
interface TrueCallerAuthResponse {
success: boolean;
phoneNumber?: string;
verified?: boolean;
user?: any;
isNewUser?: boolean;
error?: string;
errorCode?: string;
}Error Handling
The package provides comprehensive error handling:
try {
const result = await trueCallerService.authenticate();
} catch (error) {
if (error.code === 'NOT_AVAILABLE') {
// Truecaller not installed or not available
} else if (error.code === 'INIT_ERROR') {
// SDK initialization failed
} else if (error.code === 'AUTH_ERROR') {
// Authentication failed
}
}Backend Integration
To complete the authentication flow, you need to implement backend endpoints:
1. Token Exchange Endpoint
Exchange the authorization code for user profile:
// POST /api/truecaller/token-exchange
{
"authorizationCode": "string",
"state": "string",
"codeVerifier": "string",
"scopesGranted": ["profile", "phone"]
}2. Authentication Endpoint
Authenticate the user with your backend:
// POST /api/truecaller/authenticate
{
"phoneNumber": "string",
"name": "string",
"email": "string",
"truecallerId": "string",
"verified": boolean
}Troubleshooting
Common Issues
"Truecaller not available"
- Ensure Truecaller app is installed
- Check if the app is up to date
- Verify Client ID configuration
"SDK initialization failed"
- Check AndroidManifest.xml configuration
- Verify Client ID is correct
- Ensure all required permissions are granted
"Authentication failed"
- Check network connectivity
- Verify OAuth scopes are correct
- Ensure backend endpoints are working
Debug Mode
Enable debug logging:
// The package includes comprehensive logging
// Check console for detailed error messagesContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Changelog
1.0.3
- Fixed config plugin dependency issue
- Moved @expo/config-plugins to dependencies
- Resolved "Unexpected token 'typeof'" error
1.0.2
- Added built-in Expo config plugin
- Automatic AndroidManifest.xml configuration
- Simplified Expo setup process
- Fixed config plugin validation errors
1.0.1
- Added Expo configuration support
- Added custom Expo config plugin for automated AndroidManifest.xml setup
- Updated documentation with Expo Development Build instructions
- Enhanced installation guide for Expo users
1.0.0
- Initial release
- Android SDK integration
- OAuth authentication support
- TypeScript definitions
- Comprehensive error handling
