FCM push notifications not working in AWS Lambda using Python - python

I didn't find any questions that solved my issue, hence below:
This is the code I am using to send an FCM push notification via AWS Lambda written in Python. The AWS code is deployed on Lambda using the Zappa package:
# SENDING FCM NOTIFICATION
notification_headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
}
body_en = {
'notification': {
'title': post['src'],
'body': post['title'],
'click_action': 'FLUTTER_NOTIFICATION_CLICK',
'sound': 'default'
},
'to': deviceToken,
'priority': 'high',
'content_available': 'true',
}
response_en = requests.post(
"https://fcm.googleapis.com/fcm/send",
headers = notification_headers,
data = json.dumps(body_en)
)
return response_en
Are there any imports I must do before being able to use FCM in AWS Lambda?

Related

APNS Notifications: Python HTTP/2 POST request returning 404 ({"reason":"BadPath"})

I am developing a watchOS app and I want to send push notifications to my users. I have enabled "Push Notifications" in signing and capabilities and a file called "app_name WatchKit Extension" was generated containing one entitlement called APS environment whose value is set to "development".
I have also generated a .p8 file in the Apple Developer Website with the authentication key and that also gives me the key id.
I have created a Swift class called App Delegate that conforms to UNUserNotificationCenterDelegate. I have implemented the method applicationDidFinishLaunching from where I call WKExtension.shared().registerForRemoteNotifications(). Then I implemented the didRegisterForRemoteNotifications where I receive the device token and convert it into a string by executing these lines of code:
let tokenParts = deviceToken.map { data in String(format: "%02.2hhx", data) }
let token = tokenParts.joined()
Then I send the token to the server. In the server I have a Python script that makes the post request to https://api.sandbox.push.apple.com:443 with the headers and notification payload. However, I always get a 404 error ({"reason":"BadPath"}).
I don't know what I am doing wrong. Am I configuring anything wrong? This is the Python script I am using:
import time
import httpx
import asyncio
import jwt
ALGORITHM = 'ES256'
APNS_AUTH_KEY = "path to .p8 file"
f = open(APNS_AUTH_KEY)
secret = f.read()
apns_token = jwt.encode(
{
'iss': 'cert_id',
'iat': time.time()
},
secret,
algorithm=ALGORITHM,
headers={
'alg':ALGORITHM,
'kid':'key_id'
}
)
dev_server = "https://api.sandbox.push.apple.com:443"
device_token = "9fe2814b6586bbb683b1a3efabdbe1ddd7c6918f51a3b83e90fce038dc058550"
headers = {
'method': 'POST',
'path': '/3/device/{0}'.format(device_token),
'autorization': 'bearer {0}'.format(apns_token),
'apns-push-type': 'myCategory',
'apns-expiration': '0',
'apns-priority': '10',
}
payload = {
"aps" : {
"alert" : {
"title" : "Hello Push",
"message": "This is a notification!"
},
"category": "myCategory"
}
}
async def test():
async with httpx.AsyncClient(http2=True) as client:
client = httpx.AsyncClient(http2=True)
r = await client.post(dev_server, headers=headers, data=payload)
print(r.text)
print(r)
asyncio.run(test())
Is there anything wrong with the way I am setting things up or performing the post request?
Thank you for your help!

Xero API not working for Accounts in python

I am trying to call xero Accounts api in python but not working for some reason. It works well for the rest of APIs such as Invoices, reports, and so on, but Accounts.
The following script is my python script i am using to call the api.
get_url = 'https://api.xero.com/api.xro/2.0/Accounts'
response = requests.get(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
})
json_response = response.json()
print(json_response)
But this is throwing the following error:
{'Type': None, 'Title': 'Unauthorized', 'Status': 401, 'Detail': 'AuthorizationUnsuccessful', 'Instance': '3c1649ef-6eed-4e64-8503-04fc99481db2', 'Extensions': {}}
Can anyone tell me why this is happening? why just Accounts?
Can you share what scopes you're requesting? https://developer.xero.com/documentation/oauth2/scopes
Invoices requires accounting.transactions
Reports requires accounting.reports.read
Accounts requires accounting.settings

Two distinc response from same AWS Lambda in Api Gatway and Postman

I have this simple Lambda
def lambda_handler(event, context):
# TODO implement
message = {
'statusCode': 200,
'headers': { 'Content-Type': 'application/json' },
'body': json.dumps({ 'username': 'bob', 'id': 200 })
}
return message
I couple it with a Api Gateway
I was having dificulties to confiure permissions o I created more than one api enpoint resources.
As far as I know, both resources are identical.
However when I call them from Postman they return difent results:
/activation returns
{
"statusCode": 200,
"headers": {
"Content-Type": "application/json"
},
"body": "{\"username\": \"bob murrey\", \"id\": 200}"
}
and /myPythonLambda
{
"username": "bob murrey",
"id": 200
}
I canĀ“t find any configurantion that I could change that would explaing this difference.
Obviously you have done something different in API Gateway for each endpoint.
From looking at the two different responses, it appears you have ticked the Proxy integration in Method Request for the myPythonLambda endpoint.

How to upload a file to onedrive as a specific user?

I am trying to upload files to a user OneDrive as that user.
I successfully registered my app and granted the correct permissions.
I am able to upload files to a user drive but only as application and not as the user.
I was able to do the same on google drive using google sdk which allow user impersonation.
I could not find any decent documentation on user impersonation for OneDrive.
import requests
params = {
'grant_type':'client_credentials',
'client_id': 'xxx',
'client_secret': 'yyy',
'resource':'https://graph.microsoft.com'
}
r = requests.post('https://login.microsoftonline.com/{tenant-id}/oauth2/token', data=params, verify=False)
token = r.json()['access_token']
headers = {
'Authorization':token
}
fileHandle = open('somefile.txt', 'rb')
r = requests.put('https://graph.microsoft.com/v1.0/users/{user-id}/drive/items/root:/somefile.txt:/content',
headers=headers, data=fileHandle, verify=False)
fileHandle.close()
this is part of the response I get showing the file was created/modified by my application which make sense:
'createdBy': {
'application': {
'id': 'xxx',
'displayName': 'my_app'
}
},
'lastModifiedBy': {
'application': {
'id': 'xxx',
'displayName': 'my_app'
}
},
my goal is to have my app impersonate my users to create/modify the files.
Is this even supported with onedrive api?

How to send silent notification from server to ios devices?

This is my python script which sends the fcm notifications to the devices.
It sends priority notifications not silent notifications....
How can I silence them ?
def sendGCMToTopiciOS():
url = 'https://fcm.googleapis.com/fcm/send'
headers = {
'UserAgent': "GCM-Server",
'Content-Type': 'application/json',
'Authorization': 'key=' + 'XXXXXXXXXXXXXXXXXXXX',
}
data = {'title': 'Yugam', 'message': 'Hello Everyone', 'event': '13', 'workshop': '-1',
'link': 'https://www.google.com'}
notification = {
'body': data.get('message'),
'title': data.get('title')
}
values = {
'to': '/topics/' + 'global',
'data': data,
'notification': notification,
"aps":{
"content-available":1}
}
pipe = requests.post(url=url, json=values, headers=headers)
return pipe.json()
To send a data-message you need to skip the notification part of the json payload
The 'notification' field will cause iOS 10 to send your notifications to the system, automatically displaying notifications based on the given values. If you're looking for a completely silent notification try:
values = {
'to': '/topics/' + 'global',
'content_available': true
'priority': 'high',
'data': data
}
This will be delivered in the background without an alert. The 'content_available' field will also convert to 'content-available':1 after passing through the GCM server for APNS.

Categories

Resources