一文讲透支付宝沙箱的基本应用

一文讲透支付宝沙箱的基本应用

首页模拟经营简单沙箱2更新时间:2024-04-25

在长期的教学过程中,了解到很多同学在进行毕业设计或课程设计时会开发一些相应的商城系统,都有在线支付的相关需求,而做为个人,想在实现在线支付在很多平台是不具备相关条件的,很多平台要求具备独立法人资格的企业或个人商业户才可以申请在线支付,而支付宝提供的沙箱环境,对于个人实现在线支付测试环境来讲,是一个不错的选择,本文主要讲解基于支付宝的沙箱环境来实现在线支付的功能。主要结合一个简易的商城系统来讲解说明在线支付的基本操作流程和相关API的应用,从而实现基于支付宝沙箱在线支付的基本功能。

一、案例说明

本案例基于一个简易的商城系统,在这个系统基础上实现在了在线沙箱支付的基本应用。系统只保留了基本的商品展示和购物基本功能,其它功能接口全部删除。系统基于前后端分离的开发方式,前端使用VUE开发实现,后端使用Springboot结合Mybatis开发实现。

首页商品展示

商品详情

点击立即付款后进入支付宝付款流程

点击下一步:

确认付款

完成支付

看完了案例的演示,是不是有一种想试一试的冲突,感觉好简单?OK,那么我们一起开始学习支付宝沙箱支付的旅程!

二,支付宝沙箱环境准备2.1 支付宝沙箱介绍

沙箱环境是支付宝开放平台为开发者提供的与生产环境完全隔离的联调测试环境,开发者在沙箱环境中完成的接口调用不会对生产环境中的数据造成任何影响。

沙箱为开放的产品提供有限功能范围的支持,可以覆盖产品的绝大部分核心链路和对接逻辑,便于开发者快速学习/尝试/开发/调试。

沙箱环境会自动完成或忽略一些场景的业务门槛,例如:开发者无需等待产品开通,即可直接在沙箱环境调用接口,使得开发集成工作可以与业务流程并行,从而提高项目整体的交付效率。

注意:

2.2 支付宝沙箱注册及配置

打开支付宝开发者页面进行注册登陆:https://opendocs.alipay.com/common/02kkv7

登陆后进入开放平台控制台:选择左下解沙箱

在沙箱应用中可以查看沙箱的相关信息,其中APPID需要复制并记录,我们在进行支付时要指定APPID。

其它的均保持默认配置即可,接口的加签方式选择系统默认密钥即可,选用公钥模式,点击查看可以看到对应的公钥和私钥:做支付时需要用到。

支付宝网关地址:https://OpenAPI.alipaydev.com/gateway.do

支付宝沙箱网关地址,开发者在沙箱环境调用 OpenAPI 发送 http(s) 请求的目标地址,需配置在AlipayClient中。此地址为固定的,在程序中需要配置。

选择左边沙账户:创建申请个人和商家对应的虚拟账户,并可以在线模拟充值和取现。

至此,我们需要准备的沙箱环境和配置己准备就绪。

三,内网穿透工具准备

支付宝沙箱支付成功后,要回调本地的服务地址进行支付结果的通知,而我们的测试环境是运行在内网中,所以需要借助内网穿透工具来实现外网调用内网的服务接口。内网穿透的工具网上有很多免费的,我们今天使用的是NATAPP这款工具。

1、打开官网注册并登陆:https://natapp.cn/login

2、登陆后选择购买隧道:选择免费隧道(有效期一个月)

3、指定名字,选择Web协议,并指定本地的应用通讯的端口

4、购买成功后会生成认证令牌:复制并保存

5、下载客户端工具:根据你电脑情况选择合适的版本下载,这里我选用Windows64位

6、创建配置文件:config.ini 具体下载:https://natapp.cn/article/config_ini

放在客户端natapp.exe同级目录下,并将其中的authtoken换成我们刚申请的免费隧道的令牌

7、启动客户端:windows下,直接双击natapp.exe 即可。红框内就是我们的隧道通信地址。

注意:每次启动客户端都会分配一个新的隧道地址:要注意后期更换程序中配置 的地址。

8、测试:此时t2vnvc.natappfree.cc临时域名就是代表了本地应用程序的访问地址http://localhost:80

可以直接使用此域名来访问应用程序下的任意一个接口,如能访问,则环境OK。

http://t2vnvc.natappfree.cc/order/findAll 查询所有订单:测试成功

四,沙箱支付相关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 1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXHFN5nV1QQbVTe3Q3XWIWTNAgMBAAECggEBAI2JI8WBRCBVj2306cgg2XfSQOWbfdNjLHTzMaUfdemxPk2VapiG WSzMzV6MBv2Im2tsxHfXFGQw5RNq2ibzT8jZftajmqc auPMdr42WIn9ls4xPM6tm3kc8Q68MsB9soWEx5mnyf 3A7kBfa7BxbLUvAZkZ7Y2Lb1PcMh3tYso7FYERStxpdtUgPSkqXgZERrzrtHpFDe05CI/xjZUfmvXsTrKiIXxqvil9hYGISkMyVJjaJUXvZwmgzLtHd7I8z7sNXOw26Ie1DihCy3VzPh5pwZPQId2v2LBABdUogTwVfb7GAV6swP OMxoffYPdW7AV 82zOYybm3GjKCTiECgYEA57ukyNybLE7h7yeDSFKdkoBnY7RmIW4NRwQNFopb5LlNt9vTm5easuEdDhPlGoNpJ5Ul/ms9pDVDnH2ZkU7IaiMPd/MxQpQ5dos5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skSme69lDbIBDpsmSbQpUKhTEA4Wv36mqrbee 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 = "MIIEvgIBADANBgkqhkiG9w0BAQEFAASCBKgwggSkAgEAAoIBAQCs5FX6NlZEq8t43tnAT91hcG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uj0svtsSl5SeHk8ENOyVB7y7 P0R6QY5rJot/7sg5D8kvbouf/Bdhci7OxO0H8PH7MlPkhdc18WjlrLnkXXkojLTdygmp/RyhfNsfGhN8crz/vhynOHQm95jP0sYDECgYBGJ2zgrEVY5pc4TpurhTL/atDWc9ZxTwHx9PKyXh6wz3Ay9v5EWtI 9h2T2eAcbp5NPwifpY8dlXqp7WxjPdDncyGjtT17Tyyo3iH4sgip1TSIqJadFxhl4bGFpSfxohSwM5zkK8QfdrmZL4svTYZ48ZDMqazdeh0mH9MTA5WdwQKBgFO79TUR5fq 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); 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/4OEwxJfHxEi5fBzQQJBE6vo8pX7mTeeP7f1RBxAgRsswMvCQs1SX362XdD3IRWErf8dUOqV0tT5ahjhXd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Tyyo3iH4sgip1TSIqJadFxhl4bGFpSfxohSwM5zkK8QfdrmZL4svTYZ48ZDMqazdeh0mH9MTA5WdwQKBgFO79TUR5fq 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); 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 1i00CIAlOPm7vLWslw1qJT4ubZuL0HPQLWEoD3ab0OdgaJvPdoWvnUVzBQqwZgnXHFN5nV1QQbVTe3Q3XWIWTN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LiQ5J6Tq7U0phFjFFjR/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/ApZSBoPqBZozkijWXhsQDlCmIpvd/H4LlHAcpQe67owOAujsJezrGA2cg7Exm50rUGyiAVhA3ICsqi9PVFWU4FbD3jdELHTD3+gP2l7/LzWMeEIUj9Y0vw6wU9xI/hPl1emZGt9iUHLce3NetowYh96kdR6vnfYSYBZhJw==&return_url=http://t2vnvc.natappfree.cc/alipay/success¬ify_url=http://t2vnvc.natappfree.cc/alipay/notify&version=1.0&app_id=2021000121607425&sign_type=RSA2×tamp=2022-07-17 16:09:55&alipay_sdk=alipay-sdk-java-4.10.192.ALL&format=json"> <input type="hidden" name="biz_content" value="{"out_trade_no":"2271716507374","product_code":"QUICK_WAP_WAY","subject":"新新商城-生活家电-米家互联网洗烘一体机Pro 20kg支付订单","total_amount":"3299.00"}"> <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接口地址,根据官方案例进行修改即可。

查看全文
大家还看了
也许喜欢
更多游戏

Copyright © 2024 妖气游戏网 www.17u1u.com All Rights Reserved