标签:hid weight src utf-8 hashmap += date note char
支付宝H5支付
首先我们必须注册一个支付宝应用(本案例就直接用支付宝的沙箱环境,这个沙箱也就是支付宝提供给开发者的一个测试环境)
登录地址:https://open.alipay.com/platform/home.htm
1、怎么注册一个支付宝应用?看图(至于应用里面需要的资料你就跟着填就ok了,我就不多讲了,关于公钥秘钥这些,支付宝也有它自己的工具自动生成)
2、怎么获取沙箱环境?(看图)
就这样,支付宝的基本配置我们都能get到了,下面开始写代码吧!
3、思路描述
支付宝的h5支付比微信的h5支付简单很多,下面先跟大家看看项目文件数量吧
就7个文件左右就可以实现支付了,是不是很简单呢?(下一篇是微信h5就没有那么简单了)
接着我说说里面每个文件他们的作用后再看代码吧!!!
AlipayConfig.java ----------------------------用于存储支付宝的相关配置信息
AlinotifyServlet.java ----------------------------用于支付后,返回的结果,接着做你的对应业务的
AlipayServlet.java ----------------------------用于实现支付操作
logFile.java ----------------------------用于打印日志
Constants.java ----------------------------用于存储常量
index.jsp ----------------------------用于用户发起支付请求
return_jsp.jsp ---------------------------用于支付后返回的页面
好,现在开始代码展示:
首先要配置AlipayConfig.java (这些参数我现在用的都是沙箱环境的)
package fe.client.pay.alipay.config; import fe.client.pay.tool.Constants; public class AlipayConfig { // 商户appid public static String APPID = "2017092077552049"; // 私钥 pkcs8格式的 public static String RSA_PRIVATE_KEY = "greterthhoihrhigfdhouiihgfdooihrroihhigdshgfdfoihgdhgfdkjlnfdbknunifdhugfhidfhglkfdvkjlfilhfdiohrewiouihvfbkjnvfdbkjncdhkjoihfdi3uy9283hjdofhgghnxociby98knlknsdkljfsdlkfsdjsdjoflsdjfsldgfjsdf"; // 服务器异步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 public static String notify_url = "http://"+Constants.SERVER_ADDRESS+"/goshop/notify_url.jsp"; // 页面跳转同步通知页面路径 需http://或者https://格式的完整路径,不能加?id=123这类自定义参数,必须外网可以正常访问 商户可以自定义同步跳转地址 public static String return_url = "http://"+Constants.SERVER_ADDRESS+"/goshop/return_url.jsp"; // 请求网关地址 public static String URL = "https://openapi.alipaydev.com/gateway.do"; // 编码 public static String CHARSET = "UTF-8"; // 返回格式 public static String FORMAT = "json"; // 支付宝公钥 public static String ALIPAY_PUBLIC_KEY = "qazwsxdedcfrfvgytghbnujikfgvbbyujikjgfgfiuouyfugbgikbnojopih"; // 日志记录目录 public static String log_path = "/log"; // RSA2 public static String SIGNTYPE = "RSA2"; }
Constants.java
package fe.client.pay.tool; /** * 该类专门用于存储项目中用到的常量类 * ClassName: Constants * @Description: TODO * @author 邝梓荣 * @date 2018-11-21 */ public class Constants { //服务器地址 public final static String SERVER_ADDRESS = "127.0.0.1"; // public final static String SERVER_ADDRESS = "www.wigoule.com"; //上传时读到服务器内存中设定的限制(与服务器配置成正比 与同时上传的人数成反比关系) public final static int SIZE_THRESHOLD = 64*1024; //3des加密24字节秘钥 public final static byte[] keyBytes = {0x11, 0x22, 0x4F, 0x58, (byte)0x88, 0x10, 0x40, 0x38 , 0x28, 0x25, 0x79, 0x51, (byte)0xCB, (byte)0xDD, 0x55, 0x66 , 0x77, 0x29, 0x74, (byte)0x98, 0x30, 0x40, 0x36, (byte)0xE2}; }
logFile.java
package fe.client.pay.alipay.util; import java.io.FileWriter; import java.io.IOException; import fe.client.pay.alipay.config.AlipayConfig; public class logFile { /** * 写日志,方便测试(看网站需求,也可以改成把记录存入数据库) * @param sWord 要写入日志里的文本内容 */ public static void logResult(String sWord) { FileWriter writer = null; try { writer = new FileWriter(AlipayConfig.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(); } } } } }
AlipayServlet.java
package fe.client.pay.alipay.sevice; import java.io.IOException; import java.net.URLDecoder; import java.net.URLEncoder; import fe.client.pay.alipay.config.AlipayConfig; import fe.client.pay.tool.Constants; import fe.client.pay.tool.NumberTool; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradeWapPayModel; import com.alipay.api.request.AlipayTradeWapPayRequest; import fe.project.ProjectCommonUtil; @WebServlet(name = "alipayServlet", urlPatterns = "/alipayServlet") public class AlipayServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(AlipayServlet.class); ProjectCommonUtil util=new ProjectCommonUtil(); public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.service(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ doPost(request, response); } /** * 商品订单支付 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ String notifyUrl = "http://"+"2ec17585.ngrok.io"+"/alinotifyServlet"; String returnUrl = "http://"+"2ec17585.ngrok.io"+"/zhyq/client/alipay/jsp/return_jsp.jsp"; try { Pay(notifyUrl,returnUrl,request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 支付宝支付接口 * @Description: TODO * @param @return * @param @throws Exception * @return String * @throws * @author 邝梓荣 * @date 2018-11-19 */ public String Pay(String notifyUrl, String returnUrl,HttpServletRequest request, HttpServletResponse response) throws Exception { request.setCharacterEncoding("UTF-8"); // 付款金额,必填 String total_amount=new String(request.getParameter("money").getBytes("ISO-8859-1"),"UTF-8"); //自定义参数,可空 String passback_params = new String(request.getParameter("orderIds").getBytes("ISO-8859-1"),"UTF-8"); // 商户订单号,商户网站订单系统中唯一订单号,必填 String out_trade_no = NumberTool.getCurrTime(); // 商品描述,可空 String body = "订单支付"; // 订单名称,必填 String subject = "购乐网商品支付"; // 超时时间 可空 String timeout_express="2m"; // 销售产品码 必填 String product_code="QUICK_WAP_WAY"; // SDK 公共请求类,包含公共请求参数,以及封装了签名与验签,开发者无需关注签名与验签 //调用RSA签名方式 AlipayClient client = new DefaultAlipayClient(AlipayConfig.URL, AlipayConfig.APPID, AlipayConfig.RSA_PRIVATE_KEY, AlipayConfig.FORMAT, AlipayConfig.CHARSET, AlipayConfig.ALIPAY_PUBLIC_KEY,AlipayConfig.SIGNTYPE); AlipayTradeWapPayRequest alipay_request=new AlipayTradeWapPayRequest(); // 封装请求支付信息 AlipayTradeWapPayModel model = new AlipayTradeWapPayModel(); model.setOutTradeNo(out_trade_no); model.setSubject(subject); model.setTotalAmount(total_amount); model.setBody(body); model.setTimeoutExpress(timeout_express); model.setProductCode(product_code); model.setPassbackParams(URLEncoder.encode(passback_params,"UTF-8")); alipay_request.setBizModel(model); // 设置异步通知地址 alipay_request.setNotifyUrl(notifyUrl); // 设置同步地址 alipay_request.setReturnUrl(returnUrl); // form表单生产 String form = ""; try { // 调用SDK生成表单 form = client.pageExecute(alipay_request).getBody(); response.setContentType("text/html;charset=" + AlipayConfig.CHARSET); response.getWriter().write(form);//直接将完整的表单html输出到页面 response.getWriter().flush(); response.getWriter().close(); } catch (AlipayApiException e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } }
AlinotifyServlet.java
package fe.client.pay.alipay.sevice; import java.io.IOException; import java.io.PrintWriter; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import fe.client.pay.alipay.config.AlipayConfig; import fe.client.pay.tool.Constants; import fe.client.pay.tool.NumberTool; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.Logger; import com.alipay.api.AlipayApiException; import com.alipay.api.AlipayClient; import com.alipay.api.DefaultAlipayClient; import com.alipay.api.domain.AlipayTradeWapPayModel; import com.alipay.api.internal.util.AlipaySignature; import com.alipay.api.request.AlipayTradeWapPayRequest; import fe.dao.Dao; import fe.project.ProjectCommonUtil; import fe.res.ResourceManage; @WebServlet(name = "alinotifyServlet", urlPatterns = "/alinotifyServlet") public class AlinotifyServlet extends HttpServlet { private static final long serialVersionUID = 1L; private static final Logger logger = Logger.getLogger(AlinotifyServlet.class); ProjectCommonUtil util=new ProjectCommonUtil(); public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { super.service(request, response); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ doPost(request, response); } /** * 商品订单支付 */ public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{ try { Goods(request, response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /** * 处理商品订单 * @throws Exception */ public void Goods(HttpServletRequest request, HttpServletResponse response) throws Exception { //获取支付宝POST过来反馈信息 Map<String,String> params = new HashMap<String,String>(); Map requestParams = request.getParameterMap(); for (Iterator 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] + ","; } //乱码解决,这段代码在出现乱码时使用。如果mysign和sign不相等也可以使用这段代码转化 //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "gbk"); params.put(name, valueStr); } //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以下仅供参考)// //商户订单号 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 trade_status = new String(request.getParameter("trade_status").getBytes("ISO-8859-1"),"UTF-8"); System.out.println("==================================================================================="); System.out.println("000000000000000000000000000000000000000000000000====="+trade_status); System.out.println("==================================================================================="); //获取支付宝的通知返回参数,可参考技术文档中页面跳转同步通知参数列表(以上仅供参考)// //计算得出通知验证结果 //boolean AlipaySignature.rsaCheckV1(Map<String, String> params, String publicKey, String charset, String sign_type) boolean verify_result = AlipaySignature.rsaCheckV1(params, AlipayConfig.ALIPAY_PUBLIC_KEY, AlipayConfig.CHARSET, "RSA2"); PrintWriter out = response.getWriter(); if(verify_result){//验证成功 ////////////////////////////////////////////////////////////////////////////////////////// //交易状态TRADE_FINISHED的通知触发条件是商户签约的产品不支持退款功能的前提下,买家付款成功;或者,商户签约的产品支持退款功能的前提下,交易已经成功并且已经超过可退款期限。 //状态TRADE_SUCCESS的通知触发条件是商户签约的产品支持退款功能的前提下,买家付款成功 if(trade_status.equals("TRADE_FINISHED")){ //判断该笔订单是否在商户网站中已经做过处理 //如果没有做过处理,根据订单号(out_trade_no)在商户网站的订单系统中查到该笔订单的详细,并执行商户的业务程序 //请务必判断请求时的total_fee、seller_id与通知时获取的total_fee、seller_id为一致的 } else if (trade_status.equals("TRADE_SUCCESS")){ String orderIds = (String) params.get("passback_params"); String[] orderId = orderIds.split(","); for(int i=0; i<orderId.length; i++){ // Order o = orderService.getOrder(Integer.parseInt(orderId[i])); // o.setStatus("1"); // orderService.updateOrder(o); } } out.flush(); out.println("success"); //请不要修改或删除 ////////////////////////////////////////////////////////////////////////////////////////// }else{//验证失败 out.println("fail"); } } }
index.jsp吧(这个页面其中有很多其他引入的东西可以不用的,因为页面是我直接复制一个项目的页面改一下body,我就懒得改上面了)
<%@ page contentType="text/html; charset=UTF-8" language="java" errorPage="" %> <jsp:directive.page import="fe.assets.FixedAssetsReport"/> <jsp:directive.page import="fe.zhyq.asset.service.AssetReportService"/> <jsp:directive.page import="fe.dao.DataTable"/> <jsp:directive.page import="fe.dao.FieldSet"/> <jsp:directive.page import="fe.datapool.DataPool"/> <jsp:directive.page import="fe.res.ResourceManage"/> <jsp:directive.page import="fe.sys.User"/> <jsp:directive.page import="fe.util.HtmlFormat"/> <jsp:directive.page import="java.util.Date"/> <jsp:directive.page import="java.util.Iterator"/> <!DOCTYPE html> <html> <head> <jsp:include flush="true" page="/common/header39.jsp"/> <script type=‘text/javascript‘ src=‘/js39/flyrise.report.merge.js‘></script> <link rel="stylesheet" type="text/css" href="/css39/bg_newsample_blue.css"/> <link rel="stylesheet" type="text/css" href="/css39/report.css"/> <script type="text/javascript" src="/js39/flyrise.organizeSelecter.js"></script> <script type="text/javascript" charset="utf-8" src="/js39/tag/flyrise.pagetag.js"></script> <script type="text/javascript" charset="utf-8" src="/js39/flyrise.feajax.js"></script> <script src="/js39/angularjs/angular.min.js"></script> <script src="/zhyq/js/syspublic.js"></script> <style type="text/css"> *{ margin:0; padding:0; } ul,ol{ list-style:none; } body{ font-family: "Helvetica Neue",Helvetica,Arial,"Lucida Grande",sans-serif; } .hidden{ display:none; } .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: 30px; border-radius: 5px; font-size: 16px; } #main{ width:100%; margin:0 auto; font-size:14px; } .red-star{ color:#f00; width:10px; display:inline-block; } .null-star{ color:#fff; } .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; } #foot{ margin-top:10px; position: absolute; bottom: 15px; width: 100%; } .foot-ul{ width: 100%; } .foot-ul li { width: 100%; text-align:center; color: #666; } .note-help { color: #999999; font-size: 12px; line-height: 130%; margin-top: 5px; width: 100%; display: block; } #btn-dd{ margin: 20px; text-align: center; } .foot-ul{ width: 100%; } .one_line{ display: block; height: 1px; border: 0; border-top: 1px solid #eeeeee; width: 100%; margin-left: 20px; } .am-header { display: -webkit-box; display: -ms-flexbox; display: box; width: 100%; position: relative; padding: 7px 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; } </style> </head> <body ng-app="zhyq_reportproject_app" ng-controller="zhyq_reportproject_controller" style="margin:0px; overflow:hidden;" class="report-tab-box"> <div id="main"> <form name=alipayment action=‘/alipayServlet‘ method=‘post‘ target="_blank"> <div id="body" style="clear:left"> <dl class="content"> <dt>商户订单号:</dt> <dd> <input id="orderIds" name="orderIds" /> </dd> <hr class="one_line"> <dt>订单名称:</dt> <dd> <input id="WIDsubject" name="WIDsubject" /> </dd> <hr class="one_line"> <dt>付款金额:</dt> <dd> <input id="money" name="money" /> </dd> <hr class="one_line"/> <dt>商品描述:</dt> <dd> <input id="WIDbody" name="WIDbody" /> </dd> <hr class="one_line"> <dt></dt> <dd id="btn-dd"> <span class="new-btn-login-sp"> <button class="new-btn-login" type="submit" style="text-align:center;">确 认</button> </span> <span class="note-help">如果您点击“确认”按钮,即表示您同意该次的执行操作。</span> </dd> </dl> </div> </form> <div id="foot"> <ul class="foot-ul"> <li> 支付宝版权所有 2015-2018 ALIPAY.COM </li> </ul> </div> </div> <script type="text/javascript"> function GetDateNow() { var vNow = new Date(); var sNow = ""; sNow += String(vNow.getFullYear()); sNow += String(vNow.getMonth() + 1); sNow += String(vNow.getDate()); sNow += String(vNow.getHours()); sNow += String(vNow.getMinutes()); sNow += String(vNow.getSeconds()); sNow += String(vNow.getMilliseconds()); document.getElementById("orderIds").value = sNow; document.getElementById("WIDsubject").value = "手机网站支付测试商品"; document.getElementById("money").value = "0.01"; document.getElementById("WIDbody").value = "购买测试商品0.01元"; } GetDateNow(); </script> </body> </html>
返回页面就不展示代码了,反正什么都可以
至于包,要引入支付宝的两个sdk包
最后!总结!!!
如果你还是觉得有点复杂,那我直接告诉你改哪些地方就可以直接运行吧!
支付包H5支付的就说到这里吧,希望大家多多支持,
有不懂的,或者想要源码的可以点击QQ在线联系找我喔
下一篇(微信H5支付demo)
标签:hid weight src utf-8 hashmap += date note char
原文地址:https://www.cnblogs.com/LarryBlogger/p/9993361.html