253 lines
11 KiB
VB.net
253 lines
11 KiB
VB.net
Imports System.Net.Http
|
|
Imports System.Web
|
|
Imports System
|
|
Imports Microsoft.AspNetCore.Authentication.Cookies
|
|
Imports Microsoft.AspNetCore.Builder
|
|
Imports Microsoft.AspNetCore.Hosting
|
|
Imports Microsoft.AspNetCore.Http
|
|
Imports Microsoft.Extensions.Configuration
|
|
Imports Microsoft.Extensions.DependencyInjection
|
|
Imports Microsoft.Extensions.Hosting
|
|
|
|
'Public Class Startup
|
|
' Public Sub New(ByVal configuration As IConfiguration)
|
|
' configuration = configuration
|
|
' End Sub
|
|
|
|
' Public ReadOnly Property Configuration As IConfiguration
|
|
|
|
' Public Sub ConfigureServices(ByVal services As IServiceCollection)
|
|
' services.Configure(Configuration)
|
|
|
|
' services.Configure(Of CookiePolicyOptions)(Function(options)
|
|
' options.CheckConsentNeeded = Function(context) True
|
|
' options.MinimumSameSitePolicy = SameSiteMode.None
|
|
' End Function)
|
|
' services.AddSession(Function(options)
|
|
' options.IdleTimeout = TimeSpan.FromSeconds(10)
|
|
' options.Cookie.HttpOnly = True
|
|
' options.Cookie.IsEssential = True
|
|
' End Function)
|
|
' services.AddAuthentication(Function(options)
|
|
' options.DefaultAuthenticateScheme = CookieAuthenticationDefaults.AuthenticationScheme
|
|
' options.DefaultSignInScheme = CookieAuthenticationDefaults.AuthenticationScheme
|
|
' options.DefaultChallengeScheme = "HMRC"
|
|
' End Function).AddCookie().AddOAuth("HMRC", Function(options)
|
|
' options.ClientId = Configuration("clientId")
|
|
' options.ClientSecret = Configuration("clientSecret")
|
|
' options.CallbackPath = New PathString(Configuration("oauthCallbackUri"))
|
|
' options.Scope.Add("hello")
|
|
' options.SaveTokens = True
|
|
' options.AuthorizationEndpoint = Configuration("uri") & "/oauth/authorize"
|
|
' options.TokenEndpoint = Configuration("uri") & "/oauth/token"
|
|
' End Function)
|
|
' services.AddRazorPages(Function(options)
|
|
' options.Conventions.AddPageRoute("/HelloWorld/Index", "")
|
|
' End Function)
|
|
' End Sub
|
|
|
|
' Public Sub Configure(ByVal app As IApplicationBuilder, ByVal env As IWebHostEnvironment)
|
|
' If env.IsDevelopment() Then
|
|
' app.UseDeveloperExceptionPage()
|
|
' Else
|
|
' app.UseExceptionHandler("/Error")
|
|
' app.UseHsts()
|
|
' End If
|
|
|
|
' app.UseHttpsRedirection()
|
|
' app.UseStaticFiles()
|
|
' app.UseRouting()
|
|
' app.UseAuthorization()
|
|
' app.UseAuthentication()
|
|
' app.UseSession()
|
|
' app.UseCookiePolicy()
|
|
' app.UseEndpoints(Function(endpoints)
|
|
' endpoints.MapRazorPages()
|
|
' endpoints.MapControllerRoute(name:="default", pattern:="{controller=HelloWorld}/{action=Index}")
|
|
' End Function)
|
|
' End Sub
|
|
'End Class
|
|
|
|
|
|
|
|
|
|
|
|
Public Class CHMRC
|
|
|
|
Shared Sub hmrcTEST()
|
|
'Dim client As HttpClient = HttpClientBuilder.create().build()
|
|
'Dim request As HttpGet = New HttpGet("https://test-api.service.hmrc.gov.uk/hello/world")
|
|
'request.addHeader("Accept", "application/vnd.hmrc.1.0+json")
|
|
'Dim response As HttpResponse = client.execute(request)
|
|
'Dim statusCode As Integer = response.getStatusLine().getStatusCode()
|
|
'Dim responseBody As String = EntityUtils.toString(response.getEntity())
|
|
|
|
|
|
Exit Sub
|
|
|
|
Debug.WriteLine("HMRC Start")
|
|
Dim oauth2 As Chilkat.OAuth2 = New Chilkat.OAuth2()
|
|
Dim success As Boolean
|
|
oauth2.ListenPort = 3017
|
|
oauth2.AuthorizationEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/authorize"
|
|
oauth2.TokenEndpoint = "https://test-api.service.hmrc.gov.uk/oauth/token"
|
|
oauth2.ClientId = "xybTOMaQWcuifeW5xnGggojlACWC"
|
|
oauth2.ClientSecret = "bf1cfb6e-1bcb-4282-b7a0-3d3ccb2b1dc1"
|
|
oauth2.Scope = "read:vat write:vat"
|
|
Dim url As String = oauth2.StartAuth()
|
|
|
|
If oauth2.LastMethodSuccess <> True Then
|
|
Debug.WriteLine(oauth2.LastErrorText)
|
|
Exit Sub
|
|
End If
|
|
|
|
Dim http As Chilkat.Http = New Chilkat.Http()
|
|
|
|
System.Diagnostics.Process.Start(url)
|
|
|
|
|
|
Dim numMsWaited As Integer = 0
|
|
|
|
|
|
While (numMsWaited < 120000) AndAlso (oauth2.AuthFlowState < 3)
|
|
oauth2.SleepMs(100)
|
|
numMsWaited = numMsWaited + 100
|
|
End While
|
|
' If there was no response from the browser within 30 seconds, then
|
|
' the AuthFlowState will be equal to 1 Or 2.
|
|
' 1: Waiting for Redirect. The OAuth2 background thread Is waiting to receive the redirect HTTP request from the browser.
|
|
' 2: Waiting for Final Response. The OAuth2 background thread Is waiting for the final access token response.
|
|
' In that case, cancel the background task started in the call to StartAuth.
|
|
|
|
If oauth2.AuthFlowState < 3 Then
|
|
oauth2.Cancel()
|
|
Debug.WriteLine("No response from the browser!")
|
|
Exit Sub
|
|
End If
|
|
|
|
Debug.WriteLine("HMRC here")
|
|
|
|
|
|
' Check the AuthFlowState to see if authorization was granted, denied, Or if some error occurred
|
|
' The possible AuthFlowState values are:
|
|
' 3 Completed with Success. The OAuth2 flow has completed, the background thread exited, And the successful JSON response Is available in AccessTokenResponse property.
|
|
' 4: Completed with Access Denied. The OAuth2 flow has completed, the background thread exited, And the error JSON Is available in AccessTokenResponse property.
|
|
' 5: Failed Prior To Completion. The OAuth2 flow failed To complete, the background thread exited, And the error information Is available in the FailureInfo property.
|
|
|
|
If oauth2.AuthFlowState = 5 Then
|
|
Debug.WriteLine("OAuth2 failed to complete.")
|
|
Debug.WriteLine(oauth2.FailureInfo)
|
|
Exit Sub
|
|
End If
|
|
|
|
If oauth2.AuthFlowState = 4 Then
|
|
Debug.WriteLine("OAuth2 authorization was denied.")
|
|
Debug.WriteLine(oauth2.AccessTokenResponse)
|
|
Exit Sub
|
|
End If
|
|
|
|
If oauth2.AuthFlowState <> 3 Then
|
|
Debug.WriteLine("Unexpected AuthFlowState:" & Convert.ToString(oauth2.AuthFlowState))
|
|
Exit Sub
|
|
End If
|
|
|
|
Debug.WriteLine("OAuth2 authorization granted!")
|
|
Debug.WriteLine("Access Token = " & oauth2.AccessToken)
|
|
Dim json As Chilkat.JsonObject = New Chilkat.JsonObject()
|
|
json.Load(oauth2.AccessTokenResponse)
|
|
json.EmitCompact = False
|
|
Debug.WriteLine(json.Emit())
|
|
|
|
|
|
' The JSON response looks Like this
|
|
|
|
' {
|
|
' "token_type": "Bearer",
|
|
' "scope": "user_impersonation",
|
|
' "expires_in": "3599",
|
|
' "ext_expires_in": "0",
|
|
' "expires_on": "1524783438",
|
|
' "not_before": "1524779538",
|
|
' "resource": "https://mydomain.api.crm.dynamics.com",
|
|
' "access_token": "...",
|
|
' "refresh_token": "...",
|
|
' "id_token": "..."
|
|
' }
|
|
|
|
' If an "expires_on" member does Not exist, then add the JSON member by
|
|
' getting the current system date/time And adding the "expires_in" seconds.
|
|
' This way we'll know when the token expires.
|
|
|
|
If json.HasMember("expires_on") <> True Then
|
|
Dim dtExpire As Chilkat.CkDateTime = New Chilkat.CkDateTime()
|
|
dtExpire.SetFromCurrentSystemTime()
|
|
dtExpire.AddSeconds(json.IntOf("expires_in"))
|
|
json.AppendString("expires_on", dtExpire.GetAsUnixTimeStr(False))
|
|
End If
|
|
|
|
Debug.WriteLine(json.Emit())
|
|
Dim fac As Chilkat.FileAccess = New Chilkat.FileAccess()
|
|
'fac.WriteEntireTextFile("qa_data/tokens/hmrc.json", json.Emit(), "utf-8", False)
|
|
fac.WriteEntireTextFile("C:\Users\DEVELOPER1\Desktop\hmrc.json", json.Emit(), "utf-8", False)
|
|
|
|
|
|
End Sub
|
|
|
|
Shared Sub VATTEST(hmrc_app_server_token)
|
|
|
|
Dim rest As New Chilkat.Rest
|
|
Dim success As Boolean
|
|
|
|
' URL: https://test-api.service.hmrc.gov.uk/organisations/vat/123456789/returns
|
|
Dim bTls As Boolean = True
|
|
Dim port As Integer = 443
|
|
Dim bAutoReconnect As Boolean = True
|
|
success = rest.Connect("test-api.service.hmrc.gov.uk", port, bTls, bAutoReconnect)
|
|
If (success <> True) Then
|
|
Debug.WriteLine("ConnectFailReason: " & rest.ConnectFailReason)
|
|
Debug.WriteLine(rest.LastErrorText)
|
|
Exit Sub
|
|
End If
|
|
|
|
|
|
' See the Online Tool for Generating JSON Creation Code
|
|
Dim json As New Chilkat.JsonObject
|
|
json.UpdateString("periodKey", "#001")
|
|
json.UpdateNumber("vatDueSales", "100.00")
|
|
json.UpdateNumber("vatDueAcquisitions", "100.00")
|
|
json.UpdateNumber("totalVatDue", "200")
|
|
json.UpdateNumber("vatReclaimedCurrPeriod", "100.00")
|
|
json.UpdateNumber("netVatDue", "100")
|
|
json.UpdateNumber("totalValueSalesExVAT", "500")
|
|
json.UpdateNumber("totalValuePurchasesExVAT", "500")
|
|
json.UpdateNumber("totalValueGoodsSuppliedExVAT", "500")
|
|
json.UpdateNumber("totalAcquisitionsExVAT", "500")
|
|
json.UpdateBool("finalised", True)
|
|
|
|
rest.AddHeader("Content-Type", "application/json")
|
|
rest.AddHeader("Authorization", "Bearer " & hmrc_app_server_token)
|
|
rest.AddHeader("Accept", "application/vnd.hmrc.1.0+json")
|
|
|
|
Dim sbRequestBody As New Chilkat.StringBuilder
|
|
json.EmitSb(sbRequestBody)
|
|
Dim sbResponseBody As New Chilkat.StringBuilder
|
|
success = rest.FullRequestSb("POST", "/organisations/vat/123456789/returns", sbRequestBody, sbResponseBody)
|
|
If (success <> True) Then
|
|
Debug.WriteLine(rest.LastErrorText)
|
|
Exit Sub
|
|
End If
|
|
|
|
Dim respStatusCode As Integer = rest.ResponseStatusCode
|
|
If (respStatusCode >= 400) Then
|
|
Debug.WriteLine("Response Status Code = " & respStatusCode)
|
|
Debug.WriteLine("Response Header:")
|
|
Debug.WriteLine(rest.ResponseHeader)
|
|
Debug.WriteLine("Response Body:")
|
|
Debug.WriteLine(sbResponseBody.GetAsString())
|
|
Exit Sub
|
|
End If
|
|
|
|
|
|
End Sub
|
|
End Class
|