Rest API App working in 'Sandbox' but not 'Live' - python

For some reason My App is not working on live mode using PayPal REST API. This is the error I get on my Apache server:
[:error] [pid 29701] WARNING:root:Not logging full request/response headers and body in live mode for compliance
Here is my code, I'm using Django:
def payPaypal(sku, price, ship_code):
has_paypal_error = False
paypal_approval_url = None
paypalrestsdk.configure({
'mode': settings.PAYPAL_STATUS, # live
'client_id': settings.PAYPAL_LIVE_CLIENT_ID,
'client_secret': settings.PAYPAL_LIVE_CLIENT_SECRET
})
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "paypal" },
"redirect_urls": {
"return_url": "mysite_url/thanks",
"cancel_url": "mysite_url" },
"transactions": [ {
"amount": {
"total": price[ship_code].amount,
"currency": price[ship_code].currency },
"description": "my description.",
"item_list": {
"items": [ {
"name": "name description",
"sku": sku,
"quantity": "1",
"price": price[ship_code].amount,
"currency": price[ship_code].currency
}]
}
}]
})
if payment.create():
for link in payment.links:
if link.rel == "approval_url":
paypal_approval_url = link.href
else:
has_paypal_error = True
return has_paypal_error, paypal_approval_url
And inside my form:
elif cd['payment_type'] == "2": # PayPal
is_paypal = True
has_paypal_error, paypal_approval_url = payPaypal(sku, price, ship_code)
payment_error_msg = _('Something went wrong, please try again')
thanks.html
if request.method == 'GET' and request.GET.get('paymentId'):
paymentId = request.GET.get('paymentId')
payment = paypalrestsdk.Payment.find(paymentId)
payer_id = payment.payer.payer_info.payer_id
if payment.execute({"payer_id": payer_id}):
sendInvoiceEmailToUser(email_to_send_invoce, email_invoce_lang)
sendSuccessNotificationToCrew(email_crew)
return render(request, 'thanks.html')
Looking at the response going "live", it looks like the "approval_url" is correct:
[{'href': u'https://api.paypal.com/v1/payments/payment/PAY-######', 'method': u'GET', 'rel': u'self'},
{'href': u'https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout&token=EC-####', 'method': u'REDIRECT', 'rel': u'approval_url'},
{'href': u'https://api.paypal.com/v1/payments/payment/PAY-####/execute', 'method': u'POST', 'rel': u'execute'}]
Live APP Settings

I found the problem, and it had nothing to do with PayPal.
I forgot to add the paypal domains in the ALLOWED_HOSTS in my settings.py from my Django App
ALLOWED_HOSTS = [ 'mysite.com.', '.paypal.com', 'paypal.com.' ]

Related

Getting user in a app.view() handle method

I've have a modal for submitting ticket to trello, everything is working great but i need to output in slack a message to the user that his ticket is published.
In the slack api documentation (chapter 'Listening for view submissions') i can read :
# Handle a view_submission request
#app.view("view_1")
def handle_submission(ack, body, client, view, logger):
user = body["user"]["id"]
When i try the same I've got a KeyError: 'user'. Without that line the code work great but I need the user to know that his ticket is published on Trello and provide him the link (and other informations)
EDIT : I've printed the body dict content and nothing about the user :
{
"id":"XXXXXXXXX",
"team_id":"XXXXXXXXX",
"type":"modal",
"private_metadata":"",
"callback_id":"ticket_submission",
"state":{
"values":{
"block_type":{
"type":{
"type":"static_select",
"selected_option":{
"text":{
"type":"plain_text",
"text":"Feature",
"emoji":true
},
"value":"feature"
}
}
},
"block_priority":{
"priority":{
"type":"static_select",
"selected_option":{
"text":{
"type":"plain_text",
"text":"Critical",
"emoji":true
},
"value":"critical"
}
}
},
"block_description":{
"description":{
"type":"plain_text_input",
"value":"This is the description"
}
},
}
},
"hash":"1674058454.YvY8jNKh",
"title":{
"type":"plain_text",
"text":"Create Ticket",
"emoji":true
},
"clear_on_close":false,
"notify_on_close":false,
"close":{
"type":"plain_text",
"text":"Cancel",
"emoji":true
},
"submit":{
"type":"plain_text",
"text":"Submit",
"emoji":true
},
"previous_view_id":"None",
"root_view_id":"XXXXXXXXX",
"app_id":"XXXXXXXXX",
"external_id":"",
"app_installed_team_id":"XXXXXXXXX",
"bot_id":"XXXXXXXXX"
}

How would I get my response to the Google Assistant via Dialogflow, Actions SDK, Python, etc

I am trying to get my reply to the Google assistant as a string to search it through a Google spreadsheet and return additional information about it. Specifically, I have a Google spreadsheet with two columns, one being for the name of a thing, and another for my rating of it. I'm using ngrok and Flask to get my script's response online. The two parts I'm struggling with are...
(1) Getting my requested thing into the program.
(2) Switching the url of the webhook and/or changing the webhook so that the system can output the final result.
I am a beginner so I'm probably misusing a few terms here but anyways my code is below. I put a bunch of underscores in the places where I thought sensitive information was.
action.json >>
"actions": [
{
"description": "Welcome Intent",
"name": "MAIN",
"fulfillment": {
"conversationName": "jdii ratings"
},
"intent": {
"name": "actions.intent.MAIN",
"trigger": {
"queryPatterns": [
"What did I rate $Test:text",
"Look up $Test:text on my ratings spreadsheet"
]
},
"parameters": [
{
"name": "text",
"type": "Test"
}
]
}
}
],
"conversations": {
"jdii ratings": {
"name": "jdii ratings",
"url": "<_________>",
"fulfillmentApiVersion": 2
}
}
}
program.py >>
import random
import types
import gspread
from flask import Flask
from google.cloud import dialogflow_v2
from oauth2client.service_account import ServiceAccountCredentials
app = Flask(__name__)
wanted_thingy = "Squirt"
def get_requested_thingy_rating(requested_thingy_name):
scopes = [
'https://www.googleapis.com/auth/spreadsheets',
'https://www.googleapis.com/auth/drive'
]
credentials = ServiceAccountCredentials.from_json_keyfile_name("_______.json", scopes)
file = gspread.authorize(credentials)
sheet = file.open("JDII Ratings API")
requested_thingy_rating_final = 0.0
if not isinstance(requested_thingy_name, types.NoneType):
sheet = sheet.sheet1
thingy_list = sheet.col_values(1)
ratings_list = sheet.col_values(2)
requested_thingy_rating = 0.0
if requested_thingy_name in thingy_list:
thingy_pos = thingy_list.index(requested_thingy_name)
requested_thingy_rating = ratings_list[thingy_pos]
requested_thingy_rating_final = str(requested_thingy_rating)
# split_string = ready_string.split('\'')
# requested_thingy_rating_final = split_string[1]
print(requested_thingy_rating_final)
return requested_thingy_rating_final
#app.route("/start", methods=['POST', 'GET', 'PUT'])
def main():
response = {
"expectUserResponse": True,
"expectedInputs": [
{
"inputPrompt": {
"richInitialPrompt": {
"items": [
{
"simpleResponse": {
"textToSpeech": "What would you like to look up?",
"displayText": "What would you like to look up?"
}
}
]
}
},
"possibleIntents": [
{
"intent": "actions.intent.TEXT"
}
]
}
]
}
response_text = json.dumps(response)
return response_text
#app.route("/webhook", methods=['POST', 'GET', 'PUT'])
def main2():
global wanted_thingy
wanted_thingy_final = str(wanted_thingy)
wanted_thingy_rating = get_requested_thingy_rating(wanted_thingy_final)
print(wanted_thingy)
string = f"You rated {wanted_thingy} a {wanted_thingy_rating} out of ten."
response2 = {
"expectUserResponse": False,
"finalResponse": {
"richResponse": {
"items": [
{
"simpleResponse": {
'ssml': f'<speak>{string}</speak>'
}
}
]
}
}
}
response_text = json.dumps(response2)
return response_text
app.run()

PayPal credit card payment does not execute

I am using the PayPal Sandbox account. Python SDK PayPal-Python-SDK
I have successfully created a payment using credit card vaults (credit/debit cards) but unable to execute the payment getting error.
card = Card.objects.get(id = request.data['cardId'])
paypalrestsdk.configure({
"mode": settings.PAYPAL_MODE, # sandbox or live
"client_id": settings.PAYPAL_CLIENT_ID,
"client_secret": settings.PAYPAL_CLIENT_SECRET
})
payment = paypalrestsdk.Payment({
"intent": "sale",
"payer": {
"payment_method": "credit_card",
"funding_instruments": [{
"credit_card_token": {
"credit_card_id": card.token,
}
}]
},
"transactions": [{
"amount": {
"total": float(request.data['amount']),
"currency": "USD"
},
"description": "Payment by vaulted credit card."
}]
})
if payment.create():
print(payment.id)
print("Payment created successfully")
# ID of the payment. This ID is provided when creating payment.
payment = paypalrestsdk.Payment.find(payment.id)
# PayerID is required to approve the payment(card token).
if payment.execute({"payer_id": card.token}): # return True or False (card.token : added card token - CARD-7K172274P2897384FLZJ3VCC)
print("Payment[%s] execute successfully" % (payment.id))
else:
print(payment.error)
else:
print(payment.error)
the error I am getting :
Failed. Response status: 404. Response message: Not Found. Error message: {\"name\":\"INVALID_RESOURCE_ID\",\"message\":\"Requested resource ID was not found.\",\"information_link\":\"https://developer.paypal.com/docs/api/payments/#errors\",\"debug_id\":\"be43810866322\"}

Facebook Messenger bot Generic Template Not Working

I have created a Facebook Messenger bot which works fine. I have used the Button Template and Image template, and both work perfectly. But when I try the Generic Template, I get no response. I have simply copy pasted the code from here, by performing the appropriate modifications.
I don't know how to debug. Facebook Messenger gives no output on the messaging box. I am currently running the app via Heroku.
Here is my code:
def send_message(token, recipient):
r = requests.post("https://graph.facebook.com/v2.6/me/messages",
params={"access_token": token},
data=json.dumps({
"recipient":{
"id":recipient
},
"message":{
"attachment":{
"type":"template",
"payload":{
"template_type":"generic",
"elements":[
{
"title":"Welcome to Peter\'s Hats",
"image_url":"http://www.godominion.com/content/images/feature-img-small-appliance-electronics.png",
"subtitle":"We\'ve got the right hat for everyone.",
"default_action": {
"type": "web_url",
"url": "https://peterssendreceiveapp.ngrok.io/view?item=103",
"messenger_extensions": true,
"webview_height_ratio": "tall",
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"
},
"buttons":[
{
"type":"web_url",
"url":"https://petersfancybrownhats.com",
"title":"View Website"
}
]
}
]
}
}
}
}),
headers={'Content-type': 'application/json'})
if r.status_code != requests.codes.ok:
print r.text
I would appreciate any help.
Thank you.
EDIT 1: SOLUTION
I got rid of the issue by commenting out:
"messenger_extensions": true,
and
"fallback_url": "https://peterssendreceiveapp.ngrok.io/"},
I'm sure this is not the correct method. But as I am creating a bot, without actual links, this works.
On the second button, "url":"https://petersfancybrownhats.com" is broken.
Try like this
firstly make a function
def function():
extra_data = {
"attachment": {
"type": "template",
"payload": {
"template_type": "generic",
"elements": [
{
"title": "Any Title",
"image_url": "https://mbtskoudsalg.com/images/road-clipart-journey-3.png",
"subtitle": "Subtitle.",
"buttons": [
{
"type": "web_url",
"title": "View",
"url": "**MAKE SURE TO WHITELIST THIS URL**", # URL
"messenger_extensions": "true",
"webview_height_ratio": "full"
}
]
}
]
}
}
}
# w_message = "Hi there! How may I help you?"
fb_message_template(extra_data["attachment"], "****RECIEVER ID****")
Make another function
import requests
# // Importing User Defined Modules // #
from get_environ_var import get_environ_var
# // Global vars // #
ACCESS_TOKEN = "FB_ACCESS_TOKEN"
def fb_message_template(extra_data, sender_id):
"""This function sends template message to facebook"""
data = {
'recipient': {'id': sender_id},
'message': {
"attachment": extra_data
}
}
qs = 'access_token=' + ACCESS_TOKEN
resp = requests.post('https://graph.facebook.com/v2.6/me/messages?' + qs, json=data)
print(resp.content)

Python/JSON - does order matter and why is this JSON post to a REST API failing?

I'm posting to the office 365 rest API and am creating the dump as per below:
def CreateEvent(auth, cal_id, subject, start_time, end_time, attendees, content):
create_url = 'https://outlook.office365.com/api/v1.0/me/calendars/{0}/events'.format(cal_id)
headers = {"Content-type": "application/json", "Accept": "application/json"}
data = {"Subject":"","Attendees": [],"End": {},"Start": {},"Body": {}}
data["Subject"] = subject
data["StartTimeZone"] = "GMT Standard Time"
data["Start"] = start_time
data["EndTimeZone"] = "GMT Standard Time"
data["End"] = end_time
data["Attendees"] = attendees
data["Body"]["ContentType"] = "Text"
data["Body"]["Content"] = content
content_data = json.dumps(data)
#return data
response = requests.post(create_url,data,headers=headers,auth=auth)
return response
This produces an unordered dump, which i believe shouldn't cause any issues?
however, when i post manually using Y i get a 201 and the event is created, when i post using the function which produces the below dump, i get a 400
y="""
{
"Subject": "TESTTTT",
"Body": {
"ContentType": "HTML",
"Content": "I think it will meet our requirements!"
},
"Start": "2016-12-02T11:30:00Z",
"StartTimeZone": "GMT Standard Time",
"End": "2016-12-02T11:45:00Z",
"EndTimeZone": "GMT Standard Time",
"Attendees": [
{
"EmailAddress": {
"Name": "Alex ",
"Address": "alex#test.com"
},
"Type": "Required"
}
]
}
"""
what my function returns and give a 400
{
'Body': {
'Content': 'test data',
'ContentType': 'Text'
},
'End': '2016-12-02T06:00:00Z',
'StartTimeZone': 'GMT Standard Time',
'EndTimeZone': 'GMT Standard Time',
'Start': '2016-12-02T02:00:00Z',
'Attendees': [{
'EmailAddress': {
'Name': 'Alex ',
'Address': 'alex#test.com'
},
'Type': 'Required'
}],
'Subject': 'Maintenance: test'
}
At a glance, I believe you just need to change
response = requests.post(create_url,data,headers=headers,auth=auth)
to
response = requests.post(create_url,content_data,headers=headers,auth=auth)
You were correct in calling the json.dumps() method to serialize the dictionary. Just pass that string to the server instead.

Categories