true, CURLOPT_CUSTOMREQUEST=>$method, CURLOPT_HTTPHEADER=>$requestHeaders, CURLOPT_CONNECTTIMEOUT=>5, CURLOPT_TIMEOUT=>30 ]; if($body!==null){ $json=json_encode($body,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR); $requestHeaders[]='Content-Type: application/json'; $options[CURLOPT_HTTPHEADER]=$requestHeaders; $options[CURLOPT_POSTFIELDS]=$json; } curl_setopt_array($ch,$options); $raw=curl_exec($ch); if($raw===false){$error=curl_error($ch);curl_close($ch);throw new RuntimeException('API connection failed: '.$error);} $status=(int)curl_getinfo($ch,CURLINFO_RESPONSE_CODE); curl_close($ch); $data=$raw===''?[]:json_decode($raw,true,512,JSON_THROW_ON_ERROR); if($status<200||$status>=300||isset($data['error'])){$message=$data['error']['message']??('HTTP '.$status);throw new RuntimeException('Fenzon API: '.$message);} return$data; }; $session=$request('POST',$apiBase.'/auth/session',['X-Fenzon-Api-Key: '.$apiKey]); $token=(string)($session['data']['session_token']??$session['data']['token']??''); if($token==='')throw new RuntimeException('The API did not return a session token.'); $auth=['Authorization: Bearer '.$token]; return static fn(string $method,string $endpoint,?array $body=null):array=>$request($method,$apiBase.'/'.ltrim($endpoint,'/'),$auth,$body); } // 2. Small pagination helper for list endpoints. function fenzonList(Closure $api,string $endpoint,array $query=[]):array{ $rows=[];$page=1; do{ $params=array_replace($query,['limit'=>100,'page'=>$page]); $response=$api('GET',$endpoint.'?'.http_build_query($params)); foreach((array)($response['data']??[])as$row)if(is_array($row))$rows[]=$row; $hasMore=!empty($response['pagination']['has_more']); $page=(int)($response['pagination']['next_page']??($page+1)); }while($hasMore); return$rows; } try{ $api=fenzonApi($apiKey,$apiBase); // API records expose their values below "fields". Keep access local and explicit. $field=static fn(array $row,string $key,mixed $default=null):mixed=>$row['fields'][$key]['value']??$default; // 3. Document header - GET /documents/{id} $document=(array)(($api('GET','documents/'.$documentId)['data']??[])); if(!$document)throw new RuntimeException('Document not found.'); $language=trim((string)$field($document,'language_code','de'))?:'de'; $accountId=(int)$field($document,'account_id',0); // 4. Account and contacts - GET /accounts/{id} + /accounts/{id}/contacts $account=[]; $contacts=[]; if($accountId>0){ $account=(array)(($api('GET','accounts/'.$accountId.'?'.http_build_query(['language'=>$language]))['data']??[])); $contacts=fenzonList($api,'accounts/'.$accountId.'/contacts',['language'=>$language]); } // 5. Document items - Fenzon already resolves configuration/article/free-text differences. // graphics=1 adds the standard SVG for configured positions. Static articles keep their // translated generated name/description and can receive their product image below. $items=fenzonList($api,'documents/'.$documentId.'/items',[ 'language'=>$language, 'graphics'=>$graphics ]); $descriptionText=static function(mixed $description):string{ if(is_string($description)||is_numeric($description))return trim((string)$description); if(!is_array($description))return''; $lines=[]; foreach($description as$row){ if(!is_array($row)||($row['type']??'')==='combinationBreak')continue; $label=trim((string)($row['label']??'')); $name=trim((string)($row['name']??'')); if($label!==''&&$name!=='')$lines[]=$label.': '.$name; elseif($name!=='')$lines[]=$name; elseif($label!=='')$lines[]=$label; } return implode("\n",$lines); }; $productCache=[]; $transferItems=[]; foreach($items as$item){ $generated=(array)($item['generated']??[]); $productId=(int)$field($item,'product_id',0); // A product/article can provide a static image independently of a configuration. // Cache products so the same product is requested only once per transfer. $productImage=''; if($graphics>0&&$productId>0){ if(!isset($productCache[$productId])){ $productCache[$productId]=(array)(($api('GET','products/'.$productId.'?'.http_build_query(['language'=>$language]))['data']??[])); } $productImage=trim((string)$field($productCache[$productId],'image','')); } // Configured items return one or more SVGs. For the standard transfer the first // available SVG is sufficient; graphics=2 can still be used if the target needs more. $svg=null; foreach((array)($generated['svgs']??[])as$graphic){ if(is_string($graphic)&&stripos($graphic,'(int)($item['id']??0), 'position'=>(int)$field($item,'position',0), 'type'=>(string)($generated['type']??$field($item,'type','')), 'product_id'=>$productId?:null, 'reference'=>(string)$field($item,'reference',''), 'sku'=>(string)$field($item,'sku',''), 'name'=>$name, 'description'=>$description, 'quantity'=>(float)$field($item,'quantity',1), 'unit'=>(string)$field($item,'unit',''), 'unit_price'=>(float)$field($item,'unit_sale_price',0), 'discount_percent'=>(float)$field($item,'discount_percent',0), 'vat_rate'=>(float)$field($item,'vat_rate',0), 'total_net'=>(float)$field($item,'total_net',0), 'total_vat'=>(float)$field($item,'total_vat',0), 'total_gross'=>(float)$field($item,'total_gross',0), 'graphic'=>[ 'svg'=>$svg, 'image'=>$productImage!==''?[ 'product_id'=>$productId, 'path'=>$productImage, 'source_endpoint'=>'products/'.$productId ]:null ] ]; } // 6. Build a vendor-neutral payload. IDs are stable source references for target-system upserts. $transferContacts=[]; foreach($contacts as$contact)$transferContacts[]=[ 'id'=>(int)($contact['id']??0), 'first_name'=>(string)$field($contact,'first_name',''), 'last_name'=>(string)$field($contact,'last_name',''), 'email'=>(string)$field($contact,'email',''), 'phone'=>(string)$field($contact,'phone',''), 'mobile'=>(string)$field($contact,'mobile','') ]; $payload=[ 'source'=>'fenzon', 'account'=>$account?[ 'id'=>(int)($account['id']??0), 'name'=>(string)$field($account,'name',''), 'email'=>(string)$field($account,'email',''), 'phone'=>(string)$field($account,'phone',''), 'vat_id'=>(string)$field($account,'vat_id',''), 'address'=>[ 'street'=>(string)$field($account,'address_street',''), 'zip'=>(string)$field($account,'address_zip',''), 'city'=>(string)$field($account,'address_city',''), 'country_code'=>(string)$field($account,'country_code','') ] ]:null, 'contacts'=>$transferContacts, 'document'=>[ 'id'=>(int)($document['id']??0), 'type'=>(string)$field($document,'type',''), 'subtype'=>(string)$field($document,'subtype',''), 'number'=>(string)$field($document,'number',''), 'reference'=>(string)$field($document,'reference',''), 'date'=>(string)$field($document,'date',''), 'due_date'=>(string)$field($document,'due_date',''), 'language_code'=>$language, 'currency'=>(string)$field($document,'currency','EUR'), 'vat_type'=>(string)$field($document,'vat_type','excl'), 'subtotal'=>(float)$field($document,'subtotal',0), 'vat_total'=>(float)$field($document,'vat_total',0), 'discount_total'=>(float)$field($document,'discount_total',0), 'total'=>(float)$field($document,'total',0) ], 'items'=>$transferItems ]; // 7. No target configured: print the exact normalized payload for inspection/testing. if($targetUrl===''){ header('Content-Type: application/json; charset=utf-8'); echo json_encode($payload,JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); exit; } // 8. Target-system adapter. This is the only block normally adapted for ERP/Fibu/middleware. $headers=['Accept: application/json','Content-Type: application/json']; if($targetToken!=='')$headers[]='Authorization: Bearer '.$targetToken; $ch=curl_init($targetUrl); curl_setopt_array($ch,[ CURLOPT_RETURNTRANSFER=>true, CURLOPT_POST=>true, CURLOPT_HTTPHEADER=>$headers, CURLOPT_POSTFIELDS=>json_encode($payload,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES|JSON_THROW_ON_ERROR), CURLOPT_CONNECTTIMEOUT=>5, CURLOPT_TIMEOUT=>30 ]); $raw=curl_exec($ch); if($raw===false){$error=curl_error($ch);curl_close($ch);throw new RuntimeException('Target-system connection failed: '.$error);} $status=(int)curl_getinfo($ch,CURLINFO_RESPONSE_CODE); curl_close($ch); if($status<200||$status>=300)throw new RuntimeException('Target system returned HTTP '.$status.'.'); /* * Optional invoice finalization belongs here, after a confirmed transfer. * The document status is intentionally not changed by this example. * Only add a Fenzon lock/finalization call when that writable action is * explicitly exposed by the current document runtime schema. */ header('Content-Type: application/json; charset=utf-8'); echo json_encode([ 'transferred'=>true, 'document_id'=>$documentId, 'target_status'=>$status ],JSON_PRETTY_PRINT|JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES); }catch(Throwable$e){ http_response_code(500); header('Content-Type: text/plain; charset=utf-8'); echo "Fenzon third-party data transfer\n\n".$e->getMessage()."\n"; }