I'm trying to integrate CyberSource's REST API into a Django (Python) application. I'm following this GitHub example example.
It works like a charm but it is not clear to me from the example or from the documentation how to specify the device's fingerprint ID.
Here's a snippet of the request I'm sending in case it comes useful (note: this is just a method that lives inside a POPO):
def authorize_payment(self, card_token: str, total_amount: Money, customer: CustomerInformation = None,
merchant: MerchantInformation = None):
try:
request = {
'payment_information': {
# NOTE: REQUIRED.
'card': None,
'tokenized_card': None,
'customer': {
'customer_id': card_token,
},
},
'order_information': {
'amount_details': {
'total_amount': str(total_amount.amount),
'currency': str(total_amount.currency),
},
},
}
if customer:
request['order_information'].update({
'bill_to': {
'first_name': customer.first_name,
'last_name': customer.last_name,
'company': customer.company,
'address1': customer.address1,
'address2': customer.address2,
'locality': customer.locality,
'country': customer.country,
'email': customer.email,
'phone_number': customer.phone_number,
'administrative_area': customer.administrative_area,
'postalCode': customer.zip_code,
}
})
serialized_request = json.dumps(request)
data, status, body = self._payment_api_client.create_payment(create_payment_request=serialized_request)
return data.id
except Exception as e:
raise AuthorizePaymentError from e
Related
The get_assets method obtains a list of assets from the database and for each item in the list calls the __build_asset_response method to build a response in dictionary format. However, when there are many assets, the time to do the build_asset_response is very high. Does anyone know a method to optimize the time?
def get_assets(user, data):
if data.get('asset_id'):
assets = Asset.objects.filter(pk__in=data['asset_id'])
return [__build_asset_response(asset) for asset in assets]
assets = Asset.objects.filter(QueryHelper.filter_by_rol(user))
return [__build_asset_response(asset) for asset in assets]
This is the buil_asset_response private method:
def __build_asset_response(asset):
asset_dict = {
'id': asset.pk,
'name': asset.name,
'accessibility': manage_accessibility.build_accessibility_type_response(asset.accessibility),
'folder': "",
'user_id': {
'id': asset.user.id,
'name': str(asset.user)
},
'organization': {
'id': asset.idOrganization.id,
'name': str(asset.idOrganization),
},
'asset_type_id': asset.idAssetType and __build_asset_type_response(asset.idAssetType) or {},
'file': settings.MEDIA_URL + asset.archivo.name,
'tag_ids': [tag.name for tag in asset.tag_ids.all()],
'lastModified': timezone.localtime(asset.last_modified_date).strftime("%Y-%m-%d %H:%M:%S"),
'used_in_publication': asset.used_in_publication
}
if asset.idFolder:
folder = manage_folder.build_folder_response(asset.idFolder)
else:
folder = ''
asset_dict.update({
'folder': folder,
})
return asset_dict
We have written python script to create the cloud function , the trigger is Https. We need to invoke fetch the output of the function , So for that we are using the environment variables but some how that is not getting stored ?
def generate_config(context):
""" Entry point for the deployment resources. """
name = context.properties.get('name', context.env['name'])
project_id = context.properties.get('project', context.env['project'])
region = context.properties['region']
resources = []
resources.append(
{
'name': 'createfunction',
'type': 'gcp-types/cloudfunctions-v1:projects.locations.functions',
'properties':
{
'function': "licensevalidation",
'parent': 'projects//locations/',
'sourceArchiveUrl': 'gs://path',
'entryPoint':'handler',
'httpsTrigger': {"url": "https://.cloudfunctions.net/licensevalidation","securityLevel": "SECURE_ALWAYS"},
'timeout': '60s',
'serviceAccountEmail' : '.iam.gserviceaccount.com',
'availableMemoryMb': 256,
'runtime': 'python37' ,
'environmentvaiable' :
}
}
)
call ={
'type': 'gcp-types/cloudfunctions-v1:cloudfunctions.projects.locations.functions.call',
'name': 'call',
'properties':
{
'name':'/licensevalidation',
'data': '{""}'
},
'metadata': {
'dependsOn': ['createfunction']
}
}
resources.append(call)
return{
'resources': resources,
'outputs':
[
{
'name': 'installationtoken',
'value': 'os.environ.get(environment_variable)'
},
]
}
EDIT: This is has been identified as a bug here.
I am trying to make a Google Meet along with a new calendar event. However, for some reason the returning event does not include any conferenceData, not even one with status fail.
Here is my code. I have omitted the authentication step as I do not get an authentication error.
def generateMeet(emails=None, fake=False):
if emails is None:
emails = []
if fake:
return "https://www.google.com", get_random_string(10)
now = datetime.utcnow().isoformat() + 'Z' # 'Z' indicates UTC time
inonehour = (datetime.utcnow() + timedelta(hours=1)).isoformat() + 'Z'
event = {
'summary': 'Orb Meeting',
'start': {
'dateTime': now,
'timeZone': 'America/New_York',
},
'end': {
'dateTime': inonehour,
'timeZone': 'America/New_York',
},
'sendUpdates': "none",
'reminders': {
'useDefault': False,
},
'attendees': [{'email': x} for x in emails],
'conferenceDataVersion': 1,
'conferenceData': {
'createRequest': {
'requestID': get_random_string(10),
'conferenceSolutionKey': {
'type': 'hangoutsMeet'
},
}
}
}
ret = service.events().insert(calendarId='primary', body=event).execute()
return ret['conferenceData']['entryPoints'], ret['id']
This returns a key error, as conference data does not exist. Here is the full 'ret' object before I run the return:
{'kind': 'calendar#event', 'etag': '"3197938620273000"', 'id': '5fb6epfe93sceba9scjt1nevsk', 'status': 'confirmed',
'htmlLink': 'https://www.google.com/calendar/event?eid=NWZiNmVwZmU5M3NjZWJhOXNjanQxbmV2c2sgZm9ycmVzdG1pbG5lckBt',
'created': '2020-09-01T14:08:30.000Z', 'updated': '2020-09-01T14:08:30.162Z', 'summary': 'Orb Meeting',
'creator': {'email': '[my email]', 'self': True},
'organizer': {'email': '[my email]', 'self': True},
'start': {'dateTime': '2020-09-01T10:08:28-04:00', 'timeZone': 'America/New_York'},
'end': {'dateTime': '2020-09-01T11:08:28-04:00', 'timeZone': 'America/New_York'},
'iCalUID': '5fb6epfe93sceba9scjt1nevsk#google.com', 'sequence': 0,
'attendees': [{'email': '[my other email]', 'displayName': 'Forrest Milner', 'responseStatus': 'needsAction'}],
'reminders': {'useDefault': False}}
Can anyone tell me why the conferenceData part of my request might be dropped? I am setting the conferenceDataVersion to 1, and using a random string.
I have tried adding dummy "invitees". In this trial, I invited my second gmail account, and in other trials I have invited several dummy accounts with domain "example.com". This updates the attendees, but does not make the conference data appear.
I have also tried waiting a few minutes and then listing all my events. Even after waiting, the conference data was not filled in. When I check my calendar on the GUI (https://calendar.google.com/calendar/r) it also does not have a Google Meet attached.
Thank you for any help.
Yes, it is a bug, if it's high priority you can 'patch' your created event with something like this:
const eventPatch = {
conferenceData: {
createRequest: { requestId: "yourRandomString" },
},
};
let response = await calendar.events.patch({
calendarId: 'primary',
eventId: "createdEventID",
resource: eventPatch,
sendNotifications: true,
conferenceDataVersion: 1,
});
Reference: https://developers.google.com/calendar/create-events#conferencing
The conferenceDataVersion It's not a part of requestBody anymore. Must be passed inside your insert method.
On NodeJS it's something like this:
calendar.events.insert({
calendarId: 'calendarIdHere',
requestBody: yourOldRequestBodyObject,
conferenceDataVersion: 1
});
#André Eccel is correct. Here's a working Python example of how to add a google meet link to your event:
import uuid
request_id = str(uuid.uuid1())
event = {'summary': "My Birthday Party",
'description': "There will be flamingos.",
'start': start,
'end': end,
'recurrence':recurrence,
'attendees': attendees,
'conferenceData': {'createRequest': {
'requestId': request_id,
"conferenceSolutionKey": {"type": "hangoutsMeet"}}}
}
service.events().insert(calendarId=cal_id,body=event,conferenceDataVersion=1).execute()
Following the docs, there's an example to export all for a specific OU
def create_drive_ou_all_data_export(service, matter_id):
ou_to_search = 'ou id retrieved from admin sdk'
drive_query_options = {'includeSharedDrives': True}
drive_query = {
'corpus': 'DRIVE',
'dataScope': 'ALL_DATA',
'searchMethod': 'ORG_UNIT',
'orgUnitInfo': {
'org_unit_id': ou_to_search
},
'driveOptions': drive_query_options,
'startTime': '2017-03-16T00:00:00Z',
'endTime': '2017-09-23T00:00:00Z',
'timeZone': 'Etc/GMT+2'
}
drive_export_options = {'includeAccessInfo': False}
wanted_export = {
'name': 'My first drive ou export',
'query': drive_query,
'exportOptions': {
'driveOptions': drive_export_options
}
}
return service.matters().exports().create(
matterId=matter_id, body=wanted_export).execute()
However, it does not show how to just export for a given user, is this possible? Also, where are all of the different body options for creating an export? The examples do not seem to show all of the parameters available.
You'd want to use searchMethod:account
Reference Query: https://developers.google.com/vault/reference/rest/v1/Query
Reference searchmethod: https://developers.google.com/vault/reference/rest/v1/Query#SearchMethod
Reference AccountInfo: https://developers.google.com/vault/reference/rest/v1/Query#AccountInfo
drive_query = {
'corpus': 'DRIVE',
'dataScope': 'ALL_DATA',
'searchMethod': 'ACCOUNT', # This is different
'accountInfo': { # This is different
'emails': ['email1#company.com', 'email2#company.com', 'email3#company.com']
},
'driveOptions': drive_query_options,
'startTime': '2017-03-16T00:00:00Z',
'endTime': '2017-09-23T00:00:00Z',
'timeZone': 'Etc/GMT+2'
}
I try to use the Google Adwords API, with the official library here : https://github.com/googleads/googleads-python-lib
I use an Manager Account on Google Adwords and want to work with my client's accounts.
I can get all the the Adwords account ID (like 123-456-7891) but I don't know how to pass the account ID to my Google Adwords functions as a parameter.
Here's my main function :
def main(argv):
adwords_client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
add_campaign(adwords_client)
I see any Account ID parameter in the official samples, as :
import datetime
import uuid
from googleads import adwords
def add_campaign(client):
# Initialize appropriate services.
campaign_service = client.GetService('CampaignService', version='v201809')
budget_service = client.GetService('BudgetService', version='v201809')
# Create a budget, which can be shared by multiple campaigns.
budget = {
'name': 'Interplanetary budget #%s' % uuid.uuid4(),
'amount': {
'microAmount': '50000000'
},
'deliveryMethod': 'STANDARD'
}
budget_operations = [{
'operator': 'ADD',
'operand': budget
}]
# Add the budget.
budget_id = budget_service.mutate(budget_operations)['value'][0][
'budgetId']
# Construct operations and add campaigns.
operations = [{
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise #%s' % uuid.uuid4(),
# Recommendation: Set the campaign to PAUSED when creating it to
# stop the ads from immediately serving. Set to ENABLED once you've
# added targeting and the ads are ready to serve.
'status': 'PAUSED',
'advertisingChannelType': 'SEARCH',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC',
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'networkSetting': {
'targetGoogleSearch': 'true',
'targetSearchNetwork': 'true',
'targetContentNetwork': 'false',
'targetPartnerSearchNetwork': 'false'
},
# Optional fields
'startDate': (datetime.datetime.now() +
datetime.timedelta(1)).strftime('%Y%m%d'),
'frequencyCap': {
'impressions': '5',
'timeUnit': 'DAY',
'level': 'ADGROUP'
},
'settings': [
{
'xsi_type': 'GeoTargetTypeSetting',
'positiveGeoTargetType': 'DONT_CARE',
'negativeGeoTargetType': 'DONT_CARE'
}
]
}
}, {
'operator': 'ADD',
'operand': {
'name': 'Interplanetary Cruise banner #%s' % uuid.uuid4(),
'status': 'PAUSED',
'biddingStrategyConfiguration': {
'biddingStrategyType': 'MANUAL_CPC'
},
'endDate': (datetime.datetime.now() +
datetime.timedelta(365)).strftime('%Y%m%d'),
# Note that only the budgetId is required
'budget': {
'budgetId': budget_id
},
'advertisingChannelType': 'DISPLAY'
}
}]
campaigns = campaign_service.mutate(operations)
How can I tell Adwords API in which account I want to add this campaign ?
Thanks for your help !
OK my bad, I missed a documentation method (http://googleads.github.io/googleads-python-lib/googleads.adwords.AdWordsClient-class.html#SetClientCustomerId).
# ID of your customer here
CUSTOMER_SERVICE_ID = '4852XXXXX'
# Load customer account access
client = adwords.AdWordsClient.LoadFromStorage(path="googleads.yaml")
client.SetClientCustomerId(CUSTOMER_SERVICE_ID)
And the customer ID is now associate with the AdwordsClient variable as "client" set as parameters for other functions.