示例#1
0
class WSClient(object):
    endpoint = 'https://ws.ingbusinessonline.pl/ing-ccs/cdc00101?wsdl'
    cert = None
    ca_cert = None
    key = None
    company = ''
    username = ''
    timeout = 300

    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_headers(self):
        hdr = self.client.get_element('ns21:CcsHeader')
        data = {
            'FinInstID': 'INGBankŚląski',
            'PartnerID': self.company,
            'PassID': self.username,
            'ProdID': {
                'manufacturer': 'zeep',
                'ver': zeep.__version__,
                'langVer': 'en',
            },
            'Version': 2,
            'Revision': 2,
        }
        return hdr(**data)

    def get_msg_id(self):
        prefix = 'REQ'
        rnd = ''.join([
            random.choice('123456789ABCDEFGHJKLMNQRSTUVWXYZ')
            for i in range(16)
        ])
        return '%s%s' % (prefix, rnd)

    def get_history(self, account_number, start_date, end_date):
        method = self.client.service.GetAccountReport
        doctype = self.client.get_type('ns1:GetAccountReportRequestType')
        data = {
            'MsgId': {
                'Id': self.get_msg_id()
            },
            'AcctRptQryDef': {
                'AcctRptCrit': {
                    'NewCrit': {
                        'SchCrit': {
                            'AcctId': {
                                'EQ': {
                                    'IBAN': account_number,
                                }
                            },
                            'AcctRptValDt': {
                                'DtSch': {
                                    'FrDt': start_date,
                                    'ToDt': end_date,
                                },
                            },
                        }
                    }
                }
            }
        }
        document = doctype({'GetAcctRpt': data})
        resp = method(document['Document'], _soapheaders=[self.get_headers()])
        return History(resp.Rpt)

    def transfer_domestic(self, account_number, transfers, initiator=''):
        method = self.client.service.DomesticTransfer
        doctype = self.client.get_type('ns1:TransferRequestType')
        _country = re.compile(r'^[A-Z]{2}')
        _charfilter = re.compile(r'[^A-Za-z0-9/\-+()/\']')
        dmstc_from_acc = _country.sub('', account_number)
        now = datetime.now()
        to_send = []
        for txf in transfers:
            dmstc_to_acc = _country.sub('', txf['account_number'])
            transfer = {
                'PmtId': {
                    'EndToEndId':
                    _charfilter.sub(
                        '',
                        unidecode(
                            txf.get('description',
                                    'not provided').replace(u' ', u'_')))[:32],
                },
                'Amt': {
                    'InstdAmt': {
                        '_value_1': txf['amount'],
                        'Ccy': txf.get('currency', 'PLN'),
                    },
                },
                'CdtrAgt': {
                    'FinInstnId': {
                        'ClrSysMmbId': {
                            'MmbId': dmstc_to_acc[2:10],
                        }
                    }
                },
                'Cdtr': {
                    'Nm': charfilter(txf['account_holder_name'],
                                     allow_polish=True),
                    'PstlAdr': {
                        'AdrLine':
                        cleanaddress(txf.get('account_holder_address', ''),
                                     allow_polish=True)[:35],
                        'Ctry':
                        txf.get('account_holder_country', 'pl').upper(),
                    }
                },
                'CdtrAcct': {
                    'Id': {
                        'Othr': {
                            'Id': dmstc_to_acc,
                        }
                    }
                },
                'RmtInf': {
                    'Ustrd':
                    charfilter(txf.get('description', ''),
                               allow_polish=True)[:140].strip(),
                }
            }
            to_send.append(transfer)
        data = {
            'GrpHdr': {
                'MsgId': self.get_msg_id(),
                'CreDtTm': now,
                'NbOfTxs': len(transfers),
                'InitgPty': {
                    'Nm': initiator,
                },
            },
            'PmtInf': {
                'PmtInfId': now.strftime('%Y%m%d%H%M%S'),
                'PmtMtd': 'TRF',
                'ReqdExctnDt': now.date(),
                'Dbtr': {
                    'Nm': self.company,
                },
                'DbtrAcct': {
                    'Id': {
                        'Othr': {
                            'Id': dmstc_from_acc,
                        }
                    }
                },
                'DbtrAgt': {
                    'FinInstnId': {
                        'ClrSysMmbId': {
                            'ClrSysId': {
                                'Cd': 'PLKNR',
                            },
                            'MmbId': dmstc_from_acc[2:10],
                        },
                    }
                },
                'CdtTrfTxInf': to_send,
            }
        }
        document = doctype({'CstmrCdtTrfInitn': data})
        resp = method(document['Document'])
        return [(sts.TxSts, sts.AccptncDtTm)
                for sts in resp.OrgnlPmtInfAndSts[0].TxInfAndSts]

    def transfer_sepa(self, account_number, transfers, initiator=''):
        method = self.client.service.SEPATransfer
        doctype = self.client.get_type('ns1:TransferRequestType')
        _charfilter = re.compile(r'[^A-Za-z0-9/\-+()/\']')
        now = datetime.now()
        to_send = []
        for txf in transfers:
            transfer = {
                'PmtId': {
                    'EndToEndId':
                    _charfilter.sub(
                        '',
                        unidecode(
                            txf.get('description',
                                    'not provided').replace(u' ', u'_')))[:32],
                },
                'Amt': {
                    'InstdAmt': {
                        '_value_1': txf['amount'],
                        'Ccy': txf['currency'],
                    },
                },
                'Cdtr': {
                    'Nm': charfilter(txf['account_holder_name']),
                    'PstlAdr': {
                        'AdrLine':
                        cleanaddress(txf.get('account_holder_address',
                                             ''))[:35],
                        'Ctry':
                        txf.get('account_holder_country', 'pl').upper(),
                    }
                },
                'CdtrAcct': {
                    'Id': {
                        'IBAN': txf['account_number'],
                    }
                },
                'RmtInf': {
                    'Ustrd': charfilter(txf.get('description',
                                                ''))[:140].strip(),
                },
                'PmtTpInf': {
                    'SvcLvl': {
                        'Cd': 'SEPA',
                    }
                },
            }
            to_send.append(transfer)
        data = {
            'GrpHdr': {
                'MsgId': self.get_msg_id(),
                'CreDtTm': now,
                'NbOfTxs': len(transfers),
                'InitgPty': {
                    'Nm': initiator,
                },
            },
            'PmtInf': {
                'PmtInfId': now.strftime('%Y%m%d%H%M%S'),
                'PmtMtd': 'TRF',
                'ReqdExctnDt': now.date(),
                'Dbtr': {
                    'Nm': self.company,
                },
                'DbtrAcct': {
                    'Id': {
                        'IBAN': account_number,
                    }
                },
                'ChrgBr': 'SLEV',
                'DbtrAgt': {
                    'FinInstnId': {
                        'BIC': 'ING',
                    }
                },
                'CdtTrfTxInf': to_send,
            }
        }
        document = doctype({'CstmrCdtTrfInitn': data})
        resp = method(document['Document'])
        return [(sts.TxSts, sts.AccptncDtTm)
                for sts in resp.OrgnlPmtInfAndSts[0].TxInfAndSts]

    def transfer_swift(self, account_number, transfers, initiator=''):
        raise NotImplementedError("SWIFT is not implemented")
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")
transport_response = transport_soap.service.CreateTransaction(
    credentials_name, credentials_site_id, credentials_key, transport_request)
transport_key = transport_response.TransportKey
print("TransportKey Received: %s\n" % transport_key)
# Initiate transaction with TransportKey
print("Sending TransportKey %s to Terminal %s" % (transport_key, ip_address))
genius_comm = urllib3.PoolManager()