【问题标题】:Invalide Access Token header Twilio Programmable voice React Native iOS无效的访问令牌标头 Twilio 可编程语音 React Native iOS
【发布时间】:2020-05-12 07:22:48
【问题描述】:

我正在尝试使用 react-native-twilio-programmable-voice 实现语音通话。

它表示来自TwilioVoice.initWithToken(accessToken) 的就绪状态,但是当我调用Twilio.connect() 方法时,我在eventlisternerconnectionDidDisconnect 方法中得到Invalid Access Token header。我正在使用 React Native 0.61.5react-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

请帮忙。

提前致谢

【问题讨论】:

    标签: twilio react-native-ios twilio-programmable-voice


    【解决方案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();
    

    【讨论】:

      猜你喜欢
      • 2020-01-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-09
      • 2022-09-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多