### Install from NPM
Source: https://developer.net2phone.com/dialer/sdk
Install the net2phone dialer SDK using NPM.
```bash
$ npm install @net2phone/dialer-sdk
```
--------------------------------
### Usage Example
Source: https://developer.net2phone.com/dialer/sdk
Example demonstrating how to create a dialer instance, place a call, subscribe to events, and dispose of the dialer.
```javascript
// Create a dialer instance during the page load.
const net2PhoneDialer = new Net2PhoneDialer({
// Pass the options as the object to the constructor function
rootHtmlElement: document.getElementById('net2phone-dialer')
});
// Invoke methods on the dialer instance.
// Methods are typically asynchronous and return JavaScript promises.
net2PhoneDialer
.placeCall({ to: 'PHONE_NUMBER_HERE' })
.catch(console.error);
// Subscribe to events
function onNet2PhoneDialerEvent(event) {
console.log(event);
}
const subscription = net2PhoneDialer.subscribe(onNet2PhoneDialerEvent);
// Unsubscribe when your app is not interested in the events anymore.
subscription.dispose();
// Dispose the dialer to remove.
// This will remove it from the DOM and inbound calls won't be received anymore.
net2PhoneDialer.dispose();
```
--------------------------------
### Error Handling Example
Source: https://developer.net2phone.com/dialer/sdk
Example demonstrating how to catch and handle specific dialer errors.
```javascript
const {
Net2PhoneDialerError,
InvalidPhoneNumberError
} = Net2phoneDialer.errors;
try {
await net2phoneDialer.placeCall({ to: 'invalid_input' });
} catch (e) {
if (e instanceof InvalidPhoneNumberError) {
console.log(
'The phone call was not dispatched. The phone number was invalid.',
e.message);
}
if (e instanceof Net2PhoneDialerError) {
console.log('Some other known error from the dialer.', e.message)
}
console.error('Unknown error.', e);
}
```
--------------------------------
### Initialize the library
Source: https://developer.net2phone.com/dialer/sdk
Import and initialize the library after installation.
```javascript
import Net2PhoneDialer from "@net2phone/dialer-sdk";
const net2PhoneDialer = new Net2PhoneDialer({
rootHtmlElement: document.getElementById('net2phone-dialer')
});
```
--------------------------------
### Example API Request with API Key
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
Demonstrates how to authenticate an API request using an API key by including it in the X-API-Key header.
```bash
curl -X GET "https://api.n2p.io/v2/users/@me" \
-H "X-API-Key: {YOUR_API_KEY}"
```
--------------------------------
### Obtain Access Token
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
HTTP POST request to the token endpoint to get an access token using the authorization code.
```curl
curl -X "POST" "https://auth.net2phone.com/connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=authorization_code
&client_id={YOUR_CLIENT_ID}
&client_secret={YOUR_CLIENT_SECRET}
&code=EAA140C603616C8FE72819536348A52AA01B3DBF7FEB052AB25CE42402C83E16
&redirect_uri=https://www.example.com/callback
&code_verifier={GENERATED_CODE_VERIFIER}"
```
--------------------------------
### Load from CDN - ES Modules
Source: https://developer.net2phone.com/dialer/sdk
Load the SDK from a CDN using ES Modules.
```html
```
--------------------------------
### Load from CDN - Universal Module Definition
Source: https://developer.net2phone.com/dialer/sdk
Load the SDK from a CDN using Universal Module Definition.
```html
```
--------------------------------
### Create Dialer Constructor Options
Source: https://developer.net2phone.com/dialer/sdk
TypeScript interface defining the options for the Net2PhoneDialer constructor.
```typescript
interface Net2PhoneDialerConstructorOptions {
rootHtmlElement: HTMLElement;
}
interface Net2PhoneDialer {
// The constructor requires an options object to be passed
(options: Net2PhoneDialerConstructorOptions): Net2PhoneDialer;
}
```
--------------------------------
### Place Call Command Interface
Source: https://developer.net2phone.com/dialer/sdk
Defines the structure for initiating a call, including the recipient's phone number. It also shows the Net2PhoneDialer interface with the placeCall method and related error classes.
```typescript
interface PlaceCallCommand {
// The phone number to call to.
to: string;
}
interface Net2PhoneDialer {
placeCall(placeCallCommand: PlaceCallCommand): Promise
}
// This error will be returned in case of invalid phone number.
class InvalidPhoneNumberError extends Net2PhoneDialerError {}
// This error will be returned in case of already ringing outgoing call.
class OutgoingCallAlreadyRingingError extends Net2PhoneDialerError {}
// This error will be returned in case of denied microphone permission.
class MicrophonePermissionError extends Net2PhoneDialerError {}
// This error will be returned in case of not authenticated user.
class AuthenticationError extends Net2PhoneDialerError {}
```
--------------------------------
### Event Subscription and Subscribe Method
Source: https://developer.net2phone.com/dialer/sdk
Illustrates the EventSubscription interface for managing subscriptions and the subscribe method on Net2PhoneDialer to receive call state change events.
```typescript
interface EventSubscription {
// Unsubscribe (callback related to this subscription will not be invoked anymore).
dispose(): void
}
interface Net2PhoneDialer {
// This can be called multiple times to have more than one subscription.
subscribe(callback: (event: CallStateChanged) => void): EventSubscription;
}
```
--------------------------------
### Callback Parameters
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
A table detailing the query parameters returned in the redirect URI after the user has been authorized.
```table
Parameter| Type| Description
---|---|---
code| string| The authorization code to use to get `access_token`.
state| string| The same value the client set in the request. This will be present only if the client supplied it in the request.
The client is expected to check that the state in the redirect matches the state it originally set. This protects against CSRF and other related attacks.
```
--------------------------------
### Dispose Dialer Interface
Source: https://developer.net2phone.com/dialer/sdk
Shows the Net2PhoneDialer interface with the dispose method, used to clean up the dialer instance and its event subscriptions.
```typescript
interface Net2PhoneDialer {
dispose(): void
}
```
--------------------------------
### Exchange Refresh Token for Access Token
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
This cURL command demonstrates how to exchange a refresh token for a new access token using the token endpoint.
```curl
curl -X "POST" "https://auth.net2phone.com/connect/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=refresh_token
&client_id={YOUR_CLIENT_ID}
&refresh_token=AEC4F36E513545D7F4DFF750ECEF0C3823986FBEE225F53CEE186AB3D15941D8
&client_secret={YOUR_CLIENT_SECRET}"
```
--------------------------------
### Authorization Endpoint URL
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
This is the URL to which the client application redirects the user to initiate the authorization process. It includes parameters like client ID, redirect URI, scope, and PKCE-related fields.
```url
https://auth.net2phone.com/connect/authorize?response_type=code
&client_id={YOUR_CLIENT_ID}
&redirect_uri=https://www.example.com/callback
&scope=public_api.v2
&code_challenge={GENERATED_CODE_CHALLENGE}
&code_challenge_method=S256
&state=icpNL0m3rPX1hmp5hQ8sNVnr
```
--------------------------------
### Redirect with Authorization Code URL
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
This is the URL to which the authorization server redirects the user back after successful authentication, containing the authorization code and the state parameter.
```url
https://www.example.com/callback?code=EAA140C603616C8FE72819536348A52AA01B3DBF7FEB052AB25CE42402C83E16&state=icpNL0m3rPX1hmp5hQ8sNVnr
```
--------------------------------
### Authorization Endpoint Parameters
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
A table detailing the parameters used in the authorization request to the net2phone authorization server.
```table
Parameter| Type| Required| Description
---|---|---|---
response_type| string| Yes| Use `code` as the value. This indicates the client expects to receive an authorization `code`.
redirect_uri| string| Yes| Indicates the URL to return the user to after authorization is complete. Remember this should be one of the redirect URIs mentioned during the client registration.
client_id| string| Yes| This is the ID you received after registering your client using the registration form.
scope| string| Yes| Use `public_api.v2` to get access to all **V2** endpoints.
Use `public_api.v1` if you want to access **V1** endpoints.
Use `offline_access` if you want `refresh_token` while obtaining the `access_token`.
Multiple scopes should be separated by a space.
If you are requesting `public_api.v1` scope, the `offline_access` scope is also required due to V1 API implementation details.
state| string| No| A random string generated by your client, the same value will be passed back as a query string with key `state` to the `redirect_uri`.
You can use this to verify once the user is redirected back to `redirect_uri`.
This is generally used to prevent CSRF attacks.
code_challenge| string| Yes| The code challenge generated as previously described above.
code_challenge_method| string| Yes| Use **S256** as the value.
```
--------------------------------
### Call State Changed Event and Interfaces
Source: https://developer.net2phone.com/dialer/sdk
Defines the structure of the CallStateChanged event and the nested interfaces for Call, CallResult, CallDirection, and CallState, detailing the properties and enums related to call status.
```typescript
interface CallStateChanged {
type: 'callStateChanged'
call: Call
}
interface Call {
// Unique identifier of the call.
id: string;
// The current state of the call.
state: CallState;
direction: CallDirection;
// The final call status.
// Set to `null` when `state` is not "completed".
result: CallResult | null;
// E.164 phone number or an extension.
// Set to 'null' if the phone number is hidden.
from: string | null;
// E.164 phone number or an extension.
// Set to `null` if the phone number is hidden.
to: string | null;
caller: {
// The optional display name as set in the call information.
caller_display_name: string | null;
};
start_time: Date;
// The time when the call transitioned to an "answered" state.
// Set to `null` until then.
answer_time: Date | null;
// The time when the call transitioned to a "disconnected" state.
// Set to `null` until then.
end_time: Date | null;
}
enum CallResult {
// The call was answered and some conversation happened.
// This may also include calls with automated responses,
// For example, there was no actual talk, but voicemail was recorded.
Answered = 'answered',
// The call wasn't answered:
// - The call rang for too long and was missed.
// - The callee was busy.
// - The call was rejected by a callee.
// - The call was rejected, blocked or dropped by net2phone.
// - The call was cancelled early by a caller.
NotAnswered = 'not_answered'
}
enum CallDirection {
Inbound = 'inbound',
Outbound = 'outbound'
}
enum CallState {
// The initial (first) state of the call.
Connecting = 'connecting',
// The call was accepted on the other side.
Answered = 'answered',
// The final (last) state of the call.
// This event is always emitted, no matter if a call was successful,
// or it was rejected, canceled, blocked, etc.
// See the "result" field for the details.
Disconnected = 'disconnected'
}
```
--------------------------------
### Token Response Payload
Source: https://developer.net2phone.com/api-explorer/v2?articleId=authentication
Successful response payload from the token endpoint containing access token and related information.
```json
{
"access_token": "{access_token_string}",
"expires_in": 3600,
"token_type": "Bearer",
"refresh_token": "AEC4F36E513545D7F4DFF750ECEF0C3823986FBEE225F53CEE186AB3D15941D8",
"scope": "public_api.v2 offline_access"
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.