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"
}
Related
I am using the payment_intent API to generate payment intent for payment sheet initialization.
As per the document, payment_intent is the POST method. Showing different errors in android and iOS.
https://stripe.com/docs/api/payment_intents/create
Note:- It's working in postman not working on mobile.
Case 1 Android
It is not working with the POST method. It worked with the GET method this is weird.
Case 2 iOS
It is not working with the GET and POST methods both.
With POST received the following error
_response": "{
\"error\": {
\"code\": \"parameter_missing\",
\"doc_url\": \"https://stripe.com/docs/error-codes/parameter-missing\",
\"message\": \"Missing required param: amount.\",
\"param\": \"amount\",
\"type\": \"invalid_request_error\"
}
}
With GET method received the following error
"_response":"resource exceeds maximum size"
End Point URL:-
let data = JSON.stringify({
customer: customerId,
currency: 'inr',
amount: 1000,
'automatic_payment_methods[enabled]': 'true',
});
let config = {
method: 'GET',
url: 'https://api.stripe.com/v1/payment_intents',
headers: {
Authorization:
'Bearer sk_test_DmXI7Jw1PnJAWYps3iCpvKkttIGX00pPfGLTjj',
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(function (response) {
console.info(JSON.stringify(response));
})
.catch(function (error) {
console.error('-----', error.response);
});
Following this document
https://stripe.com/docs/payments/accept-a-payment?platform=react-native&ui=payment-sheet#react-native-flowcontroller
https://stripe.com/docs/api/payment_intents/create
Added snack URL to reproduce the issue.
https://snack.expo.dev/#vishaldhanotiya/stripe-payment-intent
Error Log
To clarify a few things:
1/ You shared your (test mode) secret key in your code snippet, please delete that and roll your API keys (https://stripe.com/docs/keys#keeping-your-keys-safe).
2/ Your iOS/Android apps should not be making requests to Stripe's APIs directly with your secret API key, as that means you are bundling your secret key with your apps which means anyone running your app has access to your secret key.
Instead, you need to make requests from your iOS app to your server and your server should use Stripe's server-side libraries to make requests to Stripe's APIs. Your iOS/Android apps can only make requests with your publishable key.
3/ The PaymentIntent endpoint supports both POST and GET. You can create a PaymentIntent by POSTing to the /v1/payment_intents endpoint, you retrieve a single PaymentIntent with a GET to the /v1/payment_intents/:id endpoint and you list PaymentIntents with a GET to the /v1/payment_intents endpoint.
4/ The error in your POST request shows "Missing required param: amount." so you need to debug your code to make sure the amount parameter is getting through. You can use Stripe's Dashboard Logs page https://dashboard.stripe.com/test/logs to debug what parameters your code is sending to Stripe's API.
Finally, I found a solution. The issue occurred because I am send parameters without encoding.
I found a solution from this link
https://stackoverflow.com/a/58254052/9158543.
let config = {
method: 'post',
url: 'https://api.stripe.com/v1/payment_intents',
headers: {
Authorization:
'Bearer sk_test_51J3PfGLTjj',
'Content-Type': 'application/x-www-form-urlencoded'
}
};
let paymentDetail = {
customer: 'cus_MSiYLjtdaJPiCW',
currency: 'USD',
amount: 100,
'automatic_payment_methods[enabled]': true
};
let formBody: any = [];
for (let property in paymentDetail) {
let encodedKey = encodeURIComponent(property);
let encodedValue = encodeURIComponent(paymentDetail[property]);
formBody.push(encodedKey + '=' + encodedValue);
}
formBody = formBody.join('&');
const result = await axios
.post('https://api.stripe.com/v1/payment_intents', formBody, {
headers: config.headers
})
.then(function (response) {
console.info(JSON.stringify(response));
})
.catch(function (error) {
console.error('-----', error.response);
});
I am developing a newsletter pop-up using nuxtJS and vuetify.
The process is simple: you enter you email adresse, mailchimp to the rest.
I am having an issue with Mailchimp API.
When I test the API using postman with the same setup, it works fine without any problems. (I can verify by checking the mailchimp account).
But when I try to subscribe through the pop-up, I recieve this error:
Error recieved
This my function code:
let data = {
"email_address": payload,
"status": "subscribed",
"merge_fields": {
"FIRSTNAME": "",
"LASTNAME": ""
}
}
const base64ApiKey = Buffer.from(`c18ab83bd3e9032e080d49f526285039-us6`).toString("base64");
// const base64ApiKey = "c18ab83bd3e9032e080d49f526285039-us6";
this.$axios.post("https://us6.api.mailchimp.com/3.0/lists/c3a3dea1fc/members/", data, {
method: 'POST',
mode: 'no-cors',
headers: {
"Access-Control-Allow-Headers": "Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length",
"Content-Type": "application/json",
Authorization: `auth ${base64ApiKey}`,
"Access-Control-Allow-Origin": "*",
},
withCredentials: true,
credentials: 'include',
// proxyHeaders: false,
// credentials: false
}).then(res => {
console.log(res.data);
}).catch(err => {
console.log(err);
});
}
It's obviously a CORS problem, I tried on another machine and still have the same error.
A CORS issue is not to be setup on the front-end but rather on the backend/dashboard panel of the service.
So, there is probably a way to whitelist your localhost and production URL on the Mailchip dashboard.
Try to Google this out to find a guide.
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.
I'm working inside of a Google Chrome extension and I would like to use Google's Client API, https://apis.google.com/js/client.js, to retrieve a user's Google+ ID.
I've supplied the following values in my manifest.json:
"oauth2": {
"client_id": "[CLIENT ID].apps.googleusercontent.com",
"scopes": [
"https://www.googleapis.com/auth/plus.login",
"https://www.googleapis.com/auth/plus.me"
]
}
Providing these values allows me to successfully call chrome.identity.getAuthToken: http://developer.chrome.com/apps/identity.html
getAuthToken: function () {
chrome.identity.getAuthToken({
interactive: false
}, function (authToken) {
if (chrome.runtime.lastError) {
// User isn't signed into Google Chrome.
console.error(chrome.runtime.lastError.message);
}
});
}
Once I have an auth token, I'm able to issue an AJAX request and successfully get my info:
$.ajax({
url: 'https://www.googleapis.com/plus/v1/people/me',
headers: {
'Authorization': 'Bearer ' + authToken
},
success: function (response) {
console.log("Received user info", response);
},
error: function (error) {
console.error(error);
}
});
None of this uses the aforementioned Google Client API, though. It would be nice to leverage that instead, but I'm wondering if it is not meant for Google Chrome extensions. I'm able to at least get things sort of working like so:
GoogleAPI.auth.authorize({
client_id: '[CLIENT ID].apps.googleusercontent.com',
scope: 'https://www.googleapis.com/auth/plus.login https://www.googleapis.com/auth/plus.me',
// Set immediate to false if authResult returns null
immediate: true
}, function(){
GoogleAPI.client.load('plus', 'v1', function () {
var request = GoogleAPI.client.plus.people.get({
'userId': 'me'
});
request.execute(function (response) {
console.log("Response:", response);
});
});
But I've already specified these values in my manifest -- so it seems a bit odd to re-refrence them. I could load my manifest and parse it, but I've already got something successfully working above.
Additionally, you have to call GoogleAPI.client.setApiKey to use Google's stuff. This works on a development environment because I am able to whitelist my machine's IP, but this would not work in a production environment as there will be many clients connecting.
So, should Google's Client API not be used within Google Chrome extensions?