firebase-admin的Java集成到服務器

1.添加maven

<dependency>
    <groupId>com.google.firebase</groupId>
    <artifactId>firebase-admin</artifactId>
    <version>6.10.0</version>
</dependency>

2.創建firebase-adminsdk.json文件,在firebase控制檯中下載json文件將內容複製到firebase-adminsdk.json中

.

3.直接上工具類

package com.supermonkey.futureready.common.utils;

import com.google.auth.oauth2.GoogleCredentials;
import com.google.firebase.FirebaseApp;
import com.google.firebase.FirebaseOptions;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.UserRecord;
import com.google.firebase.messaging.*;
import com.supermonkey.futureready.common.entity.User;
import com.supermonkey.futureready.common.exception.BusinessException;
import org.springframework.core.io.ClassPathResource;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;

/**
 * {@code description: FireBaseUtil Firebase Cloud Message}
 * Google_FireBase推送工具類
 *
 * @author zhangkai
 * @version 1.0
 * @since 2019/7/5 15:48
 */
@Component
public class FireBaseUtil {

    //獲取AndroidConfig.Builder對象
    private static AndroidConfig.Builder androidConfigBuilder = AndroidConfig.builder();
    //獲取AndroidNotification.Builder對象
    private static AndroidNotification.Builder androidNotifiBuilder = AndroidNotification.builder();
    public static FirebaseApp firebaseApp;
    private static final String FIREBASE_DB_URL = "https://你的firebase地址.firebaseio.com";
    private static final String FIREBASE_STORAGE_BUCKET = "你的firebase地址";
    private static final String FIREBASE_PROJECT_ID = "你的firebase地址";

    static {
        init();
    }


    public static void main(String[] args) {
        try {
            FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);

            UserRecord user = getUserById("some-uid");
            System.out.println(user.toString());

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void init() {
        try {
            //設置環境
            InputStream serviceAccount = new ClassPathResource("firebase-adminsdk.json").getInputStream();
            FirebaseOptions options = new FirebaseOptions.Builder()
                    .setCredentials(GoogleCredentials.fromStream(serviceAccount))
                    .setDatabaseUrl(FIREBASE_DB_URL)
                    .build();

            firebaseApp = FirebaseApp.initializeApp(options);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static UserRecord getUserById(String uid){
        FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);
        UserRecord user = null;
        try {
            user = instance.getUserAsync(uid).get();
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("get user from firebase by uid error");
        }
        return user;
    }

    public static UserRecord getUserByEmail(String email) {
        try {
            // [START get_user_by_email]
            UserRecord userRecord = FirebaseAuth.getInstance(firebaseApp).getUserByEmailAsync(email).get();
            // See the UserRecord reference doc for the contents of userRecord.
//            System.out.println("Successfully fetched user data: " + userRecord.getEmail());
            return userRecord;
            // [END get_user_by_email]
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("get user from firebase by email error");
        }
    }

    /**
     * {@code description: 創建用戶}
     *
     * @param user
     * @author zhangkai
     * @since 2019/9/27 11:03
     */
    public static UserRecord createUser(User user) {
        try {
            UserRecord.CreateRequest request = new UserRecord.CreateRequest()
                    .setEmail(user.getEmail())
                    .setEmailVerified(false)
                    //.setPassword(ProjectAbout.PASSWORD)
                    .setDisplayName(user.getFullName())
                    .setDisabled(false);
            FirebaseAuth instance = FirebaseAuth.getInstance(firebaseApp);
            UserRecord userRecord = instance.createUserAsync(request).get();
            System.out.println("Successfully created new user: " + userRecord.getUid());
            return userRecord;
        } catch (Exception e) {
            e.printStackTrace();
            throw new BusinessException("create firebase user error");
        }
    }

    /**
     * 單設備推送
     * @param token   註冊token
     * @param title   推送題目
     * @param body    推送內容
     * @return
     * @throws IOException
     * @throws FirebaseMessagingException
     */
    public static void pushSingle( String token, String title, String body) throws IOException, FirebaseMessagingException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例爲空的情況
        if (firebaseApp == null) {
            return;
        }
        //構建消息內容
        //Notification(String title, String body, String imageUrl)
        Message message = Message.builder().setNotification(new Notification(title, body))
                .setToken(token)
                .build();
        //發送後,返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("單個設備推送成功 : " + response);
    }
    /**
     * 單設備推送
     * @param token   註冊token
     * @param title   推送題目
     * @param body    推送內容
     * @param map     額外的參數
     * @return
     * @throws IOException
     * @throws FirebaseMessagingException
     */
    public static void pushSingle(String token, String title, String body, Map<String,String> map) throws IOException, FirebaseMessagingException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例爲空的情況
        if (firebaseApp == null) {
            return;
        }
        //構建消息內容
        //Notification(String title, String body, String imageUrl)
        Message message = Message.builder().setNotification(new Notification(title, body))
                .putAllData(map)
                .setToken(token)
                .build();
        //發送後,返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("單個設備推送成功 : " + response);
    }
    /**
     * {@code description: 單設備推送}
     * @param token   註冊token
     * @param title   推送題目
     * @param body    推送內容
     * @param extra   額外的參數
     * @return
     * @throws IOException
     * @throws FirebaseMessagingException
     * @author zhangkai
     * @since 2019/10/14 11:24
     */
    public static void pushSingle( String token, String title, String body, String extra) throws IOException, FirebaseMessagingException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例爲空的情況
        if (firebaseApp == null) {
            return;
        }
        //構建消息內容
        //Notification(String title, String body, String imageUrl)
        Message message = Message.builder().setNotification(new Notification(title, body))
                .putData("extra",extra)
                .setToken(token)
                .build();
        //發送後,返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("單個設備推送成功 : " + response);
    }

    /**
     * 給設備訂閱主題
     * @param tokens  設備的token,最大1000個
     * @param topic   要添加的主題
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void registrationTopic( List<String> tokens, String topic) throws FirebaseMessagingException, IOException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例不存在的情況
        if (firebaseApp == null) {
            return;
        }
        //訂閱,返回主題管理結果對象。
        TopicManagementResponse response = FirebaseMessaging.getInstance(firebaseApp).subscribeToTopic(tokens, topic);
        System.out.println("添加設備主題,成功:" + response.getSuccessCount() + ",失敗:" + response.getFailureCount());
    }

    /**
     * 取消設備的訂閱主題
     * @param tokens  設備的token,最大1000個
     * @param topic   取消的主題
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void cancelTopic( List<String> tokens, String topic) throws FirebaseMessagingException, IOException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例不存在的情況
        if (firebaseApp == null) {
            return;
        }
        //取消訂閱,返回主題管理結果對象。
        TopicManagementResponse response = FirebaseMessaging.getInstance(firebaseApp).unsubscribeFromTopic(tokens, topic);
        System.out.println("取消設備主題,成功:" + response.getSuccessCount() + ",失敗:" + response.getFailureCount());
    }

    /**
     * 按主題推送
     * @param topic   主題的名字
     * @param title   消息題目
     * @param body    消息體
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void sendTopicMes( String topic, String title, String body) throws FirebaseMessagingException, IOException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例不存在的情況
        if (firebaseApp == null) {
            return;
        }
        //構建消息
        Message message = Message.builder()
                .setNotification(new Notification(title, body))
                .setTopic(topic)
                .build();
        //發送後,返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("主題推送成功: " + response);
    }

    /**
     * 單條Android設備推送消息(和pushSingle方法幾乎沒有區別)
     * @param token   註冊token
     * @param title   推送題目
     * @param body    推送內容
     * @throws FirebaseMessagingException
     */
    public static void pushSingleToAndroid( String token, String title, String body) throws FirebaseMessagingException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例爲空的情況
        if (firebaseApp == null) {
            return;
        }
        androidConfigBuilder.setRestrictedPackageName("io.telecomm.telecomm");
        androidNotifiBuilder.setColor("#55BEB7");// 設置消息通知顏色
        androidNotifiBuilder.setIcon("https://www.shiku.co/images/favicon.png");// 設置消息圖標
        androidNotifiBuilder.setTitle(title);// 設置消息標題
        androidNotifiBuilder.setBody(body);// 設置消息內容
        AndroidNotification androidNotification = androidNotifiBuilder.build();
        androidConfigBuilder.setNotification(androidNotification);
        AndroidConfig androidConfig = androidConfigBuilder.build();
        //構建消息
        Message message = Message.builder()
                .setToken(token)
                .setAndroidConfig(androidConfig)
                .build();
        //發送後,返回messageID
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("單個安卓設備推送成功 : " + response);
    }

    /**
     * Android按主題推送(和sendTopicMes方法幾乎沒有區別)
     * @param topic   主題的名字
     * @param title   消息題目
     * @param body    消息體
     * @return
     * @throws FirebaseMessagingException
     * @throws IOException
     */
    public static void sendTopicMesToAndroid( String topic, String title, String body) throws FirebaseMessagingException, IOException {
        //獲取實例
        FirebaseApp firebaseApp = FirebaseApp.getInstance();
        //實例爲空的情況
        if (firebaseApp == null) {
            return;
        }
        androidNotifiBuilder.setColor("#55BEB7");// 設置消息通知顏色
        androidNotifiBuilder.setIcon("https://www.shiku.co/images/favicon.png");// 設置消息圖標
        androidNotifiBuilder.setTitle(title);// 設置消息標題
        androidNotifiBuilder.setBody(body);// 設置消息內容
        AndroidNotification androidNotification = androidNotifiBuilder.build();
        androidConfigBuilder.setNotification(androidNotification);
        AndroidConfig androidConfig = androidConfigBuilder.build();
        //構建消息
        Message message = Message.builder()
                .setTopic(topic)
                .setAndroidConfig(androidConfig)
                .build();
        String response = FirebaseMessaging.getInstance(firebaseApp).send(message);
        System.out.println("安卓主題推送成功: " + response);
    }
}