是否有任何选项可以通过客户端的Java Script获取FCM访问令牌密钥? 我使用Firebase来创建一个简单的Android应用程序'我想让一些用户选择发送推送通知消息。
function getAccessToken(){ }
var xhr = new XMLHttpRequest();
xhr.responseType = "json";
xhr.open('POST', "https://fcm.googleapis.com/v1/projects/**********/messages:send", true);
xhr.setRequestHeader('Authorization', "Bearer " + getAccessToken());

我使用以下代码片段尝试了@Ali的建议,但现在我从refreshAccessToken(...)获取了一个异常,其中包含"未为服务帐户配置范围的消息。&#34 ;。 我想澄清一下,阿里的第一条评论中的DotNet代码仍在使用相同的JSON文件。
@JavascriptInterface
private static String readToken() throws IOException, InterruptedException {
String str = new String("{\n" +
" \"type\": \"service_account\",\n" +
" \"project_id\": \"*****\",\n" +
" \"private_key_id\": \"*****\",\n" +
" \"private_key\": \"-----BEGIN PRIVATE KEY-----\\n*****\\n-----END PRIVATE KEY-----\\n\",\n" +
" \"client_email\": \"*****\",\n" +
" \"client_id\": \"*****\",\n" +
" \"auth_uri\": \"*****",\n" +
" \"token_uri\": \"*****",\n" +
" \"auth_provider_x509_cert_url\": \"*****",\n" +
" \"client_x509_cert_url\": \"*****\"\n" + "}\n");
InputStream stream = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
GoogleCredentials googleCredential = GoogleCredentials.fromStream(stream);
googleCredential.createScoped(Arrays.asList("https://www.googleapis.com/auth/firebase.messaging"));
AccessToken token = googleCredential.refreshAccessToken();
String x = token.getTokenValue();
return x;
}

答案 0 :(得分:1)
创建webview后,启用JavaScript并附加JavaScript界面并将其命名为:
WebSettings webSettings = webview.getSettings();
webSettings.setJavaScriptEnabled(true);
webview.addJavascriptInterface(this, "InterfaceName");
现在,您可以将任何Java功能分配到JavaScript界面,并通过网页访问它。
获取用户FCM令牌的示例:
@JavascriptInterface
public String readToken(){
String token = FirebaseInstanceId.getInstance().getToken();
return token;
}
获取FCM访问令牌密钥(reference)的示例:
@JavascriptInterface
private static String readToken() throws IOException {
GoogleCredential googleCredential = GoogleCredential
.fromStream(new FileInputStream("service-account.json"))
.createScoped(Arrays.asList(SCOPES));
googleCredential.refreshToken();
return googleCredential.getAccessToken();
}
将访问令牌添加到HTTP请求标头:
URL url = new URL(BASE_URL + FCM_SEND_ENDPOINT);
HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
httpURLConnection.setRequestProperty("Authorization", "Bearer " + getAccessToken());
httpURLConnection.setRequestProperty("Content-Type", "application/json; UTF-8");
return httpURLConnection;
这就是你可以在你定义界面的WebView中使用JavaScript调用该函数的方法:
<script>
var token=InterfaceName.readToken();
</scritp>