# Retrieving Signed Documents

The Signer Gateway supports two REST API calls to check transaction status and retrieve signed documents

**The two API methods are:**

* Transaction Status Request
* Signed Data Request

### Transaction Status Request

Use the “Transaction Status Request” method to retrieve transaction status such as whether transaction is Completed or Failed or Initiate

**Type of Method – GET**

To test the retrieval of signing gateway, please try the test URL below:

```html
https://testgateway.emsigner.com/api/TransactionStatusRequest?Authtoken=cbFdZK9esvBzZQ1QynL7IjKb7t92K%2BB4SoEzVA%3D&Transactionnumber=1213&Referencenumber=78123897
```

**Request Data Parameters**

| Parameter            | Data Type    | Description                                                                                                                                                                                                                                                                                  |
| -------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AuthToken \*         | String       | Pass valid URL encoded Authtoken. Eg: cbFdZK9esvBzZQ1QynL7IjKb7t92K%2BB4SoEzVA%3D                                                                                                                                                                                                            |
| Transactionnumber \* | String       | Pass unique transaction number received in the Step6.                                                                                                                                                                                                                                        |
| Referencenumber \*   | AlphaNumeric | Pass unique random number as reference number for each transaction request. Example: 1213 Note: You can pass timestamp as a reference number to create uniqueness. You are not allowed to pass reference number which has been used for any of the previous transactions. Eg: 00000000000110 |

**Response Data**

| Parameter         | Data Type            | Description                                                                                                                           |
| ----------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| IsSuccess         | Boolean              | Returns TRUE if request is success otherwise FALSE                                                                                    |
| Messages          | Collection of String | If IsSuccess is true it will return “Transaction Status successfully retrieved”.                                                      |
| Value             | Collection of Info   |                                                                                                                                       |
| Transactionnumber | String               | Returns transaction number that is received in request.                                                                               |
| Referencenumber   | String               | Returns reference number that is received in request.                                                                                 |
| Status            | String               | Returns Completed, if signing is done successfully otherwise Failed. Returns Initiate, if user just initiated and left in the middle. |
| ErrorMessage      | Collection of String | Returns error message if transaction status retrieval failed.                                                                         |

```json
{
    “IsSuccess”: true,
    “Messages”: [
    “Status Information Found”
    ],
    “Value”: {
        “TransactionNumber”: “ESG20171213161927943”,
        “ReferenceNumber”: “REFDB190”,
        “Status”: “Failed”,
        “ErrorMessage”: “You cannot use reference number which is already used in previous transactions. ::1”
    }
}
```

| Error Code | Error Msg          | Description                          |
| ---------- | ------------------ | ------------------------------------ |
| 201        | Invalid Parameters | When any parameter is empty/invalid. |
| 202        | Invalid Operation  | If API call is invalid               |

### Signed Data Request

Use the “SignedDataRequest” API to retrieve data signed through the signer gateway

Type of Method – GET

To test the retrieval of signed data from signer gateway, please try the test URL below:

```html
https://testgateway.emsigner.com/api/SignedDataRequest?Authtoken=cbFdZK9esvBzZQ1QynL7IjKb7t92K%2BB4SoEzVA%3D&Transactionnumber=1213&Referencenumber=78123897
```

**Request Data Parameters**

| Parameter            | Data Type    | Description                                                                                                                                                                                                                                                                                  |
| -------------------- | ------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| AuthToken \*         | String       | Pass valid URL encoded Authtoken. Eg: cbFdZK9esvBzZQ1QynL7IjKb7t92K%2BB4SoEzVA%3D                                                                                                                                                                                                            |
| Transactionnumber \* | String       | Pass unique transaction number received in the Step6.                                                                                                                                                                                                                                        |
| Referencenumber \*   | AlphaNumeric | Pass unique random number as reference number for each transaction request. Example: 1213 Note: You can pass timestamp as a reference number to create uniqueness. You are not allowed to pass reference number which has been used for any of the previous transactions. Eg: 00000000000110 |

**Response Data**

| Parameter         | Data Type            | Description                                                                                                                           |
| ----------------- | -------------------- | ------------------------------------------------------------------------------------------------------------------------------------- |
| IsSuccess         | Boolean              | Returns TRUE if request is success otherwise FALSE                                                                                    |
| Messages          | Collection of String | If IsSuccess is true it will return “Transaction Status successfully retrieved”.                                                      |
| Value             | Collection of Info   |                                                                                                                                       |
| Status            | String               | Returns Completed, if signing is done successfully otherwise Failed. Returns Initiate, if user just initiated and left in the middle. |
| Transactionnumber | String               | Returns transaction number that is received in request.                                                                               |
| Referencenumber   | String               | Returns reference number that is received in request.                                                                                 |
| SignedData        | Byte 64 String       | Returns Encrypted Signed DATA, if signing is done successfully otherwise Failure.                                                     |
| ErrorMessage      | Collection of String | Returns error message if transaction status retrieval failed.                                                                         |

```json
{
    “IsSuccess”: true,
    “Messages”: [
    “Signed data found successfully”
    ],
    “Value”: {
        “Status”: “Completed”,
        “TransactionNumber”: “ESG20171213132055259”,
        “ReferenceNumber”: “REFDB182”,
        “SignedData”: “Y9nCZh6XiJGW8ZQRPn8kDXr2JDBTzBRz4MT366MCfK7KX+ac9uGMWJjcPqVDRTO4PKY+ZvQT382RQxthT/qyFDJiiM09NifWF6kk9Ti/lrsqIzOOpOfSD/0CCvBAvpNZ26ywyWGD+ “,
        “ErrorMessage”: “”
    }
}
}
```

| Error Code | Error Msg            | Description                                     |
| ---------- | -------------------- | ----------------------------------------------- |
| 204        | Invalid Authtoken    | When invalid Authtoken is entered               |
| 205        | Invalid parameters   | When any parameter is empty                     |
| 206        | Invalid Operation    | If API call is invalid                          |
| 207        | No signed data found | If signed data is not available for the account |

### Decrypting Signed Data

The response from API returns encrypted Signed Data which can be decrypted using the session key that was generated while sending the signing request

To decrypt the signed data, please use the code snippet below.

```vbnet
//.NET Code
public string CompressFileLZMA(string InputFileName)
{
    string TransactionID = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    string OutputFileName = System.Web.Configuration.WebConfigurationManager.AppSettings["filepath"] + TransactionID + "_" + Path.GetFileName(InputFileName.Split('.')[0]).ToString();
    Int32 dictionary = 1 << 23;
    Int32 posStateBits = 2;
    Int32 litContextBits = 3; // for normal files
    // UInt32 litContextBits = 0; // for 32-bit data
    Int32 litPosBits = 0;
    // UInt32 litPosBits = 2; // for 32-bit data
    Int32 algorithm = 2;
    Int32 numFastBytes = 128;
    string mf = "bt4";
    bool eos = true;
    bool stdInMode = false;
    SevenZip.Sdk.CoderPropId[] propIDs =  {
        SevenZip.Sdk.CoderPropId.DictionarySize,
        SevenZip.Sdk.CoderPropId.PosStateBits,
        SevenZip.Sdk.CoderPropId.LitContextBits,
        SevenZip.Sdk.CoderPropId.LitPosBits,
        SevenZip.Sdk.CoderPropId.Algorithm,
        SevenZip.Sdk.CoderPropId.NumFastBytes,
        SevenZip.Sdk.CoderPropId.MatchFinder,
        SevenZip.Sdk.CoderPropId.EndMarker
    };
    object[] properties = {
        (Int32)(dictionary),
        (Int32)(posStateBits),
        (Int32)(litContextBits),
        (Int32)(litPosBits),
        (Int32)(algorithm),
        (Int32)(numFastBytes),
        mf,
        eos
    };
    using (FileStream inStream = new FileStream(InputFileName, FileMode.Open))
    {
        using (FileStream outStream = new FileStream(OutputFileName, FileMode.Create))
        {
            SevenZip.Sdk.Compression.Lzma.Encoder encoder = new SevenZip.Sdk.Compression.Lzma.Encoder();
            encoder.SetCoderProperties(propIDs, properties);
            encoder.WriteCoderProperties(outStream);
            Int64 fileSize;
            if (eos || stdInMode)
            fileSize = -1;
            else
                fileSize = inStream.Length;
            for (int i = 0; i < 8; i++)
            outStream.WriteByte((Byte)(fileSize >> (8 * i)));
            encoder.Code(inStream, outStream, -1, -1, null);
        }
    }
    return OutputFileName;
}
```

```java
//JAVA Code
public string CompressFileLZMA(string InputFileName)
{
    string TransactionID = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    string OutputFileName = System.Web.Configuration.WebConfigurationManager.AppSettings["filepath"] + TransactionID + "_" + Path.GetFileName(InputFileName.Split('.')[0]).ToString();
    Int32 dictionary = 1 << 23;
    Int32 posStateBits = 2;
    Int32 litContextBits = 3; // for normal files
    // UInt32 litContextBits = 0; // for 32-bit data
    Int32 litPosBits = 0;
    // UInt32 litPosBits = 2; // for 32-bit data
    Int32 algorithm = 2;
    Int32 numFastBytes = 128;
    string mf = "bt4";
    bool eos = true;
    bool stdInMode = false;
    SevenZip.Sdk.CoderPropId[] propIDs =  {
    SevenZip.Sdk.CoderPropId.DictionarySize,
    SevenZip.Sdk.CoderPropId.PosStateBits,
    SevenZip.Sdk.CoderPropId.LitContextBits,
    SevenZip.Sdk.CoderPropId.LitPosBits,
    SevenZip.Sdk.CoderPropId.Algorithm,
    SevenZip.Sdk.CoderPropId.NumFastBytes,
    SevenZip.Sdk.CoderPropId.MatchFinder,
    SevenZip.Sdk.CoderPropId.EndMarker
};
object[] properties = {
    (Int32)(dictionary),
    (Int32)(posStateBits),
    (Int32)(litContextBits),
    (Int32)(litPosBits),
    (Int32)(algorithm),
    (Int32)(numFastBytes),
    mf,
    eos
    };
    using (FileStream inStream = new FileStream(InputFileName, FileMode.Open))
    {
    using (FileStream outStream = new FileStream(OutputFileName, FileMode.Create))
    {
    SevenZip.Sdk.Compression.Lzma.Encoder encoder = new SevenZip.Sdk.Compression.Lzma.Encoder();
    encoder.SetCoderProperties(propIDs, properties);
    encoder.WriteCoderProperties(outStream);
    Int64 fileSize;
    if (eos || stdInMode)
    fileSize = -1;
    else
    fileSize = inStream.Length;
    for (int i = 0; i < 8; i++)
    outStream.WriteByte((Byte)(fileSize >> (8 * i)));
    encoder.Code(inStream, outStream, -1, -1, null);
    }
}
return OutputFileName;
}
```

### Decompressing Documents

If you sent the document in a compressed format, please use the code below to de-compress the document.

```vbnet
//.NET Code
public string DecompressFileLZMA(string InputFileName)
{
    string FileName = DateTime.Now.ToString("yyyyMMddHHmmssfff");
    using (FileStream input = new FileStream(System.Web.Configuration.WebConfigurationManager.AppSettings["filepath"] + InputFileName, FileMode.Open))
    {
        using (FileStream output = new FileStream(System.Web.Configuration.WebConfigurationManager.AppSettings["filepath"] + FileName, FileMode.Create))
        {
            SevenZip.Sdk.Compression.Lzma.Decoder decoder = new SevenZip.Sdk.Compression.Lzma.Decoder();
            byte[] properties = new byte[5];
            if (input.Read(properties, 0, 5) != 5)
                throw (new Exception("input .lzma is too short"));
            decoder.SetDecoderProperties(properties);
            long outSize = 0;
            for (int i = 0; i < 8; i++)
            {
                int v = input.ReadByte();
                if (v < 0)
                    throw (new Exception("Can't Read 1"));
                outSize |= ((long)(byte)v) << (8 * i);
            }
            long compressedSize = input.Length - input.Position;
            decoder.Code(input, output, compressedSize, outSize, null);
        }
    }
    return FileName;
}
}
```
