{"_id":"5c1d22df5e5af4003f448963","project":"550f74bb6fc8130d0038aad3","version":{"_id":"550f75de61d9d30d00af9e01","__v":17,"project":"550f74bb6fc8130d0038aad3","forked_from":"550f74bb6fc8130d0038aad6","createdAt":"2015-03-23T02:09:34.221Z","releaseDate":"2015-03-23T02:09:34.221Z","categories":["550f75de61d9d30d00af9e02","551027e38579861900a86698","551029e08579861900a8669a","551029e7498062190006328a","5bc633a722d682005c9ad9e4","5bc633b08c4b0b000d6a7eaa","5bc633b48f3ff600626e3e18","5bc63538e5a6ba000d22ee6d","5bc63587a18a6b000decd295","5bc635c0937fcb0056223d9c","5bc6360f42f41800319aeaa6","5be5d13ff1d319002baca9ce","5be5d2287cd14d00291fbfdb","5be8b3b09f7cb70023c56a39","5be8b3cbb910100044e20206","5c1d769a4f6aed001fe527f0","5c402942010f0d001496dded"],"is_deprecated":false,"is_hidden":false,"is_beta":true,"is_stable":true,"codename":"","version_clean":"3.0.0","version":"3"},"category":{"_id":"5be5d13ff1d319002baca9ce","project":"550f74bb6fc8130d0038aad3","version":"550f75de61d9d30d00af9e01","__v":0,"sync":{"url":"","isSync":false},"reference":true,"createdAt":"2018-11-09T18:26:07.698Z","from_sync":false,"order":0,"slug":"getting-started","title":"Wyre API"},"user":"54eb8076867e1917009b7160","__v":2,"parentDoc":null,"metadata":{"title":"","description":"","image":[]},"updates":["5c3baacc79bd6e001456eea1","5c4a56da31dab80057811fc3"],"next":{"pages":[],"description":""},"createdAt":"2018-12-21T17:29:03.925Z","link_external":false,"link_url":"","sync_unique":"","hidden":false,"api":{"settings":"","results":{"codes":[]},"apiSetting":null,"auth":"required","params":[],"url":""},"isReference":true,"order":6,"body":"Below are _very simple_ example [secret key signature authentication](doc:authentication#secret-key-signature-auth) implementations of authentication in a couple of different languages.\n\nEach example is annotated with `todo` notes that you must address before the code is usable. Examples contain at least an HTTP JSON API call with a signature against the Wyre production API (the _testwyre.com_ environment URI is commented out but included).\n\nFeel free to also checkout our Postman collection [here](https://github.com/sendwyre/wyre-postman-collection) for a suite of requests to all of our endpoints.\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n    function make_authenticated_request($endpoint, $method, $body) {\\n      \\t// $url = 'https://api.testwyre.com'; // todo use this endpoint for testwyre environment\\n        $url = 'https://api.sendwyre.com';\\n      \\n      \\t// todo please replace these with your own keys for the correct environment\\n        $api_key = \\\"AK-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA\\\";\\n        $secret_key = \\\"SK-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA\\\";\\n\\n        $timestamp = floor(microtime(true)*1000);\\n        $request_url = $url . $endpoint;\\n\\n        if(strpos($request_url,\\\"?\\\"))\\n            $request_url .= '&timestamp=' . sprintf(\\\"%d\\\", $timestamp);\\n        else\\n            $request_url .= '?timestamp=' . sprintf(\\\"%d\\\", $timestamp);\\n\\n        if(!empty($body))\\n            $body = json_encode($body, JSON_FORCE_OBJECT);\\n        else\\n            $body = '';\\n\\n        $headers = array(\\n            \\\"Content-Type: application/json\\\",\\n            \\\"X-Api-Key: \\\". $api_key,\\n            \\\"X-Api-Signature: \\\". calc_auth_sig_hash($secret_key, $request_url . $body)\\n        );\\n        $curl = curl_init();\\n\\n        if($method==\\\"POST\\\"){\\n          $options = array(\\n            CURLOPT_URL             => $request_url,\\n            CURLOPT_POST            =>  true,\\n            CURLOPT_POSTFIELDS      => $body,\\n            CURLOPT_RETURNTRANSFER  => true);\\n        }else {\\n          $options = array(\\n            CURLOPT_URL             => $request_url,\\n            CURLOPT_RETURNTRANSFER  => true);\\n        }\\n        curl_setopt_array($curl, $options);\\n        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\\n        $result = curl_exec($curl);\\n        curl_close($curl);\\n        var_dump($result);\\n        return json_decode($result, true);\\n    }\\n\\n    function calc_auth_sig_hash($seckey, $val) {\\n        $hash = hash_hmac('sha256', $val, $seckey);\\n        return $hash;\\n    }\\n\\n\\t\\t// try to retrieve the current account\\n    echo make_authenticated_request(\\\"/v2/account\\\", \\\"GET\\\", array());\\n\\n\\t\\t// perform a transfer\\n\\t\\t$transfer = array(\\n      \\\"sourceCurrency\\\"=>\\\"USD\\\",\\n      \\\"dest\\\"=>\\\"account:AC-XXXXXXXX\\\", // replace with your account ID\\n      \\\"sourceAmount\\\"=> \\\"100.50\\\",\\n      \\\"destCurrency\\\"=> \\\"BTC\\\",\\n      \\\"message\\\"=> \\\"convert USD to bitcoin\\\"\\n      );\\n\\t\\techo make_authenticated_request(\\\"/v2/transfers\\\", \\\"POST\\\", $transfer);\\n?>\",\n      \"language\": \"php\"\n    },\n    {\n      \"code\": \"using System;\\nusing System.Collections.Generic;\\nusing System.IO;\\nusing System.Net;\\nusing System.Security.Cryptography;\\nusing System.Text;\\nusing System.Linq;\\nusing Newtonsoft.Json.Linq;\\nusing Newtonsoft.Json;\\n\\nnamespace testauthwyre\\n{\\n    class MainClass\\n    {\\n        public static void Main(string[] args)\\n        {\\n            WyreApi wyre = new WyreApi();\\n\\n            HttpWebResponse accountResponse = wyre.Get(\\\"/v2/account\\\");\\n\\n            Console.WriteLine(GetResponseBody(accountResponse));\\n\\n            Dictionary<string, object> body = new Dictionary<string, object>();\\n            body.Add(\\\"sourceCurrency\\\", \\\"USD\\\");\\n            body.Add(\\\"destCurrency\\\", \\\"BTC\\\");\\n            body.Add(\\\"sourceAmount\\\", \\\"50.50\\\");\\n            body.Add(\\\"dest\\\", \\\"account:AC-XXXXXX\\\"); // todo use your real account ID here\\n            HttpWebResponse transferResponse = wyre.Post(\\\"/v2/transfers\\\", body);\\n\\n            Console.WriteLine(GetResponseBody(transferResponse));\\n        }\\n\\n        private static string GetResponseBody(HttpWebResponse response)\\n        {\\n            return JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()).ToString(Formatting.Indented);\\n        }\\n    }\\n\\n    public class WyreApi\\n    {\\n        private const String domain = \\\"https://api.sendwyre.com\\\";\\n        // private const String domain = \\\"https://api.testwyre.com\\\"; // todo use this endpoint for Wyre's testing environmnemt\\n      \\n      \\t// todo replace these with your api private and secret keys\\n        private const String apiKey = \\\"AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\\\";\\n        private const String secKey = \\\"SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\\\";\\n\\n        public HttpWebResponse Get(string path)\\n        {\\n            return Get(path, new Dictionary<string, object>());\\n        }\\n\\n        public HttpWebResponse Get(string path, Dictionary<string, object> queryParams)\\n        {\\n            return Request(\\\"GET\\\", path, queryParams);\\n        }\\n\\n        public HttpWebResponse Post(string path, Dictionary<string, object> body)\\n        {\\n            return Request(\\\"POST\\\", path, body);\\n        }\\n\\n        private HttpWebResponse Request(string method, string path, Dictionary<string, object> body)\\n        {\\n            Dictionary<string, object> queryParams = new Dictionary<string, object>();\\n\\n            if (method.Equals(\\\"GET\\\"))\\n                queryParams = body;\\n\\n            queryParams.Add(\\\"timestamp\\\", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());\\n\\n            string queryString = queryParams.Aggregate(\\\"\\\", (previous, current) => previous + \\\"&\\\" + current.Key + \\\"=\\\" + current.Value).Remove(0, 1);\\n\\n            string url = domain + path + \\\"?\\\" + queryString;\\n\\n            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\\n            request.Method = method;\\n            request.ContentType = \\\"application/json\\\";\\n            request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\\n\\n            if (!method.Equals(\\\"GET\\\"))\\n            {\\n                url += JsonConvert.SerializeObject(body);\\n                using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))\\n                    writer.Write(JsonConvert.SerializeObject(body));\\n            }\\n\\n            request.Headers[\\\"X-Api-Key\\\"] = apiKey;\\n            request.Headers[\\\"X-Api-Signature\\\"] = CalcAuthSigHash(secKey, url);\\n\\n            try \\n            {\\n                return (HttpWebResponse)request.GetResponse();\\n            }\\n            catch(WebException e) \\n            {\\n                string msg = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();\\n                Console.WriteLine(msg);\\n                throw new SystemException(msg);\\n            }\\n        }\\n\\n        private byte[] GetBytes(string str)\\n        {\\n            return Encoding.UTF8.GetBytes(str);\\n        }\\n\\n        private string GetString(byte[] bytes)\\n        {\\n            return BitConverter.ToString(bytes);\\n        }\\n\\n        private String CalcAuthSigHash(string key, string value)\\n        {\\n            HMACSHA256 hmac = new HMACSHA256(GetBytes(key));\\n            string hash = GetString(hmac.ComputeHash(GetBytes(value))).Replace(\\\"-\\\", \\\"\\\");\\n            return hash;\\n        }\\n    }\\n}\",\n      \"language\": \"csharp\"\n    },\n    {\n      \"code\": \"import javax.crypto.Mac;\\nimport javax.crypto.spec.SecretKeySpec;\\nimport java.io.BufferedReader;\\nimport java.io.DataOutputStream;\\nimport java.io.InputStream;\\nimport java.io.InputStreamReader;\\nimport java.lang.Integer;\\nimport java.lang.String;\\nimport java.lang.StringBuffer;\\nimport java.net.HttpURLConnection;\\nimport java.net.URL;\\n\\npublic class TestAuth {\\n\\tpublic static void main(String[] args) {\\n    // todo replace with your actual credentials\\n\\t\\tString apiKey = \\\"AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\\\";\\n\\t\\tString secretKey = \\\"SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\\\";\\n\\n    // String baseUrl = \\\"https://api.testwyre.com\\\"; // todo use this for Wyre's testing environment \\n    String baseUrl = \\\"https://api.sendwyre.com\\\";\\n\\t\\tString data = \\\"\\\";\\n\\n\\t\\tString result = executeWyreRequest(baseUrl + \\\"/v2/account\\\", \\\"\\\", \\\"GET\\\", apiKey, secretKey);\\n\\t\\tSystem.out.println(result);\\n    \\n    // todo encode request data - you probably want to use a JSON serialization library such as Jackson for this!\\n\\t\\tdata = \\\"{\\\" +\\n\\t\\t\\t\\t\\\"  \\\\\\\"dest\\\\\\\": \\\\\\\"account:AC-XXXXX\\\\\\\",\\\" + // todo replace with your account ID\\n\\t\\t\\t\\t\\\"  \\\\\\\"destCurrency\\\\\\\": \\\\\\\"USD\\\\\\\",\\\" +\\n\\t\\t\\t\\t\\\"  \\\\\\\"sourceCurrency\\\\\\\" : \\\\\\\"BTC\\\\\\\",\\\" +\\n\\t\\t\\t\\t\\\"  \\\\\\\"sourceAmount\\\\\\\" : \\\\\\\"1\\\\\\\",\\\" +\\n\\t\\t\\t\\t\\\"  \\\\\\\"message\\\\\\\": \\\\\\\"$1 worth of bitcoin!\\\\\\\"\\\" +\\n\\t\\t\\t\\t\\\"}\\\";\\n\\t\\tresult = executeWyreRequest(baseUrl + \\\"/v2/transfers\\\", data, \\\"POST\\\", apiKey, secretKey);\\n\\n\\t\\tSystem.out.println(result);\\n\\t}\\n\\n\\tpublic static String executeWyreRequest(String targetURL, String requestBody, String method, String apiKey, String secretKey) {\\n\\t\\tURL url;\\n\\t\\tHttpURLConnection connection = null;\\n\\t\\ttry {\\n\\n\\t\\t\\ttargetURL += ((targetURL.indexOf(\\\"?\\\")>0)?\\\"&\\\":\\\"?\\\") + \\\"timestamp=\\\" + System.currentTimeMillis();\\n\\n\\t\\t\\t//Create connection\\n\\t\\t\\turl = new URL(targetURL);\\n\\t\\t\\tconnection = (HttpURLConnection)url.openConnection();\\n\\t\\t\\tconnection.setRequestMethod(method);\\n\\t\\t\\tSystem.out.println(connection.getRequestMethod());\\n\\n\\t\\t\\tconnection.setRequestProperty(\\\"Content-Type\\\", \\\"application/json\\\");\\n\\t\\t\\tconnection.setRequestProperty(\\\"Content-Length\\\", Integer.toString(requestBody.getBytes().length));\\n\\n\\t\\t\\t// Provide API key and signature\\n\\t\\t\\tconnection.setRequestProperty(\\\"X-Api-Key\\\", apiKey);\\n\\t\\t\\tconnection.setRequestProperty(\\\"X-Api-Signature\\\",computeSignature(secretKey,targetURL,requestBody));\\n\\n\\t\\t\\t//Send request\\n\\t\\t\\tif(method.equals(\\\"POST\\\")) {\\n\\t\\t\\t\\tconnection.setDoOutput(true);\\n\\t\\t\\t\\tconnection.setRequestMethod(method);\\n\\n\\t\\t\\t\\tDataOutputStream wr = new DataOutputStream(\\n\\t\\t\\t\\t\\t\\tconnection.getOutputStream());\\n\\n\\t\\t\\t\\twr.write(requestBody.getBytes(\\\"UTF-8\\\"));\\n\\t\\t\\t\\twr.flush();\\n\\t\\t\\t\\twr.close();\\n\\t\\t\\t}\\n\\n\\t\\t\\t//Get Response\\n\\t\\t\\tInputStream is;\\n\\t\\t\\tif (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {\\n\\t\\t\\t\\tis = connection.getInputStream();\\n\\t\\t\\t} else {\\n\\n\\t\\t\\t\\tis = connection.getErrorStream();\\n\\t\\t\\t}\\n\\n\\t\\t\\tBufferedReader rd = new BufferedReader(new InputStreamReader(is));\\n\\t\\t\\tString line;\\n\\t\\t\\tStringBuffer response = new StringBuffer();\\n\\t\\t\\twhile((line = rd.readLine()) != null) {\\n\\t\\t\\t\\tresponse.append(line);\\n\\t\\t\\t\\tresponse.append('\\\\r');\\n\\t\\t\\t}\\n\\t\\t\\trd.close();\\n\\t\\t\\treturn response.toString();\\n\\n\\t\\t} catch (Exception e) {\\n\\n\\t\\t\\te.printStackTrace();\\n\\t\\t\\treturn null;\\n\\n\\t\\t} finally {\\n\\n\\t\\t\\tif(connection != null) {\\n\\t\\t\\t\\tconnection.disconnect();\\n\\t\\t\\t}\\n\\t\\t}\\n\\t}\\n\\n\\tpublic static String computeSignature(String secretKey, String url, String reqData) {\\n\\n\\t\\tString data = url + reqData;\\n\\n\\t\\tSystem.out.println(data);\\n\\n\\t\\ttry {\\n\\t\\t\\tMac sha256Hmac = Mac.getInstance(\\\"HmacSHA256\\\");\\n\\t\\t\\tSecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), \\\"HmacSHA256\\\");\\n\\t\\t\\tsha256Hmac.init(key);\\n\\n\\t\\t\\tbyte[] macData = sha256Hmac.doFinal(data.getBytes(\\\"UTF-8\\\"));\\n\\n\\t\\t\\tString result = \\\"\\\";\\n\\t\\t\\tfor (final byte element : macData){\\n\\t\\t\\t\\tresult += Integer.toString((element & 0xff) + 0x100, 16).substring(1);\\n\\t\\t\\t}\\n\\t\\t\\treturn result;\\n\\n\\t\\t} catch (Exception e) {\\n\\t\\t\\te.printStackTrace();\\n\\t\\t\\treturn \\\"\\\";\\n\\t\\t}\\n\\t}\\n}\",\n      \"language\": \"java\"\n    },\n    {\n      \"code\": \"require 'uri'\\nrequire 'net/http'\\nrequire 'digest/hmac'\\nrequire 'json'\\n\\nclass WyreApi\\n  # todo replace these with your real Wyre credentials\\n  ACCOUNT_ID = 'AC-XXXXXXX'\\n  API_KEY = 'AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA'\\n  SEC_KEY = 'SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA'\\n  API_URL = 'https://api.sendwyre.com'\\n  # API_URL = 'https://api.testwyre.com' # todo use this for Wyre's testing environment\\n\\n  def create_transfer options\\n    api_post '/v2/transfers', options\\n  end\\n\\n  private\\n\\n  def api_post path, post_data = {}\\n    params = {\\n      'timestamp' => (Time.now.to_i * 1000).to_s\\n    }\\n\\n    url = API_URL + path + '?' + URI.encode_www_form(params)\\n\\n    headers = {\\n      'X-Api-Key' => API_KEY,\\n      'X-Api-Signature' => calc_auth_sig_hash(url + post_data.to_json.to_s)\\n    }\\n\\n    uri = URI API_URL\\n    Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|\\n      http.request_post(url, post_data.to_json.to_s, headers) do |res|\\n        response = JSON.parse res.body\\n        raise response['message'] if res.code != '200'\\n        return response\\n      end\\n    end\\n  end\\n\\n  def calc_auth_sig_hash url_body\\n    return Digest::HMAC.hexdigest url_body, SEC_KEY, Digest::SHA256\\n  end\\nend\\n\\napi = WyreApi.new\\napi.create_transfer({'sourceAmount'=>50,'sourceCurrency'=>'USD','dest'=>'account:' + ACCOUNT_ID, 'destCurrency'=>'BTC', 'message'=>'buy some bitcoin')\\n\",\n      \"language\": \"ruby\"\n    }\n  ]\n}\n[/block]","excerpt":"","slug":"code-examples","type":"basic","title":"Code Examples"}
Below are _very simple_ example [secret key signature authentication](doc:authentication#secret-key-signature-auth) implementations of authentication in a couple of different languages. Each example is annotated with `todo` notes that you must address before the code is usable. Examples contain at least an HTTP JSON API call with a signature against the Wyre production API (the _testwyre.com_ environment URI is commented out but included). Feel free to also checkout our Postman collection [here](https://github.com/sendwyre/wyre-postman-collection) for a suite of requests to all of our endpoints. [block:code] { "codes": [ { "code": "<?php\n function make_authenticated_request($endpoint, $method, $body) {\n \t// $url = 'https://api.testwyre.com'; // todo use this endpoint for testwyre environment\n $url = 'https://api.sendwyre.com';\n \n \t// todo please replace these with your own keys for the correct environment\n $api_key = \"AK-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA\";\n $secret_key = \"SK-AAAAAAA-AAAAAAA-AAAAAAA-AAAAAAA\";\n\n $timestamp = floor(microtime(true)*1000);\n $request_url = $url . $endpoint;\n\n if(strpos($request_url,\"?\"))\n $request_url .= '&timestamp=' . sprintf(\"%d\", $timestamp);\n else\n $request_url .= '?timestamp=' . sprintf(\"%d\", $timestamp);\n\n if(!empty($body))\n $body = json_encode($body, JSON_FORCE_OBJECT);\n else\n $body = '';\n\n $headers = array(\n \"Content-Type: application/json\",\n \"X-Api-Key: \". $api_key,\n \"X-Api-Signature: \". calc_auth_sig_hash($secret_key, $request_url . $body)\n );\n $curl = curl_init();\n\n if($method==\"POST\"){\n $options = array(\n CURLOPT_URL => $request_url,\n CURLOPT_POST => true,\n CURLOPT_POSTFIELDS => $body,\n CURLOPT_RETURNTRANSFER => true);\n }else {\n $options = array(\n CURLOPT_URL => $request_url,\n CURLOPT_RETURNTRANSFER => true);\n }\n curl_setopt_array($curl, $options);\n curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);\n $result = curl_exec($curl);\n curl_close($curl);\n var_dump($result);\n return json_decode($result, true);\n }\n\n function calc_auth_sig_hash($seckey, $val) {\n $hash = hash_hmac('sha256', $val, $seckey);\n return $hash;\n }\n\n\t\t// try to retrieve the current account\n echo make_authenticated_request(\"/v2/account\", \"GET\", array());\n\n\t\t// perform a transfer\n\t\t$transfer = array(\n \"sourceCurrency\"=>\"USD\",\n \"dest\"=>\"account:AC-XXXXXXXX\", // replace with your account ID\n \"sourceAmount\"=> \"100.50\",\n \"destCurrency\"=> \"BTC\",\n \"message\"=> \"convert USD to bitcoin\"\n );\n\t\techo make_authenticated_request(\"/v2/transfers\", \"POST\", $transfer);\n?>", "language": "php" }, { "code": "using System;\nusing System.Collections.Generic;\nusing System.IO;\nusing System.Net;\nusing System.Security.Cryptography;\nusing System.Text;\nusing System.Linq;\nusing Newtonsoft.Json.Linq;\nusing Newtonsoft.Json;\n\nnamespace testauthwyre\n{\n class MainClass\n {\n public static void Main(string[] args)\n {\n WyreApi wyre = new WyreApi();\n\n HttpWebResponse accountResponse = wyre.Get(\"/v2/account\");\n\n Console.WriteLine(GetResponseBody(accountResponse));\n\n Dictionary<string, object> body = new Dictionary<string, object>();\n body.Add(\"sourceCurrency\", \"USD\");\n body.Add(\"destCurrency\", \"BTC\");\n body.Add(\"sourceAmount\", \"50.50\");\n body.Add(\"dest\", \"account:AC-XXXXXX\"); // todo use your real account ID here\n HttpWebResponse transferResponse = wyre.Post(\"/v2/transfers\", body);\n\n Console.WriteLine(GetResponseBody(transferResponse));\n }\n\n private static string GetResponseBody(HttpWebResponse response)\n {\n return JObject.Parse(new StreamReader(response.GetResponseStream()).ReadToEnd()).ToString(Formatting.Indented);\n }\n }\n\n public class WyreApi\n {\n private const String domain = \"https://api.sendwyre.com\";\n // private const String domain = \"https://api.testwyre.com\"; // todo use this endpoint for Wyre's testing environmnemt\n \n \t// todo replace these with your api private and secret keys\n private const String apiKey = \"AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\";\n private const String secKey = \"SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\";\n\n public HttpWebResponse Get(string path)\n {\n return Get(path, new Dictionary<string, object>());\n }\n\n public HttpWebResponse Get(string path, Dictionary<string, object> queryParams)\n {\n return Request(\"GET\", path, queryParams);\n }\n\n public HttpWebResponse Post(string path, Dictionary<string, object> body)\n {\n return Request(\"POST\", path, body);\n }\n\n private HttpWebResponse Request(string method, string path, Dictionary<string, object> body)\n {\n Dictionary<string, object> queryParams = new Dictionary<string, object>();\n\n if (method.Equals(\"GET\"))\n queryParams = body;\n\n queryParams.Add(\"timestamp\", DateTimeOffset.UtcNow.ToUnixTimeMilliseconds());\n\n string queryString = queryParams.Aggregate(\"\", (previous, current) => previous + \"&\" + current.Key + \"=\" + current.Value).Remove(0, 1);\n\n string url = domain + path + \"?\" + queryString;\n\n HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);\n request.Method = method;\n request.ContentType = \"application/json\";\n request.AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate;\n\n if (!method.Equals(\"GET\"))\n {\n url += JsonConvert.SerializeObject(body);\n using (StreamWriter writer = new StreamWriter(request.GetRequestStream()))\n writer.Write(JsonConvert.SerializeObject(body));\n }\n\n request.Headers[\"X-Api-Key\"] = apiKey;\n request.Headers[\"X-Api-Signature\"] = CalcAuthSigHash(secKey, url);\n\n try \n {\n return (HttpWebResponse)request.GetResponse();\n }\n catch(WebException e) \n {\n string msg = new StreamReader(e.Response.GetResponseStream()).ReadToEnd();\n Console.WriteLine(msg);\n throw new SystemException(msg);\n }\n }\n\n private byte[] GetBytes(string str)\n {\n return Encoding.UTF8.GetBytes(str);\n }\n\n private string GetString(byte[] bytes)\n {\n return BitConverter.ToString(bytes);\n }\n\n private String CalcAuthSigHash(string key, string value)\n {\n HMACSHA256 hmac = new HMACSHA256(GetBytes(key));\n string hash = GetString(hmac.ComputeHash(GetBytes(value))).Replace(\"-\", \"\");\n return hash;\n }\n }\n}", "language": "csharp" }, { "code": "import javax.crypto.Mac;\nimport javax.crypto.spec.SecretKeySpec;\nimport java.io.BufferedReader;\nimport java.io.DataOutputStream;\nimport java.io.InputStream;\nimport java.io.InputStreamReader;\nimport java.lang.Integer;\nimport java.lang.String;\nimport java.lang.StringBuffer;\nimport java.net.HttpURLConnection;\nimport java.net.URL;\n\npublic class TestAuth {\n\tpublic static void main(String[] args) {\n // todo replace with your actual credentials\n\t\tString apiKey = \"AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\";\n\t\tString secretKey = \"SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA\";\n\n // String baseUrl = \"https://api.testwyre.com\"; // todo use this for Wyre's testing environment \n String baseUrl = \"https://api.sendwyre.com\";\n\t\tString data = \"\";\n\n\t\tString result = executeWyreRequest(baseUrl + \"/v2/account\", \"\", \"GET\", apiKey, secretKey);\n\t\tSystem.out.println(result);\n \n // todo encode request data - you probably want to use a JSON serialization library such as Jackson for this!\n\t\tdata = \"{\" +\n\t\t\t\t\" \\\"dest\\\": \\\"account:AC-XXXXX\\\",\" + // todo replace with your account ID\n\t\t\t\t\" \\\"destCurrency\\\": \\\"USD\\\",\" +\n\t\t\t\t\" \\\"sourceCurrency\\\" : \\\"BTC\\\",\" +\n\t\t\t\t\" \\\"sourceAmount\\\" : \\\"1\\\",\" +\n\t\t\t\t\" \\\"message\\\": \\\"$1 worth of bitcoin!\\\"\" +\n\t\t\t\t\"}\";\n\t\tresult = executeWyreRequest(baseUrl + \"/v2/transfers\", data, \"POST\", apiKey, secretKey);\n\n\t\tSystem.out.println(result);\n\t}\n\n\tpublic static String executeWyreRequest(String targetURL, String requestBody, String method, String apiKey, String secretKey) {\n\t\tURL url;\n\t\tHttpURLConnection connection = null;\n\t\ttry {\n\n\t\t\ttargetURL += ((targetURL.indexOf(\"?\")>0)?\"&\":\"?\") + \"timestamp=\" + System.currentTimeMillis();\n\n\t\t\t//Create connection\n\t\t\turl = new URL(targetURL);\n\t\t\tconnection = (HttpURLConnection)url.openConnection();\n\t\t\tconnection.setRequestMethod(method);\n\t\t\tSystem.out.println(connection.getRequestMethod());\n\n\t\t\tconnection.setRequestProperty(\"Content-Type\", \"application/json\");\n\t\t\tconnection.setRequestProperty(\"Content-Length\", Integer.toString(requestBody.getBytes().length));\n\n\t\t\t// Provide API key and signature\n\t\t\tconnection.setRequestProperty(\"X-Api-Key\", apiKey);\n\t\t\tconnection.setRequestProperty(\"X-Api-Signature\",computeSignature(secretKey,targetURL,requestBody));\n\n\t\t\t//Send request\n\t\t\tif(method.equals(\"POST\")) {\n\t\t\t\tconnection.setDoOutput(true);\n\t\t\t\tconnection.setRequestMethod(method);\n\n\t\t\t\tDataOutputStream wr = new DataOutputStream(\n\t\t\t\t\t\tconnection.getOutputStream());\n\n\t\t\t\twr.write(requestBody.getBytes(\"UTF-8\"));\n\t\t\t\twr.flush();\n\t\t\t\twr.close();\n\t\t\t}\n\n\t\t\t//Get Response\n\t\t\tInputStream is;\n\t\t\tif (connection.getResponseCode() < HttpURLConnection.HTTP_BAD_REQUEST) {\n\t\t\t\tis = connection.getInputStream();\n\t\t\t} else {\n\n\t\t\t\tis = connection.getErrorStream();\n\t\t\t}\n\n\t\t\tBufferedReader rd = new BufferedReader(new InputStreamReader(is));\n\t\t\tString line;\n\t\t\tStringBuffer response = new StringBuffer();\n\t\t\twhile((line = rd.readLine()) != null) {\n\t\t\t\tresponse.append(line);\n\t\t\t\tresponse.append('\\r');\n\t\t\t}\n\t\t\trd.close();\n\t\t\treturn response.toString();\n\n\t\t} catch (Exception e) {\n\n\t\t\te.printStackTrace();\n\t\t\treturn null;\n\n\t\t} finally {\n\n\t\t\tif(connection != null) {\n\t\t\t\tconnection.disconnect();\n\t\t\t}\n\t\t}\n\t}\n\n\tpublic static String computeSignature(String secretKey, String url, String reqData) {\n\n\t\tString data = url + reqData;\n\n\t\tSystem.out.println(data);\n\n\t\ttry {\n\t\t\tMac sha256Hmac = Mac.getInstance(\"HmacSHA256\");\n\t\t\tSecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), \"HmacSHA256\");\n\t\t\tsha256Hmac.init(key);\n\n\t\t\tbyte[] macData = sha256Hmac.doFinal(data.getBytes(\"UTF-8\"));\n\n\t\t\tString result = \"\";\n\t\t\tfor (final byte element : macData){\n\t\t\t\tresult += Integer.toString((element & 0xff) + 0x100, 16).substring(1);\n\t\t\t}\n\t\t\treturn result;\n\n\t\t} catch (Exception e) {\n\t\t\te.printStackTrace();\n\t\t\treturn \"\";\n\t\t}\n\t}\n}", "language": "java" }, { "code": "require 'uri'\nrequire 'net/http'\nrequire 'digest/hmac'\nrequire 'json'\n\nclass WyreApi\n # todo replace these with your real Wyre credentials\n ACCOUNT_ID = 'AC-XXXXXXX'\n API_KEY = 'AK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA'\n SEC_KEY = 'SK-AAAAAAAA-AAAAAAAA-AAAAAAAA-AAAAAAAA'\n API_URL = 'https://api.sendwyre.com'\n # API_URL = 'https://api.testwyre.com' # todo use this for Wyre's testing environment\n\n def create_transfer options\n api_post '/v2/transfers', options\n end\n\n private\n\n def api_post path, post_data = {}\n params = {\n 'timestamp' => (Time.now.to_i * 1000).to_s\n }\n\n url = API_URL + path + '?' + URI.encode_www_form(params)\n\n headers = {\n 'X-Api-Key' => API_KEY,\n 'X-Api-Signature' => calc_auth_sig_hash(url + post_data.to_json.to_s)\n }\n\n uri = URI API_URL\n Net::HTTP.start(uri.host, uri.port, :use_ssl => true) do |http|\n http.request_post(url, post_data.to_json.to_s, headers) do |res|\n response = JSON.parse res.body\n raise response['message'] if res.code != '200'\n return response\n end\n end\n end\n\n def calc_auth_sig_hash url_body\n return Digest::HMAC.hexdigest url_body, SEC_KEY, Digest::SHA256\n end\nend\n\napi = WyreApi.new\napi.create_transfer({'sourceAmount'=>50,'sourceCurrency'=>'USD','dest'=>'account:' + ACCOUNT_ID, 'destCurrency'=>'BTC', 'message'=>'buy some bitcoin')\n", "language": "ruby" } ] } [/block]