Payment with REST API

I’m using Braintree payment gateway and having issues when tying to make a payment through REST API. I am calling carts/mine/payment-information endpoint with following values.

Header:

Authorization: Bearer customer-token Content-type: application/json 

Body:

{   "paymentMethod": {     "po_number": "",     "method": "braintree",     "additional_data":{          "cc_last4":"1111",          "store_in_vault":true,          "payment_method_nonce":"nonce-goes-here",          "cc_token":"",          "device_data":"",          "cc_type":"Visa",          "cc_exp_year":"2055",          "cc_exp_month":"01"      },     "extension_attributes": {       "agreement_ids": [         "string"       ]     }   },   "billingAddress": {     "id": 0,     "region": "Victoria",     "region_id": 546,     "region_code": "VIC",     "country_id": "AU",     "street": [       "Main St"     ],     "company": "Company Name",     "telephone": "987654321",     "fax": "",     "postcode": "3000",     "city": "Melbourne",     "firstname": "Firstname",     "lastname": "Lastname",     "middlename": "Middlename",     "prefix": "Mr",     "suffix": "",     "vat_id": "",     "customer_id": 0,     "email": "name@domain.name",     "same_as_billing": 0,     "customer_address_id": 0,     "save_in_address_book": 0,     "extension_attributes": {},     "custom_attributes": {}   } }  

I have generated a braintree token and used that token to generate the nonce. With the use of nonce, I was able to create a Braintree transaction as below.

   $  result = Braintree_Transaction::sale([         'amount' => $  transactionAmount,         'paymentMethodNonce' => $  nonceFromTheClient,         'options' => [             'submitForSettlement' => True         ]     ]); 

The transaction gets successful but when I try to place an order on Magento using my transaction details, I keep getting the following error.

Transaction has been declined. Please try again later

Can anyone advise me what’s wrong with my process/ request please?

Thanks!

Check if a user is a member of SharePoint group JS REST API using async await

How can I check if the current user is a member of a specific SP Group using REST API and async/await?

_spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getbyname('" + grpName + "')/CanCurrentUserViewMembership";

here’s my code but it doesn’t work and want to use async/await but how?

$  (document).ready(function() {     ExecuteOrDelayUntilScriptLoaded(showAlert, "sp.js"); });  function showAlert() {      if(isMember('Viewers') && !isMember('Owners'))         alert('Viewers'); //current user is part of the Viewers group }  function isMember(grpName) {     var _ismember = false;     var siteUrl = _spPageContextInfo.webAbsoluteUrl + "/_api/web/sitegroups/getbyname('" + grpName + "')/CanCurrentUserViewMembership";      $  .ajax({         url: siteUrl,         method: "GET",         headers: { "accept": "application/json;odata=verbose"},         success: function (data) {             console.log(data);             if(data.d.CanCurrentUserViewMembership != null) {                 return data.d.CanCurrentUserViewMembership;              }            },         error: function (error) {}     }); } 

UPDATE: ok so I managed to convert this to async/await, my next question is, how can I compare the two data returned (true/false) by the API?

isMember('Viewers')         .then(data => console.log(data.d.CanCurrentUserViewMembership + ' viewers'))         .then(             isMember('Owners')             .then(data => console.log(data.d.CanCurrentUserViewMembership + ' owners'))) 

what I want to do is if Viewers = true; and Owners = false, then I will show an alert (because I want to only show an alert if the user is a member of the Viewers group only, but if a user is a member of Viewers AND Owners, no alert should be shown)

Django REST Swagger – Gera 2 metodos GET

Estou implementando uma API REST com Django REST Swagger 2.2.0.

Para um determinado endpoint defini que esteja disponível os seguintes métodos:

http_method_names = ['post', 'put', 'get'] 

Porém, no swagger, aparece 2 versões para o método GET:

1 - http://dominio/nome_metodo 2 - http://dominio/nome_metodo/{id} 

Como faço para que o Swagger oculte o método 2?

SharePoint REST API – HTTP/1.1 500 Internal Server Error – Configuration

I am connecting to SharePoint to query lists, all was well but now I get a HTTP/1.1 500 Internal Server Error for the same request which was ok and tested. I guess the problem is from a configuration.

The response I get is

The Web application at http://hostname:80/my/personal/incorta/_api/web/lists could not be found. Verify that you have typed the URL correctly. If the URL should be serving existing content, the system administrator may need to add a new request URL mapping to the intended application.

my code

    CredentialsProvider credsProvider = new BasicCredentialsProvider();           credsProvider.setCredentials(             new AuthScope(AuthScope.ANY),             new NTCredentials("USERNAME", "PASSWORD", "https://HOSTNAME", "DOMAIN"));      CloseableHttpClient httpclient = HttpClients.custom()             .setDefaultCredentialsProvider(credsProvider)             .build();      try {         HttpGet httpget = new HttpGet("http://hostname/_api/web/lists");         httpget.setHeader("Accept", "application/json;odata=verbose");          System.out.println("Executing request " + httpget.getRequestLine());         CloseableHttpResponse response = httpclient.execute(httpget);          try {             System.out.println("----------------------------------------");             System.out.println(response.getStatusLine());                          BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));              StringBuffer result = new StringBuffer();             String line = "";             while ((line = rd.readLine()) != null) {                 result.append(line);             }              System.out.println(result);              EntityUtils.consume(response.getEntity());         } finally {             response.close();         }     } finally {         httpclient.close();     }    

System.UnauthorizedAccessException when accessing the SharePoint 2013 REST API

When I try to load AJAX scripts into private site it runs with any problems, but when I do public site I have AccessException, I read a lot of it, and I found this link, where have same problem and found solution setting Barer. But I don´t know where I set barer, someone can help me where I should copy method of the solution given in link?

There is my js:

function MenuPopulate(url, listname, target) {     var lang = "Espanol";     if ((window.location.href.indexOf("lang=en") > 0)) {         lang = "English";     }     // Getting our list items     $  .ajax({         url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$  select=Title,Enlace&$  orderby=Posicion&$  top=6&$  filter=Idioma eq '" + lang + "'",         method: "GET",         crossDomain: true,         headers: { "Accept": "application/json; odata=verbose",          "X-RequestDigest": $  ("__REQUESTDIGEST").val() },          contentType: "application/json;charset=utf-8",         success: function (data) {             completeMenu(data, target);         },         error: function (data) {             failureMenu(data, target);         }     }); } 

So first I think I should only add function like:

SharePointContextToken ContextToken = TokenHelper.ReadAndValidateContextToken(ContextTokenString, Request.Url.Authority);                  Uri sharepointUrl = new Uri(Request.QueryString["SPHostUrl"]);                  //Get the AccessToken                 string AccessToken = TokenHelper.GetAccessToken(ContextToken,sharepointUrl.Authority).AccessToken;                  HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(@"https://mysite-public.sharepoint.com/_api/web/lists");                 request.Method = "GET";                 request.Accept = "application/json;odata=verbose";                 request.Headers.Add("Authorization", "Bearer " + AccessToken);                  HttpWebResponse response =(HttpWebResponse)request.GetResponse();                 StreamReader reader = new StreamReader(response.GetResponseStream());   function MenuPopulate(url, listname, target) {     var lang = "Espanol";     if ((window.location.href.indexOf("lang=en") > 0)) {         lang = "English";     }     // Getting our list items     $  .ajax({         url: url + "/_api/web/lists/getbytitle('" + listname + "')/items?$  select=Title,Enlace&$  orderby=Posicion&$  top=6&$  filter=Idioma eq '" + lang + "'",         method: "GET",         crossDomain: true,         headers: { "Accept": "application/json; odata=verbose",          "X-RequestDigest": $  ("__REQUESTDIGEST").val() },          contentType: "application/json;charset=utf-8",         success: function (data) {             completeMenu(data, target);         },         error: function (data) {             failureMenu(data, target);         }     }); } 

This isn’t working, can anyone help me there?

Encrypts using AES GCM for data with limited visibility and long rest

This is the third iteration of my venture on creating an encryption/decryption solution. I asked a question here, which led to this question here, which led to this answer here, which led me to introducing Bouncy Castle into my solution to gain better security under the circumstances and application requirements.

Requirements: To encrypt and decrypt a string using AES 256 with a password/key (stored in web.config) in an ASP.net application.

History: If you follow the above links you’ll find that I originally tried to stick with the core .net provided solutions without the inclusion of any additional libraries. This requirement has changed and I’ve added Bouncy Castle to my solution.

Thanks to @SEJPM regularly pointing me in the right direction I decided to implement AES GCM and ditch my previous attempts.

I found this example here from @jbtule who seems to have a pretty good handle on things, and honestly I didn’t change a thing other than convert it to VB. However, based on previous suggestions given to me to use Argon2, I read that Bouncy Castle supports this now but I’m currently uncertain as how to properly implement it.

Although my code is essentially a copy @jbtule’s original post on CodeReview, that was 6 years ago.

So based on the fact that I pull the encryption key/pass from web.config and I need simple encrypt/decrypt, how does this solution stack up?

Usage:

Dim password = RetrieveFromWebConfig() Dim plainText = "Hello World" Dim encrypted = SimpleEncryptWithPassword(plainText, password) Dim decrypted = SimpleDecryptWithPassword(encrypted, password) 

Code:

Imports System Imports System.IO Imports System.Text Imports Org.BouncyCastle.Crypto Imports Org.BouncyCastle.Crypto.Engines Imports Org.BouncyCastle.Crypto.Generators Imports Org.BouncyCastle.Crypto.Modes Imports Org.BouncyCastle.Crypto.Parameters Imports Org.BouncyCastle.Security  Namespace Utilities.Encryption     Public Class Aesgcm         Public Shared ReadOnly Random As SecureRandom = New SecureRandom()         Public Shared ReadOnly NonceBitSize As Integer = 128         Public Shared ReadOnly MacBitSize As Integer = 128         Public Shared ReadOnly KeyBitSize As Integer = 256         Public Shared ReadOnly SaltBitSize As Integer = 128         Public Shared ReadOnly Iterations As Integer = 10000         Public Shared ReadOnly MinPasswordLength As Integer = 12           Shared Function SimpleEncryptWithPassword(secretMessage As String, password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As String             If String.IsNullOrEmpty(secretMessage) Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             Dim plainText = Encoding.UTF8.GetBytes(secretMessage)             Dim cipherText = SimpleEncryptWithPassword(plainText, password, nonSecretPayload)             Return Convert.ToBase64String(cipherText)         End Function          Shared Function SimpleDecryptWithPassword(encryptedMessage As String, password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As String             If String.IsNullOrWhiteSpace(encryptedMessage) Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")             Dim cipherText = Convert.FromBase64String(encryptedMessage)             Dim plainText = SimpleDecryptWithPassword(cipherText, password, nonSecretPayloadLength)             Return If(plainText Is Nothing, Nothing, Encoding.UTF8.GetString(plainText))         End Function          Shared Function SimpleEncrypt(secretMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte()             If key Is Nothing OrElse key.Length <> KeyBitSize / 8 Then Throw New ArgumentException($  "Key needs to be {KeyBitSize} bit!", "key")             If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             nonSecretPayload = If(nonSecretPayload, New Byte() {})             Dim nonce = New Byte(CInt(NonceBitSize / 8 - 1)) {}             Random.NextBytes(nonce, 0, nonce.Length)             Dim cipher = New GcmBlockCipher(New AesEngine())             Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload)             cipher.Init(True, parameters)             Dim cipherText = New Byte(cipher.GetOutputSize(secretMessage.Length) - 1) {}             Dim len = cipher.ProcessBytes(secretMessage, 0, secretMessage.Length, cipherText, 0)             cipher.DoFinal(cipherText, len)              Using combinedStream = New MemoryStream()                  Using binaryWriter = New BinaryWriter(combinedStream)                     binaryWriter.Write(nonSecretPayload)                     binaryWriter.Write(nonce)                     binaryWriter.Write(cipherText)                 End Using                  Return combinedStream.ToArray()             End Using         End Function          Shared Function SimpleDecrypt(encryptedMessage As Byte(), key As Byte(), ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte()             If key Is Nothing OrElse key.Length <> KeyBitSize / 8 Then Throw New ArgumentException($  "Key needs to be {KeyBitSize} bit!", "key")             If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")              Using cipherStream = New MemoryStream(encryptedMessage)                  Using cipherReader = New BinaryReader(cipherStream)                     Dim nonSecretPayload = cipherReader.ReadBytes(nonSecretPayloadLength)                     Dim nonce = cipherReader.ReadBytes(CInt(NonceBitSize / 8))                     Dim cipher = New GcmBlockCipher(New AesEngine())                     Dim parameters = New AeadParameters(New KeyParameter(key), MacBitSize, nonce, nonSecretPayload)                     cipher.Init(False, parameters)                     Dim cipherText = cipherReader.ReadBytes(encryptedMessage.Length - nonSecretPayloadLength - nonce.Length)                     Dim plainText = New Byte(cipher.GetOutputSize(cipherText.Length) - 1) {}                      Try                         Dim len = cipher.ProcessBytes(cipherText, 0, cipherText.Length, plainText, 0)                         cipher.DoFinal(plainText, len)                     Catch unusedInvalidCipherTextException1 As InvalidCipherTextException                         Return Nothing                     End Try                      Return plainText                 End Using             End Using         End Function          Shared Function SimpleEncryptWithPassword(secretMessage As Byte(), password As String, ByVal Optional nonSecretPayload As Byte() = Nothing) As Byte()             nonSecretPayload = If(nonSecretPayload, New Byte() {})             If String.IsNullOrWhiteSpace(password) OrElse password.Length < MinPasswordLength Then Throw New ArgumentException($  "Must have a password of at least {MinPasswordLength} characters!", "password")             If secretMessage Is Nothing OrElse secretMessage.Length = 0 Then Throw New ArgumentException("Secret Message Required!", "secretMessage")             Dim generator = New Pkcs5S2ParametersGenerator()             Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {}             Random.NextBytes(salt)             generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations)             Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter)             Dim payload = New Byte(salt.Length + nonSecretPayload.Length - 1) {}             Array.Copy(nonSecretPayload, payload, nonSecretPayload.Length)             Array.Copy(salt, 0, payload, nonSecretPayload.Length, salt.Length)             Return SimpleEncrypt(secretMessage, key.GetKey(), payload)         End Function          Shared Function SimpleDecryptWithPassword(encryptedMessage As Byte(), password As String, ByVal Optional nonSecretPayloadLength As Integer = 0) As Byte()             If String.IsNullOrWhiteSpace(password) OrElse password.Length < MinPasswordLength Then Throw New ArgumentException($  "Must have a password of at least {MinPasswordLength} characters!", "password")             If encryptedMessage Is Nothing OrElse encryptedMessage.Length = 0 Then Throw New ArgumentException("Encrypted Message Required!", "encryptedMessage")             Dim generator = New Pkcs5S2ParametersGenerator()             Dim salt = New Byte(CInt(SaltBitSize / 8 - 1)) {}             Array.Copy(encryptedMessage, nonSecretPayloadLength, salt, 0, salt.Length)             generator.Init(PbeParametersGenerator.Pkcs5PasswordToBytes(password.ToCharArray()), salt, Iterations)              Dim key = CType(generator.GenerateDerivedMacParameters(KeyBitSize), KeyParameter)             Return SimpleDecrypt(encryptedMessage, key.GetKey(), salt.Length + nonSecretPayloadLength)         End Function     End Class End Namespace 

Magento 2: Run reindexer using REST API

Is any one having tried to create REST API so using custom API one can trigger re-indexing?

which method do i have to mention in webapi.xml file as this is purely AREA::ADMIN activitiy. currently tried with POST (create) and PUT (Update). Below is the webapi.xml

<route url="/V1/customapi" method="POST">         <service class="Sark\CustomApi\Api\CustomRepositoryInterface" method="create"/>         <resources>              <resource ref="self"/>         </resources>     </route> 

Further, for controller do i have to create API folder and interface mandatory or it is optional.

Index pro-grammatically code is as follows:

$  objectManager = \Magento\Framework\App\ObjectManager::getInstance();     $  indexerCollectionFactory = $  objectManager->get("\Magento\Indexer\Model\Indexer\CollectionFactory");     $  indexerFactory = $  objectManager->get("\Magento\Indexer\Model\IndexerFactory");      $  indexerCollection = $  indexerCollectionFactory->create();     $  allIds = $  indexerCollection->getAllIds();     foreach ($  allIds as $  id) {         $  indexer = $  indexerFactory->create()->load($  id);         $  indexer->reindexAll();     } 

It would be good if any other API is also there to do the same magic (except the direct custom script file).

Ref.: http://codetheatres.com/magento/creating-custom-api-in-magento2-using-rest-protocol/

Keycloak : authenticating a Rest API written in JAVA

I’d like to authenticate a Rest service (RS) against a Keycloak server (KS).

RS is accessed via an application (APP) and not a browser for example.

So far, I’ve understood the way to proceed is as following:

  1. APP is authenticating against KS and get an ACCESS_TOKEN.
  2. APP is sending a request to the RS passing somehow the ACCESS_TOKEN.
  3. RS is extracting the ACCESS_TOKEN and validate / decode it to get the required information associated with the user.

I’ve hard time finding the right JAVA API to perform the step (3).

So far, I’ve “verified” the token using a TokenVerifier (setup using the RSA public key of the KS) => TokenVerifier.verify(). Once verified, I’m parsing it to decode it using. So far so good.

One extra step I’d like to achieve is ensuring the ACCESS_TOKEN is still valid in KS. But I did not find any JAVA API for that purpose. So instead, I’ve issued a regular HTTP request to the UserInfo endpoint using the ACCESS_TOKEN.

So is there any JAVA API to check the validity of the ACCESS_TOKEN ?

Am I doing the thing right for this kind of scenario ?