Vantiv payment gateway authentication error using python? - python

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.

Related

'InvalidRegistration' FCM when sending Push Notifications via Appium and Python

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?

How to exchange code for access token with Reddit API

I'm sure this is a broader question that applies to more than just Reddit, but currently I am attempting to exchange a code for a user access token however I am not understanding how to implement the following steps:
https://github.com/reddit-archive/reddit/wiki/OAuth2#retrieving-the-access-token
If you didn't get an error and the state value checks out,
you may then make a POST request with code to the following URL to retrieve your access token:
https://www.reddit.com/api/v1/access_token
Include the following information in your POST data (NOT as part of the URL)
grant_type=authorization_code&code=CODE&redirect_uri=URI
Okay, so what I did was this:
headers = {
CLIENT_ID: CLIENT_SECRET,
}
r = requests.post(
url="https://www.reddit.com/api/v1/access_token",
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers=headers
)
I think I am failing with the headers, I receive a 429 error, and I don't think I've understood how to arrange the headers correctly as it doesn't clearly explain in the above link.
The "user" is the client_id. The "password" for confidential clients is the client_secret. The "password" for non-confidential clients (installed apps) is an empty string.
CLIENT_ID and CLIENT_SECRET are obviously variables, and they are my Reddit App dev credentials.
EDIT:
I came up with this, it's gross but it seems to work
headers = {
"User-Agent": "MyApp v1.0",
"Authorization": "Basic " + str(base64.b64encode(str.encode(f"{CLIENT_ID}:{CLIENT_SECRET}")))[2:-1],
}
Is there a cleaner way to write that?
Final answer, using an inbuilt method in Python's request:
client_auth = requests.auth.HTTPBasicAuth(CLIENT_ID, CLIENT_SECRET)
r = requests.post(
url="https://www.example.com/api/v1/access_token",
auth=client_auth,
data={
"grant_type": "authorization_code",
"code": code,
"redirect_uri": "http://127.0.0.1:5000/callback"
},
headers={
"User-Agent": "MyApp v1.0",
}
)

Azure Analysis rest api : 401 Unauthorized. "Authentication failed."

I'm trying to make a data partition refresh (post) following this azure documentation : https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-async-refresh
Either with post or get I got 401 Unauthorized (Even when the service is Off !).
I got the token from azure AD (ServicePrincipalCredential).
I added the AD as Analysis Services Admins (https://learn.microsoft.com/en-us/azure/analysis-services/analysis-services-server-admins)
I gave the owner role to AD in Analysis Services IAM.
it worked with Analysis Services management rest api (https://learn.microsoft.com/en-us/rest/api/analysisservices/operations/list) With the same authentification (got code response 200)
My python code :
from azure.common.credentials import ServicePrincipalCredentials
import requests
credentials = ServicePrincipalCredentials(client_id="ad_client_id",
secret="ad_secret",
tenant="ad_tenant")
token = credentials.token
url = "https://westeurope.asazure.windows.net/servers/{my_server}/models/{my_model}/refreshes"
test_refresh = {
"Type": "Full",
"CommitMode": "transactional",
"MaxParallelism": 1,
"RetryCount": 1,
"Objects": [
{
"table": "my_table",
"partition": "my_partition"
}
]
}
header={'Content-Type':'application/json', 'Authorization': "Bearer {}".format(token['access_token'])}
r = requests.post(url=url, headers=header, data=test_refresh)
import json
print(json.dumps(r.json(), indent=" "))
Response I got :
{
"code": "Unauthorized",
"subCode": 0,
"message": "Authentication failed.",
"timeStamp": "2019-05-22T13:39:03.0322998Z",
"httpStatusCode": 401,
"details": [
{
"code": "RootActivityId",
"message": "aab22348-9ba7-42c9-a317-fbc231832f75"
}
]
}
I'm hopeless, could you please give me somes help to make this clear ?
Finally I resolved the issue.
I had wrong token. The api expect an OAuth2.0 authentification token (The Azure analysis services rest api documentation ins't very clear about the way to get one)
For thoses will encounter the same issu there is the way to get one.
from adal import AuthenticationContext
authority = "https://login.windows.net/{AD_tenant_ID}"
auth_context = AuthenticationContext(authority)
oauth_token = auth_context.acquire_token_with_client_credentials(resource="https://westeurope.asazure.windows.net", client_id=AD_client_id, client_secret=AD_client_id)
token = oauth_token['accessToken']
Documentation about this :
https://learn.microsoft.com/en-us/python/api/adal/adal.authentication_context.authenticationcontext?view=azure-python#acquire-token-with-client-credentials-resource--client-id--client-secret-
https://github.com/AzureAD/azure-activedirectory-library-for-python/wiki/ADAL-basics
Most likely your token is not right.
Have you tried validating your token? Use something like http://calebb.net/
I see some examples of ServicePrincipalCredentials that stipulate the context or resource like this:
credentials = ServicePrincipalCredentials(
tenant=options['tenant_id'],
client_id=options['script_service_principal_client_id'],
secret=options['script_service_principal_secret'],
resource='https://graph.windows.net'
Good samples here:
https://www.programcreek.com/python/example/103446/azure.common.credentials.ServicePrincipalCredentials
I think the solution is try a couple more things that make sense and follow the error details.
You need token which has resource (audience) set to https://*.asazure.windows.net
For token validation I like https://jwt.io
Also if you want to automate this properly you have two options
Either by Logic Apps
or with Azure Data Factory
Both of which I have very detailed posts on if you want to check them out
https://marczak.io/posts/2019/06/logic-apps-refresh-analysis-services/
https://marczak.io/posts/2019/06/logic-app-vs-data-factory-for-aas-refresh/

Can not parse JSON share document.\nRequest body:\n\nError:\nnull

I am trying to send a request to Linkedin's rest share api. I have been receiving this error message:
{
"errorCode": 0,
"message": "Can not parse JSON share document.\nRequest body:\n\nError:\nnull",
"requestId": "ETX9XFEI7N",
"status": 400,
"timestamp": 1437910620120
}
The request is send through the following python code:
import requests,json
auth_token = "some auth token"
url = "https://api.linkedin.com/v1/people/~/shares?format=json&oauth2_access_token="+auth_token
headers = {'content-type': 'application/x-www-form-urlencoded','x-li-format':'json'}
data = {
"comment":"Check out developer.linkedin.com!",
"content":{
"title": "LinkedIn Developers Resources",
"description": "Leverage LinkedIn's APIs to maximize engagement",
"submitted-url": "https://developer.linkedin.com",
"submitted-image-url": "https://example.com/logo.png"
},
"visibility":{
"code": "anyone"
}
}
response = requests.post( url , json= data , headers=headers )
return HttpResponse( response )
I made sure that I followed all the instructions in their documentation and can't find the mistake I am making.
Note: i have tried json=data and data=data both are not working
Remove content-type from the headers dictionary.
requests sets the correct Content-Type when using the json keyword argument.
You have three basic problems:
Please read the documentation on oauth2; because you are not passing in the token correctly.
The share URL does not take a oauth2_token argument.
You have the wrong content-type header.

PayPal Error 10002 Using Permissions API and TransactionSearch

I have a permissions request that looks like this:
timestamp, signature = genPermissionsAuthHeader.getAuthHeader(str(self.username), str(self.password), str(access_token), str(token_secret), "POST", "https://api-3t.sandbox.paypal.com/nvp") # https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData
log.info(timestamp)
log.info(signature)
authorization_header = "timestamp=" + timestamp + ",token=" + access_token + ",signature=" + signature
log.info(authorization_header)
headers = {
"X-PAYPAL-AUTHORIZATION": authorization_header,
}
url = "https://api-3t.sandbox.paypal.com/nvp"
nvp_params = {
"METHOD": "TransactionSearch",
"STARTDATE": "2012-01-01T05:38:48Z",
}
r = requests.post(url, data=nvp_params, headers=headers)
log.info(r.text)
self.response.content_disposition = "text/html"
self.response.write(r.text)
I have an access token and token secret from the permissions API using my PayPal credentials on developer.paypal.com under "Sandbox Accounts"
When I run this method I get the error message:
TIMESTAMP=2014%2d04%2d21T22%3a50%3a18Z&CORRELATIONID=c8f9212035b60
&ACK=Failure&VERSION=0%2e000000&BUILD=10277387&L_ERRORCODE0=10002
&L_SHORTMESSAGE0=Authentication%2f
Authorization%20Faile
d&L_LONGMESSAGE0=You%20do%20not%20have%20permissions%20to%20make%20this%20API%20call
&L_SEVERITYCODE0=ErrorNone
I can make a call to GetBasicPersonalDetails and it seems to work. Any help would be great, thanks!
I found the answer, I was missing the "SUBJECT" parameter on the parameter string being sent for the payment. So just in case anyone else runs across this in the future the full code after getting the permissions tokens to run a test payment for the sandbox is:
def test_sales(self, access_token=None, token_secret=None):
timestamp, signature = genPermissionsAuthHeader.getAuthHeader(str(self.username), str(self.password), str(access_token), str(token_secret), "POST", "https://api-3t.sandbox.paypal.com/nvp") # https://svcs.sandbox.paypal.com/Permissions/GetBasicPersonalData
log.info(timestamp)
log.info(signature)
authorization_header = "timestamp=" + timestamp + ",token=" + access_token + ",signature=" + signature
log.info(authorization_header)
headers = {
"X-PAYPAL-AUTHORIZATION": authorization_header,
}
url = "https://api-3t.sandbox.paypal.com/nvp"
nvp_params = {
"METHOD": "DoDirectPayment",
"PAYMENTACTION": "Sale",
"AMT": "22.00",
"ACCT": "4111111111111111",
"CVV2": "111",
"FIRSTNAME": "Jane",
"LASTNAME": "Smith",
"EXPDATE": "012018",
"IPADDRESS": "127.0.0.1",
"STREET": "123 Street Way",
"CITY": "Englewood",
"STATE": "CO",
"ZIP": "80112",
"VERSION": "86",
"SIGNATURE": self.signature,
"USER": self.username,
"PWD": self.password,
"SUBJECT": "person_who_you_acting_on_behalf_of#domain.com"
}
r = requests.post(url, data=nvp_params, headers=headers)
log.info("Search transaction\n\n" + r.text + "\n\n")
self.response.content_disposition = "text/html"
self.response.write(urllib.unquote(r.text).decode('utf8'))
And for generating the header I used: https://github.com/paypal/python-signature-generator-for-authentication-header
Hope this helps someone, thanks!
Here is some information on the error message you are getting. One reason is invalid API Credentials. Another possibility is you are trying to pass an expired token. Once a transaction is created on PayPal the token is no longer valid. Instead you have a transaction id created.
Below is some more information on PayPal API Error Messages.
PayPal API Error Messages
If you are attempting a transaction search for your most recent transactions in PayPal, then you can use the PaymentDetailsRequest API
Here is an integration guide from the PayPal Developer Site:
Get Payment Details PayPal API Codes
TransactionSearch is not part of the AdaptivePayments API,
so no "X-PAYPAL-AUTHORIZATION" is required with this method.
Assuming that you got the permission for TransactionSearch method on the target account (see https://developer.paypal.com/docs/classic/permissions-service/gs_PermissionsService/)
the following code will works:
import requests
api_username="username"
api_password="password"
api_signature="signature"
target_account_email="xxx.yyy-buyer#zzz.com" #customers email
data_req = {
'METHOD':'TransactionSearch',
'SUBJECT':, target_account_email,
'VERSION':'86.0',
'STARTDATE':'2009-10-11T00:00:00Z',
'USER':api_username,
'PWD':api_password,
'SIGNATURE':api_signature
}
response=requests.post(url_en_point,data=data_req,timeout=3).text
print response

Categories

Resources