SoFunction
Updated on 2025-03-09

Vue+SpringBoot's sample code to implement Alipay sandbox payment

First, I will download a series of things in Alipay sandbox. I won’t talk about the specific configurations. There are many blogs, and Ant Financial’s official also said it in detail. I will directly talk about how to display the backend payment page to the Vue frontend:

After you configure the AlipayConfig file, you can write the logic of the front-end. The page where the front-end uses Alipay is as follows:

Here are some inline code fragments.

/* The following is the payment confirmation html */
      <div style="text=#000000 bgColor=#ffffff leftMargin=0 topMargin=4">
        <header class="am-header">
          <h1>Payment confirmation</h1>
        </header>
        <div >
          <!-- <form name="alipayment" :model="payObject" target="_blank"> -->
          <div  class="show" name="divcontent">
            <dl class="content">
              <dt>Merchant Order Number :</dt>
              <dd>
                <input
                  
                  name="WIDout_trade_no"
                  readonly="true"
                  :value="payObject.WIDout_trade_no"
                />
              </dd>
              <hr class="one_line" />
              <dt>Order name :</dt>
              <dd>
                <input
                  
                  name="WIDsubject"
                  readonly="true"
                  :value=""
                />
              </dd>
              <hr class="one_line" />
              <dt>Payment amount :</dt>
              <dd>
                <input
                  
                  name="WIDtotal_amount"
                  readonly="true"
                  :value="payObject.WIDtotal_amount"
                />
              </dd>
              <hr class="one_line" />
              <dt>Product Description:</dt>
              <dd>
                <input  name="WIDbody" readonly="true" :value="" />
              </dd>
              <hr class="one_line" />
              <dd >
                <span class="new-btn-login-sp">
                  <button class="new-btn-login" style="text-align: center;" @click="paySub()">pay payment</button>
                </span>
                <span class="note-help">If you click“paypayment”Button,By this means you agree to the operation。</span>
              </dd>
            </dl>
          </div>
          <!-- </form> -->
        </div>
      </div>

I'll add the css of this page

/* The following is the payment confirmation sample css*/
.am-header {
  display: -webkit-box;
  display: -ms-flexbox;
  /* display: flex; */
  width: 100%;
  position: relative;
  padding: 15px 0;
  -webkit-box-sizing: border-box;
  -ms-box-sizing: border-box;
  box-sizing: border-box;
  background: #1d222d;
  height: 50px;
  text-align: center;
  -webkit-box-pack: center;
  -ms-flex-pack: center;
  box-pack: center;
  -webkit-box-align: center;
  -ms-flex-align: center;
  box-align: center;
}

.am-header h1 {
  -webkit-box-flex: 1;
  -ms-flex: 1;
  box-flex: 1;
  line-height: 18px;
  text-align: center;
  font-size: 18px;
  font-weight: 300;
  color: #fff;
}
#main {
  width: 100%;
  margin: 0 auto;
  font-size: 14px;
}
.show {
  clear: left;
  display: block;
}
.content {
  margin-top: 5px;
}

.content dt {
  width: 100px;
  display: inline-block;
  float: left;
  margin-left: 20px;
  color: #666;
  font-size: 13px;
  margin-top: 8px;
}

.content dd {
  margin-left: 120px;
  margin-bottom: 5px;
}

.content dd input {
  width: 85%;
  height: 28px;
  border: 0;
  -webkit-border-radius: 0;
  -webkit-appearance: none;
  inputoutline: none;
}
.one_line {
  display: block;
  height: 1px;
  border: 0;
  border-top: 1px solid #eeeeee;
  width: 100%;
  margin-left: 20px;
}
#btn-dd {
  margin: 20px;
  text-align: center;
}
.new-btn-login-sp {
  padding: 1px;
  display: inline-block;
  width: 75%;
}
.new-btn-login {
  background-color: #02aaf1;
  color: #ffffff;
  font-weight: bold;
  border: none;
  width: 100%;
  height: 50px;
  border-radius: 5px;
  font-size: 16px;
}
.note-help {
  color: #999999;
  font-size: 12px;
  line-height: 100%;
  margin-top: 5px;
  width: 100%;
  display: block;
}

Of course, the data on the html page is defined as follows:

/*Data used in html*/
      payObject: {
        //Payment data        WIDsubject: 0,
        WIDout_trade_no: "",
        WIDtotal_amount: "",
        WIDbody: ""
      },

Of course, when you want to open the payment page, you have to use a function to assign the data, which is the following code, please refer to the comments for details:

//Go to the payment page function    payOrder() {
    //I have set this as the order number when jumping to the payment interface      //Judge whether oid (order number) is a number      if (typeof  != "string") {
      //Take out user data from sessionStorage        const usertoken = ("usertoken");
        const user = (("user"));
        // (user)
        //If the user is normal (not empty)        if (usertoken != null) {
          if (user != null) {
            const uname = ;
            //I'm going to get what order I need to pay for            ().then(response => {
              const resp = ;
              if ( === 200) {
              //Generate this sNow data                var vNow = new Date();
                var sNow = "";
                sNow += String(());
                sNow += String(() + 1);
                sNow += String(());
                sNow += String(());
                sNow += String(());
                sNow += String(());
                sNow += String(());
                //Bind the data of the page                .WIDout_trade_no = sNow; //Binding tradeno                 = uname;//I am the bound username                 = ; //Return the current order number value                .WIDtotal_amount = ; //Return the total payment price              } else {
                this.$message({
                  message: ,
                  type: "warning",
                  duration: 500 // Pop-up dwell time                });
              }
            });
          } else {
            this.$message({
              message: "Please log in first",
              type: "warning",
              duration: 1000 // Pop-up dwell time            });
          }
        } else {
          this.$message({
            message: "Please log in first",
            type: "warning",
            duration: 1000 // Pop-up dwell time          });
        }
      } else {
        this.$message({
          message: "Payment error",
          type: "warning",
          duration: 1000 // Pop-up dwell time        });
      }
    },

Then I'm talking about what to do after you click to pay immediately (that is, click to pay and call the paySub() function)

    // Payment starts    /Tip users
    paySub() {
      this.$message({
        showClose: true,
        message: "Please complete the payment within 5 minutes",
        duration: 5000 // Pop-up dwell time      });

      //Go to Pay     //The payment data is passed to the backend here, which is the data defined and bound just now.      dishApi
        .pay(
          .WIDout_trade_no,
          .WIDtotal_amount,
          ,
          
        )
        .then(response => {
        //The background response is as follows          const r = ;
          if ( === 200) {
          //This is the backend response r. I got its format. As for what is here, we will say later,          //The retrieved data is first stored in sessionStorage for future reading            ("payaction", );
//Then redirect the page to the payment interface            ("#pay", "_blank");
          } else {
            this.$message({
              message: ,
              type: "warning",
              duration: 500 // Pop-up dwell time            });
          }
        });
    },

Next, we will change the springboot backend: Let's write about the backend accessed by the above() method.

    @ResponseBody
    @PostMapping("/AliPay")
    //Receive data from the front end here to payInfo    public Object goPay(@RequestBody JSONObject payInfo,HttpServletResponse response,HttpServletRequest request) throws IOException, AlipayApiException {
 // First here        JSONObject jsonObject = new JSONObject();
        try {
        //This is to parse the data transmitted from the front end            String WIDout_trade_no = ("WIDout_trade_no").toString();
            String WIDtotal_amount = ("WIDtotal_amount").toString();
            String WIDsubject = ("WIDsubject").toString();
            String WIDbody = ("WIDbody").toString();
//        (WIDout_trade_no);(WIDtotal_amount);(WIDsubject);(WIDbody);
            //Get the initialized AlipayClient            AlipayClient alipayClient = new DefaultAlipayClient(, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", , AlipayConfig.alipay_public_key, AlipayConfig.sign_type);

            //Set request parameters            AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
            (AlipayConfig.return_url);
            (AlipayConfig.notify_url);

//        String out_trade_no = new String(("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
// // Payment amount, required//        String total_amount = new String(("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
// // Order name, required//        String subject = new String(("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
// // Product description, available//        String body = new String(("WIDbody").getBytes("ISO-8859-1"),"UTF-8");

            String out_trade_no = WIDout_trade_no;
            //Payment amount, required            String total_amount = WIDtotal_amount;
            //Order name, required            String subject = WIDsubject;
            //Product description, available            String body = WIDbody;

            // The latest payment time allowed for this order will be closed after the deadline.  Value range: 1m~15d.  m-minute, h-hour, d-day, 1c-day (in the case of 1c-day, no matter when the transaction is created, it will be closed at 0 o'clock).  This parameter value does not accept decimal points, such as 1.5h, it can be converted to 90m.            String timeout_express = "10m";

            //See examples to search for official API            ("{\"out_trade_no\":\"" + out_trade_no + "\","
                    + "\"total_amount\":\"" + total_amount + "\","
                    + "\"subject\":\"" + subject + "\","
                    + "\"body\":\"" + body + "\","
                    + "\"timeout_express\":\"" + timeout_express + "\","
                    + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");


//        //ask
            String result = (alipayRequest).getBody() ;
            //The above are all from Alipay, and next is mine            //The next is a series of string operations. In short, the button attribute of the result page returned by Alipay is set to non-hidden, and some good-looking attributes are added, and then the <script> tag is taken out (because the front-end cannot display <script> with v-html). Finally, the entire modified result is sent to the front-end, and the above front-end writes the received content into sessionStorage operation.            String befAction = result;
            StringBuffer aftAction = new StringBuffer(befAction);
            aftAction = ();
            String midAction = (68);
            aftAction = new StringBuffer(midAction).reverse();
            aftAction=(" width: 200px;  padding:8px;  background-color: #428bca;  border-color: #357ebd; color: #fff;  -moz-border-radius: 10px;  -webkit-border-radius: 10px;  border-radius: 10px;  -khtml-border-radius: 10px;text-align: center;  vertical-align: middle;  border: 1px solid transparent;  font-weight: 900;  font-size:125% \"&gt; &lt;/form&gt;");
            ("formaction", aftAction);
            ("message", ());
            ("code", ());
            return jsonObject;
        }catch (Exception e)
        {
            ("message", StateCode.SERVER_FAILED.getMessage());
            ("code", StateCode.SERVER_FAILED.getCode());
            return jsonObject;
        }
    }

Next is the front-end operation again. Since the front-end just redirected the page, we will write the page after the front-end jump:

//This is the entire code of the page you jump to&lt;template&gt;
&lt;div class="top"&gt;
&lt;h1 class="top"&gt;checkout counter&lt;/h1&gt;
 &lt;div v-html="payaction"&gt;
&lt;/div&gt;
&lt;/div&gt;
&lt;/template&gt;
&lt;script&gt;
export default {
  data() {
    return {
      payaction: ""
    };
  },
  created() {
    ();
  },
  methods: {
    showPayPage() {
       
      this.$nextTick(function() {
      //We directly display the page we just wrote in sessionStorage on the current page         = ("payaction");
        //Then delete the sessionStorage data        ("payaction");
      });
    },
  }
};
&lt;/script&gt;
&lt;style scoped&gt;
.top{
margin-top: 50px;
text-align: center;
vertical-align: middle;
margin-bottom: 100px;
}
&lt;/style&gt;

At this point, all the codes are over. If you click the payment button directly on this page, you will jump to the Alipay sandbox payment interface.

This is the article about the sample code of Vue+SpringBoot to implement Alipay sandbox payment. For more related Vue+SpringBoot Alipay sandbox payment content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!