body = {
"sender_batch_header": {
"recipient_type": "EMAIL",
"email_message": "SDK payouts test txn",
"note": "Enjoy your Payout!!",
"sender_batch_id": "Test_SDK_1",
"email_subject": "This is a test transaction from SDK"
},
"items": [{
"note": "Your " + str(form.nbr_athena.data) + "€ Payout!",
"amount": {
"currency": "EUR",
"value": str(form.nbr_athena.data)
},
"receiver": str(form.email_paypal.data),
"sender_item_id": "Test_txn_5"
}]
}
request_paypal = PayoutsPostRequest()
request_paypal.request_body(body)
# Call API with your client and get a response for your call
response = sdk_paypal_client.execute(request)
# If call returns body in response, you can get the deserialized version from the result attribute of the response
batch_id = response.result.batch_header.payout_batch_id
print(batch_id)
print(response)
flash("votre monnaie à bien était envoyé !!", "success")
payment.status = Status.Success.value
db.session.add(payment)
db.session.commit()
I tried to integrate the paypal sdk on my site, but when sending the request with this line response = sdk_paypal_client.execute (request)
I receive a deep copy error
TypeError: cannot serialize '_io.BufferedReader' object i tried stringify my request but it's not good
Related
I am trying to get some data from a payload using a webhook, in the response that I sent along side I added the meta data that should return with the payload and this is how I did it (code below), if you take a close look at the keys, there I one called meta, now I am trying to get some of the data that is in the meta from my webhook view like this:
views.py webhook
#csrf_exempt
#require_http_methods(['POST', 'GET'])
def webhook(request):
payload = request.body
order_id = payload['meta']['order_id']
print(order_id)
return HttpResponse("testing...")
Sending the reponse to the payment gateway
#csrf_exempt
def process_payment(request, name, email, amount, order_id):
auth_token = "FLWSECK_TEST-9efb9ee17d8afe40c6c890294a1163de-X"
hed = {'Authorization': 'Bearer ' + auth_token}
data = {
"tx_ref":''+str(math.floor(1000000 + random.random()*9000000)),
"amount":amount,
"currency":"USD",
"order_id":order_id,
"redirect_url":f"http://localhost:3000/service-detail/booking/confirmation/{order_id}",
"payment_options":"card",
"meta":{
"order_id":order_id,
"consumer_id":23,
"consumer_mac":"92a3-912ba-1192a"
},
"customer":{
"email":email,
"name":name,
"order_id":order_id
},
"customizations":{
"title":"ForecastFaceoff",
"description":"Leading Political Betting Platform",
"logo":"https://i.im.ge/2022/08/03m/FELzix.stridearn-high-quality-logo-circle.jpg"
}
}
url = ' https://api.flutterwave.com/v3/payments'
response = requests.post(url, json=data, headers=hed)
response=response.json()
link=response['data']['link']
return redirect(link)
payload
{
"event": "charge.completed",
"data": {
"id": 4136234873,
"tx_ref": "6473247093",
"flw_ref": "FLW-MOCK-b33e86ab2342316fec664110e8eb842a3c2f956",
"device_fingerprint": "df38c8854324598c54e16feacc65348a5e446",
"amount": 152,
"currency": "USD",
"charged_amount": 152,
"app_fee": 5.78,
"merchant_fee": 0,
"processor_response": "Approved. Successful",
"auth_model": "VBVSECUREertrCODE",
"ip": "52.209.154.143",
"narration": "CARD Transaction ",
"status": "successful",
"payment_type": "card",
"created_at": "2023-02-06T11:19:45.000Z",
"account_id": 685622,
"customer": {
"id": 1970338,
"name": "destiny ",
"phone_number": null,
"email": "******#gmail.com",
"created_at": "2023-02-06T11:19:45.000Z"
},
"card": {
"first_6digits": "653188",
"last_4digits": "2340",
"issuer": "MASTERCARD CREDIT",
"country": "NG",
"type": "MASTERCARD",
"expiry": "49/32"
}
},
"event.type": "CARD_TRANSACTION"
}
The metadata is not even showing in the payload, must it show up there in the payload before I can grab the data that is sent with it?
request.body is byte not a dict, so you need to load the string as JSON.
payload = json.loads(request.body)
The meta data is not in the payload dictionary. At first try to extract the data key from the payload like this:
#csrf_exempt
#require_http_methods(['POST', 'GET'])
def webhook(request):
payload = json.loads(request.body.decode("utf-8"))
data = payload.get("data")
if data:
order_id = data.get("meta", {}).get("order_id")
print(order_id)
return HttpResponse("just testing")
Edit:
The error message
as you described above in comment JSONDecodeError: Expecting value: line 1 column 1 (char 0) indicates that json.loads() is expecting a JSON string as input.
It may be possible that request body is empty. You can check that by printing the request.body before calling json.loads().
Try this:
#csrf_exempt
#require_http_methods(['POST', 'GET'])
def webhook(request):
payload = json.loads(request.body.decode("utf-8"))
data = payload.get("data")
if data and "meta" in data:
order_id = data.get("meta").get("order_id")
print(order_id)
else:
print("Meta key not found in data or data not found in payload")
print(payload)
return HttpResponse("just testing")
It would tell you whether the "meta" is present in data dictionary or not and also prints payload dict at the end.
I was trying to build a python request module passing API tokens, however I am running into below issue every time. Sharing my entire code :
import requests
import json
def bitbucketFunction():
variables = {"test":"1234"}
callBitBucketAPI(variables)
def callBitBucketAPI(variables):
try:
headers = {
'Content-Type': 'application/json'
}
url = "https:xyz/pipelines/"
data = {
"target": {
"type": "pipeline_ref_target",
"ref_type": "branch",
"ref_name": "master",
"selector": {
"type": "custom",
"pattern": "create-aws-account"
}
},"variables":json.dumps(variables, indent=2)}
response = requests.request("POST",url, auth=('token-key', 'token-value'), data=json.dumps(data),headers=headers)
print(response.text)
except Exception as e:
print("Exception occured in callBitBucketAPI method: ", e)
bitbucketFunction()
Error:
{"error": {"message": "An invalid field was found in the JSON payload.", "fields": ["variables"], "detail": "Can not deserialize instance of io.vavr.collection.Seq out of VALUE_STRING token\n at [Source: (org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$UnCloseableInputStream); line: 1, column: 167] (through reference chain: com.atlassian.pipelines.rest.model.v1.pipeline.ImmutablePipelineModel$Builder[\"variables\"])", "data": {"key": "rest-service.request.invalid-json"}}}
I want to use the Microsoft Graph API to send messages with attachments to chats or channels.
https://learn.microsoft.com/en-us/graph/api/chatmessage-post?view=graph-rest-1.0&tabs=http#example-4-send-a-message-with-file-attachment-in-it
I can send normal messages already just fine like this:
def post_message(chat_id: str, subject: str = "", content_type: str = "text", content: str = "") -> None:
url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
json = {
"subject": subject,
"body": {
"contentType": content_type,
"content": content
}
}
res = requests.post(url, headers=header, json=json)
I try to copy the body from the example in the link above, substitute for my values and swap json variable for this one:
attachment_id = '7QW90B10D7-B5AK-420A-AC78-1156324A54F2' # not real, only to show how it looks like
json = {
"body": {
"contentType": 'html',
"content": f'i dunno what i\'m doing. <attachment id="{attachment_id}"></attachment>'
},
'attachments': [
{
'id': attachment_id,
'contentType': 'reference',
'contentUrl': 'https://foo.sharepoint.com/sites/bar/User%20documentation/Databricks/Databricks%20guide.pptx',
'name': 'Databricks guide.pptx'
}
]
}
I get requests.exceptions.HTTPError: 400 Client Error: Bad Request for url
What's wrong with the code? How to get attachment id from a file correctly because I am not sure I got the right value?
I was able to get it working with your code, (using both formats <attachment id=\"\"> and <attachment id="">), so it seems the error is probably with your attachment_id.
I retrieved the driveItem ID by following this answer, where the driveItem ID is the GUID value in the eTag property in the response.
You could get the file by the path:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/{item-path}
For example:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/test.docx
If the file is in a folder, it would be like this:
https://graph.microsoft.com/v1.0/sites/{site-id}/drive/root:/folder1/test.docx
Sample request after obtaining the ID
access_token = ""
attachment_name = "file.txt"
attachment_path = "https://domain.sharepoint.com/Shared%20Documents"
attachment_id = "12345678-1234-1234-1234-123456789123"
attachment_url = f"{attachment_path}/{attachment_name}"
chat_id = ""
req_url = f"https://graph.microsoft.com/v1.0/chats/{chat_id}/messages"
req_headers = {
"Authorization": "Bearer " + access_token,
"Content-Type": "application/json"
}
json = {
"body": {
"contentType": "html",
"content": f"Test message <attachment id=\"{attachment_id}\"></attachment>"
},
"attachments": [
{
"id": attachment_id,
"contentType": "reference",
"contentUrl": attachment_url,
"name": attachment_name
}
]
}
result = requests.post(url = req_url, headers = req_headers, json = json)
I am trying to add a new contact in Xero using python FASTAPI:
define a new contact
contact = {
"Contacts": [
{
"Name": "24 locks",
"FirstName": "Ben",
"LastName": "Bowden",
"EmailAddress": "ben.bowden#24locks.com",
"ContactPersons": [
{
"FirstName": "John",
"LastName": "Smith",
"EmailAddress": "john.smith#24locks.com",
"IncludeInEmails": "true"
}
]
}
]
}
Call xero API
get_url = 'https://api.xero.com/api.xro/2.0/Contacts'
response = requests.post(get_url,
headers = {
'Authorization': 'Bearer ' + access_token,
'Xero-tenant-id': xero_tenant_id,
'Accept': 'application/json'
},
data = contact
)
json_response = response.json()
I get the following error:
{'ErrorNumber': 17, 'Type': 'NoDataProcessedException', 'Message': 'No data has been processed for this endpoint. This endpoint is expecting Contact data to be specifed in the request body.'}
Someone can help please ?
You can assume that access_token and xero_tenant_id are correct as I am using them for other methods and they works fine.
Thanks
Try to use json = contact instead of data = contact or set header 'Content-Type': 'application/json'
Because
data for dict When not specified content-type, The default is application/x-www-form-urlencoded,
I'm running the code below and it takes the user to PayPal to make a payment and then returns them to the return_url as expected. However the code doesn't execute any further and it doesn't execute the payment.
I have based my code on https://github.com/paypal/rest-api-sdk-python:
class PayPalHandler(tornado.web.RequestHandler):
def get(self):
logging.basicConfig(level=logging.INFO)
paypal.configure({
"mode": PAYPAL_MODE,
"client_id": PAYPAL_CLIENT_ID,
"client_secret": PAYPAL_CLIENT_SECRET})
payment = paypal.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal" },
"redirect_urls": {
"return_url": "http://127.0.0.1:8000/ty",
"cancel_url": "http://127.0.0.1:8000/" },
"transactions": [ {
"item_list": {
"items": [{
"name": "membership",
"price": "2.00",
"currency": "GBP",
"quantity": 1 }]},
"amount": {
"total": "2.00",
"currency": "GBP" },
"description": "One of membership fee." } ] } )
redirect_url = ""
if payment.create():
print("Payment[%s] created successfully"%(payment.id))
for link in payment.links:
if link.method == "REDIRECT":
redirect_url = link.href
print("Redirect for approval: %s"%(redirect_url))
return self.redirect(redirect_url)
else:
print("Error while creating payment.")
print(payment.error)
response = payment.to_dict()
print response
payment = paypal.Payment.find(payment.id)
if payment.execute({"payer_id": response['payer_id']}):
print ("Payment executed successfully")
else:
print(payment.error) # Error Hash
print payment.to_dict()
print userData
So in the example at https://devtools-paypal.com/guide/pay_paypal/python?success=true&token=EC-8JL96732FP068791F&PayerID=QQGSRNHDACTLJ. Step 5 is not happening and no response is sent from PayPal?
This is Avi from PayPal here. I am not super familiar with Tornado, but after the line return self.redirect(redirect_url) happens in your code, and returns the user to the return_url, in payment.execute({"payer_id": response['payer_id']}) are you getting the payer_id correctly? Payer_id is returned appended to the return_url as one of the parameters in the format http://<return_url>?token=EC-60U79048BN7719609&PayerID=7E7MGXCWTTKK2. Also, what is the status of the payment after you execute payment = paypal.Payment.find(payment.id). The other suggestion I would have is to see if print payment.error prints a useful debug message and a debug_id which paypal merchant technical services can use to look at the issue.
You need other url where papypal redirects when the payment had been successful, where you will receive the token and the PayerID. In that GET method, you can put this part of the code (pseudocode):
payerid_param = request.get('PayerID')
payment = paypal.Payment.find(db_payment.id)
if payment.execute({"payer_id": payerid_param}):
print ("Payment executed successfully")
else:
print(payment.error) # Error Hash
You will need to save the payment_id between calls.
Why you use
return self.redirect(redirect_url)
I think you can use just
self.redirect(redirect_url)
I've never seen return statement in Tornado handlers.