def get_transaction_id(lang_code, mpi_data): data = ALL_QUERY_FIELDS.copy() # unique_id = get_unique_id() # # save passenger in the session # request.session[unique_id] = passenger data.update(mpi_data) data.update({ "terminal": BILLING_INFO["terminal_number"], "uniqueID": get_unique_id(), # this must be passed, although currently not used "amount": 0, "currency": "ILS", "transactionType": "Debit", "creditType": "RegularCredit", "transactionCode": "Phone", "validationType": "Verify", "langID": (lang_code or settings.LANGUAGE_CODE).upper(), "timestamp": datetime.now().replace(microsecond=0).isoformat() #"2011-10-22T15:44:53" #default_tz_now().isoformat() }) # encode data without using urlencode data = "&".join(["%s=%s" % i for i in data.items()]) logging.info(data) notify = not has_caller("run_billing_service_test") res = safe_fetch(BILLING_INFO["transaction_url"], method='POST', payload=data, deadline=50, notify=notify) if not res: return None elif res.content.startswith("--"): logging.error("No transaction ID received: %s" % res.content) return None else: return res.content
def do_invoice_passenger_action(passenger, action_payload): payload = { # "ReplyURL": "ReturnPage.asp", "TransType" : "", "Username" : INVOICE_INFO["invoice_username"], "CompanyCode" : "", "CompanyName" : passenger.full_name, "CompanyAddress" : "", "CompanyCity" : "", "CompanyState" : "", "CompanyZipcode" : "", "CompanyTel1" : passenger.phone, "CompanyTel2" : "", "CompanyCell" : "", "CompanyFax" : "", "CompanyEmail" : passenger.user.email, "CompanyWebsite" : "", "CompanyComments" : "", } payload.update(action_payload) url = INVOICE_INFO["invoice_url"] payload = dict([(k,v.encode('iso8859_8', 'ignore') if type(v) is types.UnicodeType else v) for (k,v) in payload.items()]) payload = urlencode(payload) result = safe_fetch(url, method="POST", payload=payload, deadline=50, headers={'Content-Type': 'application/x-www-form-urlencoded'}) return result
def do_credit_guard_trx(params): provider_url = BILLING_INFO['url'] params.update(BILLING_INFO) params.update({ 'may_be_duplicate' : "0", 'currency' : "ILS", 'request_id' : get_unique_id(), 'terminal_number' : BILLING_INFO["terminal_number_no_CVV"] }) c = Context(params) t = get_template("credit_guard_transaction.xml") rendered_payload = t.render(c) logging.info("CREDIT GUARD TRX - payload: %s" % rendered_payload) payload = str("user=%s&password=%s&int_in=%s" % (BILLING_INFO["username"], BILLING_INFO["password"], urlquote_plus(rendered_payload))) result = safe_fetch(provider_url, method="POST", payload=payload, deadline=50) logging.info("CREDIT GUARD TRX - response: %s" % result.content if result else "fetch failed") if not result: return None else: result = result.content if params["language"] == "Heb": result = result.decode("utf-8").encode("hebrew") xml = minidom.parseString(result) return xml
def GetUrl(url, access_token, data=None): """Get URL, with GET or POST depending data, adds Authorization header. Args: url: Url to access. tokens: dictionary of authentication tokens for specific user. data: If a POST request, data to be sent with the request. cookies: boolean, True = send authentication tokens in cookie headers. anonymous: boolean, True = do not send login credentials. Returns: String: response to the HTTP request. """ logging.debug('Adding authentication credentials to cookie header') method = "GET" headers = {'Authorization': 'Bearer %s' % access_token} if data: method = "POST" headers['Content-Type'] = 'multipart/form-data;boundary=%s' % BOUNDARY logging.info("GetUrl: len(data): %d" % len(data)) return safe_fetch(url, payload=data, method=method, headers=headers, deadline=60)
def find_matches(candidate_rides, order_settings): payload = { AlgoField.RIDES: [serialize_shared_ride(r) for r in candidate_rides], "order": serialize_order_settings(order_settings), "parameters": get_parameters(extra={"debug": order_settings.debug}) } payload = simplejson.dumps(payload) logging.info(u"submit=%s" % unicode(payload, "unicode-escape")) dt1 = datetime.now() response = safe_fetch(M2M_ENGINE_URL, payload="submit=%s" % payload, method=POST, deadline=50) dt2 = datetime.now() logging.info("response=%s" % response.content) matches = [] if response and response.content: matches = simplejson.loads(response.content)[AlgoField.RIDES] logging.info("%s candidates [%s], %s matches (+1 new), %s seconds" % (len(candidate_rides), ",".join( [str(ride.id) for ride in candidate_rides]), max(0, len(matches) - 1), (dt2 - dt1).seconds)) return [RideData(match) for match in matches]
def calculate_route(start_lat, start_lon, end_lat, end_lon): payload = urllib.urlencode({ "start_latitude": start_lat, "start_longitude": start_lon, "end_latitude": end_lat, "end_longitude": end_lon }) url = "%s?%s" % (ROUTING_URL, payload) logging.info("algo route: %s" % url) response = safe_fetch(url, deadline=15, notify=False) content = response.content.strip() if response else None result = { "estimated_distance": 0.0, "estimated_duration": 0.0 } if content: route = simplejson.loads(content) if "Error" in route: logging.error(route["Error"]) else: result = { "estimated_distance": float(route[AlgoField.DISTANCE]), "estimated_duration": float(route[AlgoField.TIME_SECONDS]) } return result
def calculate_route(start_lat, start_lon, end_lat, end_lon): payload = urllib.urlencode({ "start_latitude": start_lat, "start_longitude": start_lon, "end_latitude": end_lat, "end_longitude": end_lon }) url = "%s?%s" % (ROUTING_URL, payload) logging.info("algo route: %s" % url) response = safe_fetch(url, deadline=15, notify=False) content = response.content.strip() if response else None result = {"estimated_distance": 0.0, "estimated_duration": 0.0} if content: route = simplejson.loads(content) if "Error" in route: logging.error(route["Error"]) else: result = { "estimated_distance": float(route[AlgoField.DISTANCE]), "estimated_duration": float(route[AlgoField.TIME_SECONDS]) } return result
def convert_to_pdf(html): """ Using C{PDF_SERVICE_URL}, convert the given html to pdf @param html: the html will be encoded to C{utf-8} @return: the converted document """ res = safe_fetch(PDF_SERVICE_URL, payload=urlencode({"html": html.encode("utf-8")}), method="POST") return res.content if res else None
def is_ok(cls): ok = False url = "%s%s" % (cls.base_url, "Status.aspx") result = safe_fetch(url, deadline=30, notify=False) if result and result.content: status = simplejson.loads(result.content) if status.get('Status') == "OK": ok = True return ok
def telmap_fetch_results(data, request_template): """ Performs a query to telmap server Creates a query XML and sends it to Telmap servers Returns parsed result object """ c = Context(data) t = get_template(request_template) payload = u"sid=%s&requestXML=%s" % (data["server_id"], urlquote_plus(t.render(c))) # logging.info(u"sid=%s&requestXML=%s" % (data['server_id'], t.render(c))) res = safe_fetch(u"%s?%s" % (TELMAP_XML_API_URL, payload), method="GET", notify=False) # , payload=payload) if res: cleaned_response = clean_telmap_response(res.content) return minidom.parseString(cleaned_response) else: return None
def GetAccessToken(): body = urllib.urlencode({ 'grant_type': 'refresh_token', 'client_id': CLIENT_ID, 'client_secret': CLIENT_SECRET, 'refresh_token': REFRESH_TOKEN, }) headers = { 'content-type': 'application/x-www-form-urlencoded', } res = safe_fetch("https://accounts.google.com/o/oauth2/token", payload=body, headers=headers, method=POST) if res: json = simplejson.loads(res.content) return json['access_token'] else: return None
def report_conversion(udid): url = "http://tracking.taptica.com/aff_u" payload = urlencode( { "tt_adv_id": 612, "tt_deviceid": udid, "tt_appid": 501682022, "tt_time": default_tz_now().strftime("%Y-%m-%d %H:%M:%S.%f"), } ) url = "%s?%s" % (url, payload) logging.info("report_conversion: %s" % url) res = safe_fetch(url, method="GET", deadline=15) if res: res = simplejson.loads(res.content)["tt_cid"] return res
def report_conversion(udid): url = "http://tracking.taptica.com/aff_u" payload = urlencode({ "tt_adv_id": 612, "tt_deviceid": udid, "tt_appid": 501682022, "tt_time": default_tz_now().strftime("%Y-%m-%d %H:%M:%S.%f"), }) url = "%s?%s" % (url, payload) logging.info("report_conversion: %s" % url) res = safe_fetch(url, method="GET", deadline=15) if res: res = simplejson.loads(res.content)["tt_cid"] return res
def telmap_fetch_results(data, request_template): """ Performs a query to telmap server Creates a query XML and sends it to Telmap servers Returns parsed result object """ c = Context(data) t = get_template(request_template) payload = u"sid=%s&requestXML=%s" % (data['server_id'], urlquote_plus(t.render(c))) # logging.info(u"sid=%s&requestXML=%s" % (data['server_id'], t.render(c))) res = safe_fetch(u"%s?%s" % (TELMAP_XML_API_URL, payload), method="GET", notify=False) #, payload=payload) if res: cleaned_response = clean_telmap_response(res.content) return minidom.parseString(cleaned_response) else: return None
def recalc_ride(orders): """ Calculate a shared ride from a list of orders """ payload = { "orders": [serialize_order(o) for o in orders], "parameters": get_parameters() } payload = simplejson.dumps(payload) logging.info(u"recalc=%s" % unicode(payload, "unicode-escape")) response = safe_fetch(M2M_ENGINE_URL, payload="recalc=%s" % payload, method=POST, deadline=50) logging.info("response=%s" % response.content) if response and response.content: ride_data = simplejson.loads(response.content)[AlgoField.RIDES][0] return RideData(ride_data) return None
def _fetch(cls, action, data, method=POST, notify=True): url = "%s%s" % (cls.base_url, action) data.update({ 'username': cls.USERNAME, 'password': cls.PASSWORD }) data = simplejson.dumps(data) logging.info("isrproxy %s: data=%s" % (action, data)) reply = safe_fetch(url, payload=data, method=method, deadline=30, notify=notify) if reply and reply.content: logging.info("_fetch result: %s" % reply.content) result = simplejson.loads(reply.content) if result.get("success", False): return reply else: logging.error("isr_proxy %s failed: %s" % (action, result.get("error"))) return None return None
def get_transaction_id(lang_code, mpi_data): data = ALL_QUERY_FIELDS.copy() # unique_id = get_unique_id() # # save passenger in the session # request.session[unique_id] = passenger data.update(mpi_data) data.update({ "terminal": BILLING_INFO["terminal_number"], "uniqueID": get_unique_id(), # this must be passed, although currently not used "amount": 0, "currency": "ILS", "transactionType": "Debit", "creditType": "RegularCredit", "transactionCode": "Phone", "validationType": "Verify", "langID": (lang_code or settings.LANGUAGE_CODE).upper(), "timestamp": datetime.now().replace(microsecond=0).isoformat( ) #"2011-10-22T15:44:53" #default_tz_now().isoformat() }) # encode data without using urlencode data = "&".join(["%s=%s" % i for i in data.items()]) logging.info(data) notify = not has_caller("run_billing_service_test") res = safe_fetch(BILLING_INFO["transaction_url"], method='POST', payload=data, deadline=50, notify=notify) if not res: return None elif res.content.startswith("--"): logging.error("No transaction ID received: %s" % res.content) return None else: return res.content
def send_invoices_passenger(billing_transactions): trx = billing_transactions[0] if not all([_trx.passenger.id == trx.passenger.id for _trx in billing_transactions]): logging.error("all transactions should belong to the same passenger") return False if not trx.passenger.invoice_id: logging.error("failed sending invoices to passenger_id %s: passenger has no invoice_id" % trx.passenger_id) return False payload = { "TransType" : "IR:CREATE101", "Username" : INVOICE_INFO["invoice_username"], "Key" : INVOICE_INFO["invoice_key"], "InvoiceSubject" : "%s %s" %(_("Ride Summary for month"), trx.charge_date.strftime("%m/%Y")), "InvoiceItemCode" : "|".join([str(trx.order.id) for trx in billing_transactions]), "InvoiceItemDescription" : "|".join([trx.order.invoice_description for trx in billing_transactions]), "InvoiceItemQuantity" : "|".join(["1" for trx in billing_transactions]), "InvoiceItemPrice" : "|".join([str(trx.amount) for trx in billing_transactions]), "MailTo" : trx.passenger.user.email, "CompanyCode" : trx.passenger.invoice_id, "ItemPriceIsWithTax" : 1, } url = INVOICE_INFO["invoice_url"] payload = dict([(k,v.encode('iso8859_8', 'ignore') if type(v) is types.UnicodeType else v) for (k,v) in payload.items()]) payload = urlencode(payload) result = safe_fetch(url, method="POST", payload=payload, deadline=50, headers={'Content-Type': 'application/x-www-form-urlencoded'}) response_code = re.findall(r"ResponseCode:(\d+)", result.content) if response_code and response_code[0] == "100": for tx in billing_transactions: tx.invoice_sent = True tx.save() logging.info("invoices sent to passenger %s" % trx.passenger_id) return True else: logging.error("failed sending invoices to passenger_id %s: response_code=%s" % (trx.passenger_id, response_code)) return False
def _fetch(cls, action, data, method=POST, notify=True): url = "%s%s" % (cls.base_url, action) data.update({'username': cls.USERNAME, 'password': cls.PASSWORD}) data = simplejson.dumps(data) logging.info("isrproxy %s: data=%s" % (action, data)) reply = safe_fetch(url, payload=data, method=method, deadline=30, notify=notify) if reply and reply.content: logging.info("_fetch result: %s" % reply.content) result = simplejson.loads(reply.content) if result.get("success", False): return reply else: logging.error("isr_proxy %s failed: %s" % (action, result.get("error"))) return None return None
def find_matches(candidate_rides, order_settings): payload = { AlgoField.RIDES : [serialize_shared_ride(r) for r in candidate_rides], "order" : serialize_order_settings(order_settings), "parameters" : get_parameters(extra={"debug": order_settings.debug}) } payload = simplejson.dumps(payload) logging.info(u"submit=%s" % unicode(payload, "unicode-escape")) dt1 = datetime.now() response = safe_fetch(M2M_ENGINE_URL, payload="submit=%s" % payload, method=POST, deadline=50) dt2 = datetime.now() logging.info("response=%s" % response.content) matches = [] if response and response.content: matches = simplejson.loads(response.content)[AlgoField.RIDES] logging.info("%s candidates [%s], %s matches (+1 new), %s seconds" % (len(candidate_rides), ",".join([str(ride.id) for ride in candidate_rides]), max(0, len(matches)-1), (dt2 - dt1).seconds)) return [RideData(match) for match in matches]