I'm getting 'InvalidRegistration' error when I try to send a push notification to my Android device.
Header:
headers = {
'Content-Type': 'application/json',
'Authorization': 'key=' + serverToken,
{
Body:
body = {
"to": deviceToken,
"notification": {
"body": "Welcome to blabla",
"title": "Blabla trully loves you, did you know that?",
"priority": "high"
}
Response:
200
{'multicast_id': 6053848281333651847, 'success': 0, 'failure': 1, 'canonical_ids': 0, 'results': [{'error': 'NotRegistered'}]}
The idea is that I'm using Appium method driver.get_clipboard_text() to get a token which is already copied in device clipboard and store it in the following variable:
deviceToken = self.driver.get_clipboard_text()
Which I pass it to my JSON. Also, if I manually store the token in my variable it will successfully work and get the push notification on my device.
I've tried to use several formatting python types by using another variable where i store a previous one where I do call that method I mentioned from Appium, but without success.
Any thoughts?
Related
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!
I'm having trouble using the PUT method in Python. I'm trying to force a specific device to play a track on Spotify using the PUT method as described in their website https://developer.spotify.com/documentation/web-api/reference/#endpoint-start-a-users-playback to start/resume the player.
I have managed to acquire a token and used the GET method successfully with the requests library, but I'm having trouble writing a PUT command.
This is what I currently am using, but I keep getting a 400 error:
url = "https://api.spotify.com/v1/me/player/play"
payload = {"id": "f103fb953eadfb10ed89f8df3fee40be26e354ac"}
headers = {
'Content-Type': 'application/json',
'Authorization': 'Bearer %s' % (access_token) # paste your access token in here
}
dat= {
"context_uri": "spotify:album:5ht7ItJgpBH7W6vJ5BqpPr",
"offset": {
"position": 5
},
"position_ms": 0
}
response = requests.request("PUT", url, headers=headers, params = payload,data=dat)
print(response.status_code) # should print out 200 when you run the code
# shows whether status was valid
I'm trying to convert this Kibana query to Python:
PUT /.kibana/_doc/index-pattern:tempindex
{
"type": "index-pattern",
"index-pattern": {
"title": "tempindex",
"timeFieldName": "sendTime"
}
}
This is what I have so far:
HEADERS = {
'Content-Type': 'application/json'
}
uri = "http://localhost:5601/_doc/index-pattern:tempindex"
query = json.dumps({
"type": "index-pattern",
"index-pattern": {
"title": "tempindex",
"timeFieldName": "sendTime"
}
})
r = requests.put(uri, headers=HEADERS, data=query).json()
print(r)
But it gives me
{'statusCode': 404, 'error': 'Not Found', 'message': 'Not Found'}
What am I doing wrong?
P.S: Both Elastic and Kibana servers are local (Windows 10).
Seems that just changing the uri does the trick:
uri = "http://localhost:9200/.kibana/_doc/index-pattern:tempindex"
But I'm not sure about the HEADERS, cuz as lupanoide pointed out, kbn-xsrf: true should be present, but either way it seems to be working and apparently the results are the same (I haven't spotted a difference yet).
Edit: As the doc says:
kbn-xsrf: true
By default, you must use kbn-xsrf for all API calls, except in the
following scenarios:
The API endpoint uses the GET or HEAD operations
The path is whitelisted using the server.xsrf.whitelist setting
XSRF protections are disabled using the server.xsrf.disableProtection setting
So I think it should be present.
I'm trying to integrate Vantiv payment gateway using python language.
But when I request on URL https://w1.mercurycert.net/PaymentsAPI/Credit/Sale with the provided test credentials merchant id: 755847002 and password: xyz it still gives me an error message like:
Unauthorized: Access is denied due to invalid credentials.
I am passing JSON data as provided in the documentation:
card_data = {
"InvoiceNo": "1",
"RefNo": "1",
"Memo": "MPS Example JSON v1.0",
"Purchase": "1.00",
"Frequency": "OneTime",
"RecordNo": "RecordNumberRequested",
"TerminalName": "MPS Terminal",
"ShiftID": "MPS Shift",
"OperatorID": "MPS Operator",
"AcctNo": "4003000123456781",
"ExpDate": "0517",
"Address": "4 Corporate Square",
"Zip": "30329",
"CVVData": "880",
}
headers = {
'Authorization': 'Basic [Wzc1NTg0NzAwMV06W3h5el0=]',
'Content-Type': 'application/json',
}
payment = requests.post(
'https://w1.mercurycert.net/PaymentsAPI/Credit/Sale',
headers=headers,
data=card_data)
When I look at the response variable payment, it still shows that error message.
Can anyone help me on how to overcome this?
Actually, All I needed was to encode "Authorization" header and it worked.
I was using this API at wrong place, API that I used (RESP API) can be used with scanner devices only which can encode data. Instead I needed to use Hosted Checkout API and it worked for me.
I am trying to use Outlook's REST API in my python code to send an email in behalf of a user who already gives me his consent.
I was able to successfully send text emails using their /me/sendmail node with the following payload:
email_payload = {
"Message": {
"Subject": email_subject,
"Body": {
"ContentType": "Text",
"Content": email_body
},
"ToRecipients": [
{
"EmailAddress": {
"Address": to
}
}
]
}
}
However, when trying to add attachments (based on their documentation), I encounter some issues:
email_payload["Message"]["Attachments"] = [
{
"ContentType": "application/pdf",
"Name": "{0}".format("something.pdf"),
"ContentBytes": base64.b64encode(attachment.read())
}
]
Issues consist in 415 response status code with the following content:
{u'error': {u'message': u'A missing or empty content type header was found when trying to read a message. The content type header is required.', u'code': u'RequestBodyRead'}}
Couldn't find anything regarding this in their documentation. Hope somebody can enlighten me :)
For anyone else having such issues, here's the context and fix:
Initially, since I was sending only plain-text emails, my request header looked like this:
request_headers = {
'Authorization': "Bearer {0}".format(token),
}
And the actual request:
api_response = requests.post(
request_url,
json.dumps(body),
headers=request_headers
)
As you might have noticed I wasn't sending any content-type in my headers (not sure why), but everything went well so far up until when I decided to add attachments too.
Seems like if my request_headers would contain Content-Type too, everything would go well:
request_headers = {
'Authorization': 'Bearer {0}'.format(refreshed_token),
'Content-Type': 'application/json'
}