Azure Relay Service and PHP
Some Globals
<?PHP
// --Variable-------------------------------------------
$namespace = "MyServiceBusNamespace"; // Change to your namespace.
$service = "Testservice"; // Change to your service.
$serviceUrl = "https://$namespace.servicebus.windows.net/$service/";
$SOAPAction = http://schemas/testservice/ITestService/MyAction;
$sharedAccessKeyName = "TestAccessKey";
$sharedAccessKey = "Gdfi2lb4fqNdozFGTRUsvfqZSMCMzfh/2oj02CZ0LPE="; // Change!
?>
Create the SAS Token
<?PHP
// Create SAS token
function CreateToken()
{
global $namespace, $sharedAccessKeyName, $sharedAccessKey;
$expireInSeconds = 1000;
$t0 = time(); // Returns the current time measured in the number of seconds since the Unix Epoch
$expire = $t0 + $expireInSeconds;
$sr = urlencode("https://$namespace.servicebus.windows.net");
$tohash = utf8_encode($sr . "\n" . $expire);
$sig = base64_encode(
hash_hmac( 'sha256' , $tohash , $sharedAccessKey , true)
);
$sig = urlencode($sig);
$se = $expire;
$skn = $sharedAccessKeyName;
$token = "SharedAccessSignature sr=$sr&sig=$sig&se=$se&skn=$skn";
return $token;
}
Or Get the ACS Token
<?PHP
// Get the ACS token
function GetASCToken()
{
$global $namespace, $service, $issuer, $secret;
$connectionString = "Endpoint=sb://$namespace.servicebus.windows.net;SharedSecretIssuer=$issuer;SharedSecretValue=$secret";
$tokenUrl = "https://$namespace-sb.accesscontrol.windows.net/WRAPv0.9/";
$postdata = http_build_query(
array(
"wrap_name" => $issuer,
"wrap_password" => $secret,
"wrap_scope" => "http://$namespace.servicebus.windows.net/$service/"
)
);
$options = array(
'http' => array(
'header' => "Content-type: application/x-www-form-urlencoded;\r\n",
'method' => 'POST',
'content' => $postdata
)
);
$context = stream_context_create($options);
$result = file_get_contents($tokenUrl, false, $context);
// Do error handling if not authorized!
$split = preg_split("[&]", $result);
$split = preg_split("[=]", $split[0]);
$t = urldecode($split[1]);
return "WRAP access_token=\"$t\"";
}
?>
Call the Azure Relay Service
// Call the Azure Relay Service.
function CallRelay($token)
{
global $serviceUrl, $SOAPAction;
// Datacontract met SOAP envelope.
$body = "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\"><s:Header/><s:Body>" .
"<MyRequest xmlns=\"http://schemas/testservice/v1\"><Reverse>ABCDEFGHI</Reverse></MyRequest>" .
"</s:Body></s:Envelope>";
$bodyLength = strlen($body);
$header = "Content-type: application/x-www-form-urlencoded;\r\n".
"Content-Length: $bodyLength\r\n" .
"SOAPAction: $SOAPAction\r\n" .
"ServiceBusAuthorization: $token\r\n";
$options = array(
'http' => array(
'header' => $header,
'content' => $body,
'method' => 'POST'
)
);
$context = stream_context_create($options);
$result = file_get_contents($serviceUrl, false, $context);
// Do some error handling!
return $result;
}
<?php
$token = CreateToken();
// OR
$token = GetACSToken();
$result = CallRelay($token);
print_r(htmlentities($result));
?>