Intereting Posts

Можно ли подключиться к .NET API через PHP?

Начинающий вопрос здесь. У меня есть сайт, написанный на PHP, который должен подключаться к используемому нами приложению. Приложение DocuWare предоставляет платформу платформы DocuWare .NET .NET . Можно ли использовать это в PHP?

На сайте приведены примеры, но они написаны на C #. Я привел пример со своего сайта, в котором показано, как подключиться к приложению на C #.

using System; using System.Collections.Generic; using System.Linq; using System.Net.Cache; using System.Net.Http; using DocuWare.Platform.ServerClient; namespace DocuWare.PlatformClientExamples { static partial class Examples { static Uri uri = new Uri("http://chw-dw-01/docuware/platform"); static public ServiceConnection Connect() { return ServiceConnection.Create(uri, "admin", "admin"); } static public ServiceConnection ConnectWithUserAgent() { return ServiceConnection.Create(uri, "admin", "admin", userAgent: new System.Net.Http.Headers.ProductInfoHeaderValue[] { new System.Net.Http.Headers.ProductInfoHeaderValue("DocuWare+.NET+API+Test+Client", "1.0") }); } static public ServiceConnection ConnectWithOrg() { return ServiceConnection.Create(uri, "admin", "admin", organization: "Peters Engineering"); } static public ServiceConnection ConnectWithCaching() { var handler = new WebRequestHandler() { CachePolicy = new RequestCachePolicy(RequestCacheLevel.Default) }; return ServiceConnection.Create(uri, "admin", "admin", httpClientHandler: handler); } static public ServiceConnection ConnectWithNTLM() { return ServiceConnection.CreateWithWindowsAuthentication(uri, "Administrator", "admin"); } static public ServiceConnection ConnectWithDefaultUser() { return ServiceConnection.CreateWithWindowsAuthentication(uri, System.Net.CredentialCache.DefaultCredentials); } } } 

Возможно ли это сделать на PHP с использованием альтернатив, или нам нужно изменить наш сайт PHP на C #, прежде чем мы сможем это сделать?

Вы можете подключиться к платформе DocuWare с помощью всего, что понимает HTTP. Я подключил его к Java, C / AL (Navision), Swift, …

Попробовали ли вы, чтобы Клиент «поиграть» с платформой?

Я создал класс для проверки подлинности в соответствии с API-интерфейсом REST 6.0 Documentware версии 6.10. Надеюсь, что это поможет (пожалуйста, извините немецкие комментарии):

 class DwPlatformAuthentication { /** * Authentication-Cookie * @var string $_auth */ private static $_auth = null; /** * BrowserId-Cookie * @var string $_browserid */ private static $_browserid = null; /** * liefert den Authentication-Cookie zurück */ public static function GetDwPlatformAuth() { return self::$_auth; } /** * liefert den BrowserId-Cookie zurück */ public static function GetDwPlatformBrowserId() { return self::$_browserid; } /** * stellt eine Verbindung zu Docuware (REST-Schnittstelle) her */ public static function GetAuthentication() { // enthält Konstanten für Datenbankverbindung (zB DOCUWARE_USER) require_once 'config.php'; // startet die Session session_start(); // ermittelt den aktuellen Authentifizierungs-Cookie if(isset($_SESSION['dwplatformauth']) && isset($_SESSION['dwplatformbrowserid'])){ self::$_auth = $_SESSION['dwplatformauth']; self::$_browserid = $_SESSION['dwplatformbrowserid']; } else{ // ermittelt einen neuen Authentifizierungs-Cookie, wenn keiner gespeichert ist // definiert den URL $url = DOCUWARE_HOST.'DocuWare/Platform/Account/Logon'; // definiert die POST-Parameter $data = array( 'UserName' => DOCUWARE_USER, 'Password' => DOCUWARE_PASS, 'Organization' => DOCUWARE_ORGA ); // use key 'http' even if you send the request to https://... $options = array( "http" => array( "header" => "Content-Type: application/x-www-form-urlencoded\r\n", "method" => "POST", "content" => http_build_query($data, "", "&") ), ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); //print_r($http_response_header); // ermittelt den Response-Header // ermittelt den Authentifizierungs-Cookie $dwplatformauth = explode('=', $http_response_header[8]); $dwplatformauth = explode(';', $dwplatformauth[1]); $dwplatformauth = $dwplatformauth[0]; // schreibt den Wert des Authentifizierungs-Cookies in eine Session-Variable if(isset($dwplatformauth) && $dwplatformauth != null){ $_SESSION['dwplatformauth'] = $dwplatformauth; } // ermittelt den DWPLATFORMBROWSERID-Cookie $dwplatformbrowserid = explode('=', $http_response_header[10]); $dwplatformbrowserid = explode(';', $dwplatformbrowserid[1]); $dwplatformbrowserid = $dwplatformbrowserid[0]; // schreibt den Wert des DWPLATFORMBROWSERID-Cookies in eine Session-Variable if(isset($dwplatformbrowserid) && $dwplatformbrowserid != null){ $_SESSION['dwplatformbrowserid'] = $dwplatformbrowserid; } self::$_auth = $_SESSION['dwplatformauth']; self::$_browserid = $_SESSION['dwplatformbrowserid']; } }} 

Вы можете использовать класс DwPlatformAuthentication в другом классе для создания документа:

 class DwPlatformDocument { /** * Indexfelder des Archiv, die bearbeitet werden sollen * @var DwPlatformFields $dwFields */ public $dwFields; /** * Der Name des Archivs. * Die FileCabinetId kann in den Eigenschaften (Allgemein) des Archivs über die DocuWare-Administration abgelesen werden. * @var string $fileCabinetId */ public $fileCabinetId; /** * speichert einen Datensatz in Docuware * @param DwPlatformFields $dwFields Daten, die an Docuware übergeben werden sollen * @param int $dwdocid Primary Key des Docuware-Datensatzes, der geändert werden soll * @return int $dwdocid Primärschlüssel des Datensatzes in Docuware */ public function saveDocuware($dwFields, $dwdocid = null) { if (empty ( $this->fileCabinetId )) { throw new Exception ( 'Die Eigenschaft fileCabinetId muss definiert werden.' ); } // bindet Klasse zur Authentifizierung von Docuware Platform Services ein require_once 'docuware/DwPlatformAuthentication.php'; // bindet Klasse zur Erzeugung von Indexfeldern eines Dokuments (Docuware Platform Service) ein require_once 'docuware/DwPlatformFields.php'; // stellt eine Verbindung zu Docuware her und ermittelt die Authentifizierungs-Cookies DwPlatformAuthentication::GetAuthentication (); // liefert den Wert des Authentifizierungs-Cookies zurück und speichert ihn in einer Variable $dwplatformauth = DwPlatformAuthentication::GetDwPlatformAuth (); // liefert den Wert des DWPLATFORMBROWSERID-Cookies zurück und speichert ihn in einer Variable $dwplatformbrowserid = DwPlatformAuthentication::GetDwPlatformBrowserId (); // UPDATE if (is_numeric ( $dwdocid )) { // definiert den URL // ermittelt die Indexfelder inkl. Indexdaten zu einem Dokument $url = DOCUWARE_HOST . 'DocuWare/Platform/FileCabinets/' . $this->fileCabinetId . '/Documents/' . $dwdocid . '/Fields'; } else { // INSERT // definiert den URL $url = DOCUWARE_HOST . 'DocuWare/Platform/FileCabinets/' . $this->fileCabinetId . '/Documents'; } // ermittelt die POST-Parameter aus den DwPlatformFields $data = array (); // zählt die Elemente des DwPlatformFields-Objekts $countFields = 0; foreach ( $dwFields->Fields as $field ) { $data ["Fields[" . $countFields . "].FieldName"] = $field->FieldName; $data ["Fields[" . $countFields . "].Item"] = $field->Item; $data ["Fields[" . $countFields . "].ItemElementName"] = $field->ItemElementName; $countFields ++; } // use key 'http' even if you send the request to https://... $options = array ( 'http' => array ( 'header' => "Content-type: application/x-www-form-urlencoded; charset=utf-8\r\n" . "Cookie: DWOrganization=YourCompanyName; " . "openInNewWindow=False; " . "DWPLATFORMBROWSERID=" . $dwplatformbrowserid . "; " . ".DWPLATFORMAUTH=" . $dwplatformauth . "\r\n", // ACHTUNG: "\r\n" muss in doppelten Anführungszeichen (") stehen -> '\r\n' funktioniert nicht!!! 'method' => 'POST', 'content' => http_build_query ( $data, '', '&' ) ) ); $context = stream_context_create ( $options ); $result = file_get_contents ( $url, false, $context ); // speichert die Antwort des POST-Request in einem XML-Objekt $xml = new SimpleXMLElement ( $result ); // UPDATE if (is_numeric ( $dwdocid )) { $dwdocid = ( string ) $xml->Field [9]->Int; } else { // INSERT $dwdocid = ( string ) $xml->attributes ()->Id; } return $dwdocid; } /** * lädt ein Dokument ins Docuware * @param DwPlatformFields $dwFields Indexdaten, die an Docuware übergeben werden sollen * @param string $filename Pfad der Datei, die ins Docuware geladen werden soll * @return int $dwdocid Primary Key des Datensatzes in Docuware */ public function uploadDocument ($dwFields, $filename){ if (empty ( $this->fileCabinetId )) { throw new Exception ( 'Die Eigenschaft fileCabinetId muss definiert werden.' ); } // bindet Klasse zur Authentifizierung von Docuware Platform Services ein require_once 'docuware/DwPlatformAuthentication.php'; // bindet Klasse zur Erzeugung von Indexfeldern eines Dokuments (Docuware Platform Service) ein require_once 'docuware/DwPlatformFields.php'; // stellt eine Verbindung zu Docuware her und ermittelt die Authentifizierungs-Cookies DwPlatformAuthentication::GetAuthentication (); // liefert den Wert des Authentifizierungs-Cookies zurück und speichert ihn in einer Variable $dwplatformauth = DwPlatformAuthentication::GetDwPlatformAuth (); // liefert den Wert des DWPLATFORMBROWSERID-Cookies zurück und speichert ihn in einer Variable $dwplatformbrowserid = DwPlatformAuthentication::GetDwPlatformBrowserId (); // definiert den URL $url = DOCUWARE_HOST . 'DocuWare/Platform/FileCabinets/' . $this->fileCabinetId . '/Documents'; // definiert Zeitstempel, der als Grenze für Multipart Content-type verwendet wird define ( 'MULTIPART_BOUNDARY', md5 ( time () ) ); // definiert den Teil, der die Indexdaten als JSON enthält $content = "--".MULTIPART_BOUNDARY."\r\n"; $content .= "Content-Disposition: form-data; name=\"Fields\"\r\n". "Content-type: application/json\r\n\r\n"; $content .= $dwFields->getJSON () . "\r\n"; // definiert den Inhalt für den POST-REQUEST, der die Datei enthält $content .= "--".MULTIPART_BOUNDARY."\r\n". "Content-Disposition: form-data; name=\"file\"; filename=\"".$filename."\"\r\n". "Content-Type: text/plain\r\n". "Content-Transfer-Encoding: base64\r\n\r\n"; // ermittelt den Inhalt der Datei und fügt diesen zum Inhalt des POST-REQUESTs an $content .= file_get_contents($filename)."\r\n"; $content .= "--".MULTIPART_BOUNDARY."--\r\n\r\n"; // ACHTUNG: diese Syntax muss unbedingt eingehalten werden // definiert die Parameter (header, method, content etc.) für den POST-REQUEST // übergibt die Authentifizierungs-Cookies (im Header) $options = array( "http" => array( "header" => "Content-Type: multipart/form-data; boundary=".MULTIPART_BOUNDARY."\r\n". "Cookie: DWOrganization=YourCompanyName; ". "openInNewWindow=False; ". "DWPLATFORMBROWSERID=".$dwplatformbrowserid."; ". ".DWPLATFORMAUTH=".$dwplatformauth."\r\n", // ACHTUNG: "\r\n" muss in doppelten Anführungszeichen (") stehen -> '\r\n' funktioniert nicht!!! "method" => "POST", "content" => $content, ), ); // sendet eine Anfrage an den Docuware-Server $context = stream_context_create ( $options ); try { // Nur einfache Fehler melden error_reporting(E_ERROR); $result = file_get_contents ( $url, false, $context ); // speichert die Antwort des POST-Request in einem XML-Objekt $xml = new SimpleXMLElement ( $result ); // ermittelt die dwdocid aus der Antwort der Docuware-Servers $dwdocid = ( string ) $xml->attributes ()->Id; return $dwdocid; } catch (Exception $e) { return false; } }} 

возможно, вам нужны классы для DocuwareField:

 class DwPlatformFields { public $Fields; public function __construct() { $this->Fields = new ArrayObject ( array () ); } public function AddField($field) { $this->Fields->append ( $field ); } public function CreateDocumentUploadContent($multipart_boundary) { $multipart_boundary = "--" . $multipart_boundary; $countFields = 0; foreach ( $this->Fields as $field ) { $content .= $multipart_boundary."\r\n". "Content-Disposition: form-data; name=\"Fields[".$countFields."].FieldName\"\r\n\r\n". $field->FieldName."\r\n"; $content .= $multipart_boundary."\r\n". "Content-Disposition: form-data; name=\"Fields[".$countFields."].Item\"\r\n\r\n". $field->Item."\r\n"; $content .= $multipart_boundary."\r\n". "Content-Disposition: form-data; name=\"Fields[".$countFields."].ItemElementName\"\r\n\r\n". $field->ItemElementName."\r\n"; $countFields++; } $content .= $multipart_boundary; return $content; } public function getJSON() { $json .= '{"Fields":['; foreach ( $this->Fields as $field ) { $json .= json_encode ( $field ) . ","; } $json .= "]}"; return $json; }} class Field { public $FieldName; public $Item; public $ItemElementName; public function __construct($name, $item, $element) { $this->FieldName = $name; $this->Item = $item; $this->ItemElementName = $element; }} 

Вы можете использовать его следующим образом:

  require 'docuware/DwPlatformFields.php'; require 'docuware/DwPlatformDocument.php'; $dwFields = new DwPlatformFields(); $dwFields->AddField(new Field('PROJEKT', $bezeichnung, 'String')); $dwFields->AddField(new Field('PROJEKTID', $projekt_id, 'Decimal')); $fileCabinetId = 'd7b3a06e-9d6a-4ba3-b317-672b18cb7913'; $dwDocument = new DwPlatformDocument(); $dwDocument->fileCabinetId = $fileCabinetId; return $dwDocument->saveDocuware($dwFields, $dwdocid);