毕业设计中使用支付宝沙箱完成在线支付流程(二)

本文涉及的产品
函数计算FC,每月15万CU 3个月
简介: 毕业设计中使用支付宝沙箱完成在线支付流程

毕业设计中使用支付宝沙箱完成在线支付流程(一)https://developer.aliyun.com/article/1423176


四,沙箱支付相关API说明

支付宝支付提供了很多种支付应用场景以及对应的API应用,打开网址:https://open.alipay.com/api

     可以看到有对应的应用类型:选中其中某一个进入,则有相关的文档介绍和API应用案例,所以学习和使用起来还是比较简单。

4.1 当面付

     如果我们想通过支付宝生成二维码,让客户端扫描二维码进行支付,可以选择当面付:

     https://open.alipay.com/api/detail?code=I1080300001000041016#api-detail-content

   

各个接口有在线文档和在线调试的案例,可以自行查看。以其中的统一收单线下交易预创建为例说明:

 package com.java.sdk.demo;
 import com.alipay.api.AlipayApiException;
 import com.alipay.api.AlipayClient;
 import com.alipay.api.DefaultAlipayClient;
 import com.alipay.api.CertAlipayRequest;
 import com.alipay.api.AlipayConfig;
 import com.alipay.api.domain.AlipayTradePrecreateModel;
 import com.alipay.api.response.AlipayTradePrecreateResponse;
 import com.alipay.api.request.AlipayTradePrecreateRequest;
 import com.alipay.api.FileItem;
 import java.util.Base64;
 import java.util.ArrayList;
 import java.util.List;
 public class AlipayTradePrecreate {
     public static void main(String[] args) throws AlipayApiException {
         String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs5FX6NlZEq8t43tnAT91hcGhTPL6Iieq/e1foh3N0ME601PwtfXzFPac0Qp5qygLtyZkYFY8UiYqdXPQpvO4T4ah5Rus8IiCwGDBpyg3ha6xSWnD7QCvc/YgOJ+ei1XD6F5Y+t2X3gbTCsy1H9wTe9XLh78tcpuhib/4OEwxJfHxEi5fBzQQJBE6vo8pX7mTeeP7f1RBxAgRsswMvCQs1SX362XdD3IRWErf8dUOqV0tT5ahjhXdbFv6fUQmnt+1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXH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5WdwQKBgFO79TUR5fq+u0sBjYW7VLiQ5J6Tq7U0phFjFFjR/eYqkKUtE5K/BdOsSQjwY21TOkoTazyDJiVLEx5pWQueIa0ez1WPNswz7VN2su9N/jwP+G5ILrz1I+nj2PiWXVbfWZ2qd2h0qB27CF7gZ9lQgjg5dQMt4Fmd7f8uzBzrwLQW";
         String alipayPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAydfxVYSMISxqvitww5063ZQFVRzrcRW9a+xQ0Pozz7ve9IeK1h9p7xFwSUtTNi/ki9ZcnZ7wP0xunKrYPVXyUvRz/vSVnovkzvmcSTdqlgtzTAQTJFYL0nmzhnv4RWbcDnVbo+IIlu8g0p6wQv7V8P5EGpbh63+d3q/DYhsbxVVZN1fKjnw/y38/GuqGoiaxkcrf6h65rGO/aRGbX6gbGnRxUgBOEiFGFdkuCx9ACg4cskSme69lDbIBDpsmSbQpUKhTEA4Wv36mqrbee+hGf5sTaqDUHl0/SPgP45ab15J3BeWHB/yXbdK4Z/gPfMFMweOupg54Sm+kJOGmq73cMwIDAQAB";
         AlipayConfig alipayConfig = new AlipayConfig();
         alipayConfig.setServerUrl("https://openapi.alipaydev.com/gateway.do");
         alipayConfig.setAppId("2021000121607425");
         alipayConfig.setPrivateKey(privateKey);
         alipayConfig.setFormat("json");
         alipayConfig.setAlipayPublicKey(alipayPublicKey);
         alipayConfig.setCharset("UTF8");
         alipayConfig.setSignType("RSA2");
         AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
         AlipayTradePrecreateRequest request = new AlipayTradePrecreateRequest();
         AlipayTradePrecreateModel model = new AlipayTradePrecreateModel();
         model.setOutTradeNo("20150320010101001");
         model.setTotalAmount("88.88");
         model.setSubject("Iphone6 16G");
         request.setBizModel(model);
         AlipayTradePrecreateResponse response = alipayClient.execute(request);
         //可以将此字符串返回到客户端,使用二维码生成工具来生成二维码图片即可
         System.out.println("支付地址:"+response.getQrCode());
         if (response.isSuccess()) {
             System.out.println("调用成功");
        } else {
             System.out.println("调用失败");
        }
    }
 }

4.2 手机网站支付API

     如果我们基于手机网站来实现在线支付,比如HTML5网站或小程序等,可以通过手机网站支付API进行实现:

https://open.alipay.com/api/detail?code=I1080300001000041949

各个接口有在线文档和在线调试的案例,可以自行查看。以其中的手机网站支付接口2.0为例说明:

 package com.java.sdk.demo;
 import com.alipay.api.AlipayApiException;
 import com.alipay.api.AlipayClient;
 import com.alipay.api.DefaultAlipayClient;
 import com.alipay.api.CertAlipayRequest;
 import com.alipay.api.AlipayConfig;
 import com.alipay.api.response.AlipayTradeWapPayResponse;
 import com.alipay.api.domain.AlipayTradeWapPayModel;
 import com.alipay.api.request.AlipayTradeWapPayRequest;
 import com.alipay.api.FileItem;
 import java.util.Base64;
 import java.util.ArrayList;
 import java.util.List;
 public class AlipayTradeWapPay {
     public static void main(String[] args) throws AlipayApiException {
         String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs5FX6NlZEq8t43tnAT91hcGhTPL6Iieq/e1foh3N0ME601PwtfXzFPac0Qp5qygLtyZkYFY8UiYqdXPQpvO4T4ah5Rus8IiCwGDBpyg3ha6xSWnD7QCvc/YgOJ+ei1XD6F5Y+t2X3gbTCsy1H9wTe9XLh78tcpuhib/4OEwxJfHxEi5fBzQQJBE6vo8pX7mTeeP7f1RBxAgRsswMvCQs1SX362XdD3IRWErf8dUOqV0tT5ahjhXdbFv6fUQmnt+1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXHFN5nV1QQbVTe3Q3XWIWTNAgMBAAECggEBAI2JI8WBRCBVj2306cgg2XfSQOWbfdNjLHTzMaUfdemxPk2VapiG+WSzMzV6MBv2Im2tsxHfXFGQw5RNq2ibzT8jZftajmqc+auPMdr42WIn9ls4xPM6tm3kc8Q68MsB9soWEx5mnyf+3A7kBfa7BxbLUvAZkZ7Y2Lb1PcMh3tYso7FYERStx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G9w0BAQEFAAOCAQ8AMIIBCgKCAQEAydfxVYSMISxqvitww5063ZQFVRzrcRW9a+xQ0Pozz7ve9IeK1h9p7xFwSUtTNi/ki9ZcnZ7wP0xunKrYPVXyUvRz/vSVnovkzvmcSTdqlgtzTAQTJFYL0nmzhnv4RWbcDnVbo+IIlu8g0p6wQv7V8P5EGpbh63+d3q/DYhsbxVVZN1fKjnw/y38/GuqGoiaxkcrf6h65rGO/aRGbX6gbGnRxUgBOEiFGFdkuCx9ACg4cskSme69lDbIBDpsmSbQpUKhTEA4Wv36mqrbee+hGf5sTaqDUHl0/SPgP45ab15J3BeWHB/yXbdK4Z/gPfMFMweOupg54Sm+kJOGmq73cMwIDAQAB";
         AlipayConfig alipayConfig = new AlipayConfig();
         alipayConfig.setServerUrl("https://openapi.alipaydev.com/gateway.do");
         alipayConfig.setAppId("2021000121607425");
         alipayConfig.setPrivateKey(privateKey);
         alipayConfig.setFormat("json");
         alipayConfig.setAlipayPublicKey(alipayPublicKey);
         alipayConfig.setCharset("UTF8");
         alipayConfig.setSignType("RSA2");
         AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
         AlipayTradeWapPayRequest request = new AlipayTradeWapPayRequest();
         AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
         model.setOutTradeNo("70501111111S001111119");
         model.setTotalAmount("9.00");
         model.setSubject("大乐透");
         //手机网站支付指定productCode为固定值:QUICK_WAP_WAY
         model.setProductCode("QUICK_WAP_WAY");
         model.setSellerId("2088102147948060");
         request.setBizModel(model);
         AlipayTradeWapPayResponse response = alipayClient.pageExecute(request);
         //getBody()返回的就是提交支付的嵌套页面,返回前端后自动跳转到支付宝支付操作界面
         System.out.println(response.getBody());
         if (response.isSuccess()) {
             System.out.println("调用成功");
        } else {
             System.out.println("调用失败");
        }
    }
 }

4.3 电脑网站支付API

如果我们基于PC电脑网站来实现在线支付,比如相关电商平台等,可以通过电脑网站支付API进行实现:

https://open.alipay.com/api/detail?code=I1080300001000041203#api-detail-content

各个接口有在线文档和在线调试的案例,可以自行查看。以其中的统一收单下单并支付页面接口为例说明:

package com.java.sdk.demo;
 import com.alipay.api.AlipayApiException;
 import com.alipay.api.AlipayClient;
 import com.alipay.api.DefaultAlipayClient;
 import com.alipay.api.CertAlipayRequest;
 import com.alipay.api.AlipayConfig;
 import com.alipay.api.domain.AlipayTradePagePayModel;
 import com.alipay.api.response.AlipayTradePagePayResponse;
 import com.alipay.api.request.AlipayTradePagePayRequest;
 import com.alipay.api.FileItem;
 import java.util.Base64;
 import java.util.ArrayList;
 import java.util.List;
 public class AlipayTradePagePay {
     public static void main(String[] args) throws AlipayApiException {
         String privateKey = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs5FX6NlZEq8t43tnAT91hcGhTPL6Iieq/e1foh3N0ME601PwtfXzFPac0Qp5qygLtyZkYFY8UiYqdXPQpvO4T4ah5Rus8IiCwGDBpyg3ha6xSWnD7QCvc/YgOJ+ei1XD6F5Y+t2X3gbTCsy1H9wTe9XLh78tcpuhib/4OEwxJfHxEi5fBzQQJBE6vo8pX7mTeeP7f1RBxAgRsswMvCQs1SX362XdD3IRWErf8dUOqV0tT5ahjhXdbFv6fUQmnt+1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXHFN5nV1QQbVTe3Q3XWIWTNAgMBAAECggEBAI2JI8WBRCBVj2306cgg2XfSQOWbfdNjLHTzMaUfdemxPk2VapiG+WSzMzV6MBv2Im2tsxHfXFGQw5RNq2ibzT8jZftajmqc+auPMdr42WIn9ls4xPM6tm3kc8Q68MsB9soWEx5mnyf+3A7kBfa7BxbLUvAZkZ7Y2Lb1PcMh3tYso7FYERStxpdtUgPSkqXgZERrzrtHpFDe05CI/xjZUfmvXsTrKiIXxqvil9hYGISkMyVJjaJUXvZwmgzLtHd7I8z7sNXOw26Ie1DihCy3VzPh5pwZPQId2v2LBABdUogTwVfb7GAV6swP+OMxoff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dqlgtzTAQTJFYL0nmzhnv4RWbcDnVbo+IIlu8g0p6wQv7V8P5EGpbh63+d3q/DYhsbxVVZN1fKjnw/y38/GuqGoiaxkcrf6h65rGO/aRGbX6gbGnRxUgBOEiFGFdkuCx9ACg4cskSme69lDbIBDpsmSbQpUKhTEA4Wv36mqrbee+hGf5sTaqDUHl0/SPgP45ab15J3BeWHB/yXbdK4Z/gPfMFMweOupg54Sm+kJOGmq73cMwIDAQAB";
         AlipayConfig alipayConfig = new AlipayConfig();
         alipayConfig.setServerUrl("https://openapi.alipaydev.com/gateway.do");
         alipayConfig.setAppId("2021000121607425");
         alipayConfig.setPrivateKey(privateKey);
         alipayConfig.setFormat("json");
         alipayConfig.setAlipayPublicKey(alipayPublicKey);
         alipayConfig.setCharset("UTF8");
         alipayConfig.setSignType("RSA2");
         AlipayClient alipayClient = new DefaultAlipayClient(alipayConfig);
         AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
         AlipayTradePagePayModel model = new AlipayTradePagePayModel();
         model.setOutTradeNo("20150320010101001");
         model.setTotalAmount("88.88");
         model.setSubject("Iphone6 16G");
         //电脑网站支付指定productCode为固定值:FAST_INSTANT_TRADE_PAY
         model.setProductCode("FAST_INSTANT_TRADE_PAY");
         request.setBizModel(model);
         AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
         //getBody()返回的就是提交支付的嵌套页面,返回前端后自动跳转到支付宝支付操作界面
         System.out.println(response.getBody());
         if (response.isSuccess()) {
             System.out.println("调用成功");
        } else {
             System.out.println("调用失败");
        }
    }
 }

五,沙箱支付功能实现

我们今天就以电脑网站支付为例进行讲解实现。

后台开发实现步骤:

5.1:支付功能的实现

  1、创建配置类:配置沙箱相关环境信息   把配置类中相关的信息改为自己的即可。

 

package com.qiu.config;
 import com.qiu.util.general.PropertiesUtil;
 import lombok.Data;
 import org.springframework.stereotype.Component;
 /**
  * @author ZNZ
  */
 @Data
 @Component
 public class AlipayConfig {
     /**
      * 沙箱appId
      */
     public static final String APPID = "2021000121607425";
     /**
      * 请求网关 固定
      */
     public static final String URL = "https://openapi.alipaydev.com/gateway.do";
     /**
      * 设置内网穿透回调地址
      */
     public static final String CALLBACK = "fcswjw.natappfree.cc";
     /**
      * 编码
      */
     public static final String CHARSET = "UTF-8";
     /**
      * 返回格式
      */
     public static final String FORMAT = "json";
     /**
      * RSA2
      */
     public static final String SIGNTYPE = "RSA2";
     /**
      * 异步通知地址
      */
      public static final String NOTIFY_URL = "http://"+CALLBACK+"/alipay/notify";
     /**
      * 同步地址
      */
      //使用内网穿透进行回调
     public static final String RETURN_URL = "http://"+CALLBACK+"/alipay/success";
     /**
      * 应用私钥 pkcs8格式
      */
     public static final String RSA_PRIVATE_KEY =
             "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs5FX6NlZEq8t43tnAT91hcGhTPL6Iieq/e1foh3N0ME601PwtfXzFPac0Qp5qygLtyZkYFY8UiYqdXPQpvO4T4ah5Rus8IiCwGDBpyg3ha6xSWnD7QCvc/YgOJ+ei1XD6F5Y+t2X3gbTCsy1H9wTe9XLh78tcpuhib/4OEwxJfHxEi5fBzQQJBE6vo8pX7mTeeP7f1RBxAgRsswMvCQs1SX362XdD3IRWErf8dUOqV0tT5ahjhXdbFv6fUQmnt+1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXHFN5nV1QQbVTe3Q3XWIWTNAgMBAAECggEBAI2JI8WBRCBVj2306cgg2XfSQOWbfdNjLHTzMaUfdemxPk2VapiG+WSzMzV6MBv2Im2tsxHfXFGQw5RNq2ibzT8jZftajmqc+auPMdr42WIn9ls4xPM6tm3kc8Q68MsB9soWEx5mnyf+3A7kBfa7BxbLUvAZkZ7Y2Lb1PcMh3tYso7FYERStxpdtUgPSkqXgZERrzrtHpFDe05CI/xjZUfmvXsTrKiIXxqvil9hYGISkMyVJjaJUXvZwmgzLtHd7I8z7sNXOw26Ie1DihCy3VzPh5pwZPQId2v2LBABdUogTwVfb7GAV6swP+OMxoffYPdW7AV+82zOYybm3GjKCTiECgYEA57ukyNybLE7h7yeDSFKdkoBnY7RmIW4NRwQNFopb5LlNt9vTm5easuEdDhPlGoNpJ5Ul/ms9pDVDnH2ZkU7IaiMPd/MxQpQ5dos5tRsjb02YwligiD3ZxDBRCNSjcqiR7+5jYb68H2c8bXLtOtZ/dsYyqZmEhH0OsV/2WKMr9bUCgYEAvv9EO9J2UEVBPkEKvhLfH7X8GZK6CROEehNG8qbDqxJ5AbFmo8lzNvbcHjJoiwEMzYU1q5VMhMVMepk1Lk5Q4VRouAMTUY3o8byQMeX7BYHlmmLaXuw8NAFFE43Mr14UGkrWesZR9u1LSw0QPNag3cyL2XxmgpWCmPAwLzQ+obkCgYEAnFukKFOR8CeZkwCaOGZmI7+4AzJp5wyWsOAu5JKexomxwuj0svtsSl5SeHk8ENOyVB7y7+P0R6QY5rJot/7sg5D8kvbouf/Bdhci7OxO0H8PH7MlPkhdc18WjlrLnkXXkojLTdygmp/RyhfNsfGhN8crz/vhynOHQm95jP0sYDECgYBGJ2zgrEVY5pc4TpurhTL/atDWc9ZxTwHx9PKyXh6wz3Ay9v5EWtI+9h2T2eAcbp5NPwifpY8dlXqp7WxjPdDncyGjtT17Tyyo3iH4sgip1TSIqJadFxhl4bGFpSfxohSwM5zkK8QfdrmZL4svTYZ48ZDMqazdeh0mH9MTA5WdwQKBgFO79TUR5fq+u0sBjYW7VLiQ5J6Tq7U0phFjFFjR/eYqkKUtE5K/BdOsSQjwY21TOkoTazyDJiVLEx5pWQueIa0ez1WPNswz7VN2su9N/jwP+G5ILrz1I+nj2PiWXVbfWZ2qd2h0qB27CF7gZ9lQgjg5dQMt4Fmd7f8uzBzrwLQW";
     /**
      * 沙箱支付宝公钥
      */
     public static final String ALIPAY_PUBLIC_KEY =
             "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAydfxVYSMISxqvitww5063ZQFVRzrcRW9a+xQ0Pozz7ve9IeK1h9p7xFwSUtTNi/ki9ZcnZ7wP0xunKrYPVXyUvRz/vSVnovkzvmcSTdqlgtzTAQTJFYL0nmzhnv4RWbcDnVbo+IIlu8g0p6wQv7V8P5EGpbh63+d3q/DYhsbxVVZN1fKjnw/y38/GuqGoiaxkcrf6h65rGO/aRGbX6gbGnRxUgBOEiFGFdkuCx9ACg4cskSme69lDbIBDpsmSbQpUKhTEA4Wv36mqrbee+hGf5sTaqDUHl0/SPgP45ab15J3BeWHB/yXbdK4Z/gPfMFMweOupg54Sm+kJOGmq73cMwIDAQAB";
     private AlipayConfig() {
    }
 }

 2、定义支付接口地址:用户点击立即购买后提交请求至下单接口,添加订单成功后,发送请求到支付接口,向支付宝发送支付请求。

前端页面代码:在前端工程src/comments/mall/MallPurchase.vue中

 createOrder(formName){
         this.$refs[formName].validate((valid) => {
             if (valid) {
               if(this.isVip){
                 this.order.payPrice = this.order.discountPrice;
              }
               let loading = this.$loading({lock: true, text: "订单提交中",background:"rgba(255,255,255,0.1)"});
               this.$http.post('/order/add',this.$qs.stringify(this.order,{skipNulls: true})).then((rep)=>{
                 loading.close();
                 if(rep.data.code===200){
                   let orderNo = this.order.orderNo;
                   let orderName = '新新商城-'+this.productInfo.productType+'-'+this.productInfo.productName+'支付订单';
                   let payPrice = this.order.payPrice;
                   let loading = this.$loading({lock: true, text: "正在跳转支付页面",background:"rgba(255,255,255,0.1)"});
                   this.$http.post('/alipay/create?orderNo='+orderNo+'&orderName='+orderName+'&payPrice='+payPrice).then((response)=>{
                     loading.close();
                     const div = document.createElement('div');
                     div.innerHTML = response.data;
                     document.body.appendChild(div);
                     document.forms[document.forms.length-1].submit();
                  }).catch((err)=>{loading.close();this.$msg.error(err)})
                }
              }).catch((err)=>{loading.close();this.$msg.error(err);})
               this.orderFormVisible=false;
            }else{
               return false;
            }
        });
      }

后端对应的支付接口实现:AlipayController

 /**
      * 创建支付
      * @param orderNo
      * @param orderName
      * @param payPrice
      * @return
      */
     @ResponseBody
     @PostMapping(value = "/create", produces = "text/html;charset=utf-8")
     public String create(@RequestParam("orderNo") String orderNo,
                          @RequestParam("orderName") String orderName,
                          @RequestParam("payPrice") String payPrice) {
         return alipayService.create(orderNo, orderName, payPrice);
    }

业务方法实现:

  /**
      * 创建支付订单
      *
      * @param orderId   订单编号
      * @param orderName 订单名称
      * @param payPrice 支付金额
      * @return 支付表单
      */
     @Override
     public String create(String orderId, String orderName, String payPrice) {
         //创建支付宝支付连接客户端
         AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID,
                 AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT,
                 AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,
                 AlipayConfig.SIGNTYPE);
         AlipayTradeWapPayRequest payRequest = new AlipayTradeWapPayRequest();
         AlipayTradeWapPayModel model = new AlipayTradeWapPayModel();
         model.setOutTradeNo(orderId);
         model.setSubject(orderName);
         model.setTotalAmount(payPrice);
         model.setProductCode(PRODUCTCODE);
         payRequest.setBizModel(model);
         payRequest.setReturnUrl(AlipayConfig.RETURN_URL);
         payRequest.setNotifyUrl(AlipayConfig.NOTIFY_URL);
         try {
             return client.pageExecute(payRequest).getBody();
        } catch (AlipayApiException e) {
             log.error("[支付宝] 支付失败", e);
        }
         return null;
    }

此接口返回的字符串其实是一个FORM表单,并执行自动提交:所以接口执行完后自动跳转到支付宝支付平台页面。

 <form name="punchout_form" method="post" action="https://openapi.alipaydev.com/gateway.do?charset=UTF-8&method=alipay.trade.wap.pay&sign=bdVLwcblQMIpdDuHtLtrT6J9KK4IH0Y0FgfS4TVO61VBrG8xfKHitFafkoNAKL6CvPjEoxAhr2cSjluRirt6FpLAffrTd0iVHctBD6JBoK3oUy1j472c8onqZ9x5y896bi3zRObobc7ygJEvvR04RdwIAQPPHObkKjvNEta5qqHOW9S%2FApZSBoPqBZozkijWXhsQDlCmIpvd%2FH4LlHAcpQe67owOAujsJezrGA2cg7Exm50rUGyiAVhA3ICsqi9PVFWU4FbD3jdELHTD3%2BgP2l7%2FLzWMeEIUj9Y0vw6wU9xI%2FhPl1emZGt9iUHLce3NetowYh96kdR6vnfYSYBZhJw%3D%3D&return_url=http%3A%2F%2Ft2vnvc.natappfree.cc%2Falipay%2Fsuccess&notify_url=http%3A%2F%2Ft2vnvc.natappfree.cc%2Falipay%2Fnotify&version=1.0&app_id=2021000121607425&sign_type=RSA2&timestamp=2022-07-17+16%3A09%3A55&alipay_sdk=alipay-sdk-java-4.10.192.ALL&format=json">
 <input type="hidden" name="biz_content" value="{&quot;out_trade_no&quot;:&quot;2271716507374&quot;,&quot;product_code&quot;:&quot;QUICK_WAP_WAY&quot;,&quot;subject&quot;:&quot;新新商城-生活家电-米家互联网洗烘一体机Pro 20kg支付订单&quot;,&quot;total_amount&quot;:&quot;3299.00&quot;}">
 <input type="submit" value="立即支付" style="display:none" >
 </form>
 <script>document.forms[0].submit();</script>

然后就进入到了我们文章开头展示的支付流程页面:

可以对照着沙箱的商家账户和买家账户的钱数来看看是否实现了买家账户扣款和商家账户收款的功能。

5.2:回调本地接口更改支付状态

      在线支付成功了,买家支付宝的账户的钱也已经转移到了商家的账户,可是本地应用怎么知道支付是否成功呢?我们在本地的应用中也需要根据支付成功与否来更改订单的支付状态,这就需要我们定义回调通知接口来实现。

     我们在AlipayConfig中已经定义了回调的接口地址:

 

  /**
      * 异步通知地址
      */
      public static final String NOTIFY_URL = "http://"+CALLBACK+"/alipay/notify";

    那么这个接口主要实现的功能就是根据支付的结果来实现订单状态的更新:

    在AlipayController中定义alipay/notify接口:

 /**
     * @param map
     */
     @ResponseBody
     @PostMapping(value = "/notify")
     public String payNotify(@RequestParam Map<String, String> map) {
         if (TRADE_SUCCESS.equals(map.get(TRADE_STATUS))) {
             String payTime = map.get(TRADE_TIME);
             String tradeNo = map.get(OUT_TRADE_NO);
             String tradeName = map.get(TRADE_NAME);
             String payAmount = map.get(TRADE_AMOUNT);
             log.info("[支付成功] {交易时间:{},订单号:{},订单名称:{},交易金额:{}}", payTime, tradeNo, tradeName, payAmount);
        }
         return "success";
    }
 /**
      * 支付回调成功
      * @param map
      * @param response
      */
     @GetMapping(value = "/success")
     public void success(@RequestParam Map<String, String> map, HttpServletResponse response) {
         try {
             String tradeNo = map.get(OUT_TRADE_NO);
             if (tradeNo.contains(VIP)) {
                 openMember(response, tradeNo);
            } else {
                 updateProductStatus(response, tradeNo);
            }
        } catch (IOException e) {
             e.printStackTrace();
        }
    }
  /**
      * 支付成功,更新商品状态为待发货
      *
      * @param response HTTP响应
      * @param tradeNo 订单编号
      * @throws IOException IO异常信息
      */
     private void updateProductStatus(HttpServletResponse response, String tradeNo) throws IOException {
          Integer orderId = orderService.selectIdByKey(orderNo);
          Order order = new Order();
          order.setOrderId(orderId);
          order.setOrderState("待发货");
          orderService.updateById(order);
         //跳转到我的订单页面
          response.sendRedirect("http://localhost:8080/#/myOrder");
    }

六,总结

   支付宝沙箱支付给了我们一个模拟支付宝在线支付的环境来进行测试,在本地通过沙箱支付测试成功后,可以在实际应用中,将对应的账户修改为自己企业账号申请的对公支付的账户信息即可,支付宝对整个开发提供的文档和案例也是比较丰富的,对于我们日常学习或做一些学校要求的简单课设来讲,这篇文章所讲解的基本支付功能应该能帮到大家的。如果还需要实现其它的像退款等相关功能,查看文中给的API接口地址,根据官方案例进行修改即可。

相关实践学习
【文生图】一键部署Stable Diffusion基于函数计算
本实验教你如何在函数计算FC上从零开始部署Stable Diffusion来进行AI绘画创作,开启AIGC盲盒。函数计算提供一定的免费额度供用户使用。本实验答疑钉钉群:29290019867
建立 Serverless 思维
本课程包括: Serverless 应用引擎的概念, 为开发者带来的实际价值, 以及让您了解常见的 Serverless 架构模式
相关文章
|
移动开发 前端开发 JavaScript
一文讲透支付宝沙箱的基本应用
沙箱环境是支付宝开放平台为开发者提供的与生产环境完全隔离的联调测试环境,开发者在沙箱环境中完成的接口调用不会对生产环境中的数据造成任何影响。沙箱为开放的产品提供有限功能范围的支持,可以覆盖产品的绝大部分核心链路和对接逻辑,便于开发者快速学习/尝试/开发/调试。沙箱环境会自动完成或忽略一些场景的业务门槛,例如:开发者无需等待产品开通,即可直接在沙箱环境调用接口,使得开发集成工作可以与业务流程并行,从而提高项目整体的交付效率。......
1997 0
一文讲透支付宝沙箱的基本应用
|
4月前
|
存储 移动开发 监控
微信支付开发避坑指南
【9月更文挑战第11天】在进行微信支付开发时,需遵循官方文档,确保权限和参数配置正确。开发中应注重安全,验证用户输入,合理安排接口调用顺序,并处理异常。上线后需实时监控支付状态,定期检查配置,关注安全更新,确保系统稳定运行。
|
8月前
|
JavaScript 前端开发 Java
毕业设计中使用支付宝沙箱完成在线支付流程(一)
毕业设计中使用支付宝沙箱完成在线支付流程
296 0
|
8月前
|
前端开发 Java 测试技术
毕业设计中使用支付宝沙箱完成在线支付流程
毕业设计中使用支付宝沙箱完成在线支付流程
255 0
|
XML Java API
87分布式电商项目 -微信扫码支付申请
87分布式电商项目 -微信扫码支付申请
100 0
87分布式电商项目 -微信扫码支付申请
|
小程序 IDE Serverless
支付宝小程序云内测福利发放
参与小程序云开发邀测活动,做首批内测用户
152 0
|
安全 前端开发 小程序
微信商户平台转账到零钱功能接入实战
近期营销活动中需要商户转账到微信用户零钱,实战角度说下接入过程,期间用的时间也比较多,把遇到的问题以及如何处理问题过程记录一下,希望对有同样需求的同学有所帮助,尽量少用一些时间,更专注业务处理.本文仅以发起商家转账( /v3/transfer/batches)功能进行讲解.
微信商户平台转账到零钱功能接入实战
|
新零售 区块链
区块链多商户商城开发(功能)丨区块链商城系统开发(逻辑及案例)丨区块链商城源码案例系统
 社交新零售,以社交赋能新零售模式,提升零售效率为目的的企业升级解决方案。社交新零售,是在消费升级时代,企业构建以消费者为中心的先进模式,从而获得竞争优势和效率提升。
|
区块链
区块链积分商城开发详情丨区块链积分商城系统开发(方案及逻辑)丨区块链商城系统源码及流程
 The blockchain mall creates a perfect integration platform of consumer shopping and blockchain technology,so that the advantages of blockchain technology can serve the actual transaction scenario of consumer shopping and help consumers realize the dream of value-added shopping.The model first uses