我一直在尝试使用python和请求库进行soap调用,因为它在xml文件定义上非常灵活。我尝试过zeed和sud,不幸的是,在我创建实例之前,zeed不允许我定义portypes并且suds不允许我更改enconding文件,suds只是使用utf-8,然后我决定使用request library for raw soap呼叫。但是,响应始终为状态500。
我的问题是:
响应
response.status_code 500
response.text <?xml version='1.0' ?>
<env:Envelope xmlns:env='http://schemas.xmlsoap.org/soap/envelope/'>
<env:Body>
<env:Fault>
<faultcode>env:Client</faultcode>
<faultstring>Internal Error</faultstring>
</env:Fault>
</env:Body>
</env:Envelope>
代码
import os
import pystache
import requests
import base64
import urllib
from wsse.client.requests.auth import WSSEAuth
invoice_file_name = '10101010101-03-F004-00000001.zip'
invoice_file_path = 'path_to/10101010101-03-F004-00000001.zip'
with open(invoice_file_path, 'rb') as file:
invoice_file_data = base64.b64encode(file.read())
xml_send_bill_path = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'templates',
'send_bill.xml'
)
with open(xml_send_bill_path, 'r') as file:
xml_send_bill = file.read()
xml_send_bill_string = pystache.render(xml_send_bill, {
'SunatRUC': '20100066603',
'SunatUser': 'MODDATOS',
'SunatPass': 'moddatos',
'InvoiceFileName': invoice_file_name,
'InvoiceFileContent': invoice_file_data
})
WSDL_URL = 'https://e-factura.sunat.gob.pe/ol-ti-itcpfegem/billService?wsdl'
#WSDL_URL = 'https://e-beta.sunat.gob.pe/ol-ti-itcpfegem-beta/billService?wsdl';
encoded_request = xml_send_bill_string.encode('iso-8859-1')
headers = {
'content-type': 'text/xml',
'charset': 'iso-8859-1',
"Content-Length": str(len(encoded_request))
}
response = requests.post(
url=WSDL_URL,
data=encoded_request,
headers=headers,
auth = WSSEAuth('20100066603MODDATOS', 'moddatos')
)
print ("response.status_code", response.status_code)
print ("response.text", response.text)
XML模板
<?xml version='1.0' encoding='ISO-8859-1' standalone='no'?>
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:ser="http://service.sunat.gob.pe" xmlns:wsse="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd">
<soapenv:Header>
<wsse:Security>
<wsse:UsernameToken>
<wsse:Username>{{SunatRUC}}{{SunatUser}}</wsse:Username>
<wsse:Password>{{SunatPass}}</wsse:Password>
</wsse:UsernameToken>
</wsse:Security>
</soapenv:Header>
<soapenv:Body>
<ser:sendBill>
<fileName>{{InvoiceFileName}}</fileName>
<contentFile>{{{InvoiceFileContent}}}</contentFile>
</ser:sendBill>
</soapenv:Body>
</soapenv:Envelope>