1

i have a html page for Checkout Integration of mastercard "Hosted Checkout Integration" , but i have a Problem with sessionId how can i call result of javascript function into another javascript function i want call from this function "sessionId"

function getSessionID(){
                axios({
                  method: 'POST',
                  url: 'https://banquemisr.gateway.mastercard.com/api/rest/version/61/merchant/xxxxx_xxx/session',
                  data: JSON.stringify({
                    apiOperation: 'CREATE_CHECKOUT_SESSION',
                    interaction: {
                        operation : "PURCHASE",
                    },
                    order : {
                        amount: function() {
                        //Dynamic calculation of amount
                        return realAmount + commission;
                    },
                        currency: "EGP",
                        description : "Ordered goods",
                        id: idValue,
                    },
                  }),

                auth: {
                    username: "merchant.xxxx_xxx",
                    password: "xxxxxxxxxxxxxxxxxxxxxxxxx"
                },
                crossOrigin: null,
                }).then(function (response) {
                    console.log('Authenticated');
                    localStorage.setItem('sessionId',response.data.session.id)
                    
                 });

into this function

 Checkout.configure({
            session: {
                id : sessionId;
            },
            interaction: {
              operation : "PURCHASE",
                merchant: {
                    name: "xxxxx_xxx",
                    address: {
                        line1: clientAddress1,
                        line2: clientAddress2
                    }
                }
            }
        });

i try to get it by

return getSessionID()

but not words , any Thoughts

my full code page :

<!doctype html>
<html>
 <head> 
     <title>xxxxx</title>    
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css" integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
     <link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css">
  <script src="https://banquemisr.gateway.mastercard.com/checkout/version/61/checkout.js" data-error="errorCallback" data-cancel="cancelCallback"></script> 
        <script src="https://unpkg.com/axios/dist/axios.min.js"></script>

  <script type="text/javascript">
  /* ############################# Config */



function session_id() {
    return /SESS\w*ID=([^;]+)/i.test(document.cookie) ? RegExp.$1 : false;
}

    //Type Your commission that will be added to the real amount
    let commission = 0;

    //Start amount
    let realAmount = 0;

    //currency
    let currency = "EGP";

    //Goods Item name and details
    let itemDescription = "xxxxx";

    //Store Name
    let clietnName = document.title;//"Store Name";
    //Store address 1 & 2
    let clientAddress1 = "200 Sample St";
    let clientAddress2 = "1234 Example Townt";

    //cancel page redirect
    let cancelURL = 'https://google.com';


    //payment id    
    let idValue = Math.random().toString(36).substr(2, 9);
    let str = "merchant.xxxxx:xxxxx";
    let enc = window.btoa(str);
    console.log(enc);
    getSessionID();
  /* ########################### End config */
            function errorCallback(error) {
                  console.log(JSON.stringify(error));
                  alert(JSON.stringify(error));
            }
            function cancelCallback() {
                  console.log('Payment cancelled');
                  window.href = cancelURL;
            }
            
            Checkout.configure({
                session: {
                    id : return getSessionID();
                },
                interaction: {
                  operation : "PURCHASE",
                    merchant: {
                        name: "xxxxx",
                        address: {
                            line1: clientAddress1,
                            line2: clientAddress2
                        }
                    }
                }
            });
async function getSessionID() {
    const response = await axios({
    method: "POST",
    url: "https://banquemisr.gateway.mastercard.com/api/rest/version/61/merchant/xxxxx/session",
    data: JSON.stringify({
      apiOperation: "CREATE_CHECKOUT_SESSION",
      interaction: {
        operation: "PURCHASE",
      },
      order: {
        amount: function () {
          //Dynamic calculation of amount
          return realAmount + commission;
        },
        currency: "EGP",
        description: "Ordered goods",
        id: idValue,
      },
    }),

    auth: {
      username: "merchant.xxxxx",
      password: "xxxxx",
    },
    crossOrigin: null,
  });

  return response.data.session.id;
}

async function foo(){
    const sessionID = await getSessionID();
}
            function makePayment()
            {
                realAmount = parseFloat(document.getElementById('amount').value);
                
                document.getElementById('amount').disabled = true;
                document.getElementById('pay').disabled = true;
                document.getElementById('cancel').disabled = true;
                Checkout.showPaymentPage();
               return false;
            }
        </script> 
 </head> 
 <style>
    
    .card-header .icons .fa-cc-discover{
        color: #027878;
    }
    .card-header .icons .fa-cc-amex{
        color: #ef6903;
    }
    label.labelamount{
        color: #ef6903;
    }
    .card-body label{
        font-size: 14px;
    }
    .submitpay{
        color: #fff;
        background-color: #ef6903;
        width: 83%;
    margin: auto;
    border: 2px solid #ef6903;
  border-radius: 5px;
    }
    .icons{
        text-align: right;
    }
    .inputamout{
        width: 85%;
    }
    body{
        background:  url("http://www.rimallytravel.com/wp-content/themes/altair/bg.jpg") no-repeat fixed center;

    }
    .imgbq{
        margin: auto;
    }
    .imglogo{
        width: 100%;
    }
    </style>
<body class="bg-danger pt-5">
    <div class="container">
       
            <div class="row">
          
                    <div class="col-md-4 offset-md-4 col-10 offset-1 pl-0 pr-0">
                        <div class="card1">
                                <img class="imglogo" src="http://www.rimallytravel.com/wp-content/uploads/2017/10/ww.png" alt="logo"  >
                                <br /><br /><br />
                        </div>
                    </div>
             </div>




      <div class="row">
          
          <div class="col-md-4 offset-md-4 col-10 offset-1 pl-0 pr-0">
              <div class="card">
                  
                    <div class="card-header">
                      <div class="row">
                          <div class="col-md-6 col-12 pt-2">
                              <h6 class="m-0"><strong>Payment Details</strong></h6>
                          </div>
                          <div class="col-md-6 col-12 icons">
                             <img class="imgcredit" src="http://www.rimallytravel.com/wp-content/uploads/2017/10/Credit-Card-Visa-And-Master-Card-PNG-File-300x65.png" alt="banq" width="170" >
                              
                          </div>
                      </div>
                    </div>
                    <div class="card-body">
                      <form onsubmit="return makePayment()">
                                <div class="col-md-12 col-12">
                                    <div class="form-group">
                                      <label class="labelamount" for="exampleInputamount"><strong>Amount</strong></label>
                                    </br>
                                      <input class="inputamout" type="number" min="1" step="0.01" id="amount" style="text-align: center;" required> EGP
                                  </div>
                                </div>
                            </div>
                           
                            <input class="submitpay" type="submit" id="pay" value="Pay Now">
         <br />
         <img class="imgbq" src="http://www.rimallytravel.com/wp-content/themes/altair/bq.png" alt="banq" width="125" >
         <br />
         <input type="hidden" id="cancel" onclick="cancelCallback()" value="Cancel"  >
                      </form>
                    </div>
              </div>
          </div>
      </div>
  </div>    
  <script>
    document.getElementById('amount').value = realAmount;
</script>   

</body>
</html>
1
  • I hope this code is just for debugging, because storing auth data (such as password above) client side is a VERY bad idea! Commented Mar 5, 2022 at 18:12

2 Answers 2

1

You need to use async-await, as your current getSessionID() does not return any value.

Try this:

async function getSessionID() {
    const response = await axios({
    method: "POST",
    url: "https://banquemisr.gateway.mastercard.com/api/rest/version/61/merchant/xxxxx_xxx/session",
    data: JSON.stringify({
      apiOperation: "CREATE_CHECKOUT_SESSION",
      interaction: {
        operation: "PURCHASE",
      },
      order: {
        amount: function () {
          //Dynamic calculation of amount
          return realAmount + commission;
        },
        currency: "EGP",
        description: "Ordered goods",
        id: idValue,
      },
    }),

    auth: {
      username: "merchant.xxxx_xxx",
      password: "xxxxxxxxxxxxxxxxxxxxxxxxx",
    },
    crossOrigin: null,
  });

  return response.data.session.id;
}

async function foo(){
    const sessionID = await getSessionID();
}
Sign up to request clarification or add additional context in comments.

8 Comments

thanx for your help, i used your code but it not work too
This implementation looks correct. If you have an error probably caused by another thing.
@n1md7 maybe i call this function by wrong way . i used it like that Checkout.configure({ session: { id : return getSessionID(); };
i edit my questions , i put a fuul code page
{"cause":"INVALID_REQUEST","explanation":"Missing parameter","field":"merchant","validationType":"MISSING"}
|
0

You can use async/await in getSessionId as suggested by @agrawal-d but if you return axios right await it also returns a promise.

However, that function is not async anymore so u need to call it appropriately.

Try this

function getSessionID() {
  return axios({
    method: 'POST',
    url: 'https://banquemisr.gateway.mastercard.com/api/rest/version/61/merchant/xxxxx_xxx/session',
    data: JSON.stringify({
      apiOperation: 'CREATE_CHECKOUT_SESSION',
      interaction: {
        operation: 'PURCHASE',
      },
      order: {
        amount: function () {
          //Dynamic calculation of amount
          return realAmount + commission;
        },
        currency: 'EGP',
        description: 'Ordered goods',
        id: idValue,
      },
    }),

    auth: {
      username: 'merchant.xxxx_xxx',
      password: 'xxxxxxxxxxxxxxxxxxxxxxxxx',
    },
    crossOrigin: null,
  }).then(function (response) {
    console.log('Authenticated');
    localStorage.setItem('sessionId', response.data.session.id);
    return response.data.session.id;
  });
}

(async function () {
  // You need async context to use await
  Checkout.configure({
    session: {
      id : await getSessionID(),
    },
    interaction: {
      operation : "PURCHASE",
      merchant: {
        name: "xxxxx_xxx",
        address: {
          line1: clientAddress1,
          line2: clientAddress2
        }
      }
    }
  });
})();

// Or with `then` chain

getSessionID().then(sessionId => {
  Checkout.configure({
    session: {
      id : sessionId, //👈🏻
    },
    interaction: {
      operation : "PURCHASE",
      merchant: {
        name: "xxxxx_xxx",
        address: {
          line1: clientAddress1,
          line2: clientAddress2
        }
      }
    }
  });
})

4 Comments

Thank you Sir on help You have replaced your code But the page freezes after put amount into the form No error appears
That sounds like another problem.
Pretty sure not related to this code though.
Thanks again - I am not an expert in Java Script - I do not know where the problem

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.