{"_id":"576878f9788e1b2400b29baf","__v":22,"category":{"_id":"55909cb433090f0d004d25d9","__v":4,"pages":["55909cb533090f0d004d25de","55909cb533090f0d004d25df","55909cb533090f0d004d25e0","55936ccc47f40b170036087f","55936d259755e117000fbdf5","559372059755e117000fbe08"],"project":"558b53f749dc4f0d00517de0","version":"55909cb433090f0d004d25d8","sync":{"url":"","isSync":false},"reference":false,"createdAt":"2015-06-25T01:06:00.994Z","from_sync":false,"order":0,"slug":"getting-started","title":"Getting Started"},"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"},"project":"558b53f749dc4f0d00517de0","user":"56cdfe00e538330b0021ab76","parentDoc":null,"updates":[],"next":{"pages":[],"description":""},"createdAt":"2016-06-20T23:15:05.273Z","link_external":false,"link_url":"","sync_unique":"","hidden":false,"api":{"results":{"codes":[]},"settings":"","auth":"required","params":[],"url":""},"isReference":false,"order":3,"body":"通过本教程可以快速上手Wyre MassPay API. \n**什么是MassPay?\n**\n客户可以使用MassPay在不同货币间转账。如果您有跨国转账汇款的需求,MassPay是您的首选。\n\n**目录:\n**\n1. [开设Wyre账户](https://docs.sendwyre.com/docs/tutorial-cn#开设Wyre账户)\n2. [发送API请求](https://docs.sendwyre.com/docs/tutorial-cn#发送API请求)\n3. [创建第一笔转账请求](https://docs.sendwyre.com/docs/tutorial-cn#创建第一笔转账请求)\n4. [转账示例](https://docs.sendwyre.com/docs/tutorial-cn#转账示例)\n5. [代码示例](https://docs.sendwyre.com/docs/tutorial-cn#代码示例)\n6. [相关链接和联系方式](https://docs.sendwyre.com/docs/tutorial-cn#相关链接和联系方式)\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"1. 开设Wyre账户\"\n}\n[/block]\n首先,如果您没有账户,需要[创建一个账户](https://dash.sendwyre.com/register)。这个过程中需要核对email和手机号。\n开始转账前您需要有以下的信息:\n- API Key\n- SECRET Key\n- ACCOUNT ID\n\n这些信息可以在登陆后的[Your Account | API Keys](https://dash.sendwyre.com/settings/api-keys)里找到。\n当生成一个API key后,页面显示如下图。\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/hn3gjUiiRDGMUqQbYGQq_KeysExample.png\",\n        \"KeysExample.png\",\n        \"494\",\n        \"363\",\n        \"#7cb36b\",\n        \"\"\n      ],\n      \"border\": false,\n      \"caption\": \"\"\n    }\n  ]\n}\n[/block]\n最后还需要AccountID。可以从key的details链接里找到。\n[block:image]\n{\n  \"images\": [\n    {\n      \"image\": [\n        \"https://files.readme.io/NhLfZz3qRW9XyJXK652k_KeysExample2.png\",\n        \"KeysExample2.png\",\n        \"667\",\n        \"308\",\n        \"#87a4b9\",\n        \"\"\n      ]\n    }\n  ]\n}\n[/block]\n**注意**\n请不要包含\"account:\"字符串。\n**例如:account:pm9ddj8jr8rrq53fsk9v4bfhunieu72t**应为**pm9ddj8jr8rrq53fsk9v4bfhunieu72t**。\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"2. 发送API请求\"\n}\n[/block]\nWyre API文档链接为https://api.sendwyre.com/v2/。返回格式为JSON。 \nWyre利用如下的HTTP头字段作为安全措施。\n[block:parameters]\n{\n  \"data\": {\n    \"0-0\": \"X-Api-Key\",\n    \"1-0\": \"X-Api-Signature\",\n    \"h-0\": \"头字段\",\n    \"h-1\": \"描述\",\n    \"0-1\": \"您的Wyre API key\",\n    \"1-1\": \"用secret key计算得到的[密钥散列消息认证码](https://zh.wikipedia.org/wiki/%E9%87%91%E9%91%B0%E9%9B%9C%E6%B9%8A%E8%A8%8A%E6%81%AF%E9%91%91%E5%88%A5%E7%A2%BC)\"\n  },\n  \"cols\": 2,\n  \"rows\": 2\n}\n[/block]\n计算您的密钥散列消息认证码的步骤如下(代码示例在页底):\n1. 在请求URL后加上毫秒时间戳。例如为了得到账户细节,请求URL为[https://api.sendwyre.com/v2/account?timestamp=1426252182534](https://api.sendwyre.com/v2/account?timestamp=1426252182534)。\n2. 将请求的URL和HTTP请求内容合并成一个UTF-8字符串。GET请求内容为一个空字符串。 \n3. 用SHA-256和您的API Secret Key计算签名。\n以下是Wyre MassPay API节点。点击名称链接进入相应文档。\n[block:parameters]\n{\n  \"data\": {\n    \"h-0\": \"名称\",\n    \"h-1\": \"API节点\",\n    \"h-2\": \"HTTP方法\",\n    \"1-0\": \"[实时价格](https://docs.sendwyre.com/docs/checking-live-exchange-rates)\",\n    \"2-0\": \"[创建转账](https://docs.sendwyre.com/docs/creating-a-transfer-and-getting-a-quote)\",\n    \"3-0\": \"[转账确认](https://docs.sendwyre.com/docs/confirming-a-quote)\",\n    \"h-3\": \"描述\",\n    \"0-1\": \"[https://api.sendwyre.com/v2/account](https://api.sendwyre.com/v2/account)\",\n    \"1-1\": \"[https://api.sendwyre.com/v2/rates](https://api.sendwyre.com/v2/rates)\",\n    \"2-1\": \"[https://api.sendwyre.com/v2/transfers](https://api.sendwyre.com/v2/transfers)\",\n    \"0-0\": \"[账户详情](https://docs.sendwyre.com/docs/getting-your-account-and-checking-balances)\",\n    \"4-0\": \"[转账状态](https://docs.sendwyre.com/docs/getting-transfer-status-updates)\",\n    \"0-2\": \"GET\",\n    \"1-2\": \"GET\",\n    \"2-2\": \"POST\",\n    \"3-2\": \"POST\",\n    \"4-2\": \"GET\",\n    \"3-1\": \"[https://api.sendwyre.com/v2/transfer/:transferId/confirm](https://api.sendwyre.com/v2/:transferId/confirm)\",\n    \"4-1\": \"[https://api.sendwyre.com/v2/transfer/:transferId](https://api.sendwyre.com/v2/:transferId)\",\n    \"0-3\": \"账户详情包括联系方式,所有货币的结余,相关授权和支付方式。\",\n    \"1-3\": \"不同交易所的比特币价格。\",\n    \"2-3\": \"创建两种货币间的转账。目的地可以是email地址,比特币钱包地址或者银行账户。可以开启自动确认功能,但并不推荐。\",\n    \"3-3\": \"转账只会在您确认所有细节之后的30秒内执行。\",\n    \"4-3\": \"如果您不想用callbackUrl,您可以通过本API获得订单状态。不同订单状态种类在[这里](http://masspay.snapcard.io/docs/transfer-statuses)。\"\n  },\n  \"cols\": 4,\n  \"rows\": 5\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"创建第一个转账请求\"\n}\n[/block]\n一个转账请求是一个包含最多7个字段的JSON POST请求。\n\n- `sourceAmount` - 只需要选择 `sourceAmount` 或者 `destAmount`中一个。`sourceAmount`是从主账户中扣除的用来转账的金额。这种情况下您可以指定从账户中扣除的金额,入账金额将由交易费用和汇率确定。\n- `sourceCurrency` - 转出货币代码[ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Current_codes)\n- `dest` - 转账地址。可以是email地址,电话号码,blockchain地址,或银行账户。\n- `destAmount` - 只需要选择 `sourceAmount` 或者 `destAmount`中一个。`destAmount`是将被转入目标地址的金额。`sourceAmount`可以由`destAmount`,交易费用和汇率计算出。\n- `destCurrency` - 转入货币代码。可以和转出货币代码不同。如果不同则汇率会被自动计算。\n- `callbackUrl` - 可选,Wyre返回转账状态的Url。\n- `autoConfirm` - 可选,默认自动确认转账的参数。不推荐。\n\n以下例子将巴西雷亚尔转换为美元并发送到我们工程师的银行账户。\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"dest\\\": {\\n    \\\"paymentMethodType\\\":\\\"INTERNATIONAL_TRANSFER\\\",\\n    \\\"country\\\": \\\"US\\\",\\n    \\\"currency\\\": \\\"USD\\\",\\n    \\\"firstNameOnAccount\\\": \\\"Sam\\\",\\n    \\\"lastNameOnAccount\\\":\\\"Schlachter\\\",\\n    \\\"accountNumber\\\": \\\"1234dinosaur\\\",\\n    \\\"routingNumber\\\": \\\"0000000000\\\",\\n    \\\"accountType\\\": \\\"savings\\\",\\n    \\\"bankName\\\": \\\"Bank of 'murrrica\\\",\\n    \\\"bankStreet\\\": \\\"112 Brannan St\\\",\\n    \\\"bankCity\\\": \\\"San Francisco\\\",\\n    \\\"bankPostal\\\": \\\"94108\\\",\\n    \\\"accountHolderPhoneNumber\\\": \\\"+14102239203\\\",\\n    \\\"beneficiaryType\\\": \\\"INDIVIDUAL\\\",\\n    \\\"priority\\\":\\\"HIGH\\\"\\n  },\\n  \\\"sourceCurrency\\\": \\\"BRL\\\",\\n  \\\"destCurrency\\\": \\\"USD\\\",\\n  \\\"destAmount\\\": 10,\\n  \\\"message\\\":\\\"Here's your $10!\\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n返回值类似。最重要的返回值是`id`字段。我们用这个值确认转账并获取转账状态。\n\n如果转账金额和汇率满足我们的要求,我们需要点击[转账确认](或者用自动确认功能)来确认转账。\n\n最后一步是从[转账状态](https://docs.sendwyre.com/docs/getting-transfer-status-updates)获取转账的状态--`完成`,`过期`,或者`失败`。或者你可以在`callbackUrl`字段填入一个URL。Wyre会将包含订单状态的HTTP POST请求发送到该URL。\n\n以下是包含银行账户的转账示例。\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"转账示例\"\n}\n[/block]\n**美国 USA 🇺🇸 → 🇧🇷 巴西 BRAZIL**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"dest\\\": {\\n    \\\"paymentMethodType\\\":\\\"INTERNATIONAL_TRANSFER\\\",\\n    \\\"country\\\": \\\"BR\\\",\\n    \\\"currency\\\": \\\"BRL\\\",\\n    \\\"firstNameOnAccount\\\": \\\"Robert\\\",\\n    \\\"lastNameOnAccount\\\": \\\"Baratheon\\\",\\n    \\\"accountNumber\\\": \\\"1234dinosaur\\\",\\n    \\\"bankName\\\": \\\"Mordor Credit Union\\\",\\n    \\\"cpfCnpj\\\": \\\"943759353\\\",\\n    \\\"accountType\\\": \\\"poupanca\\\",\\n    \\\"branchCode\\\": \\\"Artichoke\\\",\\n    \\\"accountHolderEmail\\\": \\\"banana:::at:::phone.com\\\",\\n    \\\"accountHolderPhoneNumber\\\": \\\"+14102239203\\\",\\n    \\\"swift\\\": \\\"DEUTUS00000\\\",\\n    \\\"beneficiaryType\\\": \\\"INDIVIDUAL\\\",\\n    \\\"priority\\\":\\\"HIGH\\\"\\n  },\\n  \\\"sourceCurrency\\\": \\\"USD\\\",\\n  \\\"destCurrency\\\": \\\"BRL\\\",\\n  \\\"destAmount\\\": 10,\\n  \\\"message\\\":\\\"A Lannister always pays his debts \\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n**巴西 BRAZIL 🇧🇷 → 🇺🇸 美国 USA**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"dest\\\": {\\n    \\\"paymentMethodType\\\":\\\"INTERNATIONAL_TRANSFER\\\",\\n    \\\"country\\\": \\\"US\\\",\\n    \\\"currency\\\": \\\"USD\\\",\\n    \\\"beneficiaryType\\\": \\\"INDIVIDUAL\\\",\\n    \\\"beneficiaryAddress\\\": \\\"112 Brannan St\\\",\\n    \\\"beneficiaryAddress2\\\": \\\"\\\", //Optional\\n    \\\"beneficiaryCity\\\": \\\"San Francisco\\\",\\n    \\\"beneficiaryState\\\": \\\"CA\\\",\\n    \\\"beneficiaryPostal\\\": \\\"94108\\\",\\n    \\\"beneficiaryPhoneNumber\\\": \\\"+14102239203\\\",\\n    \\\"beneficiaryDobDay\\\": \\\"15\\\",\\n    \\\"beneficiaryDobMonth\\\":\\\"12\\\",\\n    \\\"beneficiaryDobYear\\\":\\\"1989\\\",\\n    \\\"paymentType\\\" : \\\"LOCAL_BANK_WIRE\\\", // LOCAL_BANK_WIRE or ACH\\n    \\\"firstNameOnAccount\\\": \\\"Billy-Bob\\\",\\n    \\\"lastNameOnAccount\\\":\\\"Jones\\\",\\n    \\\"accountNumber\\\": \\\"0000000000000\\\",\\n    \\\"routingNumber\\\": \\\"0000000000\\\",\\n    \\\"accountType\\\": \\\"CHECKING\\\", //CHECKING or SAVINGS\\n    \\\"bankName\\\": \\\"Bank of America\\\"\\n  },\\n  \\\"sourceCurrency\\\": \\\"BRL\\\",\\n  \\\"destCurrency\\\": \\\"USD\\\",\\n  \\\"destAmount\\\": 10,\\n  \\\"message\\\":\\\"USD Personal example\\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n**美国 USA 🇺🇸 → 🇨🇳 中国 CHINA**\n[block:code]\n{\n  \"codes\": [\n    {\n      \"code\": \"{\\n  \\\"dest\\\": {\\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  \\\"sourceCurrency\\\": \\\"USD\\\",\\n  \\\"destCurrency\\\": \\\"CNY\\\",\\n  \\\"destAmount\\\": 10,\\n  \\\"message\\\":\\\"\\\"\\n}\",\n      \"language\": \"json\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"代码示例\"\n}\n[/block]\n你可以把自己的API Key,API Secret Key和Account ID放入以下脚本中,调整转账参数,即刻开始用MassPay转账!\n[block:code]\n{\n  \"codes\": [\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, destination, 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':destination, #email, wallet, or bank transfer dict\\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 MassPay API object\\nwyre = MassPay_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 dictionary that we will pass in as the destination\\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#send transfer and print result\\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                                False)\\nprint(transfer_result)\\ntx_id = transfer_result['id'] #grab our transfer id\\n\\n#confirm transfer\\nhttp_code, confirmation = wyre.confirm_transfer(tx_id)\\nprint(confirmation)\\n\\n#check status\\nhttp_code, status = wyre.status_transfer(tx_id)\\nprint(status)\",\n      \"language\": \"python\"\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      \"language\": \"ruby\"\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 Main {\\n  public static void main(String[] args) {\\n    String apiKey = \\\"fll36l3t35udalcqlh4ng6bm4qpbgher\\\";\\n    String secretKey = \\\"tr3epinbk3maist0n3ijk18bm6dikrq6\\\";\\n\\n    //retrieve account details and balance\\n    String url = \\\"https://api.sendwyre.com/account\\\";\\n    String method = \\\"GET\\\";\\n    String data = \\\"\\\";\\n\\n    String result = executewyreRequest(url, \\\"\\\", method, apiKey, secretKey);\\n    System.out.println(result);\\n\\n    //example transfer\\n    url = \\\"https://api.sendwyre.com/transfers\\\";\\n    method = \\\"POST\\\";\\n    data = \\\"{\\\" +\\n        \\\"  \\\\\\\"dest\\\\\\\": \\\\\\\"[email protected]\\\\\\\",\\\" +\\n        \\\"  \\\\\\\"destCurrency\\\\\\\": \\\\\\\"BTC\\\\\\\",\\\" +\\n        \\\"  \\\\\\\"sourceCurrency\\\\\\\" : \\\\\\\"USD\\\\\\\",\\\" +\\n        \\\"  \\\\\\\"sourceAmount\\\\\\\" : \\\\\\\"50\\\\\\\",\\\" +\\n        \\\"  \\\\\\\"message\\\\\\\": \\\\\\\"$50 worth of bitcoin! Food please!\\\\\\\"\\\" +\\n        \\\"}\\\";\\n    result = excutewyreRequest(url, data, method, apiKey, secretKey);\\n\\n    System.out.println(result);\\n  }\\n\\n  public static String excutewyreRequest(String targetURL, String requestBody, String method, String apiKey, String secretKey) {\\n    URL url;\\n    HttpURLConnection connection = null;\\n    try {\\n\\n      targetURL += ((targetURL.indexOf(\\\"?\\\")>0)?\\\"&\\\":\\\"?\\\") + \\\"timestamp=\\\" + System.currentTimeMillis();\\n\\n      //Create connection\\n      url = new URL(targetURL);\\n      connection = (HttpURLConnection)url.openConnection();\\n      connection.setRequestMethod(method);\\n      System.out.println(connection.getRequestMethod());\\n\\n      connection.setRequestProperty(\\\"Content-Type\\\", \\\"application/json\\\");\\n      connection.setRequestProperty(\\\"Content-Length\\\", Integer.toString(requestBody.getBytes().length));\\n\\n      //Specify API v2\\n      connection.setRequestProperty(\\\"X-Api-Version\\\",\\\"2\\\");\\n\\n      // Provide API key and signature\\n      connection.setRequestProperty(\\\"X-Api-Key\\\", apiKey);\\n      connection.setRequestProperty(\\\"X-Api-Signature\\\",computeSignature(secretKey,targetURL,requestBody));\\n\\n      //Send request\\n      if(method.equals(\\\"POST\\\")) {\\n        connection.setDoOutput(true);\\n        connection.setRequestMethod(method);\\n\\n        DataOutputStream wr = new DataOutputStream(\\n            connection.getOutputStream());\\n\\n        wr.writeBytes(requestBody);\\n        wr.flush();\\n        wr.close();\\n      }\\n\\n      //Get Response\\n      InputStream is = null;\\n      if (connection.getResponseCode() >= 400) {\\n        is = connection.getErrorStream();\\n      }  \\n      else {\\n        is = connection.getInputStream();\\n      }\\n      BufferedReader rd = new BufferedReader(new InputStreamReader(is));\\n      String line;\\n      StringBuffer response = new StringBuffer();\\n      while((line = rd.readLine()) != null) {\\n        response.append(line);\\n        response.append('\\\\r');\\n      }\\n      rd.close();\\n      return response.toString();\\n\\n    } catch (Exception e) {\\n\\n      e.printStackTrace();\\n      return null;\\n\\n    } finally {\\n\\n      if(connection != null) {\\n        connection.disconnect();\\n      }\\n    }\\n  }\\n\\n  public static String computeSignature(String secretKey, String url, String reqData) {\\n\\n    String data = url + reqData;\\n\\n    System.out.println(data);\\n\\n    try {\\n      Mac sha256Hmac = Mac.getInstance(\\\"HmacSHA256\\\");\\n      SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), \\\"HmacSHA256\\\");\\n      sha256Hmac.init(key);\\n\\n      byte[] macData = sha256Hmac.doFinal(data.getBytes());\\n\\n      String result = \\\"\\\";\\n      for (final byte element : macData){\\n        result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);\\n      }\\n      return result;\\n\\n    } catch (Exception e) {\\n      e.printStackTrace();\\n      return \\\"\\\";\\n    }\\n  }\\n}\",\n      \"language\": \"java\"\n    },\n    {\n      \"code\": \"using System;\\nusing System.IO;\\nusing System.Net;\\nusing System.Security.Cryptography;\\nusing System.Text;\\n\\nnamespace test\\n{\\n  class MainClass\\n  {\\n    public static void Main(string[] args)\\n    {\\n      wyreApi wyreApi = new wyreApi();\\n\\n      string balance = wyreApi.getAccount();\\n      Console.WriteLine(balance);\\n\\n      string transferData = \\\"{\\\" +\\n        \\\"\\\\\\\"sourceCurrency\\\\\\\": \\\\\\\"USD\\\\\\\",\\\" +\\n        \\\"\\\\\\\"dest\\\\\\\": \\\\\\\"[email protected]\\\\\\\",\\\" +\\n        \\\"\\\\\\\"sourceAmount\\\\\\\": \\\\\\\"0.01\\\\\\\",\\\" +\\n        \\\"\\\\\\\"destCurrency\\\\\\\": \\\\\\\"BTC\\\\\\\"\\\" +\\n        \\\"}\\\";\\n      string authResponse = wyreApi.transfer(transferData);\\n      Console.WriteLine(authResponse);\\n    }\\n  }\\n\\n  public class wyreApi {\\n    private const string domain = \\\"https://api.sendwyre.com\\\";\\n    private const string apiKey = \\\"xxxxxx\\\";\\n    private const string secKey = \\\"xxxxxx\\\";\\n\\n    public string getAccount() \\n    {\\n      return MakeGetReq(\\\"/account\\\");\\n    }\\n\\n    public string transfer(string jsonString)\\n    {\\n      return MakePostReq(\\\"/transfers\\\", jsonString);\\n    }\\n\\n    private string MakeGetReq(string apiRoute)\\n    {\\n      WebRequest req = AssembleWebRequest(apiRoute);\\n      req.Method = \\\"GET\\\";\\n      WebResponse response = req.GetResponse();\\n      string responseString = ParseWebResponse(response);\\n      return responseString;\\n    }\\n\\n    private string MakePostReq(string apiRoute, string jsonData)\\n    {\\n      WebRequest req = AssembleWebRequest(apiRoute, jsonData);\\n      req.Method = \\\"POST\\\";\\n      WriteJsonToRequest(req, jsonData);\\n\\n\\n      WebResponse response = req.GetResponse();\\n      string responseString = ParseWebResponse(response);\\n      return responseString;\\n    }\\n\\n    private WebRequest AssembleWebRequest(string apiRoute, string jsonData = \\\"\\\")\\n    {\\n      string url = domain + apiRoute + (apiRoute.Contains(\\\"?\\\")?\\\"&\\\":\\\"?\\\") + \\\"timestamp=\\\"+DateTime.Now.Ticks; \\n      WebRequest request = WebRequest.Create(url);\\n      string authSig = CalcAuthSigHash(secKey, url + jsonData);\\n\\n      request.ContentType = \\\"application/json\\\";\\n      request.Headers[\\\"X-Api-Key\\\"] = apiKey;\\n      request.Headers[\\\"X-Api-Signature\\\"] = authSig;\\n      request.Headers[\\\"X-Api-Version\\\"] = \\\"2\\\";\\n      return request;\\n    }\\n\\n    private void WriteJsonToRequest(WebRequest req, string jsonData)\\n    {\\n      var streamWriter = new StreamWriter(req.GetRequestStream ());\\n      streamWriter.Write(jsonData);\\n      streamWriter.Close();\\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)));\\n      hash = hash.Replace(\\\"-\\\", \\\"\\\");\\n      return hash;\\n    }\\n\\n    private string ParseWebResponse(WebResponse response)\\n    {\\n      StreamReader streamReader = new StreamReader(response.GetResponseStream());\\n      string result = streamReader.ReadToEnd();\\n      streamReader.Close();\\n      return result;\\n    }\\n  }\\n}\",\n      \"language\": \"csharp\"\n    },\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    $transfer = array(\\n      \\\"sourceCurrency\\\"=>\\\"USD\\\",\\n      \\\"dest\\\"=>\\\"[email protected]\\\",\\n      \\\"destAmount\\\"=> 55.05,\\n      \\\"destCurrency\\\"=>\\\"EUR\\\",\\n      \\\"message\\\"=> \\\"buy sam pizza\\\"\\n      );\\n    echo make_authenticated_request(\\\"/transfers\\\", \\\"POST\\\", $transfer);\\n?>\",\n      \"language\": \"php\"\n    }\n  ]\n}\n[/block]\n\n[block:api-header]\n{\n  \"type\": \"link\",\n  \"title\": \"相关链接和联系方式\"\n}\n[/block]\n## **链接**\n\n[Wyre主页](https://www.sendwyre.com)\n\n[Wyre注册页](https://www.sendwyre.com/wallet/sign-up)\n\n[MassPay开发者中心](http://masspay.sendwyre.com/)\n\n## **参考**\n\n[区块链技术介绍](https://bitcoin.org/en/how-it-works)\n\n[公司信息](https://angel.co/sendwyre)\n\n## **联系方式**\n\n*[email protected]*\n*415-374-7356*\n1550 Bryant St, Ste 750\nSan Francisco, CA 94107\n\n或者\n\n*使用我们主页右下角的在线聊天*","excerpt":"","slug":"tutorial-cn","type":"basic","title":"教程 🇨🇳"}
通过本教程可以快速上手Wyre MassPay API. **什么是MassPay? ** 客户可以使用MassPay在不同货币间转账。如果您有跨国转账汇款的需求,MassPay是您的首选。 **目录: ** 1. [开设Wyre账户](https://docs.sendwyre.com/docs/tutorial-cn#开设Wyre账户) 2. [发送API请求](https://docs.sendwyre.com/docs/tutorial-cn#发送API请求) 3. [创建第一笔转账请求](https://docs.sendwyre.com/docs/tutorial-cn#创建第一笔转账请求) 4. [转账示例](https://docs.sendwyre.com/docs/tutorial-cn#转账示例) 5. [代码示例](https://docs.sendwyre.com/docs/tutorial-cn#代码示例) 6. [相关链接和联系方式](https://docs.sendwyre.com/docs/tutorial-cn#相关链接和联系方式) [block:api-header] { "type": "link", "title": "1. 开设Wyre账户" } [/block] 首先,如果您没有账户,需要[创建一个账户](https://dash.sendwyre.com/register)。这个过程中需要核对email和手机号。 开始转账前您需要有以下的信息: - API Key - SECRET Key - ACCOUNT ID 这些信息可以在登陆后的[Your Account | API Keys](https://dash.sendwyre.com/settings/api-keys)里找到。 当生成一个API key后,页面显示如下图。 [block:image] { "images": [ { "image": [ "https://files.readme.io/hn3gjUiiRDGMUqQbYGQq_KeysExample.png", "KeysExample.png", "494", "363", "#7cb36b", "" ], "border": false, "caption": "" } ] } [/block] 最后还需要AccountID。可以从key的details链接里找到。 [block:image] { "images": [ { "image": [ "https://files.readme.io/NhLfZz3qRW9XyJXK652k_KeysExample2.png", "KeysExample2.png", "667", "308", "#87a4b9", "" ] } ] } [/block] **注意** 请不要包含"account:"字符串。 **例如:account:pm9ddj8jr8rrq53fsk9v4bfhunieu72t**应为**pm9ddj8jr8rrq53fsk9v4bfhunieu72t**。 [block:api-header] { "type": "link", "title": "2. 发送API请求" } [/block] Wyre API文档链接为https://api.sendwyre.com/v2/。返回格式为JSON。 Wyre利用如下的HTTP头字段作为安全措施。 [block:parameters] { "data": { "0-0": "X-Api-Key", "1-0": "X-Api-Signature", "h-0": "头字段", "h-1": "描述", "0-1": "您的Wyre API key", "1-1": "用secret key计算得到的[密钥散列消息认证码](https://zh.wikipedia.org/wiki/%E9%87%91%E9%91%B0%E9%9B%9C%E6%B9%8A%E8%A8%8A%E6%81%AF%E9%91%91%E5%88%A5%E7%A2%BC)" }, "cols": 2, "rows": 2 } [/block] 计算您的密钥散列消息认证码的步骤如下(代码示例在页底): 1. 在请求URL后加上毫秒时间戳。例如为了得到账户细节,请求URL为[https://api.sendwyre.com/v2/account?timestamp=1426252182534](https://api.sendwyre.com/v2/account?timestamp=1426252182534)。 2. 将请求的URL和HTTP请求内容合并成一个UTF-8字符串。GET请求内容为一个空字符串。 3. 用SHA-256和您的API Secret Key计算签名。 以下是Wyre MassPay API节点。点击名称链接进入相应文档。 [block:parameters] { "data": { "h-0": "名称", "h-1": "API节点", "h-2": "HTTP方法", "1-0": "[实时价格](https://docs.sendwyre.com/docs/checking-live-exchange-rates)", "2-0": "[创建转账](https://docs.sendwyre.com/docs/creating-a-transfer-and-getting-a-quote)", "3-0": "[转账确认](https://docs.sendwyre.com/docs/confirming-a-quote)", "h-3": "描述", "0-1": "[https://api.sendwyre.com/v2/account](https://api.sendwyre.com/v2/account)", "1-1": "[https://api.sendwyre.com/v2/rates](https://api.sendwyre.com/v2/rates)", "2-1": "[https://api.sendwyre.com/v2/transfers](https://api.sendwyre.com/v2/transfers)", "0-0": "[账户详情](https://docs.sendwyre.com/docs/getting-your-account-and-checking-balances)", "4-0": "[转账状态](https://docs.sendwyre.com/docs/getting-transfer-status-updates)", "0-2": "GET", "1-2": "GET", "2-2": "POST", "3-2": "POST", "4-2": "GET", "3-1": "[https://api.sendwyre.com/v2/transfer/:transferId/confirm](https://api.sendwyre.com/v2/:transferId/confirm)", "4-1": "[https://api.sendwyre.com/v2/transfer/:transferId](https://api.sendwyre.com/v2/:transferId)", "0-3": "账户详情包括联系方式,所有货币的结余,相关授权和支付方式。", "1-3": "不同交易所的比特币价格。", "2-3": "创建两种货币间的转账。目的地可以是email地址,比特币钱包地址或者银行账户。可以开启自动确认功能,但并不推荐。", "3-3": "转账只会在您确认所有细节之后的30秒内执行。", "4-3": "如果您不想用callbackUrl,您可以通过本API获得订单状态。不同订单状态种类在[这里](http://masspay.snapcard.io/docs/transfer-statuses)。" }, "cols": 4, "rows": 5 } [/block] [block:api-header] { "type": "link", "title": "创建第一个转账请求" } [/block] 一个转账请求是一个包含最多7个字段的JSON POST请求。 - `sourceAmount` - 只需要选择 `sourceAmount` 或者 `destAmount`中一个。`sourceAmount`是从主账户中扣除的用来转账的金额。这种情况下您可以指定从账户中扣除的金额,入账金额将由交易费用和汇率确定。 - `sourceCurrency` - 转出货币代码[ISO 3166-1 alpha-3](https://en.wikipedia.org/wiki/ISO_3166-1_alpha-3#Current_codes) - `dest` - 转账地址。可以是email地址,电话号码,blockchain地址,或银行账户。 - `destAmount` - 只需要选择 `sourceAmount` 或者 `destAmount`中一个。`destAmount`是将被转入目标地址的金额。`sourceAmount`可以由`destAmount`,交易费用和汇率计算出。 - `destCurrency` - 转入货币代码。可以和转出货币代码不同。如果不同则汇率会被自动计算。 - `callbackUrl` - 可选,Wyre返回转账状态的Url。 - `autoConfirm` - 可选,默认自动确认转账的参数。不推荐。 以下例子将巴西雷亚尔转换为美元并发送到我们工程师的银行账户。 [block:code] { "codes": [ { "code": "{\n \"dest\": {\n \"paymentMethodType\":\"INTERNATIONAL_TRANSFER\",\n \"country\": \"US\",\n \"currency\": \"USD\",\n \"firstNameOnAccount\": \"Sam\",\n \"lastNameOnAccount\":\"Schlachter\",\n \"accountNumber\": \"1234dinosaur\",\n \"routingNumber\": \"0000000000\",\n \"accountType\": \"savings\",\n \"bankName\": \"Bank of 'murrrica\",\n \"bankStreet\": \"112 Brannan St\",\n \"bankCity\": \"San Francisco\",\n \"bankPostal\": \"94108\",\n \"accountHolderPhoneNumber\": \"+14102239203\",\n \"beneficiaryType\": \"INDIVIDUAL\",\n \"priority\":\"HIGH\"\n },\n \"sourceCurrency\": \"BRL\",\n \"destCurrency\": \"USD\",\n \"destAmount\": 10,\n \"message\":\"Here's your $10!\"\n}", "language": "json" } ] } [/block] 返回值类似。最重要的返回值是`id`字段。我们用这个值确认转账并获取转账状态。 如果转账金额和汇率满足我们的要求,我们需要点击[转账确认](或者用自动确认功能)来确认转账。 最后一步是从[转账状态](https://docs.sendwyre.com/docs/getting-transfer-status-updates)获取转账的状态--`完成`,`过期`,或者`失败`。或者你可以在`callbackUrl`字段填入一个URL。Wyre会将包含订单状态的HTTP POST请求发送到该URL。 以下是包含银行账户的转账示例。 [block:api-header] { "type": "link", "title": "转账示例" } [/block] **美国 USA 🇺🇸 → 🇧🇷 巴西 BRAZIL** [block:code] { "codes": [ { "code": "{\n \"dest\": {\n \"paymentMethodType\":\"INTERNATIONAL_TRANSFER\",\n \"country\": \"BR\",\n \"currency\": \"BRL\",\n \"firstNameOnAccount\": \"Robert\",\n \"lastNameOnAccount\": \"Baratheon\",\n \"accountNumber\": \"1234dinosaur\",\n \"bankName\": \"Mordor Credit Union\",\n \"cpfCnpj\": \"943759353\",\n \"accountType\": \"poupanca\",\n \"branchCode\": \"Artichoke\",\n \"accountHolderEmail\": \"[email protected]\",\n \"accountHolderPhoneNumber\": \"+14102239203\",\n \"swift\": \"DEUTUS00000\",\n \"beneficiaryType\": \"INDIVIDUAL\",\n \"priority\":\"HIGH\"\n },\n \"sourceCurrency\": \"USD\",\n \"destCurrency\": \"BRL\",\n \"destAmount\": 10,\n \"message\":\"A Lannister always pays his debts \"\n}", "language": "json" } ] } [/block] **巴西 BRAZIL 🇧🇷 → 🇺🇸 美国 USA** [block:code] { "codes": [ { "code": "{\n \"dest\": {\n \"paymentMethodType\":\"INTERNATIONAL_TRANSFER\",\n \"country\": \"US\",\n \"currency\": \"USD\",\n \"beneficiaryType\": \"INDIVIDUAL\",\n \"beneficiaryAddress\": \"112 Brannan St\",\n \"beneficiaryAddress2\": \"\", //Optional\n \"beneficiaryCity\": \"San Francisco\",\n \"beneficiaryState\": \"CA\",\n \"beneficiaryPostal\": \"94108\",\n \"beneficiaryPhoneNumber\": \"+14102239203\",\n \"beneficiaryDobDay\": \"15\",\n \"beneficiaryDobMonth\":\"12\",\n \"beneficiaryDobYear\":\"1989\",\n \"paymentType\" : \"LOCAL_BANK_WIRE\", // LOCAL_BANK_WIRE or ACH\n \"firstNameOnAccount\": \"Billy-Bob\",\n \"lastNameOnAccount\":\"Jones\",\n \"accountNumber\": \"0000000000000\",\n \"routingNumber\": \"0000000000\",\n \"accountType\": \"CHECKING\", //CHECKING or SAVINGS\n \"bankName\": \"Bank of America\"\n },\n \"sourceCurrency\": \"BRL\",\n \"destCurrency\": \"USD\",\n \"destAmount\": 10,\n \"message\":\"USD Personal example\"\n}", "language": "json" } ] } [/block] **美国 USA 🇺🇸 → 🇨🇳 中国 CHINA** [block:code] { "codes": [ { "code": "{\n \"dest\": {\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 \"sourceCurrency\": \"USD\",\n \"destCurrency\": \"CNY\",\n \"destAmount\": 10,\n \"message\":\"\"\n}", "language": "json" } ] } [/block] [block:api-header] { "type": "link", "title": "代码示例" } [/block] 你可以把自己的API Key,API Secret Key和Account ID放入以下脚本中,调整转账参数,即刻开始用MassPay转账! [block:code] { "codes": [ { "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, destination, 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':destination, #email, wallet, or bank transfer dict\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 MassPay API object\nwyre = MassPay_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 dictionary that we will pass in as the destination\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#send transfer and print result\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 False)\nprint(transfer_result)\ntx_id = transfer_result['id'] #grab our transfer id\n\n#confirm transfer\nhttp_code, confirmation = wyre.confirm_transfer(tx_id)\nprint(confirmation)\n\n#check status\nhttp_code, status = wyre.status_transfer(tx_id)\nprint(status)", "language": "python" }, { "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')", "language": "ruby" }, { "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 Main {\n public static void main(String[] args) {\n String apiKey = \"fll36l3t35udalcqlh4ng6bm4qpbgher\";\n String secretKey = \"tr3epinbk3maist0n3ijk18bm6dikrq6\";\n\n //retrieve account details and balance\n String url = \"https://api.sendwyre.com/account\";\n String method = \"GET\";\n String data = \"\";\n\n String result = executewyreRequest(url, \"\", method, apiKey, secretKey);\n System.out.println(result);\n\n //example transfer\n url = \"https://api.sendwyre.com/transfers\";\n method = \"POST\";\n data = \"{\" +\n \" \\\"dest\\\": \\\"[email protected]\\\",\" +\n \" \\\"destCurrency\\\": \\\"BTC\\\",\" +\n \" \\\"sourceCurrency\\\" : \\\"USD\\\",\" +\n \" \\\"sourceAmount\\\" : \\\"50\\\",\" +\n \" \\\"message\\\": \\\"$50 worth of bitcoin! Food please!\\\"\" +\n \"}\";\n result = excutewyreRequest(url, data, method, apiKey, secretKey);\n\n System.out.println(result);\n }\n\n public static String excutewyreRequest(String targetURL, String requestBody, String method, String apiKey, String secretKey) {\n URL url;\n HttpURLConnection connection = null;\n try {\n\n targetURL += ((targetURL.indexOf(\"?\")>0)?\"&\":\"?\") + \"timestamp=\" + System.currentTimeMillis();\n\n //Create connection\n url = new URL(targetURL);\n connection = (HttpURLConnection)url.openConnection();\n connection.setRequestMethod(method);\n System.out.println(connection.getRequestMethod());\n\n connection.setRequestProperty(\"Content-Type\", \"application/json\");\n connection.setRequestProperty(\"Content-Length\", Integer.toString(requestBody.getBytes().length));\n\n //Specify API v2\n connection.setRequestProperty(\"X-Api-Version\",\"2\");\n\n // Provide API key and signature\n connection.setRequestProperty(\"X-Api-Key\", apiKey);\n connection.setRequestProperty(\"X-Api-Signature\",computeSignature(secretKey,targetURL,requestBody));\n\n //Send request\n if(method.equals(\"POST\")) {\n connection.setDoOutput(true);\n connection.setRequestMethod(method);\n\n DataOutputStream wr = new DataOutputStream(\n connection.getOutputStream());\n\n wr.writeBytes(requestBody);\n wr.flush();\n wr.close();\n }\n\n //Get Response\n InputStream is = null;\n if (connection.getResponseCode() >= 400) {\n is = connection.getErrorStream();\n } \n else {\n is = connection.getInputStream();\n }\n BufferedReader rd = new BufferedReader(new InputStreamReader(is));\n String line;\n StringBuffer response = new StringBuffer();\n while((line = rd.readLine()) != null) {\n response.append(line);\n response.append('\\r');\n }\n rd.close();\n return response.toString();\n\n } catch (Exception e) {\n\n e.printStackTrace();\n return null;\n\n } finally {\n\n if(connection != null) {\n connection.disconnect();\n }\n }\n }\n\n public static String computeSignature(String secretKey, String url, String reqData) {\n\n String data = url + reqData;\n\n System.out.println(data);\n\n try {\n Mac sha256Hmac = Mac.getInstance(\"HmacSHA256\");\n SecretKeySpec key = new SecretKeySpec(secretKey.getBytes(), \"HmacSHA256\");\n sha256Hmac.init(key);\n\n byte[] macData = sha256Hmac.doFinal(data.getBytes());\n\n String result = \"\";\n for (final byte element : macData){\n result += Integer.toString((element & 0xff) + 0x100, 16).substring(1);\n }\n return result;\n\n } catch (Exception e) {\n e.printStackTrace();\n return \"\";\n }\n }\n}", "language": "java" }, { "code": "using System;\nusing System.IO;\nusing System.Net;\nusing System.Security.Cryptography;\nusing System.Text;\n\nnamespace test\n{\n class MainClass\n {\n public static void Main(string[] args)\n {\n wyreApi wyreApi = new wyreApi();\n\n string balance = wyreApi.getAccount();\n Console.WriteLine(balance);\n\n string transferData = \"{\" +\n \"\\\"sourceCurrency\\\": \\\"USD\\\",\" +\n \"\\\"dest\\\": \\\"[email protected]\\\",\" +\n \"\\\"sourceAmount\\\": \\\"0.01\\\",\" +\n \"\\\"destCurrency\\\": \\\"BTC\\\"\" +\n \"}\";\n string authResponse = wyreApi.transfer(transferData);\n Console.WriteLine(authResponse);\n }\n }\n\n public class wyreApi {\n private const string domain = \"https://api.sendwyre.com\";\n private const string apiKey = \"xxxxxx\";\n private const string secKey = \"xxxxxx\";\n\n public string getAccount() \n {\n return MakeGetReq(\"/account\");\n }\n\n public string transfer(string jsonString)\n {\n return MakePostReq(\"/transfers\", jsonString);\n }\n\n private string MakeGetReq(string apiRoute)\n {\n WebRequest req = AssembleWebRequest(apiRoute);\n req.Method = \"GET\";\n WebResponse response = req.GetResponse();\n string responseString = ParseWebResponse(response);\n return responseString;\n }\n\n private string MakePostReq(string apiRoute, string jsonData)\n {\n WebRequest req = AssembleWebRequest(apiRoute, jsonData);\n req.Method = \"POST\";\n WriteJsonToRequest(req, jsonData);\n\n\n WebResponse response = req.GetResponse();\n string responseString = ParseWebResponse(response);\n return responseString;\n }\n\n private WebRequest AssembleWebRequest(string apiRoute, string jsonData = \"\")\n {\n string url = domain + apiRoute + (apiRoute.Contains(\"?\")?\"&\":\"?\") + \"timestamp=\"+DateTime.Now.Ticks; \n WebRequest request = WebRequest.Create(url);\n string authSig = CalcAuthSigHash(secKey, url + jsonData);\n\n request.ContentType = \"application/json\";\n request.Headers[\"X-Api-Key\"] = apiKey;\n request.Headers[\"X-Api-Signature\"] = authSig;\n request.Headers[\"X-Api-Version\"] = \"2\";\n return request;\n }\n\n private void WriteJsonToRequest(WebRequest req, string jsonData)\n {\n var streamWriter = new StreamWriter(req.GetRequestStream ());\n streamWriter.Write(jsonData);\n streamWriter.Close();\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)));\n hash = hash.Replace(\"-\", \"\");\n return hash;\n }\n\n private string ParseWebResponse(WebResponse response)\n {\n StreamReader streamReader = new StreamReader(response.GetResponseStream());\n string result = streamReader.ReadToEnd();\n streamReader.Close();\n return result;\n }\n }\n}", "language": "csharp" }, { "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 $transfer = array(\n \"sourceCurrency\"=>\"USD\",\n \"dest\"=>\"[email protected]\",\n \"destAmount\"=> 55.05,\n \"destCurrency\"=>\"EUR\",\n \"message\"=> \"buy sam pizza\"\n );\n echo make_authenticated_request(\"/transfers\", \"POST\", $transfer);\n?>", "language": "php" } ] } [/block] [block:api-header] { "type": "link", "title": "相关链接和联系方式" } [/block] ## **链接** [Wyre主页](https://www.sendwyre.com) [Wyre注册页](https://www.sendwyre.com/wallet/sign-up) [MassPay开发者中心](http://masspay.sendwyre.com/) ## **参考** [区块链技术介绍](https://bitcoin.org/en/how-it-works) [公司信息](https://angel.co/sendwyre) ## **联系方式** *[email protected]* *415-374-7356* 1550 Bryant St, Ste 750 San Francisco, CA 94107 或者 *使用我们主页右下角的在线聊天*