如何获取设备令牌以发送通知?

时间:2021-07-16 07:34:58

标签: php firebase codeigniter firebase-cloud-messaging token

我已经在 Codeigniter 中构建了网络版本,并且一直在使用 React Native 开发移动版本。 要发出新订单通知,我将使用 firebase 云消息。 怎么样,我在哪里可以得到这个设备令牌?

public function sendFCMNotification($registration_ids, $message){

        $SERVER_API_KEY ='my server api key';
        // payload data, it will vary according to requirement
        $data = [
            "registration_ids" => $registration_ids, 
            "data" => $message
        ];
        $dataString = json_encode($data);
    
        $headers = [
            'Authorization: key=' . $SERVER_API_KEY,
            'Content-Type: application/json',
        ];
    
        $ch = curl_init();
      
        curl_setopt($ch, CURLOPT_URL, 'https://fcm.googleapis.com/fcm/send');
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
               
        $response = curl_exec($ch);
      
        curl_close($ch);
      
        return $response;
    }

2 个答案:

答案 0 :(得分:0)

在您的 React-Native 应用程序中,您可以像这样获取令牌:

messaging().getToken().then(token => { saveTokenToDatabase(token);});

然后监听任何令牌变化

messaging().onTokenRefresh(token => {saveTokenToDatabase(token);});

saveTokenToDatabase 方法用于将令牌保存到您的后端,以便您稍后访问它以发送消息

答案 1 :(得分:0)

在android中你需要使用这个类来获取设备令牌

公共类 MyFirebaseMessagingService 扩展了 FirebaseMessagingService {

@Override
public void onNewToken(String token) {
    super.onNewToken(token);
    Log.e("newToken", token);
    //Add your token in your sharefpreferences.
    SharedPreferenceManager app_sp = new SharedPreferenceManager(this);
    app_sp.putString(Constants.FIREBASE_TOKEN, token);

此服务请求将设备令牌更新到您的服务器 // updatetokenAPI.updateToken(token);