.NET Examples
- find_items_by_keywords example
- fetch_token example
- get_categories example
- get_orders example
- add_fixed_price_item example
VB.NET Example for findItemsByKeywords
Sample: Basic Call
Retrieves a set of items based on keywords provided.
Code
Basic C# code to search for items matching "The King":
Imports System Public Class FindItemsByKeywordsExample Public Const STANDARD_API_URL As String = "https://api.bonanza.com/api_requests/standard_request" Public Shared Sub xMain() Dim requestName As String = "findItemsByKeywords" Dim keywords As string = "The King" Dim json As String = "{'keywords':'" & keywords & "'}" Dim contentToPost As String = requestName + "=" + json Dim response As String = "" Try Dim url as String = STANDARD_API_URL Dim request As System.net.HttpWebRequest = System.net.WebRequest.Create(url) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "KsEeX0w61fBmGlR") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "test") Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As System.net.HttpWebResponse = request.GetResponse() Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() System.Console.WriteLine(strResponse) Catch ex As Exception Throw New Exception("failed to get token. " & ex.Message & vbCrLf & ex.StackTrace) End Try End Sub End Class
Data
jsonPayload's value (JSON):
{"keywords":"The King"}
jsonResponse's value (JSON):
{ "timestamp":"2009-10-31T14:47:13.000Z", "version":"1.0", "findItemsByKeywordsResponse":{ "paginationOutput":{ "totalEntries":2471394, "pageNumber":1, "entriesPerPage":20 }, "item":[ { "primaryCategory":{ "categoryName":"Clothing, Shoes amp; Accessories >> Unisex Clothing, Shoes amp; Accs >> Unisex Adult Clothing >> T-Shirts", "categoryId":155193 }, "listingInfo":{ "price":9.99, "convertedBuyItNowPrice":9.99, "bestOfferEnabled":"true", "listingType":"FixedPrice", "buyItNowPrice":9.99, "startTime":"2009-10-31T00:09:01.000Z", "lastChangeTime":"2009-10-31T00:09:01.000Z" }, "viewItemURL":"https://www.bonanza.com/booths/tshirt_seller_dev/items/CHESS__THE_KING__LOGO_Royal_Blue_T_SHIRT", "location":"CA", "title":"CHESS \"THE KING\" LOGO Royal Blue T-SHIRT", "sellerInfo":{ "feedbackRatingStar":"Blue", "membershipLevel":null, "sellerUserName":"T-Shirt Sellin' Deven", "availableForChat":"false", "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg", "positiveFeedbackPercent":"100" }, "itemId":7410001, "storeInfo":{ "storeName":"Deven's T-Shirt Shoppe", "storeDiscount":null, "storeURL":"https://www.bonanza.com/booths/tshirt_seller_dev", "storeHasBonanza":"false", "storeItemCount":6 }, "shippingInfo":{ "shippingServiceCost":2.99, "shippingType":"Flat", "shipToLocations":"US" }, "sellingStatus":{ "convertedCurrentPrice":9.99, "sellingState":"Active", "currentPrice":9.99 }, "postalCode":"94536", "paymentMethod":["Paypal"], "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/2889/3800/shirt-chess-king.jpg", "globalId":"Bonanza", "descriptionBrief":"This shirt is only for KINGS!" }, { "primaryCategory":{ "categoryName":"Home amp; Garden", "categoryId":11700 }, "listingInfo":{ "price":10.0, "convertedBuyItNowPrice":10.0, "bestOfferEnabled":"true", "listingType":"FixedPrice", "buyItNowPrice":10.0, "startTime":"2009-10-31T00:04:35.000Z", "lastChangeTime":"2009-10-31T00:04:35.000Z" }, "viewItemURL":"https://www.bonanza.com/booths/â?¦", "location":"Bolingbrook, IL", "title":"Elvisâ?¦", "sellerInfo":{ "feedbackRatingStar":"Yellow", "membershipLevel":null, "sellerUserName":"â?¦", "availableForChat":"false", "userPicture":"http://s3.amazonaws.com/bonanzaimages/user_profile_image/afu/user_profile_images/â?¦.jpg", "positiveFeedbackPercent":"100" }, "itemId":7920002, "storeInfo":{ "storeName":"â?¦", "storeDiscount":null, "storeURL":"https://www.bonanza.com/booths/â?¦", "storeHasBonanza":"false", "storeItemCount":1 }, "shippingInfo":{ "shippingServiceCost":0, "shippingType":"Free", "shipToLocations":"US" }, "sellingStatus":{ "convertedCurrentPrice":10.0, "sellingState":"Active", "currentPrice":10.0 }, "postalCode":"60446", "paymentMethod":["MOCC","Paypal"], "galleryURL":"http://s3.amazonaws.com/bonanzaimages/afu/images/â?¦", "globalId":"Bonanza", "descriptionBrief":"â?¦" }, â?¦ ] }, "ack":"Success" }
VB.NET Example for fetchToken
Sample: User Token Fetching
Code
VB.NET code to fetch a token:
Imports System Public Class FetchTokenExample Public Const SECURE_API_URL As String = "https://api.bonanza.com/api_requests/secure_request" Public Shared Sub xMain() Dim contentToPost As String = "fetchTokenRequest={}" Dim response As String = "" Try Dim url as String = SECURE_API_URL Dim request As System.net.HttpWebRequest = System.net.WebRequest.Create(url) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "KsEeX0w61fBmGlR") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "test") Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As System.net.HttpWebResponse = request.GetResponse() Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() System.Console.WriteLine(strResponse) Catch ex As Exception System.Console.WriteLine("Failed to call Bonanza with content " & contentToPost & ", " & ex.Message & vbCrLf & ex.StackTrace) Throw End Try End Sub End Class
Data
jsonResponse's value (JSON [formatted for legibility]):
{ "ack": "Success", "version": "1.0beta", "timestamp": "2015-08-28T09:34:16Z", "fetchTokenResponse": { "authToken": "rXaGR1tCDv", "hardExpirationTime": "2016-08-28T09:34:16Z", "authenticationURL":"https://www.bonanza.com/login?apitoken=rXaGR1tCDv" } }
VB.NET Example for getCategories
Sample: Getting Categories
Code
VB.NET code to get information of all children categories of the provided categoryID:
Imports System Public Class GetCategoriesExample Public Const STANDARD_API_URL As String = "https://api.bonanza.com/api_requests/standard_request" Public Shared Sub xMain() Dim requestName As String = "getCategoriesRequest" Dim categoryId as integer = 2984 Dim json As String = "{'categoryId':" & categoryId & "}" Dim contentToPost As String = requestName & "=" & json Dim response As String = "" Try Dim url as String = STANDARD_API_URL Dim request As System.net.HttpWebRequest = System.net.WebRequest.Create(url) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "KsEeX0w61fBmGlR") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "test") Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As System.net.HttpWebResponse = request.GetResponse() Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() System.Console.WriteLine(strResponse) Catch ex As Exception System.Console.WriteLine("Failed to call Bonanza with content " & contentToPost & ", " & ex.Message & vbCrLf & ex.StackTrace) Throw End Try End Sub End Class
Data
response_json's value (JSON [formatted for legibility]):
{ "ack":"Success", "version":"1.0beta", "timestamp":"2015-01-14T16:47:26.000Z", "getCategoriesResponse":{ "categoryArray":[ { "categoryId":1261, "categoryLevel":2, "categoryName":"Baby >> Other", "leafCategory":"true", "categoryBriefName":"Other", "traitCount":4 }, { "categoryId":19068, "categoryLevel":2, "categoryName":"Baby >> Toys for Baby", "leafCategory":"false", "categoryBriefName":"Toys for Baby", "traitCount":4 }, { "categoryId":20394, "categoryLevel":2, "categoryName":"Baby >> Bathing & Grooming", "leafCategory":"false", "categoryBriefName":"Bathing & Grooming", "traitCount":4 } ] } }
VB.NET Example for getOrders
Sample: Getting Orders
Code
VB.NET code to get order information for a seller in a specific time period
Imports System Public Class GetOrdersExample Public Const SECURE_API_URL As String = "https://api.bonanza.com/api_requests/secure_request" Public Shared Sub xMain() Dim requestName As String = "getOrdersRequest" Dim authToken As string = "11Fbw30vSZ" Dim orderRole As string = "Seller" Dim json As String = "{'requesterCredentials':{'bonanzleAuthToken':'" & authToken & "'}, 'orderRole':'" & orderRole & "'}" Dim contentToPost As String = requestName + "=" + json Dim response As String = "" Try Dim url as String = SECURE_API_URL Dim request As System.net.HttpWebRequest = System.net.WebRequest.Create(url) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "KsEeX0w61fBmGlR") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "test") Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As System.net.HttpWebResponse = request.GetResponse() Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() System.Console.WriteLine(strResponse) Catch ex As Exception Throw New Exception("failed to get token. " & ex.Message & vbCrLf & ex.StackTrace) End Try End Sub End Class
Data
response_json's value (JSON [formatted for legibility]):
{ "ack":"Success", "version":"1.0beta", "timestamp":"2015-01-14T16:55:25.000Z", "getOrdersResponse":{ "orderArray":[ { "order":{ "amountPaid":"104.32", "amountSaved":0.0, "buyerCheckoutMessage":"", "buyerUserID":6157, "buyerUserName":"JDoe", "checkoutStatus":{ "status":"Complete" }, "createdTime":"2013-04-25T16:54:25Z", "creatingUserRole":"Buyer", "itemArray":[ { "item":{ "itemID":205172, "sellerInventoryID":null, "sku":null, "title":"76 Blank DVD Cases", "price":"24.0", "quantity":1 } } ], "orderID":1811, "orderStatus":"Shipped", "subtotal":24.0, "taxAmount":0.0, "total":"104.32", "transactionArray":{ "transaction":{ "buyer":{ "email":"testy@bonanza.com" }, "providerName":"Checkout by Amazon", "providerID":"104-1031316-4215451", "finalValueFee":"3.3" } }, "paidTime":"2013-04-25T17:08:24Z", "shippedTime":"2014-04-28T23:19:08Z", "shippingAddress":{ "addressID":6710, "cityName":"SEATTLE", "country":"US", "countryName":null, "name":"Test User", "postalCode":"98122-90210", "stateOrProvince":"WA", "street1":null, "street2":null }, "shippingDetails":{ "insuranceFee":0, "amount":"81.52", "servicesArray":[], "shippingService":"Standard shipping" } } }], "hasMoreOrders":"false", "paginationResult":{ "totalNumberOfEntries":2, "totalNumberOfPages":1 }, "pageNumber":1 } }
VB.NET Example for addFixedPriceItem
Sample: Adding an Item
Code
VB.NET code to add an item
Imports System Public Class AddFixedPriceItemExample Public Const SECURE_API_URL As String = "https://api.bonanza.com/api_requests/secure_request" Public Shared Sub Main() Dim requestName As String = "addFixedPriceItemRequest" Dim authToken As string = "11Fbw30vSZ" Dim json As String = "{" json += "'requesterCredentials':{'bonanzleAuthToken':'" & authToken & "'}," json += "'item':{" json += "'title': 'NET Lightsaber'," json += "'primaryCategory': {'categoryId':163128}," json += "'description': 'An elegant weapon, for a more civilized age<br>* SELLER <strong>NOT LIABLE</strong> FOR DISMEMBERMENT *'," json += "'itemSpecifics': [['condition', 'used'], ['danger', 'extreme']]," json += "'price': 42," json += "'quantity': 3," json += "'shippingType': 'Free'," json += "'pictureDetails': {'pictureURL': ['http://images.discountstarwarscostumes.com/products/9284/1-1/luke-skywalker-blue-lightsaber.jpg', 'http://www.rankopedia.com/CandidatePix/29862.gif']}," json += "'variations': [{ 'quantity': 2, 'nameValueList': [{ 'name': 'Colour', 'value': 'Blue'},{'name':'Style','value':'Single'}]},{'quantity':1,'nameValueList':[{'name':'Colour','value':'Red'},{'name':'Style','value':'Double'}] }]" json += "}" json += "}" Dim contentToPost As String = requestName + "=" + json Dim response As String = "" Try Dim url as String = SECURE_API_URL Dim request As System.net.HttpWebRequest = System.net.WebRequest.Create(url) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "KsEeX0w61fBmGlR") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "test") Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As System.net.HttpWebResponse = request.GetResponse() Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() System.Console.WriteLine(strResponse) Catch ex As Exception Throw New Exception("failed to get token. " & ex.Message & vbCrLf & ex.StackTrace) End Try End Sub End Class
Data
jsonResponse's value (JSON [formatted for legibility] ):
{ "ack":"Success", "version":"1.0beta", "timestamp":"2015-01-14T17:05:23.000Z", "addFixedPriceItemResponse":{ "itemId":206013, "categoryId":163128, "sellingState":"Ready for sale", "message":null } }
Posting Request to Bonanza
Public Const API_URL As String = "https://api.bonanza.com/api_requests/secure_request" Private Shared Function BrowseURL(ByVal contentToPost As String) As String Try Dim request As Systemdot_net.HttpWebRequest = Systemdot_net.WebRequest.Create(API_URL) request.Headers.Add("X-BONANZLE-API-DEV-NAME", "YOUR-DEVELOPER-KEY-HERE") request.Headers.Add("X-BONANZLE-API-CERT-NAME", "YOUR-CERT-KEY-HERE") Systemdot_net.ServicePointManager.ServerCertificateValidationCallback = New Net.Security.RemoteCertificateValidationCallback(AddressOf CertificateValidationCallBack) Dim contentBytes() As Byte = System.Text.Encoding.UTF8.GetBytes(contentToPost) request.Method = "POST" request.ContentLength = contentBytes.Length 'request.ContentType = "application/json" Dim requestStream As System.IO.Stream = request.GetRequestStream() requestStream.Write(contentBytes, 0, contentBytes.Length) requestStream.Close() Dim response As Systemdot_net.HttpWebResponse = request.GetResponse() ' Read the response into a StreamReader Dim responseReader As IO.StreamReader = New IO.StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8) Dim strResponse As String = responseReader.ReadToEnd() 'Trace.WriteLine(strResponse) Return strResponse Catch ex As Exception Trace.WriteLine("Failed to call Bonanza with content " & contentToPost & ", " & ex.Message & vbCrLf & ex.StackTrace) Throw End Try End Function Private Shared Function CertificateValidationCallBack(ByVal sender As Object, ByVal certificate As System.Security.Cryptography.X509Certificates.X509Certificate, ByVal chain As System.Security.Cryptography.X509Certificates.X509Chain, ByVal sslPolicyErrors As Systemdot_net.Security.SslPolicyErrors) As Boolean Return True End Function
Fetch Token Request
Dim contentToPost As String = "fetchTokenRequest={""validationCompleteURL"":""" & System.Web.HttpUtility.UrlEncode(returnURL) & """}" Dim response As String = "" Try response = BrowseURL(contentToPost) Catch ex As Exception Throw New Exception("failed to get token. " & ex.Message & vbCrLf & ex.StackTrace) End Try
And in response you have JSON string from server.
Using JSON library
You can use the JSON library (http://json.codeplex.com/) to convert JSON text into objects. First, you need to add this class in your code which declares many classes used in the API.
Imports System.Runtime.Serialization Namespace Bonanza #Region "Base Class" <DataContract()> _ Public Class ResponseBaseclass <DataMember()> Public timeStamp As DateTime <DataMember()> Public version As String = "" <DataMember()> Public ack As String = "" <DataMember()> Public errorMessage As errorMessage End Class #End Region <DataContract()> _ Public NotInheritable Class errorMessage <DataMember()> _ Public message As String = Nothing End Class #Region "Fetch Token Response " Public Class fetchTokenResponseType <DataMember()> Public authToken As String <DataMember()> Public authenticationURL As String <DataMember()> Public emailRecognized As Boolean <DataMember()> Public hardExpirationTime As DateTime End Class <DataContract()> _ Public Class fetchTokenResponse Inherits ResponseBaseClass <DataMember()> Public fetchTokenResponse As fetchTokenResponseType End Class #End Region #Region "GetTokenStatus" Public Class getTokenStatusResponseType <DataMember()> Public hardExpirationTime As DateTime <DataMember()> Public verified As Boolean End Class <DataContract()> _ Public Class getTokenStatusResponse Inherits ResponseBaseclass <DataMember()> Public getTokenStatusResponse As New getTokenStatusResponseType End Class #End Region #Region "Request Base Class" <DataContract()> _ Public Class requesterCredentialsType <DataMember()> Public bonanzleAuthToken As String = "" End Class <DataContract()> _ Public Class requesterCredentials <DataMember()> Public requesterCredentials As New requesterCredentialsType End Class #End Region #Region "getOrders" #Region "Order Request Type" <DataContract()> _ Public Class paginationInputType <DataMember()> Public entriesPerPage As Integer = 20 <DataMember()> Public pageNumber As Integer = 1 End Class Public Enum OrderStatusCodeType None = 0 active = 1 'The order is still in the cart and can be modified cancelled = 2 'Orders that have been cancelled inProcess = 3 'Bonanza is awaiting payment confirmation from the payment provider (Paypal, Google Checkout, Amazon, etc.). proposed = 4 'Offer has been proposed and is awaiting a response from the offer receiver shipped = 5 'Offer has been sold and marked by the seller as shipped sold = 6 'Offer has been sold but not yet marked by the seller as shipped Completed = 7 End Enum <DataContract()> _ Public Class getOrdersRequest Inherits requesterCredentials <DataMember()> Public paginationInput As New paginationInputType <DataMember()> Public createTimeFrom As DateTime = DateTime.MinValue <DataMember()> Public createTimeTo As DateTime = DateTime.MinValue <DataMember()> Public orderRole As String = "seller" <DataMember()> Public orderStatus As OrderStatusCodeType = OrderStatusCodeType.sold <DataMember()> Public soldTimeFrom As DateTime = DateTime.MinValue <DataMember()> Public soldTimeTo As DateTime = DateTime.MinValue <DataMember()> Public orderIDArray As Generic.List(Of Integer) End Class #End Region #Region "Order Response types" Public Enum checkoutStatusCodeType None = 0 Complete = 1 Pending = 2 Incomplete = 3 End Enum <DataContract()> _ Public Class checkoutStatusType <DataMember()> Public status As checkoutStatusCodeType End Class <DataContract()> _ Public Class paginationResultType <DataMember()> Public totalNumberOfEntries As Integer <DataMember()> Public totalNumberOfPages As Integer End Class <DataContract()> _ Public Class shippingDetailsType <DataMember()> Public insuranceFee As Decimal <DataMember()> Public amount As Decimal <DataMember()> Public servicesArray As Object End Class <DataContract()> _ Public Class buyerType <DataMember()> Public email As String = "" End Class <DataContract()> _ Public Class transactionType <DataMember()> Public finalValueFee As Decimal <DataMember()> Public providerID As String = "" <DataMember()> Public providerName As String = "" <DataMember()> Public buyer As buyerType End Class <DataContract()> _ Public Class transactionArrayType <DataMember()> Public transaction As transactionType End Class <DataContract()> _ Public Class shippingAddressType <DataMember()> Public name As String = "" <DataMember()> Public cityName As String = "" <DataMember()> Public country As String = "" <DataMember()> Public street1 As String = "" <DataMember()> Public addressID As Integer <DataMember()> Public street2 As String = "" <DataMember()> Public postalCode As String = "" <DataMember()> Public stateOrProvince As String = "" <DataMember()> Public countryName As String = "" End Class <DataContract()> _ Public Class itemType <DataMember()> Public price As Decimal <DataMember()> Public title As String = "" <DataMember()> Public quantity As Integer <DataMember()> Public itemID As String = "" <DataMember()> Public sellerInventoryID As String = "" <DataMember()> Public sku As String = "" End Class <DataContract()> _ Public Class itemArrayType <DataMember()> Public item As itemType End Class <DataContract()> _ Public Class orderType <DataMember()> Public amountPaid As Decimal <DataMember()> Public amountSaved As Decimal <DataMember()> Public buyerCheckoutMessage As String = "" <DataMember()> Public checkoutStatus As checkoutStatusType <DataMember()> Public orderID As Integer <DataMember()> Public total As Decimal <DataMember()> Public createdTime As DateTime <DataMember()> Public orderStatus As OrderStatusCodeType <DataMember()> Public creatingUserRole As String = "" <DataMember()> Public shippingDetails As shippingDetailsType <DataMember()> Public paidTime As DateTime <DataMember()> Public buyerUserId As Integer <DataMember()> Public shippedTime As DateTime <DataMember()> Public taxAmount As Decimal <DataMember()> Public subtotal As Decimal <DataMember()> Public shippingAddress As shippingAddressType <DataMember()> Public transactionArray As transactionArrayType <DataMember()> Public itemArray As Generic.List(Of itemArrayType) End Class <DataContract(Name:="order")> _ Public Class order <DataMember()> Public order As orderType End Class <DataContract()> _ Public Class getOrdersResponseType <DataMember()> Public orderArray As Generic.List(Of order) <DataMember()> Public paginationResult As paginationResultType <DataMember()> Public hasMoreOrders As Boolean <DataMember()> Public pageNumber As Integer End Class <DataContract()> _ Public Class getOrdersResponse Inherits ResponseBaseclass <DataMember()> Public getOrdersResponse As getOrdersResponseType End Class #End Region #End Region End Namespace
Once you have that, then you can use the following few code samples (and then I believe you can continue adding your own).
Fetch Token
Dim contentToPost As String = "fetchTokenRequest={""validationCompleteURL"":""" & System.Web.HttpUtility.UrlEncode(returnURL) & """}" Dim response As String = "" Try response = BrowseURL(contentToPost) Catch ex As Exception Throw New Exception("failed to get token. " & ex.Message & vbCrLf & ex.StackTrace) End Try Dim r1 As Bonanza.fetchTokenResponse = Nothing Try r1 = Newtonsoft.Json.JsonConvert.DeserializeObject(response, GetType(Bonanza.fetchTokenResponse)) Catch ex As Exception Throw New Exception("failed to deserialize the response. " & ex.Message) End Try If r1.ack.ToLower <> "success" Then Throw New Exception("Error in Fetch token. " & r1.errorMessage.message) End If System.Web.HttpContext.Current.Session("bonanzaToken") = r1.fetchTokenResponse.authToken System.Web.HttpContext.Current.Session("bonanzaTokenExpiresOn") = r1.fetchTokenResponse.hardExpirationTime Dim authenticationURL as String = r1.fetchTokenResponse.authenticationURL 'Redirect user to this authenticationURL so that he log in to Bonanza and authenticate
Get Token Status
Dim contentToPost As String = "getTokenStatus={""requesterCredentials"":{""bonanzleAuthToken"":""TOKEN_TO_VALIDATE_HERE""}}" Dim response As String = "" Try response = BrowseURL(contentToPost) Catch ex As Exception Throw New Exception("failed to call service. " & ex.Message & vbCrLf & ex.StackTrace) End Try Dim r1 As Bonanza.getTokenStatusResponse = Nothing Try r1 = Newtonsoft.Json.JsonConvert.DeserializeObject(response, GetType(Bonanza.getTokenStatusResponse)) Catch ex As Exception Throw New Exception("failed to deserialize the response. " & ex.Message) End Try If r1.ack.ToLower <> "success" Then Throw New Exception("Error in get token status. " & r1.errorMessage.message) End If 'Call Success, check for hardExpirationtime and verified bool here
List Orders
Dim t As New Bonanza.getOrdersRequest t.requesterCredentials = New Bonanza.requesterCredentialsType t.requesterCredentials.bonanzleAuthToken = "USER-TOKEN" t.orderStatus = Bonanza.OrderStatusCodeType.sold t.paginationInput.pageNumber = 1 Dim settings As New Newtonsoft.Json.JsonSerializerSettings settings.Formatting = Newtonsoft.Json.Formatting.Indented settings.DefaultValueHandling = Newtonsoft.Json.DefaultValueHandling.Ignore settings.NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore settings.Converters.Add(New Newtonsoft.Json.Converters.StringEnumConverter()) Dim contentToPost As String = Newtonsoft.Json.JsonConvert.SerializeObject(t, settings) contentToPost = "getOrdersRequest=" & contentToPost & "" Dim responseContent As String = "" Try responseContent = BrowseURL(contentToPost) Catch ex As Exception Throw New Exception("Failed to post request to Bonaza , " & ex.Message & vbCrLf & ex.StackTrace) End Try 'Deserialze the response... Dim response As Bonanza.getOrdersResponse = Nothing Try response = Newtonsoft.Json.JsonConvert.DeserializeObject(responseContent, GetType(Bonanza.getOrdersResponse), settings) Catch ex As Exception Throw New Exception("Failed to deserialize response. " & ex.Message & vbCrLf & responseContent) End Try If response.ack.ToLower <> "success" Then Throw New Exception("Error while fetching orders , Server Error: " & response.errorMessage.message) End If If response.getOrdersResponse Is Nothing Then Throw New Exception("Null response received for 'getOrdersResponse'") End If If response.getOrdersResponse.orderArray Is Nothing Then Throw New Exception("Null response received for 'getOrdersResponse.orderArray' for") End If For Each order As Bonanza.order In response.getOrdersResponse.orderArray 'Process Order Here Next