Home > database >  call sessionId javascript function into another function
call sessionId javascript function into another function

Time:03-06

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 >
    <div >
       
            <div >
          
                    <div >
                        <div >
                                <img  src="http://www.rimallytravel.com/wp-content/uploads/2017/10/ww.png" alt="logo"  >
                                <br /><br /><br />
                        </div>
                    </div>
             </div>




      <div >
          
          <div >
              <div >
                  
                    <div >
                      <div >
                          <div >
                              <h6 ><strong>Payment Details</strong></h6>
                          </div>
                          <div >
                             <img  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 >
                      <form onsubmit="return makePayment()">
                                <div >
                                    <div >
                                      <label  for="exampleInputamount"><strong>Amount</strong></label>
                                    </br>
                                      <input  type="number" min="1" step="0.01" id="amount" style="text-align: center;" required> EGP
                                  </div>
                                </div>
                            </div>
                           
                            <input  type="submit" id="pay" value="Pay Now">
         <br />
         <img  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>

CodePudding user response:

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();
}

CodePudding user response:

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, //           
  • Related