PayPal::SDK::REST::WebhookEvent.verify produces an invalid encoding error (rails) - ruby-on-rails-4

The Problem: force_encoding('UTF-8') produces an invalid encoding when trying to validate a paypal webhook event. The validate certificate part works fine. See image
Invalid encoding
Code
module Webhooks
class PaypalController < ApplicationController
skip_before_action :authorize_request
def hook
actual_signature = request.headers["Paypal-Transmission-Sig"]
auth_algo = request.headers["Paypal-Auth-Algo"]
auth_algo.sub!(/withRSA/i, "")
cert_url = request.headers["Paypal-Cert-Url"]
transmission_id = request.headers["Paypal-Transmission-Id"]
timestamp = request.headers["Paypal-Transmission-Time"]
webhook_id = "0PC33693PD324571U"
event_body = params["paypal"].to_json
valid = PayPal::SDK::REST::WebhookEvent.verify(transmission_id, timestamp, webhook_id, event_body, cert_url, actual_sig, auth_algo)
end
end
end
Variables
actual_signature = FQlzVbTx82BOOQMuvNEgldHHik0q0TQR0ZwrsGXCVZnJYbaFrDOrzTG1/cn0SCNDcQxEsu+hR7feu14jnHC452ACEyDqYk2IeOIjzo2RDZ5S9FMZJ56Kv7uMyLZDui16pUlB1MqZWzQVXYSR0O+hHW7pwzBoxR3YY0UOALmv0eMJ5aDK5YBJokCNkUJMpEhcPmkKGjAR1KqV6swS+2PMqxawfylPl2/I20agKjSDm7QsMXvaQZl7hm613n9s6yqBpsbzgESlvzo1Ri6VafznydJ82xpP0M+3iQLpcKzzPj3wDpzaDmR7r1zhg9Hd2eg037qDYoip6p5nCzm/c9klnQ==
auth_algo = SHA256
cert_url = https://api.sandbox.paypal.com/v1/notifications/certs/CERT-360caa42-fca2a594-1d93a270
transmission_id = 0c1badf0-4c1b-11ea-bda8-1d900e460095
timestamp = 2020-02-10T15:36:03Z
webhook_id = 0PC33693PD324571U
event_body = {"id":"WH-2YT23629NU5635806-66L81914W2515435K","event_version":"1.0","create_time":"2020-02-10T15:35:55.420Z","resource_type":"payment","event_type":"PAYMENTS.PAYMENT.CREATED","summary":"Checkout payment is created and approved by buyer","resource":{"update_time":"2020-02-10T15:35:55Z","create_time":"2020-02-10T15:35:14Z","redirect_urls":{"return_url":"http://localhost/payment/execute?paymentId=PAYID-LZAXQMY86E71517DB986120J","cancel_url":"http://localhost:3000/"},"links":[{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LZAXQMY86E71517DB986120J","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/payments/payment/PAYID-LZAXQMY86E71517DB986120J/execute","rel":"execute","method":"POST"},{"href":"https://www.sandbox.paypal.com/cgi-bin/webscr?cmd=_express-checkout\u0026token=EC-36U942266G8017214","rel":"approval_url","method":"REDIRECT"}],"id":"PAYID-LZAXQMY86E71517DB986120J","state":"created","transactions":[{"amount":{"total":"5.50","currency":"USD"},"payee":{"merchant_id":"P3DN8UTLQR3AY","email":"sb-ysww0997817#business.example.com"},"description":"Sale","item_list":{"shipping_address":{"recipient_name":"John Doe","line1":"1 Main St","city":"San Jose","state":"CA","postal_code":"95131","country_code":"US","default_address":false,"preferred_address":false,"primary_address":false,"disable_for_transaction":false}},"related_resources":[]}],"intent":"sale","payer":{"payment_method":"paypal","status":"VERIFIED","payer_info":{"email":"sb-d8kwi996334#personal.example.com","first_name":"John","last_name":"Doe","payer_id":"6WZKWRGAWJ9T6","shipping_address":{"recipient_name":"John Doe","line1":"1 Main St","city":"San Jose","state":"CA","postal_code":"95131","country_code":"US","default_address":false,"preferred_address":false,"primary_address":false,"disable_for_transaction":false},"country_code":"US"}},"cart":"36U942266G8017214"},"links":[{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2YT23629NU5635806-66L81914W2515435K","rel":"self","method":"GET"},{"href":"https://api.sandbox.paypal.com/v1/notifications/webhooks-events/WH-2YT23629NU5635806-66L81914W2515435K/resend","rel":"resend","method":"POST"}]}

Related

list indices must be integers or slices, not dict in django

I just want to iterate through the list of JSON data which I get in the payload but getting an error as list indices must be integers or slices, not dict
payload:
[{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":150,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"},{"AuditorId":10,"Agents":"sa","Supervisor":"sa","TicketId":"58742","QId":151,"Answer":"Yes","TypeSelected":"CMT Mails","Comments":"na","TicketType":"Regularticket","Action":"na","AuditSubFunction":"na","AuditRegion":"na"}]
views.py:
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = request.data[ran].get('AuditorId')
ticketid = request.data[ran].get('TicketId')
qid = request.data[ran].get('QId')
answer = request.data[ran].get('Answer')
sid = '0'
TicketType = request.data[ran].get('TicketType')
TypeSelected = request.data[ran].get('TypeSelected')
agents = request.data[ran].get('Agents')
supervisor = request.data[ran].get('Supervisor')
Comments = request.data[ran].get('Comments')
action = request.data[ran].get('Action')
subfunction = request.data[ran].get('AuditSubFunction')
region = request.data[ran].get('AuditRegion')
cursor = connection.cursor()
cursor.execute('EXEC [dbo].[sp_SaveAuditResponse] #auditorid=%s,#ticketid=%s,#qid=%s,#answer=%s,#sid=%s,#TicketType=%s,#TypeSelected=%s,#agents=%s, #supervisor =%s, #Comments=%s, #action=%s, #subfunction=%s, #region=%s',
(auditorid,ticketid,qid,answer, sid,TicketType, TypeSelected, agents, supervisor, Comments, action, subfunction,region))
return Response(True)
I ran this code on my machine and it works for the payload you provided.
#api_view(['POST'])
def SaveUserResponse(request):
for ran in request.data:
auditorid = ran.get('AuditorId')
ticketid = ran.get('TicketId')
qid = ran.get('QId')
answer = ran.get('Answer')
sid = '0'
TicketType = ran.get('TicketType')
TypeSelected = ran.get('TypeSelected')
agents = ran.get('Agents')
supervisor = ran.get('Supervisor')
Comments = ran.get('Comments')
action = ran.get('Action')
subfunction = ran.get('AuditSubFunction')
region = ran.get('AuditRegion')
If it doesn't then content of request.data must be different then payload you shared in original post

For each item update database

I'm a total beginner with Python/Django and trying to understand why this isn't working. I have a function that contains a for loop, doing some logic and then updating a model. but when I have more than 1 item in the loop I get a UNIQUE constraint failed: app_token.token_name error.
So I think I'm misunderstanding how the loop is working?
function
tokens = Token.objects.all()
for item in tokens:
if item.token_contract_address is not None:
token = Token.objects.get(pk=item.id)
parameters = {
'address':token.token_contract_address
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
resp = json.loads(response.text)
token_id = (resp['data'][next(iter(resp['data']))]['id'])
logo = (resp['data'][next(iter(resp['data']))]['logo'])
url = 'https://pro-api.coinmarketcap.com/v1/cryptocurrency/quotes/latest'
parameters = {
'id':token_id
}
session = Session()
session.headers.update(headers)
response = session.get(url, params=parameters)
id = str(token_id)
price = (json.loads(response.text)['data'][id]['quote']['USD']['price'])
market_cap = (json.loads(response.text)['data'][id]['quote']['USD']['market_cap'])
change = (json.loads(response.text)['data'][id]['quote']['USD']['percent_change_24h'])
r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name )
I'm expecting the this Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) to update the model based on the item loop?
The model is very simple:
class Token(models.Model):
token_name = models.CharField(max_length=50, blank=False, unique=True)
token_slug = models.CharField(max_length=50, blank=True,null=True)
token_price = models.FloatField(blank=True,null=True)
token_capture_date = models.DateField(blank=True,null=True)
token_contract_address = models.CharField(max_length=50, blank=True,null=True)
def __str__(self):
return str(self.token_name)
I'm using the update on the objects and have tried removing the token_name, and tried using token.token_name
If I remove token_name= it updates both items in the database with the same values? which makes me think its this line r = Token.objects.update(token_capture_date = formatedDate, token_price = price, token_name=item.token_name ) do i need to apply some kinda of filter?
Thanks
I believe that by calling Token.objects.update() you actually end up trying to update all Token objects. Since token_name has to be unique, and you are giving it the same name as another Token object it throws that error.
Since you are already in a for loop, you can simply update the token that is currently being processed.
My suggestion would be to use this code instead:
item.token_capture_date = formattedDate
item.token_price = price
item.save()
This will make it so that the current token object which is being processed in the for loop has its respective field values updated and saved in the database.
Also, this line is unnecessary: token = Token.objects.get(pk=item.id) as we already have access to the token through the looping variable item.
Do let me know if this helps!

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

django handle slowly when doing Stress Testing

i had built django server to handle some work.And when i sent 10000 requests to django,django will became slow after 4000th requests,it will report socket timeout randomly.And i take this one data to test it alone,it is ok.So,how can i fix this bug?
i have no idea to fix it
def handle(request) :
sys.stderr.write( "[info]request come in {} \n".format(sys._getframe().f_code.co_name))
ret_dict = dict()
ret_str = ""
if ("vid" in request.GET) and ("title" in request.GET):
id = request.GET["id"]
title = urllib.parse.unquote(request.GET["title"],encoding ='utf-8')
title = request.GET["title"]
req_video = dict()
req_video["vid"] = vid
req_video["title"] = title
tags = handle_function(req_video)
ret_dict["vid"] = vid
ret_dict["tags"] = tags
ret_str = json.dumps(ret_dict)
return HttpResponse(ret_str)
client codes:
for line in sys.stdin:
line = line.rstrip('\n')
fields = line.split("\t")
vid = fields[0]
title = fields[1]
page_params_mq = {'vid':vid,'title':title}
try :
rec_mq_res = get_rec_mingqiang(server_ip_mq, server_port_mq, web_page_mq, page_params_mq)
except:
print (line)
continue
vid = rec_mq_res["vid"]
tags = rec_mq_res["tags"]
fo.write(vid+"\t"+tags+"\n")
cat test_data|python client.py, there are 10000 rows in test_data,and it send request sequentially,and will be hunt randomly after 4000.
django can handle these requests quickly

SOAP Fault when Using DocuSign API with Salesforce for Creating Envelope with Templates

I am using Salesforce with DocuSign to try and create an envelope via templates.
DocuSignAPI.EnvelopeTemplates templates = soapService.requestTemplates(accountId, false);
String templateId = templates.EnvelopeTemplateDefinition[0].TemplateID;
DocuSignAPI.EnvelopeTemplate template = soapService.requestTemplate(templateId, false);
DocuSignAPI.EnvelopeInformation envelopeInformation = new DocuSignAPI.EnvelopeInformation();
envelopeInformation.Subject = 'XXXXXXXXXXX';
envelopeInformation.AccountId = accountId;
envelopeInformation.EmailBlurb = 'XXXXXXXXXXXXX';
DocuSignAPI.TemplateReference templateReference = new DocuSignAPI.TemplateReference();
templateReference.RoleAssignments = new DocuSignAPI.ArrayOfTemplateReferenceRoleAssignment();
templateReference.Template = template.EnvelopeTemplateDefinition.TemplateID;
templateReference.TemplateLocation = 'Server';
DocuSignAPI.Recipient recipient = new DocuSignAPI.Recipient();
recipient.ID = currentRecipientIndex + 1;
recipient.Type_x = 'Signer';
recipient.Email = 'XXXXXXXXXXXXXXXX';
recipient.UserName = 'XXXXXXXXXXXXXXXXX';
recipient.RoutingOrder = 1;
DocuSignAPI.ArrayOfRecipient1 recipients = new DocuSignAPI.ArrayOfRecipient1();
recipients.Recipient = new DocuSignAPI.Recipient[1];
recipients.Recipient.add(recipient);
DocuSignAPI.TemplateReferenceRoleAssignment trra = new DocuSignAPI.TemplateReferenceRoleAssignment();
trra.RoleName='Stake holder';
trra.RecipientID = recipient.ID;
templateReference.RoleAssignments.RoleAssignment = new DocuSignAPI.TemplateReferenceRoleAssignment[1];
templateReference.RoleAssignments.RoleAssignment.add(trra);
DocuSignAPI.ArrayOfTemplateReference arrayOfTemplateReference = new DocuSignAPI.ArrayOfTemplateReference();
arrayOfTemplateReference.TemplateReference = new DocuSignAPI.TemplateReference[1];
arrayOfTemplateReference.TemplateReference.add(templateReference);
DocuSignAPI.EnvelopeStatus status = soapService.createEnvelopeFromTemplates(arrayOfTemplateReference, recipients, envelopeInformation, true);
However, upon running the code, I get the following error:
Web service callout failed: WebService returned a SOAP Fault: Unspecified_Error faultcode=soap:Server faultactor=https://demo.docusign.net/api/3.0/dsapi.asmx
And this references the DocuSignAPI where the WebServiceCallout is invoked. Given the ambiguity of the error, I would appreciate any thoughts on what could be causing this.
As an update to this post, I was able to find the error. The indexing for Apex starts at 0 not 1 (unlike MatLab which is what caused my confusion). Because I was starting at index 1, the XML request was passing 'null' values at the 0th index, causing the error. Starting at 0, removed the null values from the XML and the request went through.