Заголовок недействительного токена доступа Twilio Programmable voice React Native iOS
Я пытаюсь реализовать голосовой вызов с помощью react-native-twilio-programmable-voice.
Он говорит о состоянии готовности от TwilioVoice.initWithToken(accessToken)
, но когда я звоню Twilio.connect()
метод, который я получаю Invalid Access Token header
в событиилистерconnectionDidDisconnect
метод. Я использую React Native0.61.5
а также react-native-twilio-programmable-voice 3.21.3
данные, возвращенные из connectionDidDisconnect
Eventlisterner
{
call_sid: ""
call_state: "DISCONNECTED"
error: "Invalid Access Token header"
}
вот мой код:
import React, { useState, useEffect } from 'react';
import {
View,
Text,
Image,
TouchableOpacity,
Platform,
PermissionsAndroid,
} from 'react-native';
import TwilioVoice from 'react-native-twilio-programmable-voice';
import axios from 'axios';
const Call = () => {
const [callState, setCallState] = useState('');
const [twilioInit, setTwilioInit] = useState(false);
const [name, setName] = useState('');
const [email, setEmial] = useState('');
const [calling, setCalling] = useState(false);
TwilioVoice.addEventListener('connectionDidDisconnect', function(data) {
console.log(data);
});
const getMicrophonePermission = () => {
const audioPermission = PermissionsAndroid.PERMISSIONS.RECORD_AUDIO;
return PermissionsAndroid.check(audioPermission).then(async (result) => {
if (!result) {
const granted = await PermissionsAndroid.request(audioPermission, {
title: 'Microphone Permission',
message:
'App needs access to you microphone ' +
'so you can talk with other users.',
});
}
});
};
const getAuthToken = () => {
const ENDPOINT = 'https://server.com';
return fetch(`${ENDPOINT}/twilioToken`, {
method: 'get',
})
.then((response) => {
return response.json();
})
.then((data) => {
return data.token;
})
.catch((error) => console.log(error));
};
const initlize = async () => {
if (Platform.OS === 'android') {
await getMicrophonePermission();
}
try {
const accessToken = await getAuthToken();
console.log(accessToken);
const success = await TwilioVoice.initWithToken(accessToken);
if (Platform.OS === 'ios') {
TwilioVoice.configureCallKit({
appName: 'eSIM2GO',
});
}
setTwilioInit(success);
} catch (err) {
console.log(err);
}
};
useEffect(() => {
initlize();
}, []);
const handleCall = async () => {
// if (!name && !email) {
// alert('Enter Credetials');
// } else {
// TwilioVoice.connect({ To: 'number' });
// }
TwilioVoice.connect({ To: 'number' });
};
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#040b2b',
}}
>
<Image
source={require('../../assets/free_calls.png')}
style={{ width: 300, height: 350 }}
/>
<View>
<TouchableOpacity
style={{
marginTop: 30,
backgroundColor: 'rgba(240,97,78, 0.5)',
paddingHorizontal: 100,
paddingVertical: 11,
borderRadius: 22,
}}
onPress={() => handleCall()}
>
<Text
style={{
color: '#fff',
fontFamily: 'Manjari-Regular',
fontSize: 20,
}}
>
{calling ? 'Hang Up' : 'Call'}
</Text>
</TouchableOpacity>
</View>
<View
style={{
marginVertical: 10,
}}
>
<Text
style={{
color: '#fff',
fontSize: 18,
fontFamily: 'Manjari-Regular',
}}
>
{twilioInit ? 'Ready' : 'Not Ready'}
</Text>
</View>
</View>
);
};
export default Call;
вот мой серверный код для генерации токена
public function twilioToken() {
$accountSid = '********';
$authToken = '********';
$appSid = '*********';
$capability = new ClientToken($accountSid, $authToken);
$capability->allowClientOutgoing($appSid);
$token = $capability->generateToken(29880);
return response([
'successful' => TRUE,
'token' => $token
], 200);
}
Я получаю следующий журнал из xcode
provider:didDeactivateAudioSession
Пожалуйста помоги.
заранее спасибо
1 ответ
По сути, я изменил токен доступа к запросу с сервера. к следующему коду, согласно документации twilio docs
$twilioAccountSid = 'ACxxxxxxxxxxxx';
$twilioApiKey = 'SKxxxxxxxxxxxx';
$twilioApiSecret = 'xxxxxxxxxxxxxx';
// Required for Voice grant
$outgoingApplicationSid = 'APxxxxxxxxxxxx';
// An identifier for your app - can be anything you'd like
$identity = "john_doe";
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
3600,
$identity
);
// Create Voice grant
$voiceGrant = new VoiceGrant();
$voiceGrant->setOutgoingApplicationSid($outgoingApplicationSid);
// Optional: add to allow incoming calls
$voiceGrant->setIncomingAllow(true);
// Add grant to token
$token->addGrant($voiceGrant);
// render token to string
echo $token->toJWT();