Как интегрировать Plivo SDK в Laravel?Javascript

Форум по Javascript
Ответить
Anonymous
 Как интегрировать Plivo SDK в Laravel?

Сообщение Anonymous »


Я интегрирую Plivo в Laravel, чтобы создать «нажмите, чтобы вызвать». Функция на моей странице веб -приложения. Я хочу предоставить такие функции, как Call, Hangup, Mute и звучание на этой странице. Я также хочу функцию, которая позволяет пользователям разговаривать напрямую через Интернет. Итак, когда пользователь нажимает кнопку «Вызов», пользователь может немедленно поговорить с кем -то через браузер. Не удалось загрузить Plivo Sdk: Plivo SDK не удалось загрузить ". -php prettyprint-override ">

Код: Выделить всё

@extends('layouts.app')
@section('title', "Contact: {$contact->first_name} {$contact->last_name}")
@section('styles')
 

.call-interface {
padding: 20px;
border: 1px solid #ddd;
border-radius: 8px;
margin-bottom: 20px;
}
.call-status {
font-size: 18px;
margin-bottom: 15px;
}
.call-controls button {
margin-right: 10px;
margin-bottom: 10px;
}
.call-timer {
font-size: 24px;
font-weight: bold;
margin: 15px 0;
}
.call-logs {
margin-top: 30px;
}

@endsection
@section('content')




Contact Details



[b]Name:[/b] {{ $contact->first_name }} {{ $contact->last_name }}

[b]Phone:[/b] {{ $contact->phone }}





Note
{!! $disposition ? $disposition->note : '' !!}


Select disposition
@foreach (config('data.disposition_status') as $key => $item)
status === $key ? 'selected' : '' }}>{{ $item }}
@endforeach


Call








Call Interface



Ready

00:00:00


[/i] Call


[i][/i] Hangup


[i][/i] Mute


[i][/i]  Unmute






@endsection
@push('scripts')

let client;
let currentCall = null;
let callTimer = null;
let callStartTime = null;

async function initializePlivoClient() {
try {
console.log('Initializing Plivo client...');

if (typeof window.plivoBrowserSdk === 'undefined') {
throw new Error('Plivo Browser SDK not loaded');
}

const response = await fetch('{{ route("plivo.token") }}');
const data = await response.json();

if (data.error) {
throw new Error(data.error);
}

console.log('Token received, initializing client...');

try {
const options = {
debug: "DEBUG",
permOnClick: true,
enableTracking: true,
audioConstraints: {
optional: [
{ echoCancellation: true },
{ noiseSuppression: true }
]
}
};

// Create client using the correct SDK reference
client = new window.plivoBrowserSdk.Client(options);

console.log('Client created, attempting login...');

// Login
await client.login(data.username, data.password);

console.log('Login successful');
document.getElementById('makeCall').disabled = false;
document.getElementById('call-status').innerHTML = 'Ready to call';
document.getElementById('call-status').className = 'alert alert-success';

setupEventListeners();

} catch (error) {
throw new Error(`Client initialization failed: ${error.message}`);
}

} catch (error) {
console.error('Failed to initialize Plivo client:', error);
document.getElementById('call-status').innerHTML = 'Failed to initialize phone: ' + error.message;
document.getElementById('call-status').className = 'alert alert-danger';
}
}

// Wait for SDK to load
function waitForPlivoSDK() {
return new Promise((resolve, reject) => {
let attempts = 0;
const maxAttempts = 20;

const checkSDK = setInterval(() => {
if (typeof window.plivoBrowserSdk !== 'undefined') {
clearInterval(checkSDK);
resolve();
} else {
attempts++;
if (attempts >= maxAttempts) {
clearInterval(checkSDK);
reject(new Error('Plivo SDK failed to load'));
}
}
}, 250);
});
}

// Initialize when document is ready
document.addEventListener('DOMContentLoaded', async () => {
try {
await waitForPlivoSDK();
await initializePlivoClient();
} catch (error) {
console.error('Initialization failed:', error);
document.getElementById('call-status').innerHTML = 'Failed to load Plivo SDK: ' + error.message;
document.getElementById('call-status').className = 'alert alert-danger';
}
});

function setupEventListeners() {
if (!client) {
console.error('Client not initialized');
return;
}

client.on('onLogin', () => {
console.log('Successfully logged in to Plivo');
document.getElementById('call-status').innerHTML = 'Ready to make calls';
document.getElementById('call-status').className = 'alert alert-success';
});

client.on('onLoginFailed', (error) => {
console.error('Login failed:', error);
});

client.on('onCallRemoteRinging', () =>  {
document.getElementById('call-status').innerHTML = 'Ringing...';
document.getElementById('call-status').className = 'alert alert-warning';
});

client.on('onCallAnswered', () => {
document.getElementById('call-status').innerHTML = 'Call in progress';
document.getElementById('call-status').className = 'alert alert-success';
document.getElementById('hangupCall').disabled = false;
document.getElementById('muteCall').disabled = false;
startCallTimer();
});

client.on('onCallTerminated', () => {
resetCallInterface();
logCall('completed');
});

client.on('onCallFailed', (error) => {
console.error('Call failed:', error);
resetCallInterface();
logCall('failed');
});
}

function startCallTimer() {
callStartTime = new Date();
callTimer = setInterval(() => {
const now = new Date();
const diff = new Date(now - callStartTime);
const hours = diff.getUTCHours().toString().padStart(2, '0');
const minutes = diff.getUTCMinutes().toString().padStart(2, '0');
const seconds = diff.getUTCSeconds().toString().padStart(2, '0');
document.getElementById('call-timer').innerHTML = `${hours}:${minutes}:${seconds}`;
}, 1000);
}

function resetCallInterface() {
currentCall = null;
document.getElementById('call-status').innerHTML = 'Ready';
document.getElementById('call-status').className = 'alert alert-info';
document.getElementById('hangupCall').disabled = true;
document.getElementById('muteCall').disabled = true;
document.getElementById('unmuteCall').disabled = true;
document.getElementById('call-timer').innerHTML = '00:00:00';

if (callTimer) {
clearInterval(callTimer);
callTimer = null;
}
callStartTime = null;
}

async function logCall(status) {
try {
await fetch('/api/call-logs', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-CSRF-TOKEN': document.querySelector('meta[name="csrf-token"]').content
},
body: JSON.stringify({
contact_id: '{{ $contact->id }}',
status: status,
start_time: callStartTime,
end_time: new Date(),
duration: callStartTime ? Math.round((new Date() - callStartTime) / 1000) : 0
})
});
} catch (error) {
console.error('Failed to log call:', error);
}
}

// Initialize when page loads
document.addEventListener('DOMContentLoaded', initializePlivoClient);

// Call button event listener
document.getElementById('makeCall').addEventListener('click', async () => {
try {
currentCall = await client.call('{{ $contact->phone }}');
document.getElementById('call-status').innerHTML = 'Calling...';
document.getElementById('call-status').className = 'alert alert-warning';
} catch (error) {
console.error('Error making call:', error);
document.getElementById('call-status').innerHTML = 'Call failed: ' + error.message;
document.getElementById('call-status').className = 'alert alert-danger';
}
});

// Hangup button event listener
document.getElementById('hangupCall').addEventListener('click', () => {
if (currentCall) {
currentCall.hangup();
}
});

// Mute button event listener
document.getElementById('muteCall').addEventListener('click', () => {
if (currentCall) {
currentCall.mute();
document.getElementById('muteCall').disabled = true;
document.getElementById('unmuteCall').disabled = false;
}
});

// Unmute button event listener
document.getElementById('unmuteCall').addEventListener('click', () =>  {
if (currentCall) {
currentCall.unmute();
document.getElementById('muteCall').disabled = false;
document.getElementById('unmuteCall').disabled = true;
}
});

@endpush
plivocontroller.php

Код: Выделить всё


Подробнее здесь: [url]https://stackoverflow.com/questions/79396126/how-to-integrate-plivo-sdk-in-laravel[/url]
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Javascript»