def process_data(self, payment, request, **kwargs): # Verifying the payment amount = int(payment.total // 10) pay = payment.change_status(PaymentStatus.CONFIRMED) client = Client(self._web_service) if request.GET.get('Status') == 'OK': result = client.service.PaymentVerification(self._merchant_code, request.GET['Authority'], amount) if result.Status == 100: payment.change_status(PaymentStatus.CONFIRMED) # return HttpResponse('Transaction success. RefID: ' + str(result.RefID)) elif result.Status == 101: payment.change_status(PaymentStatus.WAITING) # return HttpResponse('Transaction submitted : ' + str(result.Status)) else: payment.change_status(PaymentStatus.REJECTED) # return HttpResponse('Transaction failed. Status: ' + str(result.Status)) else: # return HttpResponse('Transaction failed or canceled by user') payment_track_id = result.RefID payment.save() return
def fetch_version_info(update_all=False): pre_fetch_version.send(object.__class__) client = Client(url=wsdl_source) result = client.service.GetAllDownloadFileInfo() for item in result.DownloadFileInfo: ver, created = Version.objects.get_or_create( ver=item['VersionId'], dumpdate=datetime.datetime.strptime(item['TextVersion'][-10:], "%d.%m.%Y").date(), ) if created or update_all: setattr(ver, 'complete_xml_url', item['FiasCompleteXmlUrl']) setattr(ver, 'complete_dbf_url', item['FiasCompleteDbfUrl']) if hasattr(item, 'FiasDeltaXmlUrl'): setattr(ver, 'delta_xml_url', item['FiasDeltaXmlUrl']) else: setattr(ver, 'delta_xml_url', None) if hasattr(item, 'FiasDeltaDbfUrl'): setattr(ver, 'delta_dbf_url', item['FiasDeltaDbfUrl']) else: setattr(ver, 'delta_dbf_url', None) ver.save() post_fetch_version.send(object.__class__)
def _get_send_status(self, track_id, signature_d, token): url = server_url[ self.company_id.dte_service_provider] + 'QueryEstUp.jws?WSDL' ns = 'urn:' + server_url[ self.company_id.dte_service_provider] + 'QueryEstUp.jws' _server = Client(url, ns) rut = self.format_rut(self.company_id.main_id_number) respuesta = _server.getEstUp(rut[:8], str(rut[-1]), track_id, token) self.sii_message = respuesta resp = xmltodict.parse(respuesta) status = False if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "-11": status = { 'warning': { 'title': _('Error -11'), 'message': _("Error -11: Espere a que sea aceptado por el SII, intente en 5s más" ) } } if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "EPR": self.state = "Proceso" if resp['SII:RESPUESTA']['SII:RESP_BODY']['RECHAZADOS'] == "1": self.sii_result = "Rechazado" elif resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "RCT": self.state = "Rechazado" status = { 'warning': { 'title': _('Error RCT'), 'message': _(resp['SII:RESPUESTA']['GLOSA']) } } return status
def _get_dte_status(self): for r in self: if not r.sii_xml_request or r.sii_xml_request.state not in ['Aceptado', 'Reparo']: continue partner_id = r.partner_id or r.company_id.partner_id token = r.sii_xml_request.get_token(self.env.user, r.company_id) signature_d = self.env.user.get_digital_signature(r.company_id) url = server_url[r.company_id.dte_service_provider] + 'QueryEstDte.jws?WSDL' _server = Client(url) receptor = r.format_rut(partner_id.commercial_partner_id.main_id_number) scheduled_date = datetime.strptime(r.scheduled_date[:10], "%Y-%m-%d").strftime("%d-%m-%Y") total = str(int(round(r.amount_total,0))) sii_code = str(r.location_id.document_type_id.code) response = None retry = 0 while response is None and retry < 1000: try: response = _server.service.getEstDte(signature_d['subject_serial_number'][:8], str(signature_d['subject_serial_number'][-1]), r.company_id.vat[2:-1], r.company_id.vat[-1], receptor[:8], receptor[-1], sii_code, str(r.sii_document_number), scheduled_date, total,token) r.sii_message = response except Exception: continue finally: retry += 1
def setDatrasClient(self, url): """ Creates a ICES/CIEM DATRAS WebServices client with the provided url. Parameters: url: string with the URL of the ICES/CIEM DATRAS WebService """ try: # It seems that DATRAS web service doesn't support strict self.datras_client = Client(url, settings=Settings(strict=False)) except: self.datras_client = None
def setWormsClient(self, url): """ Creates a WORMS WebServices client with the provided url. Parameters: url: string with the URL of the WORMS WebService """ try: self.worms_client = Client(url) except: self.worms_client = None
def get_synonyms(self, word): all_syns = [] syn_url = 'http://farsnet.nlp.sbu.ac.ir/WebAPI/services/SynsetService?WSDL' sen_url = 'http://farsnet.nlp.sbu.ac.ir/WebAPI/services/SenseService?WSDL' client = Client(syn_url) syns = client.service.getSynsetsByWord(searchStyle='EXACT', searchKeyword=word, userKey=self.userkey) client = Client(sen_url) for val in syns: if val['id'] != None: senses = client.service.getSensesBySynset(synsetId=val['id'], userKey=self.userkey) for s in senses: all_syns.append(s['word']['defaultValue']) return list(set(all_syns))
def __init__(self, ip=None, port=80, user="******", password="******", use_async=False, sub_xaddr_=None): assert (isinstance(port, int)) if sub_xaddr_ is not None: # overwrite xaddr self.xaddr = "http://%s:%i/onvif/%s" % (ip, port, sub_xaddr_) else: self.xaddr = "http://%s:%i/onvif/%s" % (ip, port, self.sub_xaddr) self.user = user self.password = password self.use_async = use_async self.service_addr = "{%s}%s" % (self.namespace, self.port) if self.use_async: self.async_transport = AsyncTransport(asyncio.get_event_loop(), cache=None) self.zeep_client = Client(wsdl=self.wsdl_file, wsse=UsernameToken(self.user, self.password, use_digest=True), settings=settings, transport=self.async_transport) else: self.zeep_client = Client(wsdl=self.wsdl_file, wsse=UsernameToken(self.user, self.password, use_digest=True), settings=settings) self.ws_client = self.zeep_client.create_service( self.service_addr, self.xaddr) self.factory = self.zeep_client.type_factory( "http://www.onvif.org/ver10/schema")
def main(args): if args.verbose: logging.config.dictConfig({ "version": 1, "formatters": { "verbose": { "format": "%(name)20s: %(message)s" } }, "handlers": { "console": { "level": "DEBUG", "class": "logging.StreamHandler", "formatter": "verbose", } }, "loggers": { "zeep": { "level": "DEBUG", "propagate": True, "handlers": ["console"], } }, }) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache() if args.cache else None session = requests.Session() if args.no_verify: session.verify = False result = urlparse(args.wsdl_file) if result.username or result.password: session.auth = (result.username, result.password) transport = Transport(cache=cache, session=session) st = time.time() settings = Settings(strict=not args.no_strict) client = Client(args.wsdl_file, transport=transport, settings=settings) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump()
def __init__(self, client: dict, **kwargs): """ Initialize and cache the current SOAP client. :param kwargs: """ fields = { key: value for key, value in client.items() if client and key in ClientSerializer.Meta.fields } self.client = Client(**fields) self.client_pk = client['pk'] self.context = kwargs['context']
def main(args): if args.verbose: logging.config.dictConfig({ 'version': 1, 'formatters': { 'verbose': { 'format': '%(name)20s: %(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'zeep': { 'level': 'DEBUG', 'propagate': True, 'handlers': ['console'], }, } }) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache() if args.cache else None session = requests.Session() if args.no_verify: session.verify = False result = urlparse(args.wsdl_file) if result.username or result.password: session.auth = (result.username, result.password) transport = Transport(cache=cache, session=session) st = time.time() strict = not args.no_strict client = Client(args.wsdl_file, transport=transport, strict=strict) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump()
def get_send_status(token, dte_service_provider, track_id, company_vat): url = SERVER_URL[dte_service_provider] + 'QueryEstUp.jws?WSDL' _server = Client(url) status = None retry = 0 while status is None and retry < RETRIES: try: status = _server.service.getEstUp(company_vat[2:-1], company_vat[-1], track_id, token) except Exception: continue finally: retry += 1 return status
def main(args): if args.verbose: logging.config.dictConfig({ 'version': 1, 'formatters': { 'verbose': { 'format': '%(name)20s: %(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'zeep': { 'level': 'DEBUG', 'propagate': True, 'handlers': ['console'], }, } }) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache() if args.cache else InMemoryCache() transport_kwargs = {'cache': cache} if args.no_verify: transport_kwargs['verify'] = False result = urlparse(args.wsdl_file) if result.username or result.password: transport_kwargs['http_auth'] = (result.username, result.password) transport = Transport(**transport_kwargs) st = time.time() client = Client(args.wsdl_file, transport=transport) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump()
def get_seed(mode): url = SERVER_URL[mode] + 'CrSeed.jws?WSDL' _server = Client(wsdl=url) seed = None retry = 0 while seed is None and retry < 1000: try: resp = _server.service.getSeed().replace( '<?xml version="1.0" encoding="UTF-8"?>', '') root = etree.fromstring(resp) seed = root[0][0].text except Exception: continue finally: retry += 1 return seed
def main(): os.system('clear') global name global start print("Digite o seu nome: ") name = input() client = Client('http://192.168.100.7:9998/WSHello?wsdl') start = client.service.chatConnect(name) ct = Thread(target=threadGet, args=(client, )) ct.start() chat(client)
def __init__(self, *args, **kwargs): self.cert = kwargs.get('cert', self.cert) self.ca_cert = kwargs.get('ca_cert', self.ca_cert) self.key = kwargs.get('key', self.key) self.company = kwargs.get('company', self.company) self.username = kwargs.get('username', self.username) self.timeout = kwargs.get('timeout', self.timeout) session = Session() if self.cert and self.key and self.ca_cert: session.cert = (self.cert, self.key) session.verify = self.ca_cert elif self.cert or self.key or self.ca_cert: raise ValueError("Must provide cert, ca_cert and key") self.client = Client(self.endpoint, transport=Transport(session=session, timeout=self.timeout))
def get_seed(self, company_id): # En caso de que haya un problema con la validación de certificado del # sii ( por una mala implementación de ellos) # esto omite la validacion try: import ssl ssl._create_default_https_context = ssl._create_unverified_context except: pass url = server_url[company_id.dte_service_provider] + 'CrSeed.jws?WSDL' ns = 'urn:'+server_url[company_id.dte_service_provider] + 'CrSeed.jws' # _server = Client(url, ns) _server = Client(url) root = etree.fromstring(_server.service.getSeed().replace( '<?xml version="1.0" encoding="UTF-8"?>', '')) seed = root[0][0].text return seed
def _get_dte_status(self, signature_d, token): url = server_url[ self.company_id.dte_service_provider] + 'QueryEstDte.jws?WSDL' ns = 'urn:' + server_url[ self.company_id.dte_service_provider] + 'QueryEstDte.jws' _server = Client(url, ns) receptor = self.format_rut( self.partner_id.vat or self.company_id.partner_id.main_id_number) date_invoice = datetime.strptime(self.date_invoice, "%Y-%m-%d").strftime("%d-%m-%Y") response = None retry = 0 while response is None and retry < 1000: try: response = _server.getEstDte( signature_d['subject_serial_number'][:8], str(signature_d['subject_serial_number'][-1]), self.company_id.vat[2:-1], self.company_id.vat[-1], receptor[:8], receptor[2:-1], str(self.document_class_id.code), str(self.sii_document_number), date_invoice, str(self.amount_total), token) except Exception: continue finally: retry += 1 self.sii_message = response resp = xmltodict.parse(response) if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == '2': status = { 'warning': { 'title': _("Error code: 2"), 'message': _(resp['SII:RESPUESTA']['SII:RESP_HDR']['GLOSA']) } } return status if resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "EPR": self.state = "Proceso" if resp['SII:RESPUESTA']['SII:RESP_BODY']['RECHAZADOS'] == "1": self.state = "Rechazado" if resp['SII:RESPUESTA']['SII:RESP_BODY']['REPARO'] == "1": self.state = "Reparo" elif resp['SII:RESPUESTA']['SII:RESP_HDR']['ESTADO'] == "RCT": self.state = "Rechazado"
def get_dte_claim(token, dte_service_provider, company_vat, document_type_code, sii_document_number): url = CLAIM_URL[dte_service_provider] + '?wsdl' settings = Settings(strict=False, extra_http_headers={'Cookie': 'TOKEN=' + token}) retry = 0 response = None _server = Client(url, settings=settings) while response is None and retry < RETRIES: try: response = _server.service.listarEventosHistDoc( company_vat[2:-1], company_vat[-1], str(document_type_code), str(sii_document_number)) except: continue finally: retry += 1 return response
def set_dte_claim(token, dte_service_provider, rut_emisor, sii_document_number, document_type_id, claim): url = CLAIM_URL[dte_service_provider] + '?wsdl' settings = Settings(strict=False, extra_http_headers={'Cookie': 'TOKEN=' + token}) _server = Client(url, settings=settings) retry = 0 response = None while response is None and retry < RETRIES: try: response = _server.service.ingresarAceptacionReclamoDoc( rut_emisor[:-2], rut_emisor[-1], str(document_type_id.code), str(sii_document_number), claim) except: continue finally: retry += 1 return response
def __init__(self, *args, **kwargs): super(IBabsBaseExtractor, self).__init__(*args, **kwargs) try: ibabs_wsdl = self.source_definition['wsdl'] except Exception: ibabs_wsdl = settings.IBABS_WSDL soap_settings = Settings( strict=False, xml_huge_tree=True, xsd_ignore_sequence_order=True, extra_http_headers={'User-Agent': settings.USER_AGENT}, ) try: self.client = Client(ibabs_wsdl, port_name='BasicHttpsBinding_IPublic', settings=soap_settings) except Error as e: log.error('Unable to instantiate iBabs client: ' + str(e))
def main(args): if args.verbose: logging.config.dictConfig({ 'version': 1, 'formatters': { 'verbose': { 'format': '%(name)s: %(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'zeep': { 'level': 'DEBUG', 'propagate': True, 'handlers': ['console'], }, } }) if args.profile: import cProfile profile = cProfile.Profile() profile.enable() cache = SqliteCache(persistent=args.cache) transport = Transport(cache=cache) st = time.time() client = Client(args.wsdl_file, transport=transport) logger.debug("Loading WSDL took %sms", (time.time() - st) * 1000) if args.profile: profile.disable() profile.dump_stats(args.profile) client.wsdl.dump()
def get_form(self, payment, data=None): client = Client(self._web_service) # converting rial to tooman amount = int(payment.total // 10) description = payment.description CallbackURL = payment.get_return_url() result = client.service.PaymentRequest(MerchantID=self._merchant_code, Amount=amount, # email, # mobile, Description=description, CallbackURL=CallbackURL) redirect_url = 'https://www.zarinpal.com/pg/StartPay/' + str(result.Authority) if result.Status == 100: payment.change_status(PaymentStatus.INPUT) raise RedirectNeeded(redirect_url)
def __init__(self, xaddr, wsse: UsernameDigestTokenDtDiff, url: Path, *, bindingName='', transport=None): if not url.is_file(): raise ONVIFError('%s doesn`t exist!' % url) self.url = url self.xaddr = xaddr if not transport: transport = AsyncTransport(None) self.client = Client(wsdl=str(url), wsse=wsse, transport=transport, settings=Settings(strict=False, xml_huge_tree=True)) self.wsClient = self.client.create_service(bindingName, xaddr) self.bindingName = bindingName
def get_dte_status(signature_d, service_provider, **kwargs): response = None retry = 0 token = sii_token(service_provider, signature_d['priv_key'], signature_d['cert']) url = SERVER_URL[service_provider] + 'QueryEstDte.jws?WSDL' _server = Client(url) while response is None and retry < RETRIES: try: response = _server.service.getEstDte( kwargs.get('rut')[:8], kwargs.get('rut')[-1], kwargs.get('company_vat')[2:-1], kwargs.get('company_vat')[-1], kwargs.get('receptor')[:8], kwargs.get('receptor')[-1], kwargs.get('document_type_code'), kwargs.get('sii_document_number'), kwargs.get('invoice_date'), kwargs.get('amount_total'), token) except Exception as error: continue finally: retry += 1 return response
def get_token(mode, private_key, cert, seed): template_string = u'''<getToken> <item> <Semilla>{}</Semilla> </item> </getToken> '''.format(seed) doc = etree.fromstring(template_string) signed_node = XMLSigner(method=methods.enveloped, digest_algorithm='sha1').sign( doc, key=private_key.encode('ascii'), cert=cert) seed_file = etree.tostring(signed_node, pretty_print=True).decode().replace('ds:', '') _logger.debug('######------- seed file %s' % seed_file) resp = None retry = 0 while resp is None and retry < 1000: try: url = SERVER_URL[mode] + 'GetTokenFromSeed.jws?WSDL' _server = Client(wsdl=url) tree = etree.fromstring(seed_file) ss = etree.tostring(tree, pretty_print=True, encoding='iso-8859-1').decode() resp = _server.service.getToken(ss) except: continue finally: retry += 1 try: response = etree.fromstring( resp.replace('<?xml version="1.0" encoding="UTF-8"?>', '')) except AttributeError: raise UserError( 'El servidor del SII no está disponible. Intente nuevamente') return response[0][0].text
async def initialize(self) -> bool: try: logging.getLogger('urllib3.connectionpool').setLevel(logging.WARNING) logging.getLogger('zeep.wsdl.wsdl').setLevel(logging.WARNING) logging.getLogger('zeep.xsd.schema').setLevel(logging.WARNING) logging.getLogger('zeep.transports').setLevel(logging.WARNING) self.__server_url = f"{self.server_address}" self.logger.info( f"Trying to connect.\nURL: {self.__server_url}\nClient supported protocols: {json.dumps(self.protocols)}" ) wsdl_file_path = f"{os.path.dirname(os.path.realpath(__file__))}/wsdl/server-201206.wsdl" self._client = Client( wsdl=wsdl_file_path, settings=Settings( raw_response=False, ), plugins=[WsAddressingExtensionPlugin(self.from_address)] ) self._client_service = self._client.create_service( '{urn://Ocpp/Cs/2012/06/}CentralSystemServiceSoap', self.__server_url ) await asyncio.sleep(1) if self.register_on_initialize: await self.action_register() await self.action_heart_beat() return True except ValueError as err: await self.handle_error(ErrorMessage(err).get(), ErrorReasons.InvalidResponse) return False except BaseException as err: await self.handle_error(ErrorMessage(err).get(), ErrorReasons.InvalidResponse) return False
def query_REGON_api( wsdl_path, key, query_params) -> Union[RegonApiSuccess, RegonApiNotFoundFailure]: client = Client(wsdl_path) # 1. Create zeep client with wsdl url sid = client.service.Zaloguj( key) # 2. Pass the access key to login endpoint with client.settings(extra_http_headers={"sid": sid}): # 4. Token must be passed as a HTTP header. # "HTTP" is an important word here, as SOAP # has a damn hell of different headers. response: str = client.service.DaneSzukajPodmioty( pParametryWyszukiwania=query_params) parsed_response: Union[OrderedDict, None] = xmltodict.parse(response) if parsed_response is None: raise HTTPException( 400, f"Response is malformed. RESPONSE = '{response}'") elif response_body := parsed_response.get("root", {}).get("dane", {}): if isinstance(response_body, list): to_parse = response_body[0] elif response_body.get("Regon"): to_parse = response_body else: error_response_reformatted = { key: response_body.get(value, None) for key, value in parsing_error_dict.items() } return RegonApiNotFoundFailure(**error_response_reformatted) response_reformatted = { key: to_parse.get(value, None) for key, value in parsing_dict.items() } return RegonApiSuccess(**response_reformatted) else:
import urllib3 import lxml.etree as etree import lxml.objectify as objectify from zeep.client import Client # Declare credentials to be used with the Stage Transaction Request credentials_name = "TEST MERCHANT" credentials_site_id = "XXXXXXXX" credentials_key = "XXXXX-XXXXX-XXXXX-XXXXX-XXXXX" ip_address = "192.168.0.123" # Generate XML and XSD Validation genius_schema = etree.XMLSchema(file='Genius.xsd') xml_parser = objectify.makeparser(schema=genius_schema) # Generate WSDL and SOAP Objects Build Transport request details transport_soap = Client( wsdl='https://transport.merchantware.net/v4/transportService.asmx?WSDL') transport_request = transport_soap.get_type("ns0:TransportRequest")( TransactionType="SALE", Amount=1.01, ClerkId="1", OrderNumber="INV1234", Dba="TEST MERCHANT", SoftwareName="Test Software", SoftwareVersion="1.0", TerminalId="01", PoNumber="PO1234", TaxAmount="0.10", EntryMode="Undefined", ForceDuplicate=True) # Stage Transaction print("Staging Transaction\n")
else: for item in result: yield item try: from zeep.client import Client from zeep import __version__ as zver z_major, z_minor, z_sub = list(map(int, zver.split('.'))) if z_minor < 20: parse_func = parse_item_as_object elif z_minor > 20: parse_func = parse_item_as_dict client = Client(wsdl=wsdl_source) except ImportError: try: from suds.client import Client parse_func = parse_item_as_dict client = Client(url=wsdl_source, proxy=PROXY or None) except ImportError: raise ImproperlyConfigured( 'Не найдено подходящей библиотеки для работы с WSDL.' ' Пожалуйста установите zeep или suds!') def fetch_version_info(update_all=False):