### Initiate Phone Authentication with OTPless Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Shows how to use the `initiate` method of the OTPless SDK to start the phone authentication process. This example is specifically for the 'Phone' channel. ```javascript initiate(CHANNEL.PHONE, { phone: mobileNumber, countryCode: countryCode, }); ``` -------------------------------- ### React Quick Start with OTPless Headless SDK Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Example of integrating OTPless authentication in a React application using the headless SDK. It demonstrates initializing the SDK, subscribing to events, sending OTP, and verifying OTP. ```jsx import React, { useEffect, useState } from 'react'; import { useOTPless, CHANNELS, EVENT_TYPES } from 'otpless-headless-js'; function ExampleOTPlessAuth() { const { init, initiate, verify, on, loading, ready } = useOTPless(); const [phone, setPhone] = useState('9876543210'); const [countryCode, setCountryCode] = useState('+91'); const [otp, setOtp] = useState(''); const [status, setStatus] = useState(''); useEffect(() => { // Always pass your actual OTPless App ID init('YOUR_APP_ID'); // Subscribe to single and multiple events const unsubAutoRead = on(EVENT_TYPES.OTP_AUTO_READ, (event) => { const autoOtp = event?.response?.otp ?? ''; setOtp(autoOtp); setStatus(`OTP auto-read: ${autoOtp}`); }); const unsubAll = on({ [EVENT_TYPES.ONETAP]: (event) => setStatus('OneTap Auth Success!'), [EVENT_TYPES.OTP_AUTO_READ]: (event) => { const autoOtp = event?.response?.otp ?? ''; setOtp(autoOtp); setStatus(`OTP auto-read: ${autoOtp}`); }, [EVENT_TYPES.FAILED]: (event) => setStatus(`Failed: ${event.response?.errorMessage}`), }); return () => { unsubAutoRead(); unsubAll(); }; }, [init, on]); const sendOtp = async () => { setStatus(''); if (!ready) { setStatus('SDK not ready yet.'); return; } try { const result = await initiate({ channel: CHANNELS.PHONE, phone, countryCode }); if (result.success) setStatus('OTP sent! Check your device.'); else setStatus(`Failed to send OTP: ${result.response?.errorMessage || 'Unknown error'}`); } catch (err) { setStatus(`Error sending OTP: ${err.message || err}`); } }; const verifyOtp = async () => { setStatus(''); if (!ready) { setStatus('SDK not ready yet.'); return; } try { const result = await verify({ channel: CHANNELS.PHONE, phone, countryCode, otp }); if (result.success) setStatus('OTP verified! Authenticated.'); else setStatus(`OTP verification failed: ${result.response?. केerrorMessage || 'Unknown error'}`); ``` -------------------------------- ### Instantiate React Component with Platform Source: https://otpless.com/docs/frontend-sdks/web-sdks/react/intro This example shows how to render the SampleGithubContainer component, specifying 'react' as the platform to get the appropriate SDK paths for React integration. ```javascript ``` -------------------------------- ### Initialize Podfile and Add Otpless Dependency Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Navigate to your iosApp directory, initialize the Podfile if it doesn't exist, and add the Otpless SDK dependency. Run 'pod install' to install the dependency. ```bash cd iosApp pod init ``` ```ruby # Pods for iosApp pod 'OtplessBM/Core', '1.1.3' ``` ```bash pod install ``` -------------------------------- ### Install OTPless Headless SDK Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Install the OTPless Headless SDK using npm, yarn, or pnpm. ```bash npm install otpless-headless-js # or yarn add otpless-headless-js # or pnpm add otpless-headless-js ``` -------------------------------- ### Start Email Authentication Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Initializes the Otpless SDK for email-based authentication. ```kotlin val otplessCMPRequest = OtplessCMPRequest( email = email ) start(otplessCMPRequest) ``` -------------------------------- ### Framework-Agnostic Usage Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Example of using the Otpless SDK directly without a framework. ```APIDOC ## ⚡️ Framework-Agnostic Usage You can use the SDK without React (in any framework): ```js import { otpless, CHANNELS, EVENT_TYPES } from 'otpless-headless-js'; // Initialize await otpless.init('YOUR_APP_ID'); // Send OTP await otpless.initiate({ channel: CHANNELS.PHONE, phone: '9876543210', countryCode: '+91', }); ``` ``` -------------------------------- ### Handle OTPless Response Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Example of processing the response from an initiate request. ```js const res: OTPlessResponse = await initiate({ channel: CHANNELS.PHONE, phone: '9876543210', countryCode: '+91', }); if (res.success) { console.log('requestId:', res.response?.requestID); } else { console.error('initiate failed:', res.response?.errorMessage); } ``` -------------------------------- ### Install jose library Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Command to install the jose library for JWT verification in Node.js. ```bash npm i jose ``` -------------------------------- ### Start OAuth Authentication Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Initializes the Otpless SDK for OAuth using a specified third-party channel. Ensure the channel name is provided in uppercase. ```kotlin val otplessCMPRequest = OtplessCMPRequest( oAuthChannel = "CHANNEL_NAME" ) // Make sure that the CHANNEL_NAME is in uppercase start(otplessCMPRequest) ``` -------------------------------- ### Example Usage of Otpless SDK Source: https://otpless.com/docs/frontend-sdks/app-sdks/android/new/headless/intro This snippet demonstrates a basic usage pattern for the Otpless SDK, likely for handling callbacks or responses. ```javascript return null; })); ``` ``` -------------------------------- ### Start Phone Authentication Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Initializes the Otpless SDK for phone-based authentication using a phone number and country code. ```kotlin val otplessCMPRequest = OtplessCMPRequest( phoneNumber = phoneNumber, countryCode = countryCode ) start(otplessCMPRequest) ``` -------------------------------- ### Session Response Examples Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/references/sessions Examples of the JSON response object returned by the session verification method. ```json { "success": true, "sessionId": "91d30c1b70e14527b6e889d8da1cdd19", "sessionToken": "eyJraWQiOiJwazAxODMiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI5MWQzMGMxYjcwZTE0NTI3YjZlODg5ZDhkYTFjZGQxOSIsImlzcyI6Imh0dHBzOi8vb3RwbGVzcy5jb20iLCJuYW1lIjoiTWloaXQgVGhha2thciIsInNlc3Npb25JZCI6IjkxZDMwYzFiNzBlMTQ1MjdiNmU4ODlkOGRhMWNkZDE5IiwiZXhwIjoxNzMzNDc0OTI4LCJpYXQiOjE3MzMzODg1MjgsInVzZXJJZCI6Ik1PLWZmMGUzYjk4NGIzMzQ5MGZhNTI2NjYyYWJhMzVlNjM4IiwiZW1haWwiOiJtaWhpdC50aGFra2FyQG90cGxlc3MuY29tIn0.pdeLlOyAta6wyuXnphKOadKGsgsaUPXDxPmLDRY8llaadIx-hoVjyVjGb7k2hzIIfDlIuN4PdQIr9lPDEWCkf0iIdKzymOUa1vSEi80ky2w6B3hmraVW9NxJpi4tJdhZ0GHJTQPjinTrPLCxSEu-n6pNvgcP2A4e47NZ9tawulkQyCDAeX8cx6PKt6g7LwWW9MU4olqnOoaeBJmsKXYZjvpmEVEifImhL_PCsTkbz4aVAN6YJP-fkY1-f4rHRAqqA7bbjDQF5jdiklFdce7tKQ-vNIVVQlFwaf4bORjkYaFsSfA8LoY20fzjOfpBC0TxrRdnyH6_HHO8nL1jQTxrOQ", "refreshToken": "eyJraWQiOiJwazAxODMiLCJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJzdWIiOiI5MWQzMGMxYjcwZTE0NTI3YjZlODg5ZDhkYTFjZGQxOSIsImlzcyI6Imh0dHBzOi8vb3RwbGVzcy5jb20iLCJuYW1lIjoiTWloaXQgVGhha2thciIsInNlc3Npb25JZCI6IjkxZDMwYzFiNzBlMTQ1MjdiNmU4ODlkOGRhMWNkZDE5IiwiZXhwIjoxNzMzOTkzMzI4LCJpYXQiOjE3MzMzODg1MjgsInVzZXJJZCI6Ik1PLWZmMGUzYjk4NGIzMzQ5MGZhNTI2NjYyYWJhMzVlNjM4IiwiZW1haWwiOiJtaWhpdC50aGFra2FyQG90cGxlc3MuY29tIn0.lltKW9PFPdQVQLie3aMsnYbHTSA0AvoYgBX3TkO1OqArc2huijqEF7M4mjAz1fU5pWO8mO0hwNeL-kSdTSCMrkTU2cz5CdRcJLIWb8SYH11rvaxOJ7-p9nK2H2cDR42kGtnCOeG0D8J5OTbetiT4VByYHOLWN5HOXNdRp2bR84Ze04oM0o2WnWKs1-FSL8vDVjvKMdsdJ50D6wQbWpToeTP-KjOhzbUhtl0HTyjV597lMqt6uJHd9ddWKuE1EwLykqVUNXP-VxJHgHdLAA2RKc9Vt-vY8n87H2zn8Gjs-EsWkeLog-m3ybZE-hyuKUe_VPkduaZrqRqeRdWa-D__uA" } ``` ```json {success: false} ``` -------------------------------- ### SDK Ready Response Object Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro This object indicates that the Otpless SDK has successfully initialized and is ready for use. It signifies a successful setup. ```json { "responseType": "SDK_READY", "statusCode": 200, "response": { "success": true } } ``` -------------------------------- ### iOS Pod Install Command Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Run this command in your project's root directory to install the necessary OTPless iOS SDK dependencies via CocoaPods. ```bash pod install ``` -------------------------------- ### Install OTPLESS SDK Dependency Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/references/secure-sdk-ionic Install the OTPLESS SDK dependency using npm. This command should be run at the root of your React Native project. ```bash npm install otpless-ionic ``` -------------------------------- ### Initiate Authentication Requests Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Use the initiate method to start authentication flows for different channels. Ensure the required parameters for each channel are provided. ```javascript const phoneAuth = () => { OTPlessSignin.initiate({ channel: "PHONE", phone: "839899038845", countryCode: "+62", }); }; ``` ```javascript const emailAuth = () => { OTPlessSignin.initiate({ channel: "EMAIL", email: "user@example.com" }); }; ``` ```javascript const oauth = (provider) => { OTPlessSignin.initiate({ channel: "OAUTH", channelType: provider }); }; ``` -------------------------------- ### Initiate Email OTP Request Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/otp Use the headless manager to start an OTP request by providing the user's email address. ```javascript let headlessRequest = {}; headlessRequest = { email } await manager.startHeadless(headlessRequest); ``` ```javascript let headlessRequest = {}; let email = "satyam@otpless.com" headlessRequest = { email } await manager.startHeadless(headlessRequest); ``` -------------------------------- ### Headless Social Auth Response Example Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/oauth An example of the JSON response received after a successful headless social authentication initiation. It confirms the channel and type used, along with a unique request identifier. ```json { "statusCode": 200, "success": true, "response": { "channel": "OAuth", "channelType": "WHATSAPP", "requestId": "xxxxxxxxxxxxxxxx" } } ``` -------------------------------- ### Initialize OtplessSDK in Java (using wrapper) Source: https://otpless.com/docs/frontend-sdks/app-sdks/android/new/headless/intro Calling Kotlin suspend functions from Java requires a wrapper object. This example shows how to initialize the OtplessSDK from Java using such a wrapper. ```java // Calling Kotlin `suspend` functions from Java is a bit tricky. // Create a Kotlin `object` wrapper that calls the suspend APIs internally and exposes // Java-friendly methods (e.g., returning `CompletableFuture`). Then call these from Java. // // Example: // /** object OtplessManager { fun initOtpless(appId: String, activity: Activity, callback: (OtplessResponse) -> Unit): CompletableFuture = GlobalScope.future { OtplessSDK.initialize(appId, activity, callback = callback) } fun startOtpless(otplessRequest: OtplessRequest, callback: (OtplessResponse) -> Unit): CompletableFuture = GlobalScope.future { OtplessSDK.start(otplessRequest, callback) } } */ OtplessManager.INSTANCE.initOtpless(APP_ID, this, (response) -> { onOtplessResponse(response); return null; }).whenComplete((unit, error) -> { // logs }); ``` -------------------------------- ### Verify JWT with Go jwx and golang-jwt Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Install dependencies and implement token parsing with JWKS key lookup and claim validation. ```bash go get github.com/golang-jwt/jwt/v5 github.com/lestrrat-go/jwx/v2/jwk ``` ```go import ( "context" "errors" "time" "github.com/golang-jwt/jwt/v5" "github.com/lestrrat-go/jwx/v2/jwk" ) const ( jwksURL = "https://otpless.com/.well-known/jwks" issuer = "https://otpless.com" audience = "PXXXXG1XXXX1NXXYAO" ) func fetchKeySet() (jwk.Set, error) { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() return jwk.Fetch(ctx, jwksURL) } func verifyOtplessIDToken(tokenStr string) (*jwt.RegisteredClaims, error) { set, err := fetchKeySet() if err != nil { return nil, err } keyFunc := func(token *jwt.Token) (interface{}, error) { if token.Method.Alg() != jwt.SigningMethodRS256.Alg() { return nil, errors.New("unexpected signing method") } kid, ok := token.Header["kid"].(string) if !ok { return nil, errors.New("no kid in token header") } key, found := set.LookupKeyID(kid) if !found { return nil, errors.New("kid not found in JWKS") } var pubKey interface{} err := key.Raw(&pubKey) return pubKey, err } claims := &jwt.RegisteredClaims{} token, err := jwt.ParseWithClaims( tokenStr, claims, keyFunc, jwt.WithAudience(audience), jwt.WithIssuer(issuer), jwt.WithLeeway(60*time.Second), jwt.WithRequiredClaim("exp"), // require 'exp' claim ) if err != nil { return nil, err } if !token.Valid { return nil, errors.New("invalid token") } return claims, nil } ``` -------------------------------- ### Verify JWT with Python Authlib Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Install required packages and use authlib to fetch JWKS and validate token claims. ```bash pip install authlib httpx ``` ```py import time, httpx from authlib.jose import jwt, JsonWebKey JWKS_URL = "https://otpless.com/.well-known/jwks" ISSUER = "https://otpless.com" AUDIENCE = "PXXXXG1XXXX1NXXYAO" async def fetch_jwks(): async with httpx.AsyncClient(timeout=5) as client: return (await client.get(JWKS_URL)).json() async def verify_otpless_id_token(token: str, leeway: int = 60): jwks = await fetch_jwks() header = jwt.get_unverified_header(token) kid = header.get("kid") jwk = next((k for k in jwks["keys"] if k["kid"] == kid), None) if not jwk: raise ValueError("Signing key not found") key = JsonWebKey.import_key(jwk) claims = jwt.decode(token, key, claims_options={ "iss": {"essential": True, "values": [ISSUER]}, "aud": {"essential": True, "values": [AUDIENCE]}, "exp": {"essential": True}, }, leeway=leeway) claims.validate() return claims ``` -------------------------------- ### Configure and Start Otpless Request Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Configure Otpless request parameters like channel type, delivery channel, OTP expiry, and length. Use this when an OTP is provided to initiate the Otpless flow. ```kotlin otplessRequest.setWithObjcChannelType(otplessCMPRequest.oAuthChannel ?: "NONE") } if (!otplessCMPRequest.deliveryChannel.isNullOrBlank()) { otplessRequest.setWithDeliveryChannelForTransaction(otplessCMPRequest.deliveryChannel) } if (!otplessCMPRequest.otpExpiry.isNullOrBlank()) { otplessRequest.setWithOtpExpiry(otplessCMPRequest.otpExpiry) } if (!otplessCMPRequest.otpLength.isNullOrBlank()) { otplessRequest.setWithOtpLength(otplessCMPRequest.otpLength) } val otp = otplessCMPRequest.otp if (!otp.isNullOrBlank()) { otplessRequest.setWithOtp(otp) job = CoroutineScope(Dispatchers.IO).launch { Otpless.shared().startWithRequest(otplessRequest = otplessRequest) { // Leave blank because response will be received in response delegate } } } else { job?.cancel() job = CoroutineScope(Dispatchers.IO).launch { Otpless.shared().startWithRequest(otplessRequest = otplessRequest) { // Leave blank because response will be received in response delegate } } } ``` -------------------------------- ### Custom UI for OTPless Authentication Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless An example HTML structure for creating a custom user interface for OTPless authentication, including input fields for mobile number and OTP, and buttons for initiating phone authentication, verifying OTP, and using OAuth providers like WhatsApp and Gmail. ```html
``` -------------------------------- ### Initiate Headless Social Auth Request Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/oauth Use this to start the headless social authentication flow. Ensure the channelType is in uppercase. Requires the manager object to be initialized. ```javascript let headlessRequest = { channelType: channelType.toUpperCase() }; await manager.startHeadless(headlessRequest); ``` ```javascript let headlessRequest = { channelType: "WHATSAPP" }; await manager.startHeadless(headlessRequest); ``` -------------------------------- ### Utility Functions for OTPless SDK Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Provides examples of using utility functions from the 'otpless-headless-js' library, including normalizing country codes, extracting only digits from a string, and redacting sensitive tokens for secure logging. ```javascript import { normalizeCountryCode, digitsOnly, redactTokens } from 'otpless-headless-js'; normalizeCountryCode('91'); // '+91' normalizeCountryCode('+1-234'); // '+1234' digitsOnly('98-765-43210'); // '9876543210' const safeData = redactTokens({ phone: '9876543210', otp: '123456', token: 'secret' }); // { phone: '9876543210', otp: '***redacted***', token: '***redacted***' } ``` -------------------------------- ### Initialize SDK and Callback Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/secure Define a callback function and initialize the OTPlessSecure instance. ```javascript ``` -------------------------------- ### Initialize OTPLESS Instance Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/pre-built-ui Create the manager instance and configure the app ID. ```js let manager = new OtplessManager(); let extras = { method: "get", params: { appId: "{{YOUR_APP_ID}}", }, }; ``` -------------------------------- ### Initialize SDK and Handle Callback Source: https://otpless.com/docs/frontend-sdks/web-sdks/react/headless Initialize the OTPLESS SDK with a callback function to manage authentication responses. This callback handles different event types like ONETAP, OTP_AUTO_READ, FAILED, and FALLBACK_TRIGGERED. ```javascript const callback = (eventCallback) => { // console.log({eventCallback}); const ONETAP = () => { const { response } = eventCallback; const token = response.token; // Implement your custom logic here. console.log({ response, token: response.token }); }; const OTP_AUTO_READ = () => { const { response: { otp } } = eventCallback; // Auto-read OTP value //console.log(otp); } const FAILED = () => { const { response } = eventCallback; console.log({ response }) } const FALLBACK_TRIGGERED = () => { const { response } = eventCallback; console.log({ response }) } const EVENTS_MAP = { ONETAP, OTP_AUTO_READ, FAILED, FALLBACK_TRIGGERED } if ("responseType" in eventCallback) EVENTS_MAP[eventCallback.responseType]() } // Initialize OTPLESS SDK with the defined callback. const OTPlessSignin = new OTPless(callback); ``` -------------------------------- ### Load OTPLESS SDK Source: https://otpless.com/docs/frontend-sdks/web-sdks/react/pre-built-ui Insert this script into the head section of your HTML to initialize the OTPLESS SDK. ```javascript <-- OTPLESS SDK --> ``` -------------------------------- ### JWT Header Structure Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Example of the header section of an OTPless ID token. ```json { "kid": "pk0183", "typ": "JWT", "alg": "RS256" } ``` -------------------------------- ### SDK_READY Response Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Indicates that the SDK has been successfully initialized and is ready for use. ```APIDOC ## SDK_READY Response Object ### Description This response object signifies a successful SDK initialization. ### Response Example ```json { "responseType": "SDK_READY", "statusCode": 200, "response": { "success": true } } ``` ``` -------------------------------- ### Email Verification - Start OTP Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/otp Initiates an OTP for email verification. Requires the email address. ```APIDOC ## POST /api/start-verification (Email) ### Description Initiates an OTP for email verification. Requires the email address. ### Method POST ### Endpoint /api/start-verification ### Parameters #### Request Body - **email** (string) - Required - The email address to verify. ### Request Example ```json { "email": "satyam@otpless.com" } ``` ### Response #### Success Response (200) - **statusCode** (integer) - The status code of the response. - **success** (boolean) - Indicates if the request was successful. - **response** (object) - Contains details about the verification process. - **channel** (string) - The verification channel used (e.g., "EMAIL"). - **deliveryChannel** (string) - The method of delivery for the OTP (e.g., "EMAIL"). - **authType** (string) - The authentication type (e.g., "OTP"). - **requestId** (string) - A unique identifier for the verification request. #### Response Example ```json { "statusCode": 200, "success": true, "response": { "channel": "EMAIL", "deliveryChannel": "EMAIL", "authType": "OTP", "requestId": "xxxxxxxxxxxxxxxx" } } ``` ``` -------------------------------- ### JWT Payload Structure Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Example of the payload section of an OTPless ID token containing user claims. ```json { "sub": "MO-1xx13cc0bf5341xxxxx6da2xxx43xxx", "aud": "PXXXXG1XXXX1NXXYAO", "country_code": "+91", "auth_time": "1758641886", "iss": "https://otpless.com", "national_phone_number": "9999999999", "phone_number_verified": true, "phone_number": "919999999999", "exp": 1758622386, "iat": 1758622086, "token": "xxxx4e11xxx95f1xxxxxa5xxxc38xxd54" } ``` -------------------------------- ### GET /.well-known/jwks Source: https://otpless.com/docs/api-reference/endpoint/verifytoken/id-token-validate Retrieves the public keys required to verify the RS256 signature of the JWT ID token. ```APIDOC ## GET /.well-known/jwks ### Description Fetch the OTPless public keys used for verifying RS256 signatures. You must select the key where the `kid` matches the JWT header. ### Method GET ### Endpoint https://otpless.com/.well-known/jwks ``` -------------------------------- ### Initialize OtplessSDK in Kotlin Source: https://otpless.com/docs/frontend-sdks/app-sdks/android/new/headless/intro Initialize the OtplessSDK in your LoginActivity's onCreate() function or LoginFragment's onViewCreated() function. Replace APP_ID with your actual App ID. ```kotlin lifecycleScope.launch(Dispatchers.IO) { OtplessSDK.initialize(APP_ID, this@LoginActivity, callback = this@LoginActivity::onOtplessResponse) } ``` -------------------------------- ### Import OtplessSDK in LoginActivity.kt Source: https://otpless.com/docs/frontend-sdks/app-sdks/android/new/headless/intro Import the OtplessSDK class in your LoginActivity.kt file to use its functionalities. ```java import com.otpless.v2.android.sdk.main.OtplessSDK; ``` -------------------------------- ### Phone Verification - Start OTP Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/otp Initiates an OTP for phone number verification. Requires country code and phone number. ```APIDOC ## POST /api/start-verification (Phone) ### Description Initiates an OTP for phone number verification. Requires country code and phone number. ### Method POST ### Endpoint /api/start-verification ### Parameters #### Request Body - **countryCode** (string) - Required - The country code for the phone number (e.g., "+91"). - **phone** (string) - Required - The phone number to verify. ### Request Example ```json { "countryCode": "+91", "phone": "9899038845" } ``` ### Response #### Success Response (200) - **statusCode** (integer) - The status code of the response. - **success** (boolean) - Indicates if the request was successful. - **response** (object) - Contains details about the verification process. - **channel** (string) - The verification channel used (e.g., "PHONE"). - **deliveryChannel** (string) - The method of delivery for the OTP (e.g., "WHATSAPP", "SMS"). - **authType** (string) - The authentication type (e.g., "OTP"). - **requestId** (string) - A unique identifier for the verification request. #### Response Example ```json { "statusCode": 200, "success": true, "response": { "channel": "PHONE", "deliveryChannel": "WHATSAPP", "authType": "OTP", "requestId": "xxxxxxxxxxxxxxxx" } } ``` ``` -------------------------------- ### Configure Gradle Dependencies Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Configuration snippets for adding OTPLESS SDK and serialization dependencies to Gradle build files. ```toml kotlinCocoapods = { id = "org.jetbrains.kotlin.native.cocoapods", version.ref = "kotlin" } ``` ```kotlin plugins { alias(libs.plugins.kotlinCocoapods) apply false } ``` ```kotlin plugins { alias(libs.plugins.kotlinCocoapods) kotlin("plugin.serialization") version "2.1.10" } ``` ```kotlin kotlin { sourceSets { androidMain.dependencies { implementation("io.github.otpless-tech:otpless-headless-sdk:0.6.5") } commonMain.dependencies { implementation("org.jetbrains.kotlinx:kotlinx-serialization-json:1.6.0") } } // Cocoapods configuration: This will create a cocoapod for your iOS app. // So, set the description that you would want in your Podspec file. cocoapods { homepage = "Your homepage name" summary = "Your cocoapods summary" version = "1.0" ios.deploymentTarget = "15.3" podfile = project.file("../iosApp/Podfile") framework { baseName = "composeApp" isStatic = true } // Add the Otpless SDK dependency to the iOS framework pod("OtplessBM/Core") { version = "1.1.3" extraOpts += listOf("-compiler-option", "-fmodules") } } } ``` -------------------------------- ### Include OTPLESS SDK Script Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/pre-built-ui Add this script to the head section of your HTML to initialize the OTPLESS SDK. ```html ``` -------------------------------- ### Initialize Otpless Headless SDK Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/intro Initialize the Otpless SDK in your login screen. Ensure APPID is replaced with your actual application ID. The `useEffect` hook manages the initialization and cleanup of the listener. ```javascript import {OtplessManager} from 'otpless-ionic'; let manager = new OtplessManager(); useEffect(() => { manager.initHeadless(APPID); manager.setHeadlessCallback(onHeadlessResult); return () => { manager.clearListener() } }, []); ``` -------------------------------- ### Step 3: Get Auth Token Callback Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/otp After OTP verification, a callback is received with the ONETAP response containing the authentication token. ```APIDOC ## Get Auth Token Callback ### Description This is a sample callback JSON received after successful OTP verification, containing the authentication token and user details. ### Response Example ```json { "responseType": "ONETAP", "statusCode": 200, "response": { "status": "SUCCESS", "token": "unique_token_here", "userId": "unique_user_id_here", "timestamp": "ISO_timestamp_here", "identities": [ { "identityType": "MOBILE", "identityValue": "919899038845", "channel": "OTP", "methods": [ "SMS" ], "verified": true, "verifiedAt": "2024-08-05T13:57:56Z" } ], "idToken": "jwt_token", "network": { "ip": "127.0.0.1", "timezone": "Asia/Kolkata", "ipLocation": {} }, "deviceInfo":{}, "sessionInfo":{}, "firebaseInfo":{} } } ``` ``` -------------------------------- ### Initialize Headless Request Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/otp Prepare the headless request object with user details for OTP initiation. This is used before calling the manager.startHeadless function. ```javascript let headlessRequest = {}; headlessRequest = { email, otp } ``` ```javascript let headlessRequest = {}; let email = "satyam@otpless.com" let otp = "123456" headlessRequest = { email, otp } await manager.startHeadless(headlessRequest); ``` -------------------------------- ### Initiate OTPLESS Login Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/pre-built-ui Trigger the login page and handle the authentication response. ```js manager.showFabButton(false); const data = await manager.showOtplessLoginPage(extras); let message: string = ""; if (data.data === null || data.data === undefined) { message = data.errorMessage; } else { message = "token: ${data.data.token}"; // todo here } ``` -------------------------------- ### Initialize Otpless SDK in DisposableEffect Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Use this block within your LoginScreen to initialize the SDK. The DisposableEffect ensures resources are cleaned up when the screen is destroyed. ```kotlin DisposableEffect(key1 = Unit) { // Use key1 as Unit so that the SDK is not re-initialized on recomposition initializeOtpless( appId = "YOUR_APPID", onOtplessResponse = { otplessResponseString -> response = otplessResponseString + "\n\n" + response handleOtplessResponse(otplessResponseString, onOTPAutoRead = { otp = it }) }, loginUri = null ) onDispose { cleanup() } } ``` -------------------------------- ### Start Email Magic Link Verification Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/magiclink Initiate a Magic Link for email verification by providing the email address. This is used for headless verification flows. ```javascript let headlessRequest = {}; headlessRequest = { email, }; await manager.startHeadless(headlessRequest); ``` ```javascript let email = "satyam@otpless.com"; let headlessRequest = {}; headlessRequest = { email, }; await manager.startHeadless(headlessRequest); ``` -------------------------------- ### OTPlessSignin.initiate Source: https://otpless.com/docs/frontend-sdks/web-sdks/react/headless Initiates the authentication process based on the selected channel (PHONE, EMAIL, or OAUTH). ```APIDOC ## SDK Method: initiate ### Description Initiates the authentication process based on the user's selected method. ### Request Body - **channel** (string) - Required - The authentication method selected by the user. - **phone** (string) - Conditional - User's phone number (required if channel is PHONE). - **countryCode** (string) - Conditional - Country code of the phone number (required if channel is PHONE). - **email** (string) - Conditional - User's email (required if channel is EMAIL). - **channelType** (string) - Conditional - Type of social login initiated (required if channel is OAUTH). ### Response - **statusCode** (number) - Outcome of the request. 2xx for success, 4xx and 5xx for failures. - **success** (boolean) - Boolean flag indicating request success. - **response** (object) - Detailed response JSON containing the response details. ``` -------------------------------- ### Select OTPLESS SDK Paths by Platform (JavaScript) Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/intro Use this component to dynamically determine the correct SDK integration paths for pre-built UI or headless implementations based on the target platform. It handles various web and mobile platforms. ```javascript export const SampleGithubContainer = ({platform}) => { let preBuilt = ""; let headless = ""; switch (platform.toLowerCase()) { case "android": preBuilt = "/frontend-sdks/app-sdks/android/loginpage"; headless = "/frontend-sdks/app-sdks/android/new/headless"; break; case "ios": preBuilt = "/frontend-sdks/app-sdks/ios/pre-built-ui"; headless = "/frontend-sdks/app-sdks/ios/new/headless"; break; case "react-native": preBuilt = "/frontend-sdks/app-sdks/react-native/pre-built-ui"; headless = "/frontend-sdks/app-sdks/react-native/new/headless"; break; case "flutter": preBuilt = "/frontend-sdks/app-sdks/flutter/pre-built-ui"; headless = "/frontend-sdks/app-sdks/flutter/new/headless"; break; case "flutter-web": preBuilt = "/frontend-sdks/web-sdks/flutter-web/pre-built-ui"; headless = "/frontend-sdks/web-sdks/flutter-web/headless"; break; case "ionic": preBuilt = "/frontend-sdks/app-sdks/ionic/pre-built-ui"; headless = "/frontend-sdks/app-sdks/ionic/headless"; break; case "javascript": preBuilt = "/frontend-sdks/web-sdks/javascript/pre-built-ui"; headless = "/frontend-sdks/web-sdks/javascript/headless"; break; case "vue": preBuilt = "/frontend-sdks/web-sdks/vue/pre-built-ui"; headless = "/frontend-sdks/web-sdks/vue/headless"; break; case "angular": preBuilt = "/frontend-sdks/web-sdks/angular/pre-built-ui"; headless = "/frontend-sdks/web-sdks/angular/headless"; break; case "react": preBuilt = "/frontend-sdks/web-sdks/react/pre-built-ui"; headless = "/frontend-sdks/web-sdks/react/headless"; break; default: githubLink = ""; } return {!["flutter-web"].includes(platform) && Use this SDK to quickly integrate a fully managed UI, customizable through the OTPLESS dashboard, enabling seamless authentication without writing any code. } Utilize our Headless SDK for ultimate flexibility. Craft your own tailored UI and seamlessly integrate OTPLESS authentication capabilities using our SDK. ; }; ``` -------------------------------- ### Email Magic Link Verification Response Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/magiclink Example response structure for a successful email Magic Link verification request. It includes details about the channel, delivery method, and request ID. ```json { "statusCode": 200, "success": true, "response": { "channel": "EMAIL", "deliveryChannel": "EMAIL", "authType": "MAGICLINK", "requestId": "xxxxxxxxxxxxxxxx" } } ``` ```json { "type": "object", "properties": { "statusCode": { "type": "integer" }, "success": { "type": "boolean" }, "response": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["PHONE", "EMAIL"] }, "deliveryChannel": { "type": "string", "enum": ["WHATSAPP", "SMS", "VIBER", "VOICE", "EMAIL"] }, "authType": { "type": "string", "enum": ["MAGICLINK"] }, "requestId": { "type": "string" } }, "required": ["channel", "deliveryChannel", "authType", "requestId"] } }, "required": ["statusCode", "success", "response"] } ``` -------------------------------- ### Verify OTP and Listen to Events with OTPless SDK Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Demonstrates how to verify an OTP using the OTPless SDK and how to subscribe to specific events like OTP auto-read or general authentication success and failure. ```javascript await otpless.verify({ channel: CHANNELS.PHONE, phone: '9876543210', countryCode: '+91', otp: '123456', }); const unsub = otpless.on(EVENT_TYPES.OTP_AUTO_READ, event => { console.log('OTP auto-read:', event.response?.otp); }); const unsubAll = otpless.on({ [EVENT_TYPES.ONETAP]: event => console.log('Auth Success:', event), [EVENT_TYPES.FAILED]: event => console.error('Failed:', event.response?.errorMessage), }); ``` -------------------------------- ### Phone Magic Link Verification Response Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/magiclink Example response structure for a successful phone Magic Link verification request. It includes details about the channel, delivery method, and request ID. ```json { "statusCode": 200, "success": true, "response": { "channel": "PHONE", "deliveryChannel": "WHATSAPP", "authType": "MAGICLINK", "requestId": "xxxxxxxxxxxxxxxx" } } ``` ```json { "type": "object", "properties": { "statusCode": { "type": "integer" }, "success": { "type": "boolean" }, "response": { "type": "object", "properties": { "channel": { "type": "string", "enum": ["PHONE", "EMAIL"] }, "deliveryChannel": { "type": "string", "enum": ["WHATSAPP", "SMS", "VIBER", "VOICE", "EMAIL"] }, "authType": { "type": "string", "enum": ["MAGICLINK"] }, "requestId": { "type": "string" } }, "required": ["channel", "deliveryChannel", "authType", "requestId"] } }, "required": ["statusCode", "success", "response"] } ``` -------------------------------- ### Define Otpless Expect Functions in commonMain Source: https://otpless.com/docs/frontend-sdks/app-sdks/cmp/headless/intro Declare expect functions in your commonMain source set for Otpless initialization, starting the authentication flow, and cleanup. These functions will be implemented in platform-specific modules. ```kotlin expect fun initializeOtpless(appId: String, onOtplessResponse: (String) -> Unit, loginUri: String?) expect fun start(otplessCMPRequest: OtplessCMPRequest) expect fun cleanup() ``` ```kotlin data class OtplessCMPRequest( val phoneNumber: String? = null, val countryCode: String? = null, val email: String? = null, val otp: String? = null, val otpExpiry: String? = null, val otpLength: String? = null, val deliveryChannel: String? = null, val oAuthChannel: String? = null ) ``` -------------------------------- ### Framework-Agnostic SDK Initialization Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Initialize and use the SDK outside of a React environment. ```js import { otpless, CHANNELS, EVENT_TYPES } from 'otpless-headless-js'; // Initialize await otpless.init('YOUR_APP_ID'); // Send OTP await otpless.initiate({ channel: CHANNELS.PHONE, phone: '9876543210', countryCode: '+91', ``` -------------------------------- ### Start Phone Magic Link Verification Source: https://otpless.com/docs/frontend-sdks/app-sdks/ionic/headless/magiclink Initiate a Magic Link for phone number verification by providing the country code and phone number. This method is used for headless verification flows. ```javascript let headlessRequest = {}; headlessRequest = { countryCode, phone } await manager.startHeadless(headlessRequest); ``` ```javascript let countryCode = "+91"; let phone = "9899038845"; let headlessRequest = {}; headlessRequest = { countryCode, phone } await manager.startHeadless(headlessRequest); ``` -------------------------------- ### POST /initiate Source: https://otpless.com/docs/frontend-sdks/web-sdks/javascript/headless Initiates the authentication process based on the selected channel (PHONE, EMAIL, or OAUTH). ```APIDOC ## POST /initiate ### Description Initiates the authentication flow for a user via phone, email, or social provider. ### Parameters #### Request Body - **channel** (string) - Required - The authentication method (PHONE, EMAIL, OAUTH). - **phone** (string) - Conditional - User's phone number (required if channel is PHONE). - **countryCode** (string) - Conditional - Country code (required if channel is PHONE). - **email** (string) - Conditional - User's email (required if channel is EMAIL). - **channelType** (string) - Conditional - Social login provider (required if channel is OAUTH). ### Response #### Success Response (2xx) - **statusCode** (number) - Outcome of the request. - **success** (boolean) - Indicates request success. - **response** (object) - Detailed response data. ```