{"_id":"55909cb533090f0d004d25e7","user":"54ea9905a6f14f0d003e96e7","parentDoc":null,"project":"558b53f749dc4f0d00517de0","category":{"_id":"55909cb433090f0d004d25da","pages":["55909cb533090f0d004d25e6","55909cb533090f0d004d25e7","55909cb533090f0d004d25e8","55909cb533090f0d004d25e9","55909cb533090f0d004d25ea","56cb225319196e1300c81fd5"],"project":"558b53f749dc4f0d00517de0","__v":2,"version":"55909cb433090f0d004d25d8","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-06-29T00:53:32.514Z","from_sync":false,"order":1,"slug":"making-requests","title":"Making Requests"},"githubsync":"","version":{"_id":"55909cb433090f0d004d25d8","project":"558b53f749dc4f0d00517de0","forked_from":"558b53f749dc4f0d00517de3","__v":8,"createdAt":"2015-06-29T01:17:40.214Z","releaseDate":"2015-06-29T01:17:40.214Z","categories":["55909cb433090f0d004d25d9","55909cb433090f0d004d25da","55909cb433090f0d004d25db","55909cb433090f0d004d25dc","56c72c00197f9f1700c811db","56c72df5b3625c0d00422c9e","56e1b646150ed52d0062c652","56e9fe9779708c0e002b6026","57312dc94245100e001743f4","57646a570742400e00c04701","5894c96f4d9c7e27002e42ba"],"is_deprecated":false,"is_hidden":false,"is_beta":false,"is_stable":true,"codename":"","version_clean":"2.0.0","version":"2"},"__v":24,"updates":["559439800c33bd0d000595bd","5a568c3e36e2650032083bcf","5b259b0327f37b000337e1be"],"next":{"pages":[],"description":""},"createdAt":"2015-06-29T00:53:46.327Z","link_external":false,"link_url":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":1,"body":"We use a handful of security mechanisms to ensure that your requests are secure. You can find information on how to make a secure authenticated request below.\n\nIn order to make an authenticated request you'll need to pass a couple of values through the HTTP headers with your request:\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"X-Api-Key\",\n    \"1-0\": \"X-Api-Signature\",\n    \"h-0\": \"HTTP Header Field\",\n    \"h-1\": \"Description\",\n    \"0-1\": \"Your Wyre API key. Your key can be found at [https://dash.sendwyre.com/settings/api-keys](https://dash.sendwyre.com/settings/api-keys)\",\n    \"1-1\": \"A signature used to verify the request was sent by the account holder. See [Calculating the request signature](/v2/docs/authentication#calculating-the-request-signature).\"\n  },\n  \"cols\": 2,\n  \"rows\": 2\n}\n[/block]\nAdditionally, you should include a GET parameter named ```timestamp``` which is the current time in millisecond epoch format. We use this timestamp to help protect against replay attacks.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Calculating the request signature\"\n}\n[/block]\nCalculating the ```X-Api-Signature``` field is a two step process\n\n1.  Concatenate the request URL with the body of the HTTP request into a UTF-8 String. Use an empty string for the HTTP body in GET requests.\n1.  Compute the signature using HMAC with SHA-256 and your API Secret Key.\n\nIf you are sending a GET request you would sign the following:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"https://api.sendwyre.com/v2/rates?timestamp=1426252182534\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\nIf you are making a POST request you would sign the following:\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"https://api.sendwyre.com/v2/transfers?timestamp=1426252182534\",\n      \"language\": \"text\"\n    }\n  ]\n}\n[/block]\n**Note:** You must send the request body exactly as you sign it, whitespace and all. The server calculates the signature based on exactly what's in the request body.\n[block:api-header]\n{\n  \"type\": \"basic\",\n  \"title\": \"Examples\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:textarea]\n{\n  \"text\": \"Below are example implementations of authentication in a couple of different languages.\",\n  \"sidebar\": true\n}\n[/block]\n\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"<?php\\n    function make_authenticated_request($endpoint, $method, $body) {\\n        $url = 'https://api.sendwyre.com';\\n        $api_key = \\\"bh405n7stsuo5ut30iftrsl71b4iqjnv\\\";\\n        $secret_key = \\\"a19cvrchgja82urvn47kirrlrrb7stgg\\\";\\n\\n        $timestamp = floor(microtime(true)*1000);\\n        $request_url = $url . $endpoint;\\n\\n        if(strpos($request_url,\\\"?\\\"))\\n            $request_url .= '&timestamp=' . $timestamp;\\n        else\\n            $request_url .= '?timestamp=' . $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            \\\"X-Api-Version: 2\\\"\\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    echo make_authenticated_request(\\\"/account\\\", \\\"GET\\\", array());\\n\\t\\t$transfer = array(\\n      \\\"sourceCurrency\\\"=>\\\"USD\\\",\\n      \\\"dest\\\"=>\\\"sam:::at:::sendwyre.com\\\",\\n      \\\"destAmount\\\"=> 55.05,\\n      \\\"destCurrency\\\"=>\\\"EUR\\\",\\n      \\\"message\\\"=> \\\"buy sam pizza\\\"\\n      );\\n\\t\\techo make_authenticated_request(\\\"/transfers\\\", \\\"POST\\\", $transfer);\\n?>\",\n      \"language\": \"php\",\n      \"name\": \"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(\\\"/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(\\\"sourceAmount\\\", \\\"10\\\");\\n            body.Add(\\\"dest\\\", \\\"[email protected]\\\");\\n            HttpWebResponse transferResponse = wyre.Post(\\\"/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 apiKey = \\\"xxx\\\";\\n        private const String secKey = \\\"xxx\\\";\\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            request.Headers[\\\"X-Api-Version\\\"] = \\\"2\\\";\\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\": \"java\",\n      \"name\": \"C#\"\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\\t\\tString apiKey = \\\"PUT YOUR API KEY HERE\\\";\\n\\t\\tString secretKey = \\\"PUT YOUR SECRET KEY HERE\\\";\\n\\n\\t\\tString url = \\\"https://api.sendwyre.com/account\\\";\\n\\t\\tString method = \\\"GET\\\";\\n\\t\\tString data = \\\"\\\";\\n\\n\\t\\tString result = executeWyreRequest(url, \\\"\\\", method, apiKey, secretKey);\\n\\t\\tSystem.out.println(result);\\n\\n\\t\\turl = \\\"https://api.sendwyre.com/transfers\\\";\\n\\t\\tmethod = \\\"POST\\\";\\n\\t\\tdata = \\\"{\\\" +\\n\\t\\t\\t\\t\\\"  \\\\\\\"dest\\\\\\\": \\\\\\\"[email protected]\\\\\\\",\\\" +\\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(url, data, method, 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//Specify API v2\\n\\t\\t\\tconnection.setRequestProperty(\\\"X-Api-Version\\\",\\\"2\\\");\\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  ACCOUNT_ID = 'ue5hsnusf8gene87asdf4es23bt9d7ak'\\n  API_KEY = '9idihi38o18mrm1234ipa1k9ooiifgts'\\n  SEC_KEY = '5e3kcoogptge6s5fh2qwertyb6g368dm'\\n  API_URL = 'https://api.sendwyre.com'\\n\\n  def create_transfer options\\n    api_post '/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      'X-Api-Version' => '2'\\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'=>'[email protected]', 'destCurrency'=>'EUR', 'message'=>'buy sam pizza')\\n\",\n      \"language\": \"ruby\",\n      \"name\": \"Ruby\"\n    },\n    {\n      \"code\": \"#dependencies:\\n#python3\\n#pip3 install requests\\n\\nimport json\\nimport hmac\\nimport time\\nfrom requests import request\\n\\nclass MassPay_API(object):\\n    def __init__(self, account_id, api_version, api_key, api_secret):\\n        self.account_id = account_id\\n        self.api_url = 'https://api.sendwyre.com/{}'.format(api_version)\\n        self.api_version = api_version\\n        self.api_key = api_key\\n        self.api_secret = api_secret\\n\\n    #authentication decorator. May raise ValueError if no json content is returned\\n    def authenticate_request(func):\\n        def wrap(self, *args, **kwargs):\\n            url, method, body = func(self, *args, **kwargs)\\n            params = {}\\n            timestamp = int(time.time() * 1000)\\n            url += '?timestamp={}'.format(timestamp)\\n            bodyJson = json.dumps(body) if body != '' else ''\\n            headers = {}\\n            headers['Content-Type'] = 'application/json'\\n            headers['X-Api-Version'] = self.api_version\\n            headers['X-Api-Key'] = self.api_key\\n            headers['X-Api-Signature'] = hmac.new(self.api_secret.encode('utf-8'), (url + bodyJson).encode('utf-8'), 'SHA256').hexdigest()\\n            print(headers['X-Api-Signature'])\\n            resp = request(method=method, url=url, params=params, data=(json.dumps(body) if body != '' else None), json=None, headers=headers)\\n            if resp.text is not None: #Wyre will always try to give an err body\\n                return resp.status_code, resp.json()\\n            return 404, {}\\n        return wrap\\n\\n    @authenticate_request\\n    def retrieve_exchange_rates(self):\\n        url = self.api_url + '/rates'\\n        method = 'GET'\\n        body = ''\\n        return url, method, body\\n\\n    @authenticate_request\\n    def retrieve_account(self):\\n        url = self.api_url + '/account'\\n        method = 'GET'\\n        body = ''\\n        return url, method, body\\n\\n    @authenticate_request\\n    def create_transfer(self, sourceAmount, sourceCurrency, destAmount, destCurrency, destAddress, message, autoConfirm):\\n        url = self.api_url + '/transfers'\\n        method = 'POST'\\n        #ONLY use either sourceAmount or destAmount, see documentation\\n        body = {'sourceCurrency':sourceCurrency,\\n                'dest':destAddress,\\n                'destCurrency':destCurrency,\\n                'message':message}\\n        if sourceAmount:\\n            body[\\\"sourceAmount\\\"] = sourceAmount\\n        elif destAmount:\\n            body[\\\"destAmount\\\"] = destAmount\\n        if autoConfirm:\\n            body['autoConfirm'] = True\\n        return url, method, body \\n\\n    @authenticate_request\\n    def confirm_transfer(self, transfer_id):\\n        url = self.api_url + '/transfer/{}/confirm'.format(transfer_id)\\n        method = 'POST'\\n        body = ''\\n        return url, method, body  \\n\\n    @authenticate_request\\n    def status_transfer(self, transfer_id):\\n        url = self.api_url + '/transfer/{}'.format(transfer_id)\\n        method = 'GET'\\n        body = ''\\n        return url, method, body  \\n\\n#USAGE Example\\naccount_id = \\\"YOUR_ACCOUNT_ID_HERE\\\" #optional\\napi_key = \\\"YOUR_API_KEY_HERE\\\"\\nsecret_key = \\\"YOUR_SECRET_KEY_HERE\\\"\\napi_version = \\\"2\\\"\\n\\n#create Wyre API object\\nWyre = Pay_API(account_id, api_version, api_key, secret_key)\\n\\n#get account info\\nhttp_code, account = Wyre.retrieve_account()\\nprint(account)\\n\\n#get exchange rate info\\nhttp_code, rate_result = Wyre.retrieve_exchange_rates()\\nprint(rate_result)\\n\\n#BTC to CNY rate\\nbtc_cny = rate_result.get(\\\"BTCCNY\\\")\\n\\n#amount of source (withdrawal) BTC we want to sent to Euro\\namount = 50\\n\\n#calculate destination (deposit) amount in CNY\\nfinal_amount = amount * btc_cny\\n\\n#example bank transfer\\nbank_transfer =   {\\n                \\\"paymentMethodType\\\":\\\"INTERNATIONAL_TRANSFER\\\",\\n                \\\"country\\\": \\\"CN\\\",\\n                \\\"currency\\\": \\\"CNY\\\",\\n                \\\"nameOnAccount\\\": \\\"成龍\\\",\\n                \\\"accountNumber\\\": \\\"1234dinosaur\\\",\\n                \\\"bankName\\\": \\\"ζ‹›ε•†ι“Άθ‘Œ\\\",\\n                \\\"accountType\\\": \\\"金卑\\\",\\n                \\\"branchCode\\\": \\\"ε…‰εŽθ·―ζ”―θ‘Œ\\\",\\n                \\\"accountHolderEmail\\\": \\\"[email protected]\\\",\\n                \\\"accountHolderPhoneNumber\\\": \\\"+14102239203\\\",\\n                \\\"swift\\\": \\\"DEUTUS00000\\\",\\n                \\\"beneficiaryType\\\": \\\"INDIVIDUAL\\\",\\n                \\\"priority\\\":\\\"HIGH\\\"\\n                }\\n\\n#don't actually run this unless you really want to give Sam pizza\\nhttp_code, transfer_result = Wyre.create_transfer(\\n                                amount, \\n                                \\\"BTC\\\", \\n                                None, #final_amount\\n                                \\\"CNY\\\", \\n                                bank_transfer, #may also be an email or SRN\\n                                \\\"sending Wyre developers pizza money\\\",\\n\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\tFalse)\\nprint(transfer_result)\\n\\ntx_id = transfer_result['id']\\nhttp_code, status = Wyre.status_transfer('AWEvg0lZhq6qpXX')\\nprint(status)\",\n      \"language\": \"python\"\n    }\n  ],\n  \"sidebar\": true\n}\n[/block]","excerpt":"","slug":"authentication","type":"basic","title":"πŸ”  Authentication"}

πŸ” Authentication


We use a handful of security mechanisms to ensure that your requests are secure. You can find information on how to make a secure authenticated request below. In order to make an authenticated request you'll need to pass a couple of values through the HTTP headers with your request: [block:parameters] { "data": { "0-0": "X-Api-Key", "1-0": "X-Api-Signature", "h-0": "HTTP Header Field", "h-1": "Description", "0-1": "Your Wyre API key. Your key can be found at [https://dash.sendwyre.com/settings/api-keys](https://dash.sendwyre.com/settings/api-keys)", "1-1": "A signature used to verify the request was sent by the account holder. See [Calculating the request signature](/v2/docs/authentication#calculating-the-request-signature)." }, "cols": 2, "rows": 2 } [/block] Additionally, you should include a GET parameter named ```timestamp``` which is the current time in millisecond epoch format. We use this timestamp to help protect against replay attacks. [block:api-header] { "type": "basic", "title": "Calculating the request signature" } [/block] Calculating the ```X-Api-Signature``` field is a two step process 1. Concatenate the request URL with the body of the HTTP request into a UTF-8 String. Use an empty string for the HTTP body in GET requests. 1. Compute the signature using HMAC with SHA-256 and your API Secret Key. If you are sending a GET request you would sign the following: [block:code] { "codes": [ { "code": "https://api.sendwyre.com/v2/rates?timestamp=1426252182534", "language": "text" } ] } [/block] If you are making a POST request you would sign the following: [block:code] { "codes": [ { "code": "https://api.sendwyre.com/v2/transfers?timestamp=1426252182534", "language": "text" } ] } [/block] **Note:** You must send the request body exactly as you sign it, whitespace and all. The server calculates the signature based on exactly what's in the request body. [block:api-header] { "type": "basic", "title": "Examples", "sidebar": true } [/block] [block:textarea] { "text": "Below are example implementations of authentication in a couple of different languages.", "sidebar": true } [/block] [block:code] { "codes": [ { "code": "<?php\n function make_authenticated_request($endpoint, $method, $body) {\n $url = 'https://api.sendwyre.com';\n $api_key = \"bh405n7stsuo5ut30iftrsl71b4iqjnv\";\n $secret_key = \"a19cvrchgja82urvn47kirrlrrb7stgg\";\n\n $timestamp = floor(microtime(true)*1000);\n $request_url = $url . $endpoint;\n\n if(strpos($request_url,\"?\"))\n $request_url .= '&timestamp=' . $timestamp;\n else\n $request_url .= '?timestamp=' . $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 \"X-Api-Version: 2\"\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 echo make_authenticated_request(\"/account\", \"GET\", array());\n\t\t$transfer = array(\n \"sourceCurrency\"=>\"USD\",\n \"dest\"=>\"[email protected]\",\n \"destAmount\"=> 55.05,\n \"destCurrency\"=>\"EUR\",\n \"message\"=> \"buy sam pizza\"\n );\n\t\techo make_authenticated_request(\"/transfers\", \"POST\", $transfer);\n?>", "language": "php", "name": "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(\"/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(\"sourceAmount\", \"10\");\n body.Add(\"dest\", \"[email protected]\");\n HttpWebResponse transferResponse = wyre.Post(\"/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 apiKey = \"xxx\";\n private const String secKey = \"xxx\";\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 request.Headers[\"X-Api-Version\"] = \"2\";\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": "java", "name": "C#" }, { "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\t\tString apiKey = \"PUT YOUR API KEY HERE\";\n\t\tString secretKey = \"PUT YOUR SECRET KEY HERE\";\n\n\t\tString url = \"https://api.sendwyre.com/account\";\n\t\tString method = \"GET\";\n\t\tString data = \"\";\n\n\t\tString result = executeWyreRequest(url, \"\", method, apiKey, secretKey);\n\t\tSystem.out.println(result);\n\n\t\turl = \"https://api.sendwyre.com/transfers\";\n\t\tmethod = \"POST\";\n\t\tdata = \"{\" +\n\t\t\t\t\" \\\"dest\\\": \\\"[email protected]\\\",\" +\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(url, data, method, 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//Specify API v2\n\t\t\tconnection.setRequestProperty(\"X-Api-Version\",\"2\");\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 ACCOUNT_ID = 'ue5hsnusf8gene87asdf4es23bt9d7ak'\n API_KEY = '9idihi38o18mrm1234ipa1k9ooiifgts'\n SEC_KEY = '5e3kcoogptge6s5fh2qwertyb6g368dm'\n API_URL = 'https://api.sendwyre.com'\n\n def create_transfer options\n api_post '/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 'X-Api-Version' => '2'\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'=>'[email protected]', 'destCurrency'=>'EUR', 'message'=>'buy sam pizza')\n", "language": "ruby", "name": "Ruby" }, { "code": "#dependencies:\n#python3\n#pip3 install requests\n\nimport json\nimport hmac\nimport time\nfrom requests import request\n\nclass MassPay_API(object):\n def __init__(self, account_id, api_version, api_key, api_secret):\n self.account_id = account_id\n self.api_url = 'https://api.sendwyre.com/{}'.format(api_version)\n self.api_version = api_version\n self.api_key = api_key\n self.api_secret = api_secret\n\n #authentication decorator. May raise ValueError if no json content is returned\n def authenticate_request(func):\n def wrap(self, *args, **kwargs):\n url, method, body = func(self, *args, **kwargs)\n params = {}\n timestamp = int(time.time() * 1000)\n url += '?timestamp={}'.format(timestamp)\n bodyJson = json.dumps(body) if body != '' else ''\n headers = {}\n headers['Content-Type'] = 'application/json'\n headers['X-Api-Version'] = self.api_version\n headers['X-Api-Key'] = self.api_key\n headers['X-Api-Signature'] = hmac.new(self.api_secret.encode('utf-8'), (url + bodyJson).encode('utf-8'), 'SHA256').hexdigest()\n print(headers['X-Api-Signature'])\n resp = request(method=method, url=url, params=params, data=(json.dumps(body) if body != '' else None), json=None, headers=headers)\n if resp.text is not None: #Wyre will always try to give an err body\n return resp.status_code, resp.json()\n return 404, {}\n return wrap\n\n @authenticate_request\n def retrieve_exchange_rates(self):\n url = self.api_url + '/rates'\n method = 'GET'\n body = ''\n return url, method, body\n\n @authenticate_request\n def retrieve_account(self):\n url = self.api_url + '/account'\n method = 'GET'\n body = ''\n return url, method, body\n\n @authenticate_request\n def create_transfer(self, sourceAmount, sourceCurrency, destAmount, destCurrency, destAddress, message, autoConfirm):\n url = self.api_url + '/transfers'\n method = 'POST'\n #ONLY use either sourceAmount or destAmount, see documentation\n body = {'sourceCurrency':sourceCurrency,\n 'dest':destAddress,\n 'destCurrency':destCurrency,\n 'message':message}\n if sourceAmount:\n body[\"sourceAmount\"] = sourceAmount\n elif destAmount:\n body[\"destAmount\"] = destAmount\n if autoConfirm:\n body['autoConfirm'] = True\n return url, method, body \n\n @authenticate_request\n def confirm_transfer(self, transfer_id):\n url = self.api_url + '/transfer/{}/confirm'.format(transfer_id)\n method = 'POST'\n body = ''\n return url, method, body \n\n @authenticate_request\n def status_transfer(self, transfer_id):\n url = self.api_url + '/transfer/{}'.format(transfer_id)\n method = 'GET'\n body = ''\n return url, method, body \n\n#USAGE Example\naccount_id = \"YOUR_ACCOUNT_ID_HERE\" #optional\napi_key = \"YOUR_API_KEY_HERE\"\nsecret_key = \"YOUR_SECRET_KEY_HERE\"\napi_version = \"2\"\n\n#create Wyre API object\nWyre = Pay_API(account_id, api_version, api_key, secret_key)\n\n#get account info\nhttp_code, account = Wyre.retrieve_account()\nprint(account)\n\n#get exchange rate info\nhttp_code, rate_result = Wyre.retrieve_exchange_rates()\nprint(rate_result)\n\n#BTC to CNY rate\nbtc_cny = rate_result.get(\"BTCCNY\")\n\n#amount of source (withdrawal) BTC we want to sent to Euro\namount = 50\n\n#calculate destination (deposit) amount in CNY\nfinal_amount = amount * btc_cny\n\n#example bank transfer\nbank_transfer = {\n \"paymentMethodType\":\"INTERNATIONAL_TRANSFER\",\n \"country\": \"CN\",\n \"currency\": \"CNY\",\n \"nameOnAccount\": \"成龍\",\n \"accountNumber\": \"1234dinosaur\",\n \"bankName\": \"ζ‹›ε•†ι“Άθ‘Œ\",\n \"accountType\": \"金卑\",\n \"branchCode\": \"ε…‰εŽθ·―ζ”―θ‘Œ\",\n \"accountHolderEmail\": \"[email protected]\",\n \"accountHolderPhoneNumber\": \"+14102239203\",\n \"swift\": \"DEUTUS00000\",\n \"beneficiaryType\": \"INDIVIDUAL\",\n \"priority\":\"HIGH\"\n }\n\n#don't actually run this unless you really want to give Sam pizza\nhttp_code, transfer_result = Wyre.create_transfer(\n amount, \n \"BTC\", \n None, #final_amount\n \"CNY\", \n bank_transfer, #may also be an email or SRN\n \"sending Wyre developers pizza money\",\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\tFalse)\nprint(transfer_result)\n\ntx_id = transfer_result['id']\nhttp_code, status = Wyre.status_transfer('AWEvg0lZhq6qpXX')\nprint(status)", "language": "python" } ], "sidebar": true } [/block]