Contents of this page

Code Sample – PHP
Code Sample – Java
Sample Error Response


Code Sample – PHP

Example of a file that uses PHP to log in to the Watson Campaign Automation and fetch information about contact sources by using the API. To use this code, you must host it on a web server and run it with a PHP engine that runs on that server.

This is a very basic example of how to make requests to and handle responses from the WCA XMLAPI. It is highly recommended to break this up into objects and to implement more robust error handling.

$pod = 0;
$username = 'foo@silverpop.com';
$password = 'bar';

$endpoint = "https://api{$pod}.silverpop.com/XMLAPI";
$jsessionid = null;

$baseXml = '%s';
$loginXml = '';
$getListsXml = '%s%s';
$logoutXml = '';

try {

    $xml = sprintf($baseXml, sprintf($loginXml, $username, $password));
    $result = xmlToArray(makeRequest($endpoint, $jsessionid, $xml));
    print_r($result);

    $jsessionid = $result['SESSIONID'];

    $xml = sprintf($baseXml, sprintf($getListsXml, 1, 2)); // VISIBILITY 1 = Shared, LIST_TYPE 2 = Regular and Query
    $result = xmlToArray(makeRequest($endpoint, $jsessionid, $xml));
    print_r($result);

    $xml = $logoutXml;
    $result = xmlToArray(makeRequest($endpoint, $jsessionid, $xml, true));
    print_r($result);

    $jsessionid = null;

    print "\nDone\n\n";
} catch (Exception $e) {
    die("\nException caught: {$e->getMessage()}\n\n");
}

// -- Functions --

function makeRequest($endpoint, $jsessionid, $xml, $ignoreResult = false)
{
    $url = getApiUrl($endpoint, $jsessionid);
    $xmlObj = new SimpleXmlElement($xml);
    $request = $xmlObj->asXml();

    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_POST, true);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $request);
    curl_setopt($curl, CURLINFO_HEADER_OUT, true);

    $headers = array(
        'Content-Type: text/xml; charset=UTF-8',
        'Content-Length: ' . strlen($request),
    );

    curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
    curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 60);
    curl_setopt($curl, CURLOPT_TIMEOUT, 60);

    $response = @curl_exec($curl);

    if (false === $response) {
        throw new Exception('CURL error: ' . curl_error($curl));
    }

    curl_close($curl);

    if (true === $response || !trim($response)) {
        throw new Exception('Empty response from WCA');
    }

    $xmlResponse = simplexml_load_string($response);

    if (false === $ignoreResult) {
        if (false === isset($xmlResponse->Body->RESULT)) {
            var_dump($xmlResponse);
            throw new Exception('Unexpected response from WCA');
        }

        return $xmlResponse->Body->RESULT;
    }

    return $xmlResponse->Body;
}

function getApiUrl($endpoint, $jsessionid)
{
    return $endpoint . ((null === $jsessionid)
        ? ''
        : ';jsessionid=' . urlencode($jsessionid));
}

function xmlToJson($xml)
{
    return json_encode($xml);
}

function xmlToArray($xml)
{
    $json = xmlToJson($xml);
    return json_decode($json, true);
}

Code Sample – Java

Example of using Java™ to call the AddRecipient XML API

String request = ''; // put
the actual XML here.
String sendEncoding = "utf-8";
HttpURLConnection urlConn = null; OutputStream out = null; InputStream in = null;
try {
URL url = new URL(apiUrl);
urlConn = (HttpURLConnection)url.openConnection(); urlConn.setRequestMethod("POST");
urlConn.setDoOutput(true);
urlConn.setRequestProperty("Content-Type","text/xml;charset=" + sendEncoding);
urlConn.connect();
String userpass = USER + ":" + PASS;
String basicAuth = "Basic " + new String(Base64.getEncoder().encodeToString(userpass.getBytes()));
urlConn.setRequestProperty ("Authorization", basicAuth);
out = urlConn.getOutputStream(); out.write(request.getBytes(sendEncoding)); out.flush();
in = urlConn.getInputStream();
InputStreamReader inReader = new InputStreamReader(in, sendEncoding); StringBuffer responseBuffer
= new StringBuffer();
char[] buffer = new char[BUFFER_SIZE]; int bytes;
while ((bytes = inReader.read(buffer)) != -1) {
responseBuffer.append(buffer, 0, bytes);
}
response = responseBuffer.toString();
} finally {
if (out != null) {
try {out.close();} catch (Exception e) {}
}
if (in != null) {
try {in.close();} catch (Exception e) {}
}
if (urlConn != null) { urlConn.disconnect();
}

Sample Error Response

A sample API call error response.

<Envelope>
  <Body>
    <RESULT>
      <SUCCESS>false</SUCCESS>
    </RESULT>
    <Fault>
      <Request/>
      <FaultCode/>
      <FaultString>
        <![CDATA[Unable to remove the recipient. 
          The list is private and you are not the owner.]]>
      </FaultString>
      <detail>
        <error>
          <errorid>140</errorid>
          <module/>
          <class>SP.Recipients</class>
          <method/>
        </error>
      </detail>
    </Fault>
  </Body>
</Envelope>

 

Join The Discussion

Your email address will not be published. Required fields are marked *