ESignContractServer.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410
  1. <?php
  2. namespace App\Servers\ESign;
  3. use App\Models\Firm;
  4. use App\Models\FirmSeal;
  5. use App\Models\Member;
  6. use App\Models\MemberSeal;
  7. use App\Models\SignContract;
  8. use App\Models\SignRecord;
  9. use App\Servers\ESign\comm\EsignHttpHelper;
  10. use App\Servers\ESign\comm\EsignLogHelper;
  11. use App\Servers\ESign\comm\EsignUtilHelper;
  12. use App\Servers\ESign\emun\HttpEmun;
  13. use App\Servers\System\CommonServer;
  14. use App\Servers\System\SmsServer;
  15. class ESignContractServer
  16. {
  17. static private $server = null;
  18. public $config = [
  19. 'eSignAppId'=>'', //app id
  20. 'eSignAppSecret'=>'', // app key
  21. 'eSignHost'=>'https://smlopenapi.esign.cn', //模拟环境
  22. // 'url'=>'https://openapi.esign.cn' //正式环境
  23. ];
  24. function __construct()
  25. {
  26. $this->config['eSignAppId']=env('E_SIGN_APP_ID');
  27. $this->config['eSignAppSecret']=env('E_SIGN_APP_SECRET');
  28. $this->config['eSignPublicKey']=env('E_SIGN_PUBLIC_KEY');
  29. $this->config['eSignHost']=env('E_SIGN_HOST');
  30. }
  31. /**
  32. * 创建对象
  33. * @return ESignContractServer
  34. */
  35. static function creatServer()
  36. {
  37. if (empty(self::$server)) self::$server = new ESignContractServer();
  38. return self::$server;
  39. }
  40. function contentMd5($filePath){
  41. if(!file_exists($filePath)){
  42. EsignLogHelper::printMsg($filePath."文件不存在");exit;
  43. }
  44. return EsignUtilHelper::getContentBase64Md5($filePath);
  45. }
  46. /**
  47. * 上传合同文件至E签宝
  48. * @param $file_url
  49. * @return mixed
  50. */
  51. function fileUploadUrl($file_url){
  52. $config=$this->config;
  53. $file_name=CommonServer::creatServer()->getFileName($file_url);
  54. $filePath=public_path($file_url);
  55. dump($filePath);
  56. $contentMd5=$this->contentMd5($filePath);
  57. $apiaddr="/v3/files/file-upload-url";
  58. $requestType = HttpEmun::POST;
  59. $data=[
  60. "contentMd5" =>$contentMd5,
  61. "contentType" =>"application/pdf",
  62. "convertToPDF" =>true,
  63. "fileName" =>$file_name,
  64. "fileSize" =>filesize($filePath)
  65. ];
  66. $paramStr = json_encode($data);
  67. //生成签名验签+json体的header
  68. $signAndBuildSignAndJsonHeader = EsignHttpHelper::signAndBuildSignAndJsonHeader($config['eSignAppId'], $config['eSignAppSecret'], $paramStr, $requestType, $apiaddr);
  69. //获取文件上传地址
  70. // EsignLogHelper::printMsg($signAndBuildSignAndJsonHeader);
  71. $response = EsignHttpHelper::doCommHttp($config['eSignHost'], $apiaddr, $requestType, $signAndBuildSignAndJsonHeader, $paramStr);
  72. // EsignLogHelper::printMsg($response->getStatus());
  73. // EsignLogHelper::printMsg($response->getBody());
  74. $fileUploadUrl=json_decode($response->getBody())->data->fileUploadUrl;
  75. $fileId=json_decode($response->getBody())->data->fileId;
  76. //文件流put上传
  77. $response=EsignHttpHelper::upLoadFileHttp($fileUploadUrl,$filePath,"application/pdf");
  78. // EsignLogHelper::printMsg($response->getStatus());
  79. // EsignLogHelper::printMsg($response->getBody());
  80. return $fileId;
  81. }
  82. /**
  83. * 获取文件状态
  84. * @param $fileId
  85. * @return int|mixed
  86. */
  87. function getFileStatus($fileId)
  88. {
  89. $config=$this->config;
  90. $apiaddr="/v3/files/{$fileId}";
  91. $requestType = HttpEmun::GET;
  92. //生成签名验签+json体的header
  93. $signAndBuildSignAndJsonHeader = EsignHttpHelper::signAndBuildSignAndJsonHeader($config['eSignAppId'], $config['eSignAppSecret'], "", $requestType, $apiaddr);
  94. //发起接口请求
  95. $response = EsignHttpHelper::doCommHttp($config['eSignHost'], $apiaddr, $requestType, $signAndBuildSignAndJsonHeader, "");
  96. $ret=json_decode($response->getBody(),true);
  97. if(isset($ret['code']) && $ret['code']==0){
  98. return $ret['data']['fileStatus'];
  99. }else{
  100. return 0;
  101. }
  102. }
  103. /**
  104. * 获取签署文件对应关键字坐标
  105. * @param $fileId
  106. * @param $keywords
  107. * @return array
  108. */
  109. function getKeywordPositions($fileId,$keywords)
  110. {
  111. $config=$this->config;
  112. $apiaddr="/v3/files/{$fileId}/keyword-positions";
  113. $requestType = HttpEmun::POST;
  114. $data=[
  115. "keywords" =>$keywords
  116. ];
  117. $paramStr = json_encode($data);
  118. //生成签名验签+json体的header
  119. $signAndBuildSignAndJsonHeader = EsignHttpHelper::signAndBuildSignAndJsonHeader($config['eSignAppId'], $config['eSignAppSecret'], $paramStr, $requestType, $apiaddr);
  120. //获取文件上传地址
  121. // EsignLogHelper::printMsg($signAndBuildSignAndJsonHeader);
  122. $response = EsignHttpHelper::doCommHttp($config['eSignHost'], $apiaddr, $requestType, $signAndBuildSignAndJsonHeader, $paramStr);
  123. // EsignLogHelper::printMsg($response->getStatus());
  124. // EsignLogHelper::printMsg($response->getBody());
  125. $ret=json_decode($response->getBody(),true);
  126. if(isset($ret['code']) && $ret['code']==0){
  127. return ['code'=>'1','msg'=>'ok','data'=>$ret['data']['keywordPositions']];
  128. }else{
  129. return ['code'=>'0','msg'=>$ret['message']];
  130. }
  131. }
  132. function setContractContract($sign_id,$fileId,$signJson,$file_name)
  133. {
  134. // $signJson = '[{"keyword":"fisher", "auth_type":"PSN", "id_no","AAAAA"}, {"keyword":"lily", "auth_type":"ORG", "id_no","AAAAA"}, {"keyword":"bob", "auth_type":"PSN", "id_no","AAAAA"}]';
  135. $signData = json_decode($signJson,true);
  136. $keywords=[];
  137. foreach ($signData as $k=>$v){
  138. $keywords[]=$v['keyword'];
  139. }
  140. //获取对应关键字定位
  141. //dd(111);
  142. $positionRet=ESignContractServer::creatServer()->getKeywordPositions($fileId,$keywords);
  143. if(empty($positionRet['code'])){
  144. return ['code'=>0,'msg'=>'签署区域定位失败'];
  145. }else{
  146. $positionData=$positionRet['data'];
  147. }
  148. $signers=[];
  149. $signUrl = [];
  150. foreach ($signData as $value){
  151. //对应关键字做xy坐标匹配
  152. foreach ($positionData as $item){
  153. if(count($item['positions'])<=0){
  154. continue;
  155. }
  156. if($item['keyword']==$value['keyword']){
  157. $position=end($item['positions']);
  158. $coordinate=end($position['coordinates']);
  159. $value['positionPage'] = $position['pageNum'];
  160. $value['positionX'] = $coordinate['positionX'];
  161. $value['positionY'] = $coordinate['positionY'];
  162. }
  163. }
  164. //签署方是机构还是个人
  165. if ($value['auth_type'] == 'PSN'){
  166. $member = Member::where('psnId',$value['id_no'])->first();
  167. //记录需要手动签署的
  168. $signUrl[]=[
  169. 'promissoryName'=>$member['name'],
  170. 'psnAccount'=>$member['phone'],
  171. 'orgName'=>'',
  172. ];
  173. //获取签章
  174. $m_id = $member->{'id'};
  175. $seal=MemberSeal::where('m_id',$m_id)->where('seal_status',1)->select(['id','seal_id'])->first();
  176. //印章ID
  177. $assignedSealId=$seal->{'seal_id'};
  178. //组装信息
  179. $signersData = [
  180. "signerType" => 0,
  181. "psnSignerInfo" => [
  182. "psnAccount" => $member->{'phone'},
  183. 'psnInfo'=>[
  184. 'psnName'=>$member->{'name'},
  185. 'psnIDCardNum'=>$member->{'id_number'},
  186. 'psnIDCardType'=>'CRED_PSN_CH_IDCARD',
  187. ],
  188. ],
  189. "signFields" =>[
  190. [
  191. "fileId" =>$fileId,
  192. "normalSignFieldConfig" => [
  193. "autoSign" =>false,
  194. "signFieldStyle" =>1,
  195. "assignedSealId"=>$assignedSealId, // 在signFields中设置 assignedSealId为授权企业印章id
  196. "signFieldPosition" => [
  197. "positionPage" =>$value['positionPage'].'',
  198. "positionX" =>(int)$value['positionX'],
  199. "positionY" =>(int)$value['positionY'],
  200. ]
  201. ]
  202. ]
  203. ],
  204. ];
  205. }else{
  206. $firm = Firm::where('orgId',$value['id_no'])-first();
  207. //记录需要手动签署的
  208. $signUrl[]=[
  209. 'promissoryName'=>$firm['legal_name'],
  210. 'psnAccount'=>$firm['phone'],
  211. 'orgName'=>$firm['firm_name'],
  212. ];
  213. //获取用户签章
  214. $firm_id = $firm->{'id'};
  215. $seal=FirmSeal::where('firm_id',$firm_id)->where('seal_type','CONTRACT')->select(['id','seal_id'])->first();
  216. //印章ID
  217. $assignedSealId=$seal->{'seal_id'};
  218. $signersData = [
  219. "signerType" => 1,
  220. "orgSignerInfo" => [
  221. "orgName" => $firm->{'firm_name'},
  222. 'orgInfo'=>[
  223. 'orgIDCardNum'=>$firm->{'license_number'},
  224. 'orgIDCardType'=>'CRED_ORG_USCC',
  225. ],
  226. "transactorInfo"=>[
  227. "psnAccount"=>$firm['phone'],
  228. 'psnInfo'=>[
  229. 'psnIDCardNum'=>$firm['legal_id_number'],
  230. 'psnIDCardType'=>'CRED_PSN_CH_IDCARD'
  231. ]
  232. ]
  233. ],
  234. "signFields" =>[
  235. [
  236. "fileId" =>$fileId,
  237. "normalSignFieldConfig" => [
  238. "autoSign" =>false,
  239. "signFieldStyle" =>1,
  240. "assignedSealId"=>$assignedSealId, // 在signFields中设置 assignedSealId为授权企业印章id
  241. "signFieldPosition" => [
  242. "positionPage" =>$value['positionPage'].'',
  243. "positionX" =>(int)$value['positionX'],
  244. "positionY" =>(int)$value['positionY'],
  245. ]
  246. ]
  247. ]
  248. ],
  249. ];
  250. }
  251. $signers[]=$signersData;
  252. //对应签署方做记录
  253. SignRecord::create([
  254. 'sign_id' => $sign_id,
  255. 'authType' => $value['auth_type'],
  256. 'id_no' => $value['id_no'],
  257. 'keyword' => $value['keyword'],
  258. 'page_num' => $value['positionPage'],
  259. 'position_x' => $value['positionX'],
  260. 'position_y' => $value['positionY'],
  261. ]);
  262. }
  263. if(empty($signers)){
  264. return ['code'=>0,'msg'=>'暂无可执行电签印章'];
  265. }
  266. $flowId= $this->createByFile($fileId,$file_name.'.pdf',$file_name,$signers);
  267. if($flowId){
  268. SignContract::where('id',$sign_id)->update(['flow_id'=>$flowId,'status'=>1]);
  269. foreach ($signUrl as $item){
  270. $urlRet= $this->getSignUrl($flowId,$item['psnAccount'],$item['orgName']);
  271. if($urlRet){
  272. $content='尊敬的'.$item['promissoryName'].',您有待签署合同《'.$file_name.'》,点击签署 '.$urlRet;
  273. SmsServer::creatServer()->sendContent($item['psnAccount'],$content);
  274. SignContract::where('id',$sign_id)->update(['sign_url'=>$urlRet]);
  275. }
  276. }
  277. return ['code'=>1,'msg'=>'发起签署成功'];
  278. }else{
  279. return ['code'=>0,'msg'=>'发起签署失败'];
  280. }
  281. }
  282. /**
  283. * 合同签署
  284. * @param $fileId
  285. * @return false
  286. */
  287. function createByFile($fileId,$fileName,$signFlowTitle,$signers)
  288. {
  289. EsignLogHelper::printMsg("**********基于文件发起签署调用开始**********");
  290. $config=$this->config;
  291. $apiaddr="/v3/sign-flow/create-by-file";
  292. $requestType = HttpEmun::POST;
  293. $data = [
  294. "docs" =>[
  295. [
  296. "fileId" =>$fileId,
  297. "fileName" =>$fileName
  298. ]
  299. ],
  300. "signFlowConfig" => [
  301. "signFlowTitle" =>$signFlowTitle,
  302. "autoStart"=>true,
  303. "autoFinish"=>true,
  304. 'notifyUrl'=>route('adminApi.notify.esignNotify')
  305. ],
  306. "signers"=>$signers
  307. ];
  308. // dd($data);
  309. $paramStr = json_encode($data);
  310. $signAndBuildSignAndJsonHeader = EsignHttpHelper::signAndBuildSignAndJsonHeader($config['eSignAppId'], $config['eSignAppSecret'], $paramStr, $requestType, $apiaddr);
  311. // EsignLogHelper::printMsg($signAndBuildSignAndJsonHeader);
  312. $response = EsignHttpHelper::doCommHttp($config['eSignHost'], $apiaddr, $requestType, $signAndBuildSignAndJsonHeader, $paramStr);
  313. // EsignLogHelper::printMsg($response->getStatus());
  314. EsignLogHelper::printMsg($response->getBody());
  315. $signFlowId = false;
  316. if($response->getStatus() == 200){
  317. $result = json_decode($response->getBody());
  318. if($result->code==0){
  319. $signFlowId = $result->data->signFlowId;
  320. EsignLogHelper::printMsg("基于文件发起签署接口调用成功,flowId: ".$signFlowId);
  321. }else{
  322. EsignLogHelper::printMsg("基于文件发起签署接口调用失败,错误信息: ".$result->message);
  323. }
  324. }else{
  325. EsignLogHelper::printMsg("基于文件发起签署接口调用失败,HTTP错误码".$response->getStatus());
  326. }
  327. EsignLogHelper::printMsg("**********基于文件发起签署调用结束**********");
  328. return $signFlowId;
  329. }
  330. /**
  331. * 合同签署链接
  332. * @param $flowId
  333. * @param $psnAccount
  334. * @param $orgName
  335. * @return null
  336. */
  337. function getSignUrl($flowId,$psnAccount,$orgName){
  338. EsignLogHelper::printMsg("**********获取合同文件签署链接开始**********");
  339. $config=$this->config;
  340. $apiaddr="/v3/sign-flow/%s/sign-url";
  341. $apiaddr = sprintf($apiaddr,$flowId);
  342. $requestType = HttpEmun::POST;
  343. $data = [
  344. "signFlowId" =>$flowId,
  345. "clientType" =>"ALL",
  346. "needLogin" =>false,
  347. "operator" => [
  348. "psnAccount" =>$psnAccount
  349. ],
  350. 'organization'=>[
  351. 'orgName'=>$orgName
  352. ],
  353. "urlType" =>2
  354. ];
  355. $paramStr = json_encode($data);
  356. $signAndBuildSignAndJsonHeader = EsignHttpHelper::signAndBuildSignAndJsonHeader($config['eSignAppId'], $config['eSignAppSecret'], $paramStr, $requestType, $apiaddr);
  357. EsignLogHelper::printMsg($signAndBuildSignAndJsonHeader);
  358. $response = EsignHttpHelper::doCommHttp($config['eSignHost'], $apiaddr, $requestType, $signAndBuildSignAndJsonHeader, $paramStr);
  359. EsignLogHelper::printMsg($response->getStatus());
  360. EsignLogHelper::printMsg($response->getBody());
  361. $url= null;
  362. if($response->getStatus() == 200){
  363. $url = json_decode($response->getBody())->data->shortUrl;
  364. EsignLogHelper::printMsg("获取合同文件签署链接调用成功,url: ".$url);
  365. }else{
  366. EsignLogHelper::printMsg("获取合同文件签署链接接口调用失败,HTTP错误码".$response->getStatus());
  367. }
  368. EsignLogHelper::printMsg("**********获取合同文件签署链接调用结束**********");
  369. return $url;
  370. }
  371. }