当前位置:网站首页>PHP e-signature SaaS API docking process
PHP e-signature SaaS API docking process
2022-06-09 04:14:00 【The summer is already slightly cool】
- One 、 technological process
- Two 、 Let's get familiar with the meaning of these fields in the interface
- 3、 ... and 、Demo file
- Four 、 The simplest interface call sequence
- 5、 ... and 、 Something to watch out for
- 1、 Create a personal signing account interface , The certificate contains in lower case x
- 2、 File upload interface , File name format
- 3、 The business code fields are not all code, It could be errCode
- 4、 Method does not exist
- 5、 Setting of the signature seal sub position
- 6、 Unified processing of interface requests , Encapsulate a method unified request
- 6、 ... and 、 At the end
One 、 technological process
Write it at the front :
I hope you can pass this article , Yes e We have a comprehensive understanding of the electronic signature of the signer , Not to get it API The document is circled, The development language here is PHP For example , Other languages can be found in Demo Link to download . No problem with interface encapsulation , The authorities have given sdk, Just need to smooth out the process .
General process : Upload the contract to e Autograph ,e The signature will be returned to us
fileId, Signature or seal of user or enterprise ( The position of signature and seal can be set : Page number ;x Axis coordinates , The bottom left corner is the origin ;y Axis coordinates , The bottom left corner is the origin ), A signed address will be generated , user / When an enterprise is opened, it can sign , There is a visa rejection operation . When a user triggers different states, there will be different callbacksaction.
| Environmental Science | domain name | Public network IP | port |
|---|---|---|---|
| Formal production environment | https://openapi.esign.cn | 118.31.181.75 | 443 |
| Sandbox simulation environment | https://smlopenapi.esign.cn | 114.55.17.44 | 443 |
Two 、 Let's get familiar with the meaning of these fields in the interface
1、accountId
- Personal account number id, When signing the contract, you can choose the signature of your name or write it manually .
2、orgId
- Organization Account No id, When signing the contract, you need to use .
3、fileId
- file ID, For signing PDF file
- source : You can upload directly by yourself , Judge whether to transfer according to the suffix of the file pdf file , Upload again , Pay attention to the interface 2 Parameters :
contentType,convert2Pdf.e Autograph . Document center - Public cloud documents - Electronic signature SaaS API The standard version -API file - Upload files - You can also create a template file and upload it .PDF Template file 3 A kind of production instruction document
- Query file upload status : View the current status of the uploaded file , This interface supports polling . When the interface returns File status status The value is 2 or 5 when , This file can be added to the signing process normally .
- Inquire about PDF Document details : View the current status of the uploaded file 、 File name 、 File size and download link , This interface does not support polling . When the interface returns File status status The value is 2 or 5 when , This file can be normally added to the signing process or downloaded PDF file .
4、templateId
- Templates ID, Executable add controls 、 Delete control operation , The template content can be adjusted after it is determined Fill content generation PDF Interface Generate contract file .
5、flowId
- technological process id, Initiate a signing process to generate id
- According to this id Query the progress of the process Signing process query , Inquire about Process signer list
- Execute after the process Process document download , The final process data is generated .
6、 Callback notification receiving instructions
- And what we care about most , Process callback Callback notification receiving instructions , The callback address is One step initiate signing Interface flowConfigInfo[‘noticeDeveloperUrl’]
- Respond to e Endorsement callback notice : When I received e After the callback notice of Alipay , The developer returns a value between 200~299 Of HTTP Status code to e Autograph ,e Alipay thinks that the push is successful . It is recommended to return to e Response from Alipay Body The data format is as follows :
{"code":"200","msg":"success"} - We use the... In the callback path
actionParameter to determine the event type , as follows :
| Action Event type | Action Event name ( Click to view the specific description ) Corresponding business operations ( Click to view the specific description ) |
|---|---|
| SIGN_FLOW_UPDATE | Signed by the undersigned |
| SIGN_FLOW_FINISH | End of the process |
| SIGN_DOC_EXPIRE_REMIND | Remind before the process document expires |
| SIGN_DOC_EXPIRE | The process file is out of date |
| BATCH _ ADD _ WATERMARK _ REMIND | Add digital watermark to the file |
| FEEDBACK_SIGNERINFO | The signer applies to modify the identity information |
| PROCESS_HANDOVER | The handler shall transfer the signing task |
| WILL_FINISH | Will certification complete |
| PARTICIPANT_MARKREAD | The undersigned has read |
| FILE_ABNORMAL_REMIND | The file is encrypted / Damaged notification |
- php The callback receives parameters and responds to Demo
// Data callback business processing
public function callback() {
// $data = '{"action":"SIGN_FLOW_UPDATE","flowId":"11111113a466442abbce094c9368ac7c","accountId":"22XXXe2a","authorizedAccountId":"33XXXe3a","signTime":"2019-07-24 19:33:06","order":1,"signResult":2,"thirdOrderNo":"cust0001","resultDescription":" Sign off ","timestamp":1563967986960,"thirdPartyUserId":"A34006"}';
$data = file_get_contents('php://input'); // php://input It's a read-only stream that can access the requested raw data . When the request mode is post, also Content-Type It's not equal to ”multipart/form-data” when , have access to php://input To get the data of the original request .
return self::callbackService($data);
}
/** * Deal with : In actual use, put this function into service in * @param $data * @return array Result array */
public function callbackService($data)
{
$result = false;
$data = json_decode($data, true);
$action = isset($data['action']) ? $data['action'] : ''; // Mark the business type of the notification
if ($action) {
switch ($action) {
case 'SIGN_DOC_EXPIRE': // The process file is out of date Callback notice
$flowId = $data['flowId']; // technological process id
$fileId = $data['fileId']; // file ID, Multiple documents are separated by commas
$timestamp = $data['timestamp']; // Time stamp
/** * TODO Deal with our business here , Manipulate our data table , Whether to add data table rollback operation as the case may be */
$result = true;
break;
case 'SIGN_FLOW_UPDATE': // The signer signs the completion callback notice
$result = true;
break;
case "SIGN_FLOW_FINISH": // The signing process is over Callback notice
$flowId = $data['flowId']; // technological process ID
$flowStatus = $data['flowStatus']; // Process status : 2 - Completed : All signatories complete the signing ;3 - Has withdrawn : The initiator cancels the signing task ;5 - Has expired : Triggered after the signing deadline expires ;7 - Rejected .
/** * Process this logic in our data table , Change the state of our data table , remarks , Update time Etc ~ * TODO Business ... Deal with our business here , Manipulate our data table , Whether to add data table rollback operation as the case may be */
$result = true;
break;
}
}
// The developer returns a value between 200~299 Of HTTP Status code to e Autograph ,e Alipay thinks that the push is successful .
// It is recommended to return to e Response from Alipay Body The data format is as follows :{"code":"200","msg":"success"}
if ($result) {
$ret = ['code' => '200', 'msg' => 'success'];
} else {
$ret = ['code' => '0', 'msg' => 'error'];
}
return json_encode($ret, JSON_UNESCAPED_UNICODE); // Array rotation json character string
}
3、 ... and 、Demo file
1、 Official website documents provided on the official website
2、Demo download
- I choose PHP Language DEMO - Request signature authentication method
81KBdownload - I downloaded it and put it on Baidu online disk , If necessary, you can go to download link :https://pan.baidu.com/s/1i42ruPO4wR9MJmf7DUrV2g Extraction code :ty79
3、Demo In the call Demo
- b2cDemo.php Document details
<?php
use factory\base\Account;
use factory\base\FileTemplate;
use factory\base\Seals;
use factory\base\SignFile;
use factory\bean\Doc;
use factory\bean\FlowInfo;
use factory\bean\PosBean;
use factory\bean\Signer;
use factory\bean\SignerAccount;
use factory\bean\Signfield;
use factory\Factory;
header("Content-type:text/html;charset=utf-8");
include("../eSignOpenAPI.php");
// This example is the signing example code for enterprise and individual scenarios , The signing method is to initiate signing in one step , If step-by-step signing is required , For some code examples of signing, please refer to b2bDemo
var_dump("-------------------------- initialization start----------------------------");
$host="https://smlopenapi.esign.cn";// Request gateway host
$project_id="";// application id
$project_scert="";// secret key
Factory::init($host,$project_id,$project_scert);
Factory::setDebug(true);// Whether to turn on logging , Pass on true or false, Logs are stored in the root directory phplog.txt file
//----------------- Basic information initialization end--------------------------
var_dump("-------------------------- initialization end----------------------------");
$filePath="D:\\IDEAproject\\PdfFile\\dstPdf\\qianshu.pdf";// File address
if(!is_file($filePath)){
echo ' file does not exist ';exit;
}
//----------------------- The personal account information is used to create a personal account interface and transfer it to -----------------------------
$thirdPartyUserIdPsn="1232133232";//thirdPartyUserId Parameters , User unique identification , Customize and keep unique
$namePsn="";//name Parameters , full name
$idTypePsn="CRED_PSN_CH_IDCARD";//idType Parameters , Document type
$idNumberPsn="";//idNumber Parameters , Id no.
$mobilePsn="";//mobile Parameters , cell-phone number
//------------------------ The enterprise account information is used to create the institutional account interface and transfer it to ----------------
$thirdPartyUserIdOrg="1212312312312";//thirdPartyUserId Parameters , User unique identification , Customize and keep unique
$nameOrg=" Hangzhou Tiangu ";//name Parameters , Name of organization
$idTypeOrg="CRED_ORG_USCC";//idType Parameters , Document type
$idNumberOrg="";//idNumber Parameters , Institution certificate No
var_dump("------------------ Create a personal account start -----------------");
$createPsn = Account::createPersonByThirdPartyUserId(
$thirdPartyUserIdPsn,
$namePsn,
$idTypePsn,
$idNumberPsn);
$createPsn->setMobile($mobilePsn);
$createPsnResp = $createPsn->execute();//execute Method to initiate a request
$createPsnJson = json_decode($createPsnResp->getBody());
$accountId = $createPsnJson->data->accountId;// Save the generated personal account , Subsequent interface calls need to use
var_dump("------------------ Create a personal account end ---------------");
var_dump("------------------ Create an enterprise account start ---------------");
$createOrg = Account::createOrganizationsByThirdPartyUserId(
$thirdPartyUserIdOrg,
$accountId,
$nameOrg,
$idTypeOrg,
$idNumberOrg
);
$createOrgResp = $createOrg->execute();
$createOrgJson=json_decode($createOrgResp->getBody());
$orgId=$createOrgJson->data->orgId;
var_dump("------------------ Create an enterprise account end ---------------");
var_dump("------------------ Create files by uploading start -----------------");
$contentBase64Md5 = UtilHelper::getContentBase64Md5($filePath);
$filesize = filesize($filePath);
$fileContent = file_get_contents($filePath);
$getFileUploadUrl = FileTemplate::getFileUploadUrl($contentBase64Md5, "application/pdf", false, " Test contract .pdf", $filesize);
$getFileUploadUrlResp = $getFileUploadUrl->execute();
$getFileUploadUrlJson = json_decode($getFileUploadUrlResp->getBody());
$fileId = $getFileUploadUrlJson->data->fileId;// file id Well preserved , Use later
$uploadUrl = $getFileUploadUrlJson->data->uploadUrl;// Upload url Well preserved , Use later
var_dump("------------------ Create files by uploading end -----------------");
var_dump("------------------ File stream upload method start -----------------");
$uploadFile = FileTemplate::uploadFile($filePath, "application/pdf", $uploadUrl);
$uploadFileResp = $uploadFile->execute();
var_dump($uploadFileResp->getBody());
var_dump("------------------ File stream upload method end -----------------");
var_dump("------------------ One step initiate signing start -----------------");
$doc = new Doc();
$doc->setFileId($fileId);
$docs = array($doc);
$flowInfo = new FlowInfo();
$flowInfo->setBusinessScene("b2c Contract signing test ")
->setAutoArchive(true)// Auto archive
->setAutoInitiate(true);// Automatically start the process
$psnSignfield = new Signfield();
$posBean = new PosBean();
$psnSignfield->setFileId($fileId)
->setPosBean($posBean->setPosPage(1)->setPosX(113)->setPosY(225));
$psnSignfields = array($psnSignfield);// Construct individuals signfields Parameter object
$orgSignfield = new Signfield();
$posBean = new PosBean();
$orgSignfield->setFileId($fileId)
->setPosBean($posBean->setPosPage(1)->setPosX(224)->setPosY(334))
->setActorIndentityType(2);// The signature of the organization must be sent to
$orgSignfields = array($orgSignfield);// Construct individuals signfields Parameter object
$signerpsn = new Signer();
$signerAccount1 = new SignerAccount();
$signerAccount1->setSignerAccountId($accountId);
$signerpsn->setSignerAccount($signerAccount1)
->setSignfields($psnSignfields);;// Incoming individuals signer Information
$signerorg = new Signer();
$signerA1ccount2 = new SignerAccount();
$signerA1ccount2->setSignerAccountId($accountId)->setAuthorizedAccountId($orgId);
$signerorg->setSignerAccount($signerA1ccount2)
->setSignfields($orgSignfields);// Transfer into the enterprise signer Information
$signers = array($signerpsn, $signerorg);//
$createFlowOneStep = SignFile::createFlowOneStep($docs, $flowInfo, $signers);
$flowOneStepResp = $createFlowOneStep->execute();
$flowOneStepJson = json_decode($flowOneStepResp->getBody());
$flowId = $flowOneStepJson->data->flowId;// technological process id Well preserved
var_dump("------------------ One step initiate signing end -----------------");
var_dump("------------------ Get the signing address start -----------------");
$getFileSignUrl = SignFile::getFileSignUrl($flowId, $accountId);
$getFileSignUrl->setOrganizeId($orgId);
$getFileSignUrlResp = $getFileSignUrl->execute();
$getFileSignUrlJson = json_decode($getFileSignUrlResp->getBody());
$shortUrl = $getFileSignUrlJson->data -> shortUrl;
var_dump(" Sign a short connection , Copy to browser to open \n".$shortUrl);
var_dump("------------------ Get the signing address end -----------------");
4、sdk Use
- sdk Use the words , According to their own directory storage location , To choose whether to add a namespace
Four 、 The simplest interface call sequence
The simplest thing I mean here is , We do not operate the template file data by calling the template interface ( The parameters in the template interface are too complex )
Let's just use one that only needs to sign the user's name , Name of the enterprise Contract of , Then the calling sequence of the interface is as follows :
- 1、 Create a personal signing account Corresponding
modifyInquire aboutCancellationInterfaces can also be encapsulated (accountId, thirdPartyUserId A choice ) - 2、 Create agency Signature account number Corresponding
modifyInquire aboutCancellationInterfaces can also be encapsulated (orgId, thirdPartyUserId A choice ) - 3、 Upload files Corresponding
Query file upload status ( When the interface returns File status status The value is 2 or 5 when , This file can be added to the signing process normally .)、Inquire about PDF Document details ( When the interface returns File status status The value is 2 or 5 when , This file can be normally added to the signing process or downloaded PDF file )You can also encapsulate - 4、 Operations for templates , skip
- 5、 choice One step initiate signing , Callback can be configured in this interface : Please refer to Demo In the document b2cDemo.php
- 6、 Callback operation : adopt
actionDetermine the type of callback , Please refer to my above for details : Callback notification receiving instructions - 7、PDF Document verification :
This step depends on the situation - 8、 If the callback is successfully signed , be Process document download file , The document address field is returned fileUrl, Valid time 1 Hours ; This link is recommended for download only , Do not preview directly ; You can view the signed document for users .
- explain : In this step, we need to design data table storage e Signature data , We need our data interaction , According to the interface request 、 Return the data Self designed data sheet .
5、 ... and 、 Something to watch out for
1、 Create a personal signing account interface , The certificate contains in lower case x
- 1、thirdPartyUserId Create a unique ID for your personal account : We need to ensure the uniqueness of the parameters , And can be associated with users , Otherwise a user will always create an account ~
- 2、idNumber Id no. : There is... In the ID card X Alphabetic , Need to pass in uppercase X. You need code to handle it :
strtoupper($data['id_number']);
2、 File upload interface , File name format
- fileName File name : Format problem File names do not support the following 9 Characters :
File name ( You must bring a file extension , Otherwise, the subsequent initiation process cannot be verified Example : contract .pdf );
Be careful :
(1) The file suffix name of this field should be consistent with the real file suffix . For example, the uploaded file type is word file , This parameter needs to be passed “xxx.docx”, It can't be “xxx.pdf”
(2) This field is recommended to be passed in directly pdf file , It is recommended to convert other types of files locally to pdf, Avoid format errors caused by interface format conversion 、 Wait a long time .
(3) File names do not support the following 9 Characters :/ \ : * " < > | ?
3、 The business code fields are not all code, It could be errCode
- Upload files Step two File stream upload , Back to yes errCode No code, This needs attention
4、 Method does not exist
- If there is a missing method , I can follow the official sdk Self increase php file , Here he is PHP The file corresponds to an interface , And then in a php File php file .SDK The packaging method is the same as JD , Very flexible .
- Be careful : It is better to choose a file name that will not be repeated for our customized file , Add your pen name suffix or something ( such as
QryPdfDetailZSF.php), If you update the official documentation , It's embarrassing to be covered .
5、 Setting of the signature seal sub position
- adopt
setPosPage(),setPosX(),setPosY()Set up :// Set the stamp area : Page number ;x Axis coordinates , The bottom left corner is the origin ;y Axis coordinates , The bottom left corner is the origin - demo as follows
$orgSignfield = new Signfield();
$posBean = new PosBean();
$orgSignfield->setFileId($fileId)
->setPosBean($posBean->setPosPage(1)->setPosX(224)->setPosY(334))
->setActorIndentityType(2);// The signature of the organization must be sent to
$orgSignfields = array($orgSignfield);// Construct individuals signfields Parameter object
6、 Unified processing of interface requests , Encapsulate a method unified request
- All interface requests are executed execute(),getBody() Method , We don't need to call... Every time . Combined with the third question , Encapsulate a method .
/** * adopt accountId Query personal signature account number * @return array */
public function qryPersonByaccountId()
{
$account = Account::qryPersonByaccountId($_REQUEST['account_id']); //use Identity\factory\base\Account;
$result = self::execResponse($account);
/** * TODO Interact with your own database */
return $result;
}
/** * Execute interface data uniformly * @param mixed $requestObject object use Identity\factory\request\EsignRequest; * @param mixed $codeName Business code field name * @return array */
public function execResponse(EsignRequest $requestObject, $codeName = 'code')
{
$executeObject = $requestObject->execute();//execute Method to initiate a request
$resultJson = $executeObject->getBody(); // To get the results json data
// Log
$log = json_encode($_REQUEST, JSON_UNESCAPED_UNICODE) . PHP_EOL . $resultJson; // Record REQUEST data , Line break , And record The response data
Log::write($log); // Log in use think\facade\Log;
$result = json_decode($resultJson, true); //json turn array
if ($result[$codeName] != $this->successCode) {
// Judge the result according to the status code
die($result['message']); // Write according to your actual situation
}
// return data data
$data = isset($result['data']) ? $result['data'] : []; // Delete and so on ,data by null
return $data;
}
6、 ... and 、 At the end
- This article is for your reference only , Welcome to point out the problem ~
边栏推荐
猜你喜欢

基于PyQt5完成的图转文功能

My creation anniversary

《Attention-ocr-Chinese-Version-mas # ter》代碼運行邏輯

170亿参数,28项公开测试集SOTA,行业最大的视觉多任务统一大模型来了

Harbor container installation and related feature deployment and use (SSL certificate +ad domain)

Rigidbody2d rotate around a fixed point rotate
![How to write test cases for [e-commerce] test coupons in 2022?](/img/f4/7b06b7319b79a886e3296fb70c0989.png)
How to write test cases for [e-commerce] test coupons in 2022?

基于PyQt5完成的抠图功能-程序实现

ACM tutorial - Hill sort

基于PyQt5完成的PDF合并
随机推荐
JVM面试
Winform UI界面设计例程——自定义控件progressBar
Expansion chip, hisi3559av100 I2C debugging
P5354 [Ynoi2017] 由乃的 OJ(树剖、位运算)
(7)属性绑定
golang ---image--热力图与照片的重叠
National information security competition for college students (ciscn) -reverse- recurrence (part)
几何运用题
Implementation of map max min with generic list
Introduction of ravless speech emotion classification data set
Openinfra Foundation launched the "targeted fund" program to promote successful open source governance experience
Functions and differences of call apply bind
How to write test cases for [e-commerce] test coupons in 2022?
1264_FreeRTOS任务的初始化以及堆栈初始化处理分析
用户控制 键盘鼠标自定义 脚本
基于PyQt5完成的图转文功能
基于PyQt5完成的PDF拆分
(5) 双向数据绑定
Matting interface based on pyqt5
Rich color changes

