I'm trying to test FCM using Postman, but I always get the following error even the FCM token is there. I got the token in the Cloud Messaging tab: Firebase Cloud Messaging token.
<HTML>
<HEAD>
<TITLE>The request was missing an Authentification Key (FCM Token). Please, refer to section "Authentification" of the FCM documentation, at https://firebase.google.com/docs/cloud-messaging/server.</TITLE>
</HEAD>
Here is what I send.
POST /fcm/send HTTP/1.1
Host: fcm.googleapis.com
Cache-Control: no-cache
Postman-Token: 9109eb13-245f-0786-21a5-6207f5426b44
Content-Type:application/json
Authorization:key=AAAAfnYrKvU:APA91bFwgeM3zuFId6UDzvIHk9qZ3lKHnX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
{ "data": { "message": "This is a Firebase Cloud Messaging Topic Message!", } }:
After spending some hours I found that in Postman you have to put the following in the Headers.
Key: Content-Type
Value: application/json
Key: Authorization
Value: key=AAAAfnYrKvU:APA91bFwgeM3zuFId6UDzvIHk9qZ3lKHnX-xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
(Firebase Cloud Messaging token)
Then click Body and select Raw, here you add the json.
{
"data": {
"title": "new messages",
"score": "5x1",
"time": "15:10"
},
"to": "/topics/alldevices"
}
I also found that you cannot send to all devices by eliminating the "to": You will have to have your app subscribe to a topic. In my case I made my app subscribed to "alldevices".
Now I can send "to":"/topics/alldevices" and all apps will receive the notification.
working code for me like this-
POST:- https://fcm.googleapis.com/fcm/send
Header-
Content-Type: application/json
Authorization:key=AAAATIOk_eI:APA91bHR-NRuK-cVTc0fsdQ-N4SOAzocN7ngomFzcV7GkeCCHb6PmCFl_7MXTEPbdw-r0MTU9UmSbyxaSxxxxxxxxx.....
Body-
{
"registration_ids": ["fBclzMXz1UQ:APA91bE268ddn8DNB95LcU2XyhjjOXE-8PJ1nZ8y0yf1-4UuUX0fFNuae9Acj5BLYZwJq72tnNUjcUax9ZvRxxxxxxxxxxxxxxxxx...."],
"notification": {
"title": "Hello",
"body": "This is test message."
}
}
This is a sample postman POST request to send notifications to devices by using tokens.
Type: POST
Url: https://fcm.googleapis.com/fcm/send
Headers
key: Content-Type,
value: application/json
key: Authorization,
value: key="This is the key in your FCM project console->Settings->Cloud Messaging->Server Key""
body: "mode": "raw"
{
"to": "Token/s received to mobile end",
"notification" : {
"body" : "message",
"content_available" : true,
"priority" : "high",
"title" : "title of the notification"
}
}
working code...
make sure You subscribe to topic ="/topics/alldevices" in your android/iOS code.
POST:- https://fcm.googleapis.com/fcm/send
Header-
Content-Type: application/json
Authorization:key=AAAAPfs2N44:APA91bFcDkUfTjbFQvrttpedPcZINcjNkofU_x35xxxxxxxxx.....
Body-
"notification":{
"title":"TITLE",
"body":"BODY",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"landing_page":"second",
"price":"$3,000.00"
},
"to":"/topics/alldevices",
"priority":"high",
"restricted_package_name":""
}
This is the sample postman request to send push notification for single mobile device
post - https://fcm.googleapis.com/fcm/send
content-type: application/json
authorization: key="<server key>"
JSON Body
{
"notification":{
"title":"Ionic 4 Notification",
"body":"This notification sent from POSTMAN using Firebase HTTP protocol",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"data":{
"title":"Ionic 4 Notification",
"body":"Ionic test 11",
"sound":"default",
"click_action":"FCM_PLUGIN_ACTIVITY",
"icon":"fcm_push_icon"
},
"to":"<put token id here>",
"priority":"high",
"restricted_package_name":""
}
#GauravInno's answer made me realize my server key was incorrect, I somehow was using the wrong key. I got the serverKey from Firebase console:
It's used in the code below request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization"):
var apsDict = [String: Any]()
// add values
guard let url = URL(string: "https://fcm.googleapis.com/fcm/send") else { return }
let serverKey = "AAAA ..."
var request = URLRequest(url: url)
request.httpMethod = "POST"
request.httpBody = try? JSONSerialization.data(withJSONObject: apsDict, options: [])
request.setValue("application/json", forHTTPHeaderField: "Content-Type")
// *** serverKey is used here ***
request.setValue("key=\(serverKey)", forHTTPHeaderField: "Authorization")
let task = URLSession.shared.dataTask(with: request) { (data, response, error) in
do {
if let jsonData = data {
print("jsonData: \(String(data: jsonData, encoding: .utf8)!)")
if let jsonDataDict = try JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? [String: AnyObject] {
print("jsonData Success Received data:\n\(jsonDataDict))")
}
}
} catch let err as NSError {
print("jsonData Error: \(err.debugDescription)")
}
}
task.resume()
Related
I've got a rails api and a react front end with axios to interact with the api. Have enabled CORS in rails, but the below request gets cancelled by the browser and can't find the reason for it.
Request copied as "fetch" call:
fetch("http://localhost:3000/api/v1/profile",
{
"credentials":"include",
"headers":{
"accept":"application/json, text/plain, */*",
"accept-language":"en-GB,en-US;q=0.9,en;q=0.8",
"authorization":"Bearer eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIiwic2NwIjoiYWNjb3VudCIsImF1ZCI6bnVsbCwiaWF0IjoxNTg2OTY4MjIwLCJleHAiOjE1ODcwNTQ2MjAsImp0aSI6IjhkNTE2YjIzLTA1MGQtNGU2MS04ZWE1LWM3ZGIwMzkxNTg0NCJ9.KuwtVNB5minrOs3lvfNjt7lVQSWNRXdqZsbErb6SrGM",
"content-type":"application/json",
"sec-fetch-dest":"empty",
"sec-fetch-mode":"cors",
"sec-fetch-site":"same-site"
},
"referrer":"http://localhost:3001/profile?",
"referrerPolicy":"no-referrer-when-downgrade",
"body":"{\"first_name\":\"testsdasd\",\"last_name\":\"asadeesdfsfs\"}",
"method":"PUT",
"mode":"cors"
});
Is this getting cancelled due to CORS? BTW other post requests are getting through.
Thanks a lot.
Below is the code using axios.
async updateProfileData(profile) {
try {
let axiosResponse = await AxiosClient.instance().put('http://localhost:3000/api/v1/profile', {
first_name: profile.first_name,
last_name: profile.last_name
},{
headers: {
"Content-Type": "application/json"
}
});
return axiosResponse;
} catch (e) {
return e.response;
}
}
Found the answer.
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at ‘http://localhost:3000/api/v1/profile’. (Reason: Credential is not supported if the CORS header ‘Access-Control-Allow-Origin’ is ‘*’).
https://developer.mozilla.org/docs/Web/HTTP/CORS/Errors/CORSNotSupportingCredentials?utm_source=devtools&utm_medium=firefox-cors-errors&utm_campaign=default
I am trying to create an automated JIRA ticket using the REST API but I keep getting a 405 error.
I am using the examples here: https://developer.atlassian.com/server/jira/platform/jira-rest-api-examples/
Also, when I visit the post URL directly I do not get any errors so I doubt it is a server issue. Any ideas?
var Client = require('node-rest-client').Client;
client = new Client();
// Provide user credentials, which will be used to log in to Jira.
var loginArgs = {
data: {
"username": "user",
"password": "pass"
},
headers: {
"Content-Type": "application/json"
}
};
client.post("https://jira.mydomain.com/rest/auth/1/session", loginArgs, function(data, response) {
if (response.statusCode == 200) {
//console.log('succesfully logged in, session:', data.session);
var session = data.session;
// Get the session information and store it in a cookie in the header
var args = {
headers: {
// Set the cookie from the session information
cookie: session.name + '=' + session.value,
"Content-Type": "application/json"
},
data: {
// I copied this from the tutorial
"fields": {
"project": {
"key": "REQ"
},
"summary": "REST ye merry gentlemen.",
"description": "Creating of an issue using project keys and issue type names using the REST API",
"issuetype": {
"name": "Request"
}
}
}
};
// Make the request return the search results, passing the header information including the cookie.
client.post("https://jira.mydomain.com/rest/api/2/issue/createmeta", args, function(searchResult, response) {
console.log('status code:', response.statusCode);
console.log('search result:', searchResult);
});
} else {
throw "Login failed :(";
}
});
I am expecting the Jira ticket of type REQ to be created with the details I added in the fields section.
I believe you are using the incorrect REST API; what you're currently doing is doing a POST to Get create issue meta which requires a GET method, hence, you're getting a 405. If you want to create an issue, kindly use Create issue (POST /rest/api/2/issue) instead.
The same request including the access token is working with CURL and Postman.
The code from Postman (masked credentials and ids) is included.
var http = require("https");
var options = {
"method": "GET",
"hostname": [
"3",
"basecampapi",
"com"
],
"path": [
"<MASKED ACCOUNT ID>",
"my",
"profile.json"
],
"headers": {
"Authorization": "Bearer <MASKED AUTH TOKEN>",
"Cache-Control": "no-cache",
"Postman-Token": "92fc7993-57aa-47f7-aaae-44925dd37f3e"
}
};
var req = http.request(options, function (res) {
var chunks = [];
res.on("data", function (chunk) {
chunks.push(chunk);
});
res.on("end", function () {
var body = Buffer.concat(chunks);
console.log(body.toString());
});
});
req.end();
Use NodeJS Request instead of NodeJS Native when creating code from a Postman request.
function getAccessToken()
{
var url = "https://gloapi.chinabrands.com/v2/user/login";
var data = {
"email": EMAILID,
"password": PWD,
"client_id": APIKEY
}
var payload = {
"data": data,
"signature": Utilities.base64Encode(data + SECRETKEY)
}
var options = {
"method": "post",
"contentType": "application/json",
"payload": payload
};
var json = UrlFetchApp.fetch(url, options).getContentText();
Browser.msgBox(json);
}
Please see attached documentation API screenshot link below.
I am trying to connect ChinaBrands API using google apps script.
I am getting error which says "{"status":0,"msg":"Requested info is empty","errcode":10006}"
See this Image : Documentation API to get AccessToken:
The documentation is a bit misleading. You need to make POST request with Content-Type: application/x-www-form-urlencoded. The request data field should be a string with your data in JSON format. I guess depending on language/libraries you use, you might need to URL encode the JSON data before making the request.
The resulting request should look like:
POST https://gloapi.chinabrands.com/v2/user/login
...
Accept: */*
Content-Type: application/x-www-form-urlencoded
signature=<md5 of string containing data in json + client secret>&data=%7B%22email%22%3A+%22name%40example.com%22%2C+%22password%22%3A+%2222password1%22%2C+%22client_id%22%3A+%1337%22%7D
Python 3 example with requests library:
url = "https://gloapi.chinabrands.com/v2/user/login"
data = {...}
json_data = json.dumps(data)
signature = md5((json_data + client_secret).encode('utf')).hexdigest()
response = requests.post(url, data={'signature': signature, 'data': json_data})
I just rewrote my firebase cloud messaging code for my web API and now use a Cloud Function to handle the subscriptions, or at least that is the theory.
Where can I go to cancel any existing subscriptions so that I can check that what seems now to be working, actually is (and that is not some hangover from before that is giving the impression of working).
This is all on a development instance of Firebase so I can delete whatever I want. I set up the subscriptions with the following code, which may or may not be coreect, but I think it means I need to look on Google rather than Firebase, but I can't find anything
let token = req.query.token;
let topic = "presents";
let uri = `https://iid.googleapis.com/iid/v1/${token}/rel/topics/${topic}`;
// Make the request to Google IID
var myHeaders = {
"Content-Type": "application/json",
Authorization: "key=" + secrets.devKey
};
var options = {
uri: uri,
method: "POST",
headers: myHeaders,
mode: "no-cors",
cache: "default"
};
rp(options)
.then(function(response) {
// console.log("rp success", response);
res.status(200).send({
msg: "Ok from Simon for " + token,
payload: response}
);
})
.catch(function(err) {
console.log("[fbm.registerForUpdates] Error registering for topic", err.message);
res.status(500).send(err);
});
The Firebase documentation seems to be incomplete on this topic. Playing around showed the following (valid at least at the time of writing, verified w/ Postman):
POST https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME request creates a subscription for a topic & token
GET https://iid.googleapis.com/iid/info/IID_TOKEN?details=true request lists all subscribed topics for a token
DELETE https://iid.googleapis.com/iid/v1/IID_TOKEN/rel/topics/TOPIC_NAME request removes a subscription for a topic for a token
DELETE https://iid.googleapis.com/v1/web/iid/IID_TOKEN request removes all subscriptions for a token
On all these requests the header 'Authorization: key=YOUR_SERVER_KEY' needs to be set.
Sample output from a GET request:
{
"connectDate": "2018-10-06",
"application": "com.chrome.macosx",
"subtype": "wp:https://192.168.0.196:8020/#9885158F-953C-48BC-BCF5-38ABF2F89-V2",
"scope": "*",
"authorizedEntity": "30916174593",
"rel": {
"topics": {
"sensorUpdate": {
"addDate": "2018-10-07"
}
}
},
"connectionType": "WIFI",
"platform": "BROWSER"
}