PHP Functions – Order of Arguments Matters

I had multiple optional arguments to a function and I was trying to bypass an argument that I didn’t need (which was in the middle). So I invoked the function with explicitly loading the optional argument that I needed but now I understood that PHP doesn’t like it. PHP will only take in arguments in order so unfortunately you’ll have to list all arguments in case you would like to miss any.

// Function definition:
function file_add($filePath, $fileName, $folderId = NULL, &$log = NULL) {
   ...
   ...
}

// This will NOT work:
file_add($tmp_file, $fileName, $log = $log);

// This will work:
file_add($tmp_file, $fileName, $folderId = NULL, $log = $log);

Hash (sha512) of public_key in PHP and Python

I had a public_key generated by open ssl that was used to create a hash for encryption in PHP. But I had a hard time converting the equivalent in Python because that’s where I wanted to go. But sooner rather than later, I figured that out. Covered both examples here:

PHP Code:

$public_key = '-----BEGIN PUBLIC KEY-----
abcdMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0wSUI+wSKOqvpm79kNslxOw3D
OLi76AEqsB5w/mQETdpOU0hTGHKNBBIO3ZVzTks3FUs+NCfHuG3bUYW3ss8OjV8f
klmeq9Xt9HgMHH51nBvBQnNJ14q7KB1onH5oBnLpIA3Yo0Xc9F0CHTiRYZzObhij
PdTycTAn5RYg3gzWQwIDAQAB
-----END PUBLIC KEY-----'
$hash = hash("sha512", $public_key);
echo "$hash\n";

Python Code: The key here is to have \n\ at each terminating line in the key. \n denotes end of line character and \ denotes concatenation of string.

import hashlib
public_key = '-----BEGIN PUBLIC KEY-----\n\
abcdMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQD0wSUI+wSKOqvpm79kNslxOw3D\n\
OLi76AEqsB5w/mQETdpOU0hTGHKNBBIO3ZVzTks3FUs+NCfHuG3bUYW3ss8OjV8f\n\
klmeq9Xt9HgMHH51nBvBQnNJ14q7KB1onH5oBnLpIA3Yo0Xc9F0CHTiRYZzObhij\n\
PdTycTAn5RYg3gzWQwIDAQAB\n\
-----END PUBLIC KEY-----'
m = hashlib.sha512()
m.update(public_key)
print m.hexdigest()

Postgres – Dump data as INSERT SQL Statements

I wanted to get data from a production database into my local machine that didn’t have the same users, schema, etc. I created a local table and then used the pg_dump to dump out data as insert statements – that helped me out. Here’s what I used to dump data as insert statements:

pg_dump -U user_name -h localhost -t table_name --data-only --column-inserts db_name > data_dump.sql

Docusign PHP API – Send document to recipient for signature

Using Docusign PHP API’s to send documents for signature.

// Input your info here:
$integratorKey = 'abcd-1234567-xxxx-xxxx-xxxx-xxxxxxxxxx';
$email = 'yourlogin@org.com';
$password = 'yourP@ssword';

$recipient_email = 'varun.verma@accellion.com';
$name = 'Varun Verma';
$document_name = 'order_form.pdf';

// construct the authentication header:
$header = "<DocuSignCredentials><Username>" . $email . "</Username><Password>" . $password . "</Password><IntegratorKey>" . $integratorKey . "</IntegratorKey></DocuSignCredentials>";

/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 1 - Login (to retrieve baseUrl and accountId)
/////////////////////////////////////////////////////////////////////////////////////////////////
$url = "https://demo.docusign.net/restapi/v2/login_information";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER, array("X-DocuSign-Authentication: $header"));

$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);

if ( $status != 200 ) {
	echo "error calling webservice, status is:" . $status;
	exit(-1);
}

$response = json_decode($json_response, true);
$accountId = $response["loginAccounts"][0]["accountId"];
$baseUrl = $response["loginAccounts"][0]["baseUrl"];
curl_close($curl);

//--- display results
echo "\naccountId = " . $accountId . "\nbaseUrl = " . $baseUrl . "\n";

/////////////////////////////////////////////////////////////////////////////////////////////////
// STEP 2 - Create an envelope with one recipient, one tab, one document and send!
/////////////////////////////////////////////////////////////////////////////////////////////////
$data = "{
  \"emailBlurb\":\"This comes from PHP\",
  \"emailSubject\":\"DocuSign API - Please Sign This Document...\",
  \"documents\":[
    {
      \"documentId\":\"1\",
      \"name\":\"".$document_name."\"
    }
  ],
  \"recipients\":{
    \"signers\":[
      {
        \"email\":\"$recipient_email\",
        \"name\":\"$name\",
        \"recipientId\":\"1\",
        \"tabs\":{
          \"signHereTabs\":[
            {
              \"anchorString\":\"Signature:\",
              \"anchorXOffset\":\"0\",
              \"anchorYOffset\":\"0\",
              \"documentId\":\"1\",
              \"pageNumber\":\"1\"
            }
          ]
        }
      }
    ]
  },
  \"status\":\"sent\"
}";  

$file_contents = file_get_contents($document_name);

$requestBody = "\r\n"
."\r\n"
."--myboundary\r\n"
."Content-Type: application/json\r\n"
."Content-Disposition: form-data\r\n"
."\r\n"
."$data\r\n"
."--myboundary\r\n"
."Content-Type:application/pdf\r\n"
."Content-Disposition: file; filename=\"order_form.pdf\"; documentid=1 \r\n"
."\r\n"
."$file_contents\r\n"
."--myboundary--\r\n"
."\r\n";

// *** append "/envelopes" to baseUrl and as signature request endpoint
$curl = curl_init($baseUrl . "/envelopes" );
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);
curl_setopt($curl, CURLOPT_HTTPHEADER, array(
	'Content-Type: multipart/form-data;boundary=myboundary',
	'Content-Length: ' . strlen($requestBody),
	"X-DocuSign-Authentication: $header" )
);

$json_response = curl_exec($curl);
$status = curl_getinfo($curl, CURLINFO_HTTP_CODE);
if ( $status != 201 ) {
	echo "error calling webservice, status is:" . $status . "\nerror text is --> ";
	print_r($json_response); echo "\n";
	exit(-1);
}

$response = json_decode($json_response, true);
$envelopeId = $response["envelopeId"];

//--- display results
echo "Document is sent! Envelope ID = " . $envelopeId . "\n\n"; 

Docusign Python API – Send document to multiple recipients for signature

I had a lot of trouble sending documents via Docusign’s Python library, specially PDF’s. Python’s encoding doesn’t really help read the pdf data and send it across to the docusign’s API via http request. Then I chose the option to convert pdf data to base64 and use that under the document section to invoke the API. Here’s a sample code to make that happen:

# DocuSign - Embedded Sending to multiple recipients for signing
import sys, json, urllib, urllib2
import base64
 
# enter your info:
username = "yourlogin@org.com"
password = "yourP@ssword"
integratorKey = "abcd-1234567-xxxx-xxxx-xxxx-xxxxxxxxxx"
document_name = "document.pdf"

# enter recipient info:
email_1 = "signer_1@org.com"
name_1 = "Signer One"
anchor_string_1 = "signer_one"
 
email_2 = "signer_2@org.com"
name_2 = "Signer Two"
anchor_string_2 = "signer_two"

# build authentication string XML
authenticateStr = "<DocuSignCredentials>" \
                    "<Username>" + username + "</Usernamegt;" \
                    "<Password>" + password + "</Password>" \
                    "<IntegratorKey>" + integratorKey + "</IntegratorKey>" \
                    "</DocuSignCredentials>"

# Login
url = 'https://demo.docusign.net/restapi/v2/login_information';   
headers = {'X-DocuSign-Authentication': authenticateStr, 'Accept': 'application/json'}
req = urllib2.Request(url, headers=headers)
response = urllib2.urlopen(req)
json_response = response.read()

status = response.code
if (status != 200): 
    print("Error calling webservice, status is: %s" % status); sys.exit()
 
# get the baseUrl and accountId from the response body
data = json.loads(json_response)
loginInfo = data['loginAccounts']
D = loginInfo[0]
baseUrl = D['baseUrl']
accountId = D['accountId']

# open pdf document in binary read mode 
f = open(document_name, 'rb')
file_contents = f.read()
f.close()

b64_content = base64.b64encode(file_contents)

dict_body = {
    "emailBlurb" : "This comes from Python API",
    "emailSubject" : "DocuSign API - Please Sign This Document...",
    "documents" : [
        {
            "documentId" : "1",
            "documentBase64" : b64_content,
            "name" : document_name
        }
    ],
    "recipients" : {
        "signers" : [
            {
                "email" : email_1,
                "name" : name_1,
                "recipientId" : "1",
                "tabs" : {
                    "signHereTabs" : [
                        {
                            "anchorString" : anchor_string_1,
                            "anchorXOffset" : "60",
                            "anchorYOffset" : "10",
                            "anchorUnits" : "pixels",
                            "documentId" : "1",
                            "pageNumber" : "1"
                        }
                    ]
                }
            },
            {
                "email" : email_2,
                "name" : name_2,
                "recipientId" : "2",
                "tabs" : {
                    "signHereTabs" : [
                        {
                            "anchorString" : anchor_string_2,
                            "anchorXOffset" : "60",
                            "anchorYOffset" : "10",
                            "anchorUnits" : "pixels",
                            "documentId" : "1",
                            "pageNumber" : "1"
                        }
                    ]
                }
            }
        ]
    },
    "status" : "sent"
}

requestBody =  "\r\n" + \
                "\r\n" + \
                "--myboundary\r\n" + \
                "Content-Type: application/json\r\n" + \
                "Content-Disposition: form-data\r\n" + \
                "\r\n" + \
                json.dumps(dict_body)+"\r\n" + \
                "--myboundary--\r\n" + \
                "\r\n"

headers = {'Content-Type' : 'multipart/form-data;boundary=myboundary',
           'Accept' : 'application/json',
           'X-DocuSign-Authentication' : authenticateStr
           }
req = urllib2.Request(url=baseUrl+"/envelopes", data=requestBody, headers=headers)
response = urllib2.urlopen(req)
json_response = response.read()
print json_response
    
sys.exit()
 

JMeter – Posting JSON to API

Every time I have to get back to JMeter for load testing, I tend to forget the steps to setup my client. So this time taking notes so it saves me time in future.

1. Open a new instance of JMeter
2. Under Test Plan, add a HTTP Header Manager to set the content type by navigating to Test Plan > Add > Config Element > HTTP Header Manager. Add new value for Name = “Content-Type” and value = “application/json” (without quotes).
3. Under Test Plan, add a thread group by navigating to Test Plan > Add > Threads (Users) > Thread Group
4. Under Thread Group, add a sampler of type HTTP Request by navigating to Thread Group > Add > Sampler > HTTP Request
5. You can add various listeners to the Thread Group. I prefer Results in Table/Tree by navigating to Thread Group > Add > Listener > View Results in Table

JMeter Setup to POST JSON