How to obtain Access Token using production environment in DocuSign? - vb.net

In Docusing I am obtained access token with demo account successfully and create envelope also, when I move to production account, I can't get access token and got error as "The remote server returned an error: (400) Bad Request." I did 20 API calls successfully and reviewed and make Go to live from developer account, API key details reflects on production login also.
Old Code
This is the code I used to obtain access token.
Dim PrivateKey As String = odjDTRep.Rows(0)("PrivateKey").ToString().Trim.Replace(vbLf, "").Replace(vbCr, "")
'This section to generate jwt Header
Dim ar1 As JObject = New JObject()
ar1.Add("typ", "JWT")
ar1.Add("alg", "RS256")
Dim header As String = Base64UrlEncoder.Encode(ar1.ToString)
'This section to generate jwt Body
Dim ar2 As JObject = New JObject()
ar2.Add("iss", odjDTRep.Rows(0)("iss_Int_Key").ToString())
ar2.Add("sub", odjDTRep.Rows(0)("sub1_Api_UserName").ToString())
ar2.Add("iat", DateDiff(DateInterval.Second, New Date(1970, 1, 1), Now().ToUniversalTime))
ar2.Add("exp", DateDiff(DateInterval.Second, New Date(1970, 1, 1), DateAdd(DateInterval.Hour, 1, Now().ToUniversalTime)))
ar2.Add("aud", odjDTRep.Rows(0)("aud").ToString())' aud i pass account.docusign.com
ar2.Add("scope", odjDTRep.Rows(0)("scope").ToString())
Dim body As String = Base64UrlEncoder.Encode(ar2.ToString)
Dim stringToSign As String = header & "." & body
Dim bytesToSign() As Byte = Encoding.UTF8.GetBytes(stringToSign)
Dim keyBytes() As Byte = Convert.FromBase64String(PrivateKey)
Dim privKeyObj = Asn1Object.FromByteArray(keyBytes)
Dim privStruct = RsaPrivateKeyStructure.GetInstance(privKeyObj)
'This section to generate jwt Signature
Dim sig As ISigner = SignerUtilities.GetSigner("SHA256withRSA")
sig.Init(True, New RsaKeyParameters(True, privStruct.Modulus, privStruct.PrivateExponent))
sig.BlockUpdate(bytesToSign, 0, bytesToSign.Length)
Dim signature() As Byte = sig.GenerateSignature()
Dim sign As String = Base64UrlEncoder.Encode(signature)
Dim a As String = header & "." & body & "." & sign
ServicePointManager.Expect100Continue = True
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls
ServicePointManager.SecurityProtocol = DirectCast(3072, SecurityProtocolType)
ServicePointManager.Expect100Continue = True
Dim request As WebRequest = WebRequest.Create("https://account.docusign.com/oauth/token?grant_type=urn:ietf:params:oauth:grant-type:jwt-bearer&assertion=" & a & "")
request.Method = "POST"
request.ContentType = "application/x-www-form-urlencoded"
request.ContentLength = 0
request.Headers.Add("X-DocuSign-Authentication", "{ ""Username"":""" & odjDTRep.Rows(0)("UserName").ToString() & """, ""Password"":""" & odjDTRep.Rows(0)("Password").ToString() & """, ""IntegratorKey"":""" & odjDTRep.Rows(0)("iss_Int_Key").ToString() & """ }")
Dim response As WebResponse = request.GetResponse()
Console.WriteLine((CType(response, HttpWebResponse)).StatusCode)
If (CType(response, HttpWebResponse)).StatusCode <> HttpStatusCode.OK Then
Return "002:Fail"
End If
Dim dataStream As Stream = response.GetResponseStream()
Dim reader As New StreamReader(dataStream)
Dim responseFromServer As String = reader.ReadToEnd()
reader.Close()
response.Close()
All details I read from SQL table and store in DataTable, from DataTable I pass all details in that code. Any other URL I need change above I mention for production environment?
New code to obtain Access token
var apiCent = new ApiClient("https://demo.docusign.net/restapi");
string ik = "xxxx-6a8b-4a7d-ba0f-xxxx";
string userId = "xxxxx-db97-xxx-a398-0e5986fadf49";
string accountId = "xxxxx-3e10-42af-xxxxx-xxxx";
string envId = "";
string authserver = "account.docusign.com";
string rsaKey = "xxxxxxxxxi7+b8i7SmfRdx8sExxxxxxxKmwIbLFOv1LtmUk/KRP8wPmMeNpq10kAzizzAeqnuBgW9ECHjV/gUA984dzk128UPmIRqTW+69e1dSknGA+nJWshyZEqJXmvFB8Ueie5EiCW6FIlXpdLVWwmJwUGiQQsV+r8hpmbhSImr5A40HQPPpasYAnKPNDgRbKwxrOONrCdUUre34Up2sk8gcAcMQRwKosPBn6/dAXadYP0sKEGSVKogguNSCyoHOLh74MPepDLnEVs9VAiyk+zQEmZxYaXhrV4pvO2C5WNXdnqHUdcC/McZOBVGwRdG0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Bq5JODGgfN9GbLpPR6KyCtUGPhIrcSyZF00PcIEckwwt1XvqFJXFzFWCs9SEq7YbmGKuxSVZ7NLOOLaX6lZ3HdBiHvqcsCdMiqw9egTqqkn2po7pGCQzwxYmGLBfF+MXDo3KTynvNMz31efrZlmQsVq3VBt9U=";
var scopes = new List<string>
{
"signature"
};
OAuth.OAuthToken authToken = apiCent.RequestJWTUserToken(ik, userId, authserver,Encoding.UTF8.GetBytes(rsaKey), 1, scopes);
string accessToken = authToken.access_token;
Now i am getting error as "Unexpected PEM type" , in production account i take IK,UserID and generated new RSA key.

First off, using legacy auth is not allowed for new applications. You are using the X-DocuSign-Authentication header with clear text password which is a legacy mechanism to authenticate. It is insecure and cannot be used.
When using JWT authentication and changing from the developer environment to the production environment you have to do the following:
Pass go-live and get approval to have your IK (app) in production.
Promote your IK to your production account.
Create a new RSA key for the new IK in the production account. You cannot use the RSA key from your developer account.
The URL for authentication is changed from https://account-s.docusign.com to https://account.docusign.com
userId for the user will be different GUID - need to update
accountId for the account will be different GUID - need to update

Related

Can we call JSON POST API from VB.NET Windows App?

Here I am always getting "The remote server returned an error: (500) Internal Server Error.". Even the API is correct and working nicely through POSTMAN and in other languages also. Please guide me so solve this issue. I am attaching the function which is calling the API directly.
Private Function SendRequest() As String
Dim response As String
Dim request As WebRequest
Dim encoding As New System.Text.ASCIIEncoding
Dim uri = ""
Dim Tran = "15"
Dim Amount As Integer = 1000
Dim ReferenceID = "015bfa15-15ec-4dc7-903c-053ffacb6688"
Dim POS = "57290070"
Dim Store = "RESTSIM00000001"
Dim Chain = "J#P-Reg"
Dim JSONString = "{""tran"":""" & Tran & """,""amount"":""" & Amount & """,""reference"":""" & ReferenceID & """,""pos"":""" & POS & """,""store"":""" & Store & """,""chain"":""" & Chain & """}"
Dim jsonDataBytes() As Byte = encoding.GetBytes(JsonConvert.SerializeObject(JSONString))
request = WebRequest.Create(uri)
request.ContentLength = jsonDataBytes.Length
request.ContentType = "application/json"
request.Method = "POST"
Using requestStream = request.GetRequestStream
requestStream.Write(jsonDataBytes, 0, jsonDataBytes.Length)
requestStream.Close()
Using responseStream = request.GetResponse.GetResponseStream
Using reader As New StreamReader(responseStream)
response = reader.ReadToEnd()
End Using
End Using
End Using
Return response
End Function

error 'The given key was not present in the dictionary' when trying to API HTTP request token with Blue Prism

Im trying to use the Blue Prism object HTTP request to get an access token for further processing the items. However, i couldn't manage to get the token due to the error 'The given key was not present in the dictionary'. I have looked all parameters and still didn't manage to solve the issue. I use a built in visual basic code to get the result as a collection which is later parsed to JSON to get the token.
The underlying visual basic code is:
Dim request As WebRequest = WebRequest.Create(addressURL)
If forcePreAuth Then
'Sometimes a web server will require the authorisation header in the initial request
'In which case we have to add the basic authorization header manually.
Dim bytes() As Byte = System.Text.Encoding.UTF8.GetBytes(String.Format("{0}:{1}",username,password))
Dim base64 As String = Convert.ToBase64String(bytes)
request.Headers.Add("Authorization", "Basic " & base64)
Else
If Not String.IsNullOrEmpty(username) AndAlso Not String.IsNullOrEmpty(password) Then
request.Credentials = New NetworkCredential(username,password)
End If
End If
If useProxy Then
Dim proxyURI As New Uri(proxyURL)
Dim proxy As New WebProxy(proxyURI, True)
Dim proxyCred As New NetworkCredential(proxyUsername, proxyPassword)
Dim credCache As New CredentialCache()
credCache.Add(proxyURI, "Basic", proxyCred)
proxy.UseDefaultCredentials = False
proxy.Credentials = credCache
request.Proxy = proxy
End If
request.Method = method
request.ContentType = contentType
Dim httpRequest As HttpWebRequest = TryCast(request, HttpWebRequest)
If httpRequest IsNot Nothing Then
If Not String.IsNullOrEmpty(accept) Then
httpRequest.Accept = accept
End If
If Not String.IsNullOrEmpty(certID) Then
httpRequest.ClientCertificates.Add(m_Certificates(certID))
End If
End If
For Each r As DataRow In headers.Rows
For Each c As DataColumn In headers.Columns
Dim columnName As String = c.ColumnName
Dim val As String = r(columnName).ToString
request.Headers.Add(columnName,val)
Next
Exit For 'Only one row is allowed
Next
If Not String.IsNullOrEmpty(body) Then
Dim requestStream As IO.Stream = request.GetRequestStream()
Using sw As New IO.StreamWriter(requestStream, New Text.UTF8Encoding(False))
sw.Write(body)
End Using
End If
Using response As WebResponse = request.GetResponse()
Dim responseStream As IO.Stream = response.GetResponseStream()
Dim sr As New IO.StreamReader(responseStream)
resultData = sr.ReadToEnd()
End Using
Screenshots:
Input parameter
Input parameter request token
Request token:
Output parameter:
Blue Prism uses a bit of a peculiar pattern regarding Certificates. The way the Utility - HTTP object is designed is to allow for the loading of certificate files (.cer, etc) on-the-fly into a local Certificate Store, which assigns a new Certificate ID each time.
Before firing your HTTP Request, use the Load Certificate action within the same Utility - HTTP object to output a valid Certificate ID, which you can then pass to HTTP Request's Certificate ID parameter.

RestSharp response forbidden

I trying get a simple request to https://c-cex.com/t/prices.json
If i use this url in browser the correct response is showed , but if i make the same request using RestRequest i receive the 403 error Forbidden in all times. i trying HttpClient,WebRequest i get the same error
I put the header with user-agent, no cache and a lot of another values but did not work
Any ideas about this problem?
Dim url As String = "https://c-cex.com/t/prices.json"
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
Dim response = client.Execute(request)
Updated code with apisign request
Dim nonce As String = CInt((DateTime.UtcNow - New DateTime(1970, 1, 1)).TotalSeconds).ToString
Dim url As String = "https://c-cex.com/t/api.html?a=getbalance&currency=BTC&apikey=" & API_KEY & "&nonce=" & nonce
Dim keybytes() = UnicodeEncoding.ASCII.GetBytes(API_SECRET)
Dim hs As System.Security.Cryptography.HMACSHA512 = New System.Security.Cryptography.HMACSHA512(keybytes)
Dim urlbytes() = UnicodeEncoding.ASCII.GetBytes(url)
Dim sh() = hs.ComputeHash(urlbytes)
Dim client As New RestSharp.RestClient(url)
Dim request = New RestRequest(url, Method.GET)
request.AddHeader("Cache-Control", "no-cache")
request.AddHeader("apisign", HttpUtility.UrlEncode(ToHexString(sh)))
Dim response = client.Execute(request)
I am getting the response without providing the header information and It looks given piece of code is working correctly for me in VB and C#.As a best practice, base URL needs to be specified in RestClient and relative URL in RestRequest.
Please recheck without adding the request header information
VB:
Imports RestSharp
Module Module1
Sub Main()
Dim host As String = "https://c-cex.com"
Dim endpoit As String = "t/prices.json"
Dim client As New RestSharp.RestClient(host)
Dim request = New RestRequest(endpoit, Method.GET)
Dim response = client.Execute(request)
Console.WriteLine("Response Body " + response.Content)
Console.WriteLine("Response Code " + response.StatusDescription)
End Sub
End Module
C#:
String host = "https://c-cex.com";
String endpoint = "t/prices.json";
RestClient _restClient = new RestClient(host);
var request = new RestRequest(endpoint, Method.GET);
var response = _restClient.Execute(request);
Console.WriteLine("Response Body :"+response.Content);
Console.WriteLine("Response Status Code :" + response.StatusDescription);

Trying to request access token from Google oauth2

i'am trying to get started with dealing googles oauth2
My application vill be so called server application. it should be workin wihtout user input. My code so far(only trying to get access token):
Dim strToken = Request.QueryString("code")
Dim strExchange = "response_type=code"
strExchange += "&redirect_uri=http://xxxx.zzzzz.com/test/google.aspx"
strExchange += "&client_id=xxxx7hju.apps.googleusercontent.com"
strExchange += "&scope=&"
strExchange += "client_secret=yJpGI1yQBCvvxxxxx&grant_type=authorization_code"
Dim url = "https://accounts.google.com/o/oauth2/auth?"
Dim webClient As New System.Net.WebClient
Dim result As String = webClient.DownloadString(url & strExchange)
Response.Write(result)
This gives me bad reguest (400)
You can try this Article which handles the google calender entries. their you are able to get proper documentation for oauth2.0 authentication technique. Hope that all the values ware taken from App.Config
clientId = ConfigurationManager.AppSettings("client_id").ToString
clientSecret = ConfigurationManager.AppSettings("client_secret").ToString
redirecturi = ConfigurationManager.AppSettings("redirect").ToString
mainUser = ConfigurationManager.AppSettings("mainuser").ToString
Public Sub authorize()
Dim Uri As String = "https://accounts.google.com/o/oauth2/auth?access_type=offline&response_type=code&client_id=" & clientId & "&redirect_uri=" & redirecturi & "&scope=https://www.googleapis.com/auth/calendar&login_hint=" & mainUser & "&include_granted_scopes=true"
Response.Redirect(Uri)
End Sub

PayPal IPN issue for notify

I have set up a PDT form and that is working and collecting payments and then returning to the appropriate url with the follow parameters
tx=1******X&st=Completed&amt=0.02&cc=GBP&cm=&item_number=NA
I am using the follow example code:
Dim strSandbox As String = "https://www.sandbox.paypal.com/cgi-bin/webscr"
Dim strLive As String = "https://www.paypal.com/cgi-bin/webscr"
Dim req As HttpWebRequest = CType(WebRequest.Create(strLive), HttpWebRequest)
'Set values for the request back
req.Method = "POST"
req.ContentType = "application/x-www-form-urlencoded"
Dim Param() As Byte = Request.BinaryRead(HttpContext.Current.Request.ContentLength)
Dim strRequest As String = Encoding.ASCII.GetString(Param)
strRequest = strRequest & "&cmd=_notify-validate"
req.ContentLength = strRequest.Length
'for proxy
'Dim proxy As New WebProxy(New System.Uri("http://url:port#"))
'req.Proxy = proxy
'Send the request to PayPal and get the response
Dim streamOut As StreamWriter = New StreamWriter(req.GetRequestStream(), Encoding.ASCII)
streamOut.Write(strRequest)
streamOut.Close()
Dim streamIn As StreamReader = New StreamReader(req.GetResponse().GetResponseStream())
Dim strResponse As String = streamIn.ReadToEnd()
streamIn.Close()
If strResponse = "VERIFIED" Then
'check the payment_status is Completed
'check that txn_id has not been previously processed
'check that receiver_email is your Primary PayPal email
'check that payment_amount/payment_currency are correct
'process payment
lit1.Text = "verified"
ElseIf strResponse = "INVALID" Then
'log for manual investigation
lit1.Text = "invalid"
Else
'Response wasn't VERIFIED or INVALID, log for manual investigation
lit1.Text = "unknown"
End If
lit1.Text = lit1.Text & "<br /><br />" & strRequest.ToString
I am only getting an invalid response so I tried to see what was being sent to Paypal but its only sending &cmd=_notify-validate and not rest of the parameters.
So I manually added to the parameters but still only got invalid.
Could someone please assist with what I am missing? The payment was successful
Thanks
I sorted it, I didnt understand the process but do now