Getting Started with Square and Django - python

I'm trying to get a simple Square credit card form to work on our Django website. I'm new to using Square, but have used similar API's such as Stripe in the past.
To start, I followed along with their Square Payment Form walkthrough. I added their SqPaymentForm library and our own javascript file where I initialized a new SqPaymentForm.
The front-end appears to be working and is generating a unique card nonce every time I enter fake credentials.
Next, I submitted the form to our back-end (including the card nonce, in a hidden nonce field).
On the back-end, I've installed the Square Connect Python SDK. I copied their "Charge the card nonce" example as closely as possible, substituting our sandbox access token and location ID:
import uuid
import squareconnect
from squareconnect.rest import ApiException
from squareconnect.apis.transactions_api import TransactionsApi
# create an instance of the Transactions API class
api_instance = TransactionsApi()
# setup authorization
api_instance.api_client.configuration.access_token = 'sandbox-access-token'
location_id = 'sandbox-location-id'
nonce = request.POST.get('nonce', 'empty')
if (nonce == 'empty'): print("Throw error")
# print(nonce)
try:
# Charge
idempotency_key = str(uuid.uuid1())
amount = {'amount': 100, 'currency': 'USD'}
body = {'idempotency_key': idempotency_key, 'card_nonce': nonce, 'amount_money': amount}
api_response = api_instance.charge(location_id, body)
print (api_response.transaction)
except ApiException as e:
print ('Exception when calling TransactionApi->charge: %s\n' % e)
I've also tried reformatting this code slightly to fit the example demonstrated in Square's connect-api-examples on GitHub.
But, when I test it in localhost (http), using the different demo credentials provided by Square on their test values page, I consistently get an 'Unauthorized' error from the API:
Exception when calling TransactionApi->charge: (401)
Reason: Unauthorized
HTTP response headers: HTTPHeaderDict(
{'Content-Type': 'application/json', 'Vary': 'Origin, Accept-Encoding', 'X-Content-Type-Options': 'nosniff', 'X-Download-Options': 'noopen', 'X-Frame-Options': 'SAMEORIGIN', 'X-Permitted-Cross-Domain-Policies': 'none', 'X-Xss-Protection': '1; mode=block', 'Date': 'Wed, 31 Jul 2019 20:59:10 GMT', 'keep-alive': 'timeout=60', 'Strict-Transport-Security': 'max-age=631152000', 'content-length': '119'})
HTTP response body: {"errors":[{"category":"AUTHENTICATION_ERROR","code":"UNAUTHORIZED","detail":"This request could not be authorized."}]}
When I look through the Troubleshooting documentation, it says the likely cause for an Unauthorized error is an invalid OAuth token. Yet, none of Square's demos or examples utilize OAuth. I don't understand why OAuth would be necessary for a simple payment form that isn't behind a sign-up page?
I've tried uploading the code to our https website to see if an SSL cert was required, but I get the same error.

You need to set your access token, then your code will work. The location id is also not set, so square sends an error. I had the same problem, and I realized that it was because I forgot to add the access token. Hope that this helps.

Related

How do I access the Linkedin search API?

https://learn.microsoft.com/en-us/linkedin/shared/integrations/people/handle-lookup
I am trying to call this API as the documentation shows, but I get this error back:
Here is the headers I am sending:
{'Authorization': 'Bearer xxxxxx', 'cache-control': 'no-cache', 'X-Restli-Protocol-Version': '2.0.0', 'X-Forwarded-For': '198.51.100.1', 'Caller-Account-Age': '2', 'Caller-Device-UUID': 'a859b63d-7135-4d96-be47-c21d392bfad2'}
I have authenticated with the right scopes and got the right OAUTH token and validated it by calling the userinfo endpoint
Here is the response I get back from calling this API:
https://api.linkedin.com/v2/clientAwareMemberHandles?q=handleString&handleString={something#something.com}
{'serviceErrorCode': 100, 'message': 'Not enough permissions to access: GET-handleString /clientAwareMemberHandles', 'status': 403}
All I am trying to do is get the user LinkedIn profile for a specific email address.
Also, is there a way to reach out to Linkedin support for this?
The API listed above.
Was expecting the member profile associated with the email.

local API of a device

I am trying to interact with an energy meter that hosts its own local API to get data. I am far from having a lot of HTTP requests knowledge and this maybe asking a lot from Stackoverflow, but how do I interact with this device on a local area network?
The directions state the HTTP request needs to consist of the following:
<headers> are a variable number of HTTP headers; each header is on its own line.
The following items must be included in the headers:
o Content-type: text/xml
o Content-Length: xx where “xx” is the number of characters in the body of the POST
o Authorization: Basic xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx where the 32-character Basic Authentication credential is formed using the EAGLE Cloud ID as the username, and the EAGLE Install Code as the password.
Ultimately I am trying to do this listed below (get meter data):
To get data from the meter, you must first discover its Hardware Address. This can be done by issuing a “device_list” command to the EAGLE through the Local API, which is done by sending a POST with the following text in the body:
<Command>
<Name>device_list</Name>
</Command>
Could anyone give me a tip on how to do this with Python requests? The code below returns a 401 as I know it doesnt incorporate the body & required header information.
import requests
url = "http://10.100.100.27/"
print(requests.post(url).text)
This is an example of what the POST request should look like from the docs.
Try the following
import requests
url = "http://10.100.100.27/cgi-bin/post_manager"
headers = {
'Content-Type': 'text/xml',
'Authorization' : 'Basic ' + '<your api key>',
}
command = 'device_list'
payload = '<Command><Name>{}</Name></Command>'.format(command)
print(requests.post(url, headers=headers, payload=payload).text)

Bad request when calling DocuSign API for JWT user token. Consent?

I'm using the DocuSign API to request a JWT user token:
with open('docusign.pem', mode='rb') as privatefile:
private_key_bytes = privatefile.read()
api_client = ApiClient()
oauth_host_name = 'account-d.docusign.com'
# not real, random:
client_id = 'dff16ff1-de93-477d-a73d-3774ac9932dc'
user_id = '7401f22e-ff2c-4777-9117-5932ace2e71a'
expires_in = 3600
result = api_client.request_jwt_user_token(client_id, user_id,
oauth_host_name,
private_key_bytes,
expires_in,
scopes=(OAuth.SCOPE_SIGNATURE,))
This returns:
(400)
Reason: Bad Request
HTTP response headers: HTTPHeaderDict({'Cache-Control': 'no-cache', 'Pragma': 'no-cache',
'Content-Type': 'application/json; charset=utf-8', 'Expires': '-1', 'Server':
'Microsoft-IIS/10.0', 'X-AspNetMvc-Version': '5.2', 'X-DocuSign-TraceToken':
'c1d090b7-cefd-4881-80c6-3f1c55ccc5b4', 'X-Content-Type-Options': 'nosniff',
'Strict-Transport-Security': 'max-age=31536000; includeSubDomains; preload,
max-age=15768000', 'X-Frame-Options': 'SAMEORIGIN', 'X-XSS-Protection': '1; mode=block;
report=/client-errors/xss', 'X-DocuSign-Node': 'DA2DFE179', 'Date':
'Sun, 23 Aug 2020 15:18:46 GMT', 'Content-Length': '28'})
HTTP response body: b'{"error":"consent_required"}'
So how to obtain "consent". This page has two sections "Admin consent for internal applications" and "Admin consent for external applications":
DocuSign obtaining consent
I'm not sure how to get consent in the sandbox. It already say "DS Admin" under "permission profile" for the user in DocuSign.
Update
I used the second technique "Admin consent for internal applications" to obtain consent with the settings:
admin_consent_scope=impersonation
response_type=code
scope=openid
And instead of the login I got the message at the DocuSign website:
"You are not an organization admin. Please contact your DocuSign Administrator."
How do I ask DocuSign to enable this feature on my developer account?
See this blog post on granting consent.
Note that the user being impersonated needs to consent to both the signature scope (if you're using the eSignature features), and the impersonation scope.
For individual consent, the two scopes are separated by a space which should be entered as %20, the encoded value.
Example:
https://account-d.docusign.com/oauth/auth?
response_type=code
&scope=signature%20impersonation
&client_id=YOUR_INTEGRATION_KEY
To use admin consent you must have an organization. This requires you to register a domain name and confirm it with DNS records.
While this is the recommended approach, it's a bit more complex.
I would consider using individual consent to get you unblocked for now.
To do that, you just construct a URL like this one:
https://account-d.docusign.com/oauth/auth?
response_type=code
&scope=YOUR_REQUESTED_SCOPES
&client_id=YOUR_INTEGRATION_KEY
&redirect_uri=YOUR_REDIRECT_URI
And proceed to agree and just ignore the code you get back. After that you can use JWT to obtain a token.
&redirect_uri=YOUR_REDIRECT_URI

Trying to test Docusign demo key on production server before purchasing, is it possible?

Currently, I have a Docusign flow working on in development, but when I try to deploy it on my production server it fails.
HTTP response headers: HTTPHeaderDict({'Content-Length': '137', 'Vary': 'Accept-Encoding', 'X-DocuSign-TraceToken': '61275999-0e6f-4d16-925c-4f9f19c7800c', 'Cache-Control': 'no-cache', 'Date': 'Fri, 21 Jun 2019 17:31:10 GMT', 'Content-Type': 'application/json; charset=utf-8'})
HTTP response body: {
"errorCode": "USER_AUTHENTICATION_FAILED",
"message": "One or both of Username and Password are invalid. Invalid access token"
}
I was hoping to be able to get it live to show it off. I have tried changing the base url from https://demo.docusign.net to https://www.docusign.net or account-d.docusign.com to account.docusign.com, but nothing.
So, this leads me to believe that a demo key just won't work at all.
Is there any way to work around this before purchasing an API plan?
In order to use an integrator key in the Production environment, it will need to pass the Go Live process, which requires a paid account to link the key to. This doesn't necessarily have to be an API plan - any paid account (Web or Enterprise) account will do.
You can show off your integration by continuing to use the DocuSign demo system (developer sandbox).
The main restriction is that you can't use the demo system to create legally binding agreements. The production system does that.

Google Data API authentication

I am trying to get my Django app (NOT using Google app engine) retrieve data from Google Contacts using Google Contacts Data API. Going through authentication documentation as well as Data API Python client docs
First step (AuthSubRequest) which is getting the single-use token works fine. The next step(AuthSubSessionToken), which is upgrade single-use token to a session token. The python API call UpgradeToSessionToken() simply didn't work for me it gave me NonAuthSubToken exception:
gd_client = gdata.contacts.service.ContactsService()
gd_client.auth_token = authsub_token
gd_client.UpgradeToSessionToken()
As an alternative I want to get it working by "manually" constructing the HTTP request:
url = 'https://www.google.com/accounts/AuthSubSessionToken'
headers = {
'Content-Type': 'application/x-www-form-urlencoded',
'Authorization': 'AuthSub token=' + authsub_token,
'User-Agent': 'Python/2.6.1',
'Host': 'https://www.google.com',
'Accept': 'text/html, image/gif, image/jpeg, *; q=.2, */*; q=.2',
'Connection': 'keep-alive',
}
req = urllib2.Request(url, None, headers)
response = urllib2.urlopen(req)
this gives me a different error:
HTTP Error 302: The HTTP server returned a redirect error that would lead to an infinite loop. The last 30x error message was: Moved Temporarily
What am I doing wrong here? I'd appreciate help/advice/suggestions with either of the methods I am trying to use: Python API call (UpgradeToSessionToken) or manually constructing HTTP request with urllib2.
According to the 2.0 documentation here there is a python example set...
Running the sample code
A full working sample client, containing all the sample code shown in this document, is available in the Python client library distribution, under the directory samples/contacts/contacts_example.py.
The sample client performs several operations on contacts to demonstrate the use of the Contacts Data API.
Hopefully it will point you in the right direction.
I had a similar issue recently. Mine got fixed by setting "secure" to "true".
next = 'http://www.coolcalendarsite.com/welcome.pyc'
scope = 'http://www.google.com/calendar/feeds/'
secure = True
session = True
calendar_service = gdata.calendar.service.CalendarService()
There are four different ways to authenticate. Is it really that important for you to use AuthSub? If you can't get AuthSub to work, then consider the ClientLogin approach. I had no trouble getting that to work.

Categories

Resources