Description
Добрый день!
Есть вопрос по Диадок. Не могу прикрепить неформализованный файл к имеющему в Диадок УПД. При вызове MessagePost.
но загрузить файл, оказывается не получалось, по причине отсутствия права подписи:
An unhandled exception of type 'Diadoc.Api.Http.HttpClientException' occurred in mscorlib.dll
Additional information: BaseUrl=https://diadoc-api.kontur.ru, PathAndQuery=/V3/PostMessage?operationId=,
AdditionalMessage=У вас нет права подписи в организации, StatusCode=Forbidden, DiadocErrorCode: DocumentService.EmployeeCannotSignDocuments
В связи с этим у меня единственный вопрос.
Так как я авторизуюсь по логину и паролю, т.е. без сертификата, то файл (неформализованный, в нашем случае PDF)
мы не подписываем, и это не требуется.
Поэтому вопрос, почему, из веб-интерфейса Диадок я могу загрузить файл к УПД, а через API Диадок пишет, что нет права подписи, хотя логин и пароль, понятное дело те же самые.
Поясню со скринами. Вот так, работает (права подписи нет):
А вот так из кода (без сертификата, т.е. точно так же, не работает, именно MessagePost):
А вот так не работает (выделил жирным ключевые моменты). Можете подсказать почему?
Ведь аккаунт тот же самый?
// init crypto api and Diadoc api
WinApiCrypt crypt = new WinApiCrypt();
DiadocApi api = new DiadocApi(konturDiadocApiKey, konturDiadocUrl, crypt);
// define proxy settings
Uri uri = new Uri(konturDiadocUrl);
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");
// set proxy
api.SetProxyCredentials(credential);
// login using user name and password
string authToken = api.Authenticate(konturLogin, SynchEDI.Common.Security.Crypt.DecryptString(konturPassword));
// save token
KonturDiadocSecurity.SetToken(authToken);
string docNum = "55190/1";
DateTime docDate = DateTime.Parse("18.12.2018");
string documentDate = docDate.ToString("dd.MM.yyyy");
Diadoc.Api.Proto.Documents.Document document = null;
string afterIndexKey = string.Empty;
while (true)
{
// get documents list within specific date range
Diadoc.Api.Proto.Documents.DocumentList documentList = api.GetDocuments(authToken, mainSaksBoxId, "Any.OutboundFinished", null, null, null, documentDate, documentDate, null, false, afterIndexKey);
if (documentList == null || documentList.TotalCount == 0)
break;
// remember last index key to select next document list
afterIndexKey = documentList.Documents[documentList.Documents.Count - 1].IndexKey;
// find document in list from a bunch of documents
document = documentList.Documents.Find(x => x.DocumentDate == documentDate && x.DocumentNumber == docNum);
// exit cycle when document found
if (document != null)
break;
} // ~while
// load file
string filePath = "55190_1.pdf";
byte[] fileContent = SynchEDI.Common.Security.Files.ReadFileToByteArray(filePath, out errMessage);
// select main box for saks (for test)
EDI.EdiRouting.OrganizationCode orgCode = EDI.EdiRouting.OrganizationCode.Saks;
switch (orgCode)
{
case EDI.EdiRouting.OrganizationCode.Igrushki: transportBoxId = mainIgrushkiBoxId; break;
case EDI.EdiRouting.OrganizationCode.Saks: transportBoxId = mainSaksBoxId; break;
}
/*
// Для того, чтобы подписать файл, требуется сертификат
var cert = new X509Certificate2(certContent);
// Подписываем содержимое файла
var signature = crypt.Sign(content, cert.RawData);
*/
// create message to post
MessageToPost message = new MessageToPost
{
FromBoxId = transportBoxId, // sender box GUID
ToBoxId = document.CounteragentBoxId // recipient box GUID
};
// create nonformalized document
NonformalizedAttachment attachment = new NonformalizedAttachment
{
Comment = $"Список сертификатов к Торг-12 ({docNum} от {documentDate})",
FileName = new FileInfo(filePath).Name,
NeedRecipientSignature = false,
DocumentDate = DateTime.Now.ToShortDateString(),
DocumentNumber = docNum,
CustomDocumentId = document.PacketId,
SignedContent = new SignedContent
{
Content = fileContent,
// Signature = null
}
};
// add attachement to message
message.AddAttachment(attachment);
// send document via Diadoc
Message response = api.PostMessage(authToken, message);