{"id":17968671,"url":"https://github.com/bchavez/coinbase","last_synced_at":"2025-11-03T19:01:36.252Z","repository":{"id":12051595,"uuid":"14637669","full_name":"bchavez/Coinbase","owner":"bchavez","description":":moneybag: A .NET/C# implementation of the Coinbase API.","archived":false,"fork":false,"pushed_at":"2024-06-09T09:38:28.000Z","size":24552,"stargazers_count":179,"open_issues_count":8,"forks_count":95,"subscribers_count":20,"default_branch":"master","last_synced_at":"2025-05-16T12:12:51.687Z","etag":null,"topics":["bitcoin","c-sharp","coinbase","coinbase-api","payment-page","payment-processing","payment-request"],"latest_commit_sha":null,"homepage":"https://developers.coinbase.com/api/v2","language":"C#","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/bchavez.png","metadata":{"files":{"readme":"README.md","changelog":"HISTORY.md","contributing":null,"funding":".github/FUNDING.yml","license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null},"funding":{"github":"bchavez"}},"created_at":"2013-11-23T06:19:36.000Z","updated_at":"2025-04-26T23:36:33.000Z","dependencies_parsed_at":"2024-06-21T05:43:18.007Z","dependency_job_id":null,"html_url":"https://github.com/bchavez/Coinbase","commit_stats":{"total_commits":238,"total_committers":9,"mean_commits":"26.444444444444443","dds":"0.17226890756302526","last_synced_commit":"dfc5e674cba167d57362498ef2aaf1228aec762c"},"previous_names":[],"tags_count":33,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bchavez%2FCoinbase","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bchavez%2FCoinbase/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bchavez%2FCoinbase/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/bchavez%2FCoinbase/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/bchavez","download_url":"https://codeload.github.com/bchavez/Coinbase/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":254527099,"owners_count":22085919,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["bitcoin","c-sharp","coinbase","coinbase-api","payment-page","payment-processing","payment-request"],"created_at":"2024-10-29T14:41:13.506Z","updated_at":"2025-11-03T19:01:31.206Z","avatar_url":"https://github.com/bchavez.png","language":"C#","funding_links":["https://github.com/sponsors/bchavez"],"categories":[],"sub_categories":[],"readme":"[![Build status](https://ci.appveyor.com/api/projects/status/t6j3xe6cr0mu8si5?svg=true)](https://ci.appveyor.com/project/bchavez/coinbase) [![Nuget](https://img.shields.io/nuget/v/Coinbase.svg)](https://www.nuget.org/packages/Coinbase/) [![Users](https://img.shields.io/nuget/dt/Coinbase.svg)](https://www.nuget.org/packages/Coinbase/) \u003cimg src=\"https://raw.githubusercontent.com/bchavez/Coinbase/master/Docs/coinbase.png\" align='right' /\u003e\n\nCoinbase .NET/C# Library\n======================\n\nProject Description\n-------------------\nA .NET implementation for the [Coinbase API](https://developers.coinbase.com/api/v2). This library uses API version 2.\n\n:loudspeaker: ***HEY!*** Be sure to checkout these other Coinbase API integrations:\n\n* [**Coinbase.Commerce**](https://github.com/bchavez/Coinbase.Commerce) - For e-commerce, merchants, and websites selling products or services looking to receive cryptocurrency as payment.\n* [**Coinbase.Pro**](https://github.com/bchavez/Coinbase.Pro) - For [retail trading](https://pro.coinbase.com) on [Coinbase Pro](https://pro.coinbase.com). Integration with orders, market data, and real-time WebSocket feeds.\n\n[1]:https://docs.microsoft.com/en-us/mem/configmgr/core/plan-design/security/enable-tls-1-2-client\n[2]:https://docs.microsoft.com/en-us/dotnet/framework/network-programming/tls\n#### Minimum Requirements\n* **.NET Standard 2.0** or later\n* **.NET Framework 4.6.1** or later\n* **TLS 1.2** or later\n\n***Note:*** If you are using **.NET Framework 4.6.1** you will need to ensure your application is using **TLS 1.2** or later. This can be configured via the registry ([**link 1**][1], [**link 2**][2]) or configured at ***application startup*** by setting the following value in `ServicePointManager`:\n```csharp\nServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;\n```\n\n#### Crypto Tip Jar\n\u003ca href=\"https://commerce.coinbase.com/checkout/119320d7-db0a-45c9-97d8-fe4088348288\"\u003e\u003cimg src=\"https://raw.githubusercontent.com/bchavez/Coinbase/master/Docs/tipjar.png\" /\u003e\u003c/a\u003e\n\n\n\n### Download \u0026 Install\n**Nuget Package [Coinbase](https://www.nuget.org/packages/Coinbase/)**\n\n```powershell\nInstall-Package Coinbase\n```\n\nUsage\n-----\n### API Authentication\nCoinbase offers two ways to authenticate your application with their API. You will need to select one of the following authentication methods:\n\n* [**OAuth2**](https://developers.coinbase.com/api/v2#oauth2-coinbase-connect) authentication.\n* [**API key + Secret**](https://developers.coinbase.com/api/v2#api-key) authentication.\n\nThis library can perform **OAuth** or **API Key + Secret** authentication make calls to Coinbase servers.\n\n----\n### Getting Started\n\nFor the most part, to get the started, simply new up a new `CoinbaseClient` object as shown below:\n```csharp\n//using OAuth Token authenticiation\nvar client = new CoinbaseClient(new OAuthConfig{ AccessToken = \"...\" });\n\n//using API Key + Secret authentication\nvar client = new CoinbaseClient(new ApiKeyConfig{ ApiKey = \"...\", ApiSecret = \"...\"});\n\n//No authentication\n//  - Useful only for Data Endpoints that don't require authentication.\nvar client = new CoinbaseClient();\n```\nOnce you have a `CoinbaseClient` object, simply call one of any of the [**Wallet Endpoints**](https://developers.coinbase.com/api/v2#wallet-endpoints) or [**Data Endpoints**](https://developers.coinbase.com/api/v2#data-endpoints). Extensive examples can be [found here](https://github.com/bchavez/Coinbase/tree/master/Source/Coinbase.Tests/Endpoints).\n\nIn one such example, to get the [spot price](https://developers.coinbase.com/api/v2#get-spot-price) of `ETH-USD`, do the following:\n```csharp\n[Test]\npublic async Task can_get_spotprice_of_ETHUSD()\n{\n   var spot = await client.Data.GetSpotPriceAsync(\"ETH-USD\");\n   spot.Data.Amount.Should().BeGreaterThan(5);\n   spot.Data.Currency.Should().Be(\"USD\");\n   spot.Data.Base.Should().Be(\"ETH\");\n}\n```\n\n#### Full API Support\n##### Data Endpoints\n* [`client.Data`](https://developers.coinbase.com/api/v2#data-endpoints) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Integration/DataTests.cs)\n* [`client.Notifications`](https://developers.coinbase.com/api/v2#notifications) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/NotificationTests.cs)\n\n##### Wallet Endpoints\n* [`client.Accounts`](https://developers.coinbase.com/api/v2#accounts) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/AccountTests.cs)\n* [`client.Addresses`](https://developers.coinbase.com/api/v2#addresses) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/AddressTests.cs)\n* [`client.Buys`](https://developers.coinbase.com/api/v2#buys) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/BuyTest.cs)\n* [`client.Deposits`](https://developers.coinbase.com/api/v2#deposits) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/DepositTests.cs)\n* [`client.PaymentMethods`](https://developers.coinbase.com/api/v2#payment-methods) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/PaymentMethodTest.cs)\n* [`client.Sells`](https://developers.coinbase.com/api/v2#sells) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/SellTest.cs)\n* [`client.Transactions`](https://developers.coinbase.com/api/v2#transactions) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/TransactionTests.cs)\n* [`client.Users`](https://developers.coinbase.com/api/v2#users) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/UserTests.cs)\n* [`client.Withdrawals`](https://developers.coinbase.com/api/v2#withdrawals) - [Examples](https://github.com/bchavez/Coinbase/blob/master/Source/Coinbase.Tests/Endpoints/WithdrawlTests.cs)\n\n### Pagination\nSome Coinbase [APIs support pagination. See developer docs here](https://developers.coinbase.com/api/v2#pagination). APIs that support pagination can specify an extra `PaginationOptions` object used to specify item page `limit` and other various options. The following code shows how to enumerate the first 3 pages where each page contains 5 buy transactions for an account.\n\n```csharp\nvar client = new CoinbaseClient(...);\n\nvar page1 = await client.Buys.ListBuysAsync(\"..accountId..\", \n                  new PaginationOptions{Limit = 5}); //Limit results to 5 items\n\nvar page2 = await client.GetNextPageAsync(page1); //Same pagination options used.\n                                                  //Limit 5 items.\n\nvar page3 = await client.GetNextPageAsync(page2); //Same pagination options used.\n                                                  //Limit 5 items.\n```\n\nUse the `.GetNextPageAsync` helper method on `CoinbaseClient` supplying the current page of data to get the next page of data.\n\n### Authentication Details\n##### OAuth Access and Refresh Tokens\nThis section only applies to developers using **OAuth** authentication, not **API key + Secret** authentication. Full documentation for Coinbase's **OAuth** token flow can be found [here](https://developers.coinbase.com/docs/wallet/coinbase-connect/integrating).\n\nBefore you begin **OAuth** you'll need to register your **OAuth** application with Coinbase. Once you have an **OAuth** application registered, you should have something similar to the following screen:\n\n![OAuth AppSetup](https://raw.githubusercontent.com/bchavez/Coinbase/master/Docs/oauthsetup.png)\n\nNote the `Client Id` and `Client Secret` values.\n\nThe following steps show how to obtain an `AccessToken` from a Coinbase user with your application:\n1. First, get authorization from the user by sending the user to a URL using:\n  ```csharp\n//Create the options and permission scopes you want your app to have access to\nvar opts = new AuthorizeOptions\n{\n   ClientId = \"YOUR_CLIENT_ID\",\n   RedirectUri = \"YOUR_REDIRECT_URL\", //Example value: http://myserver.com/callback\n   State = \"SECURE_RANDOM\",\n   Scope = \"wallet:accounts:read\"\n};\n\n//Send the user to URL created by GetAuthorizeUrl\nvar authUrl = OAuthHelper.GetAuthorizeUrl(opts);\n  ```\n`SECURE_RANDOM` is some random state that you should generate to check when the user returns back to your site.\n\n\n2. The user will be presented with a screen similar to:\n![OAuth Screen](https://developers.coinbase.com/images/docs/oauth-pongbot.png)\n\n   If your app needs more permissions, [check here for details](https://developers.coinbase.com/docs/wallet/coinbase-connect/permissions) and [here for reference](https://developers.coinbase.com/docs/wallet/coinbase-connect/reference).\n\n3. Once your app has been given permission, Coinbase will send the user's browser back to `RedirectUri`. A `code` value will be present as a query string parameter. Extract this `code` value in your application and use it to obtain an `AccessToken` as shown below:\n  ```csharp\n//http://myserver.com/callback?code=f284bdc3c1c9e24a494e285cb387c69510f28de51c15bb93179d9c7f28705398\u0026state=SECURE_RANDOM\n\nvar redirectUri = \"http://myserver.com/callback\";\nvar code = \"f284bdc3c1c9e24a494e285cb387c69510f28de51c15bb93179d9c7f28705398\";\n\n// Convert an Authorization Code to an Access Token.\n// The RedirectUri parameter is the same parameter used in Step 1's AuthorizeOptions object above.\nvar token = await OAuthHelper.GetAccessTokenAsync(code, ClientId, ClientSecret, redirectUri);\n\nvar refreshToken = token.RefreshToken; // Save for later\n\nvar client = new CoinbaseClient(new OAuthConfig{ AccessToken = token.AccessToken })\n  ```\n\n###### Explicit Token Expiration and Renewal\n`AccessToken`s have a two hour life time. Any **OAuth API** requests after two hours will be denied. However, you can use a **Refresh Token** to get a new **Access Token** (that will again later, expire after 2 hours). **Refresh Token**s don't have a life time per se, but they can only be *used once* to renew an expired **Access Token**.\n\nInitially, back in **Step 3**, when an authorization `code` is converted into an access token, you actually get two tokens, an `AccessToken` and a `RefreshToken`. In **Step 3**, the variable `refreshToken` (which was saved for later use) is used to obtain a new `AccessToken`.\n\n```csharp\nvar newTokens = await OAuthHelper.RenewAccessAsync(refreshToken, ClientAppId, ClientSecret);\nvar newClient = new CoinbaseClient(new OAuthConfig{ AccessToken = newTokens.AccessToken })\n\n// Safe for later, again because refresh tokens can only be used once for renewal.\nvar newRefreshToken = newTokens.RefreshToken;\n```\n\n###### Automatic Token Renewal\nThe `CoinbaseClient` supports automatic token renewal. If you want to avoid refreshing your `AccessToken` every two hours you can use the following `.WithAutomaticOAuthTokenRefresh()` extension method to activate automatic token renewal. When creating the `CoinbaseClient` object in **Step 3** above do the following: \n\n```csharp\nvar client = new CoinbaseClient(new OAuthConfig { AccessToken = token.AccessToken,\n                                                  RefreshToken = token.RefreshToken })\n                 .WithAutomaticOAuthTokenRefresh(ClientId, ClientSecret);\n```\nYou only need to call `.WithAutomaticOAuthTokenRefresh` once when creating the `CoinbaseClient` object. Any failed HTTP requests that require authorization will be tried again with a refreshed `AccessToken`. \n\n\n##### Two Factor Authentication\nSome APIs require **Two-Factor Authentication (2FA)**. To use APIs that require **2FA**, add a the `TwoFactorToken` header value before sending the request as shown below:\n```csharp\nusing Flurl.Http;\nusing static Coinbase.HeaderNames;\n\n//using OAuth Token\nvar client = new CoinbaseClient(new OAuthConfig{ AccessToken = \"...\" });\nvar create = new CreateTransaction\n   {\n      To = \"...btc_address...\"\n      Amount = 1.0m,\n      Currency = \"BTC\"\n   };\n\nvar response = await client\n    .WithHeader(TwoFactorToken, \"...\")\n    .Transactions.SendMoneyAsync(\"accountId\", create);\n\nif( response.HasError() )\n{\n   // something went wrong.\n}\nelse\n{\n   // transaction is okay!\n}\n``` \n\n-------\n#### Handling Callback Notifications on Your Server\n\nThis library can handle verification of notifications / webhook / callbacks from Coinbase. When an intresting event occurs, Coinbase can `POST` **JSON** notifications to your server. When receiving a notification, an **HTTP** `POST` is delivered to your server that looks similar to:\n\n```\nPOST /callmebackhere HTTP/1.1\nUser-Agent: weipay-webhooks\nContent-Type: application/json\nCB-SIGNATURE: 6yQRl17CNj5YSHSpF+tLjb0vVsNVEv021Tyy1bTVEQ69SWlmhwmJYuMc7jiDyeW9TLy4vRqSh4g4YEyN8eoQIM57pMoNw6Lw6Oudubqwp+E3cKtLFxW0l18db3Z/vhxn5BScAutHWwT/XrmkCNaHyCsvOOGMekwrNO7mxX9QIx21FBaEejJeviSYrF8bG6MbmFEs2VGKSybf9YrElR8BxxNe/uNfCXN3P5tO8MgR5wlL3Kr4yq8e6i4WWJgD08IVTnrSnoZR6v8JkPA+fn7I0M6cy0Xzw3BRMJAvdQB97wkobu97gFqJFKsOH2u/JR1S/UNP26vL0mzuAVuKAUwlRn0SUhWEAgcM3X0UCtWLYfCIb5QqrSHwlp7lwOkVnFt329Mrpjy+jAfYYSRqzIsw4ZsRRVauy/v3CvmjPI9sUKiJ5l1FSgkpK2lkjhFgKB3WaYZWy9ZfIAI9bDyG8vSTT7IDurlUhyTweDqVNlYUsO6jaUa4KmSpg1o9eIeHxm0XBQ2c0Lv/T39KNc/VOAi1LBfPiQYMXD1e/8VuPPBTDGgzOMD3i334ppSr36+8YtApAn3D36Hr9jqAfFrugM7uPecjCGuleWsHFyNnJErT0/amIt24Nh1GoiESEq42o7Co4wZieKZ+/yeAlIUErJzK41ACVGmTnGoDUwEBXxADOdA=\nAccept-Encoding: gzip;q=1.0,deflate;q=0.6,identity;q=0.3\nAccept: */*\nConnection: close\nContent-Length: 1122\n\n{\"order\":{\"id\":null,\"created_at\":null,\"status\":\"completed\",\"event\":null,\"total_btc\":{\"cents\":100000000,\"currency_iso\":\"BTC\"},\"total_native\":{\"cents\":1000,\"currency_iso\":\"USD\"},\"total_payout\":{\"cents\":1000,\"currency_iso\":\"USD\"},\"custom\":\"123456789\",\"receive_address\":\"mzVoQenSY6RTBgBUcpSBTBAvUMNgGWxgJn\",\"button\":{\"type\":\"buy_now\",\"name\":\"Test Item\",\"description\":null,\"id\":null},\"transaction\":{\"id\":\"53bdfe4d091c0d74a7000003\",\"hash\":\"4a5e1e4baab89f3a32518a88c31bc87f618f76673e2cc77ab2127b7afdeda33b\",\"confirmations\":0}}}\n```\n\nThe two important pieces of information you need to extract from this **HTTP** `POST` callback are:\n\n* The `CB-SIGNATURE` header value.\n* The ***raw*** **HTTP** body **JSON** payload. \n\nThe `WebhookHelper` static class included with this library does all the heavy lifting for you. All you need to do is call `Webhookhelper.IsValid()` supplying the `CB-SIGNATURE` header value in the **HTTP** `POST` above, and the ***raw*** **JSON** body in the **HTTP** `POST` above.\n\nThe following **C#** code shows how to use the `WebhookHelper` to validate callbacks from **Coinbase**:\n\n```csharp\nif( WebhookHelper.IsValid( Request.Body.Json, cbSignatureHeaderValue) ){\n   // The request is legit and an authentic message from Coinbase.\n   // It's safe to deserialize the JSON body. \n   var webhook = JsonConvert.DeserializeObject\u003cNotification\u003e(Request.Body.Json);\n   \n   ... do further processing.\n\n   return Response.Ok();\n}\nelse {\n   // Some hackery going on. The Webhook message validation failed.\n   // Someone is trying to spoof payment events!\n   // Log the requesting IP address and HTTP body. \n}\n```\n\n Easy peasy! **Happy crypto shopping!** :tada:\n\nAdvanced Usage\n--------------\nIn some advanced cases it may be desirable to gain access to the underlying `HttpResponseMessage` object to check **HTTP status codes**, **HTTP headers** or to manually inspect the **response body**. The `.HoistResponse()` method on `CoinbaseClient` can be used to gain access the underlying `HttpResponseMessage`. The following code demonstrates how get the underlying `HttpResponseMessage`:\n\n```csharp\nvar accountList = await client\n   .AllowAnyHttpStatus()\n   .HoistResponse(out var responseGetter)\n   .Accounts\n   .ListAccountsAsync();\n\nvar response = responseGetter();\n\nvar httpStatusCode = response.StatusCode;\n```\n\n\nReference\n---------\n* [Coinbase API Documentation](https://developers.coinbase.com/api/v2)\n\n\nBuilding\n--------\n* Download the source code.\n* Run `build.cmd`.\n\nUpon successful build, the results will be in the `\\__compile` directory. If you want to build NuGet packages, run `build.cmd pack` and the NuGet packages will be in `__package`.\n\n\n\nContributors\n---------\nCreated by [Brian Chavez](http://bchavez.bitarmory.com).\n\nA big thanks to GitHub and all contributors:\n\n* [ElanHasson](https://github.com/ElanHasson) (Elan Hasson)\n* [ryanmwilliams](https://github.com/ryanmwilliams) (Ryan Williams)\n\n---\n\n*Note: This application/third-party library is not directly supported by Coinbase Inc. Coinbase Inc. makes no claims about this application/third-party library.  This application/third-party library is not endorsed or certified by Coinbase Inc.*\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbchavez%2Fcoinbase","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fbchavez%2Fcoinbase","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fbchavez%2Fcoinbase/lists"}