支付宝支付接口的对接(沙箱环境)

支付宝支付接口的对接(沙箱环境)

一:准备工作

1.上蚂蚁金服官网注册开发者账号(https://open.alipay.com/platform/home.htm)

2.生成RSA公钥,密钥(这里使用官方推荐工具生成 https://docs.open.alipay.com/291/105971)
RSA生成工具

3.查看APPID,支付宝网关,支付宝公钥。并配置应用公钥
在这里插入图片描述

二:编写代码

在官方demo的基础上修改代码或自行编写
demo下载地址 https://docs.open.alipay.com/270/106291/

1.复制demo里的AlipayConfig.java到项目,并将配置信息写进AlipayConfig.java(准备阶段里的APPID,公钥,密钥以及同步、异步回调地址都在这里配置)

AlipayConfig.java

package com.alipay.config;

import java.io.FileWriter;
import java.io.IOException;

public class AlipayConfig {
	
//↓↓↓↓↓↓↓↓↓↓请在这里配置您的基本信息↓↓↓↓↓↓↓↓↓↓↓↓↓↓↓

	// 应用ID,您的APPID,收款账号既是您的APPID对应支付宝账号
	public static String app_id = "这里是你的APPID号";
	
	// 商户私钥,您的PKCS8格式RSA2私钥
    public static String merchant_private_key = "这里是你应用公钥所对应的私钥";	
    
	// 支付宝公钥,查看地址:https://openhome.alipay.com/platform/keyManage.htm 对应APPID下的支付宝公钥。
    public static String alipay_public_key = "这里是支付宝公钥";

	// 服务器异步通知页面路径  需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String notify_url = “这里是异步回调的地址(必须是能被外网访问的地址),用于业务逻辑的处理”;

	// 页面跳转同步通知页面路径 需http://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问
	public static String return_url = "这里是同步回调的地址,用于将结果回显给用户";

	// 签名方式
	public static String sign_type = "RSA2";
	
	// 字符编码格式
	public static String charset = "utf-8";
	
	// 支付宝网关
	public static String gatewayUrl = "https://openapi.alipaydev.com/gateway.do";
	
	// 支付宝网关
	public static String log_path = "C:\\";


//↑↑↑↑↑↑↑↑↑↑请在这里配置您的基本信息↑↑↑↑↑↑↑↑↑↑↑↑↑↑↑

    /** 
     * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库)
     * @param sWord 要写入日志里的文本内容
     */
    public static void logResult(String sWord) {
        FileWriter writer = null;
        try {
            writer = new FileWriter(log_path + "alipay_log_" + System.currentTimeMillis()+".txt");
            writer.write(sWord);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (writer != null) {
                try {
                    writer.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}


2.复制demo里的alipay.trade.page.pay.jsp到项目,并设置支付订单参数,如:商户订单号,金额,商品名等(具体有哪些参数可在开发文档查看)。

alipay.trade.page.pay.jsp

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@page import="org.springframework.beans.factory.annotation.Autowired"%>
<%@page import="javax.annotation.Resource"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>付款</title>
</head>
<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.util.Date" %>
<%@ page import="com.alipay.config.*"%>
<%@ page import="com.alipay.api.*"%>
<%@ page import="com.alipay.api.request.*"%>
<%@ page import="com.shop.service.tempService" %>
<%@ page import="com.shop.service.impl.tempServiceImpl" %>
<%@ page import="com.shop.pojo.temp" %>
<%@ page  import="org.springframework.web.context.support.WebApplicationContextUtils"%>
<%@ page import="org.springframework.web.context.WebApplicationContext"%>
<%

	//获得初始化的AlipayClient
	AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.gatewayUrl, AlipayConfig.app_id, AlipayConfig.merchant_private_key, "json", AlipayConfig.charset, AlipayConfig.alipay_public_key, AlipayConfig.sign_type);
	
	//设置请求参数
	AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
	alipayRequest.setReturnUrl(AlipayConfig.return_url);
	alipayRequest.setNotifyUrl(AlipayConfig.notify_url);
	
	//商户订单号,商户网站订单系统中唯一订单号,必填
	String out_trade_no =new String(request.getParameter("WIDout_trade_no").getBytes("ISO-8859-1"),"UTF-8");
	//付款金额,必填
	String total_amount =new String(request.getParameter("WIDtotal_amount").getBytes("ISO-8859-1"),"UTF-8");
	//订单名称,必填
	String subject =new String(request.getParameter("WIDsubject").getBytes("ISO-8859-1"),"UTF-8");
	//商品描述,可空
	String body =new String(request.getParameter("WIDbody").getBytes("ISO-8859-1"),"UTF-8");
	
	
	//自定义参数(存入数据库,不发送给Ali)
	String user_id = new String(request.getParameter("WIDuser_id").getBytes("ISO-8859-1"),"UTF-8");
	String article_id=new String(request.getParameter("WIDarticle_id").getBytes("ISO-8859-1"),"UTF-8");
	String num =new String(request.getParameter("WIDnum").getBytes("ISO-8859-1"),"UTF-8");
	String address=new String(request.getParameter("WIDaddress").getBytes("ISO-8859-1"),"UTF-8");
	
	/*
	   发送的参数,必须符合命名规范,详情见API帮助文档
	out_trade_no:商户订单id
	total_amout:付款金额
	subject:订单名
	body:商品名
	quantity:数量
	*/
	
	
	alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
			+ "\"total_amount\":\""+ total_amount +"\"," 
			+ "\"subject\":\""+ subject +"\"," 
			+ "\"body\":\""+ body +"\","
			+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
	

	//若想给BizContent增加其他可选请求参数,以增加自定义超时时间参数timeout_express来举例说明
	//alipayRequest.setBizContent("{\"out_trade_no\":\""+ out_trade_no +"\"," 
	//		+ "\"total_amount\":\""+ total_amount +"\"," 
	//		+ "\"subject\":\""+ subject +"\"," 
	//		+ "\"body\":\""+ body +"\"," 
	//		+ "\"timeout_express\":\"10m\"," 
	//		+ "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
	//请求参数可查阅【电脑网站支付的API文档-alipay.trade.page.pay-请求参数】章节
	
	//请求
	String result = alipayClient.pageExecute(alipayRequest).getBody();
	
	
	//生成预订单
	temp x = new temp();
	x.setId(out_trade_no);
	x.setUser_id(Integer.parseInt(user_id));
	x.setArticle_id(Integer.parseInt(article_id));
	x.setNum(Integer.parseInt(num));
	x.setPay_money(Float.valueOf(total_amount));
	x.setAddress(address);
	x.setTime(new Date());
	      //获取tempServiced接口
	WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(this.getServletContext());
	tempService tempservice = (tempService) wac.getBean("tempService");
	if(tempservice.getTemp(out_trade_no)==null)
	tempservice.addTemp(x);
	
	//输出
	out.println(result);
%>
<body>
</body>
</html>

扫码支付

3.请求同步回调,复制demo里的return_url.jsp到项目并修改
同步回调

<%@ page language="java" contentType="text/html; charset=utf-8"	pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>电脑网站支付return_url</title>
<script type="text/javascript">
	window.onload=function (){
		window.close();		
	};
</script>
</head>
<%@ page import="java.util.*"%>
<%@ page import="java.util.Map"%>
<%@ page import="com.alipay.config.*"%>
<%@ page import="com.alipay.api.*"%>
<%@ page import="com.alipay.api.internal.util.*"%>
<%
/* *
 * 功能:支付宝服务器同步通知页面
 * 日期:2017-03-30
 * 说明:
 * 以下代码只是为了方便商户测试而提供的样例代码,商户可以根据自己网站的需要,按照技术文档编写,并非一定要使用该代码。
 * 该代码仅供学习和研究支付宝接口使用,只是提供一个参考。


 *************************页面功能说明*************************
 * 该页面仅做页面展示,业务逻辑处理请勿在该页面执行
 */
 
	//获取支付宝GET过来反馈信息
	Map<String,String> params = new HashMap<String,String>();
	Map<String,String[]> requestParams = request.getParameterMap();
	for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
		String name = (String) iter.next();
		String[] values = (String[]) requestParams.get(name);
		String valueStr = "";
		for (int i = 0; i < values.length; i++) {
			valueStr = (i == values.length - 1) ? valueStr + values[i]
					: valueStr + values[i] + ",";
		}
		//乱码解决,这段代码在出现乱码时使用
		valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
		params.put(name, valueStr);
	}
	
	boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名

	//——请在这里编写您的程序(以下代码仅作参考)——
	if(signVerified) {
		//商户订单号
		String out_trade_no = new String(request.getParameter("out_trade_no").getBytes("ISO-8859-1"),"UTF-8");
	
		//支付宝交易号
		String trade_no = new String(request.getParameter("trade_no").getBytes("ISO-8859-1"),"UTF-8");
	
		//付款金额
		String total_amount = new String(request.getParameter("total_amount").getBytes("ISO-8859-1"),"UTF-8");
		
		out.println("trade_no:"+trade_no+"<br/>out_trade_no:"+out_trade_no+"<br/>total_amount:"+total_amount);
	}else {
		out.println("验签失败");
	}
	//——请在这里编写您的程序(以上代码仅作参考)——
%>
<body>
</body>
</html>

同步回调

4.请求异步回调,根据之前回调地址编写对应的请求响应代码做业务逻辑处理
异步回调

由于Controller只是简单的调用service函数而已,所以这里直接放service函数

@Override
	public void notify_url(HttpServletRequest request) throws AlipayApiException, UnsupportedEncodingException {
		//获取支付宝POST过来反馈信息
				Map<String,String> params = new HashMap<String,String>();
				Map<String,String[]> requestParams = request.getParameterMap();
				for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) { 
					String name = (String) iter.next();
					String[] values = (String[]) requestParams.get(name);
					String valueStr = "";
					for (int i = 0; i < values.length; i++) {
						valueStr = (i == values.length - 1) ? valueStr + values[i]
								: valueStr + values[i] + ",";
					}
					params.put(name, valueStr);
				}
		//签名认证
				boolean signVerified = AlipaySignature.rsaCheckV1(params, AlipayConfig.alipay_public_key, AlipayConfig.charset, AlipayConfig.sign_type); //调用SDK验证签名
				if(signVerified) {//验证成功
					//获取认证状态
					String trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8");
					//成功支付后在数据库添加记录
					if (trade_status.equals("TRADE_SUCCESS")){
					    //业务逻辑处理
						String order_id = params.get("out_trade_no");
						//获取预订单数据
						temp perorder = tempmapper.getTemp(order_id);
						
						//生成真正的订单
						orders x=new orders();
						x.setId(perorder.getId()); //订单id
						x.setUser_id(perorder.getUser_id());
						x.setArticle_id(perorder.getArticle_id());
						x.setNum(perorder.getNum());
						x.setPay_money(perorder.getPay_money());
						x.setAddress(perorder.getAddress());
						x.setTime(perorder.getTime());
						ordersmapper.insertOrder(x);
						
						//删除预订单缓存
						tempmapper.deleteTemp(order_id);
						
						//修改库存,销量
						articles article = articlesmapper.getArticle(x.getArticle_id());
						article.setHot(article.getHot()+x.getNum());
						article.setNum(article.getNum()-x.getNum());
						articlesmapper.updateArticle(article);
					}
				}
	}
  • 2
    点赞
  • 45
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你好!感谢你的提问。关于uniapp对接支付宝沙箱,你可以按照以下步骤进行操作: 1. 首先,你需要在支付宝开放平台注册开发者账号,并创建应用。确保你已经完成了开发者身份认证和应用信息填写。 2. 在uniapp项目中,安装uni-app插件管理器(HBuilderX工具中的插件市场中下载安装),然后搜索并安装"uni-app支付宝小程序插件"。 3. 打开HBuilderX工具,进入项目根目录,在manifest.json文件中配置插件,将"uni-app支付宝小程序插件"添加到"mp-alipay"的"plugins"节点下。 4. 在uniapp项目中创建一个支付页面,可以命名为"alipay",该页面用于支付宝支付的相关操作。 5. 在支付页面的js文件中,引入支付宝支付插件,并初始化支付参数。示例代码如下: ``` import alipay from '@/uni_modules/uni-alipay-app/uni-alipay-app.js'; export default { data() { return { orderInfo: {}, // 支付订单信息,包括订单号、金额等 }; }, methods: { // 调用支付宝支付 async aliPay() { const result = await alipay.tradeAppPay({ orderStr: 'YourOrderString', // 支付订单字符串,由后端生成 isTest: true, // 是否使用沙箱环境 }); // 处理支付结果 if (result.resultCode === '9000') { // 支付成功 // TODO: 处理支付成功逻辑 } else { // 支付失败 // TODO: 处理支付失败逻辑 } }, }, }; ``` 6. 在支付页面的wxml文件中,添加一个按钮,并绑定上一步中定义的aliPay方法。 7. 最后,你需要在支付宝开放平台的开发者中心,配置沙箱环境下的支付回调地址,并将该地址填写到你的应用支付配置中。 以上是基本的步骤,你可以根据实际需求进行调整和扩展。希望对你有所帮助!如果有任何问题,请随时向我提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值