微信小程序发起支付 Java后台处理代码----

直接上代码吧!

我把自己的业务逻辑代码删了,但是都有注释的 莫慌!

package com.mvc.controller;import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import net.sf.json.JSONObject;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;import com.mvc.entity.MoneyVo;
import com.mvc.entity.StudentVo;
import com.mvc.entity.TeacherVo;
import com.mvc.entity.TpayRecord;
import com.mvc.service.MoneyService;
import com.mvc.service.StudentService;
import com.mvc.service.TeacherService;
import com.mvc.service.TpayRecordService;
import com.mvc.util.DateUtil;
import com.mvc.util.StringofUtils;
import com.mvc.util.wxUtils.HttpRequest;
import com.mvc.util.wxUtils.IpUtils;
import com.mvc.util.wxUtils.StringUtils;
import com.mvc.util.wxUtils.weixin.PayUtil;
import com.mvc.util.wxUtils.weixin.config.WxPayConfig;/*** @Description: 本示例仅供参考,请根据自己的使用情景进行修改* @Date: 2019-03-12* @Author: gxp*/
@Controller
@RequestMapping("/weixin")
public class WeixinController{private static final String appid = "你自己的小程序appid";        //微信小程序appidprivate static final String secret = "当然还是你自己的小程序密钥";    //微信小程序密钥private static final String grant_type = "authorization_code";   //  这是我自己的Service @Autowiredprivate TpayRecordService tpayRecordDao;@Autowiredprivate MoneyService moneyService;@Autowiredprivate  StudentService studentService;@Autowiredprivate TeacherService teacherService;/*** 小程序后台登录,向微信平台发送获取access_token请求,并返回openId** @param code* @return openid* @throws WeixinException* @throws IOException*/@RequestMapping("Wxlogin")@ResponseBodypublic Object login(HttpServletRequest request,HttpServletResponse response){Map<String, Object> resultMap=new HashMap<String, Object>();String code =request.getParameter("code");if(StringofUtils.hasEmpty(code)){resultMap.put("flag", false);resultMap.put("msg", "业务参数不完整");return resultMap;}//拼接参数String param = "?grant_type=" + grant_type + "&appid=" + appid + "&secret=" + secret + "&js_code=" + code;String sr = HttpRequest.sendGet("https://api.weixin.qq.com/sns/jscode2session", param);// analysis request contentJSONObject json = JSONObject.fromObject(sr);// getting open_idString openId = json.get("openid").toString();resultMap.put("flag", true);resultMap.put("msg", "请求成功");resultMap.put("data", openId);return resultMap;}/*** @Description: 发起微信支付* @param openid* @param request* @author: gxp*/@RequestMapping("wxPay")@ResponseBodypublic Object wxPay(HttpServletRequest request,HttpServletResponse response){Map<String, Object> resultMap=new HashMap<String, Object>();String openid =request.getParameter("openid");String campusCard =request.getParameter("campusCard");String oldMeney=request.getParameter("oldMeney").toString();String money = getMoney(oldMeney);//支付金额,单位:分,这边需要转成字符串类型,否则后面的签名会失败String userId =request.getParameter("userId").toString();String userType =request.getParameter("userType").toString();if(StringofUtils.hasEmpty(openid,oldMeney,userId,userType,campusCard)){resultMap.put("flag", false);resultMap.put("msg", "业务参数不完整");return resultMap;}try{//生成的随机字符串String nonce_str = StringUtils.getRandomStringByLength();//商品名称String body = "XX商品充值";//获取本机的ip地址String spbill_create_ip = IpUtils.getIpAddr(request);String orderNo = nonce_str;Map<String, String> packageParams = new HashMap<String, String>();packageParams.put("appid", WxPayConfig.appid);packageParams.put("body", body);packageParams.put("mch_id", WxPayConfig.mch_id);packageParams.put("nonce_str", nonce_str);packageParams.put("notify_url", WxPayConfig.notify_url);packageParams.put("openid", openid);packageParams.put("out_trade_no", orderNo);//商户订单号packageParams.put("spbill_create_ip", spbill_create_ip);packageParams.put("total_fee", money);//支付金额,这边需要转成字符串类型,否则后面的签名会失败packageParams.put("trade_type", WxPayConfig.TRADETYPE);// 除去数组中的空值和签名参数packageParams = PayUtil.paraFilter(packageParams);String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串//MD5运算生成签名,这里是第一次签名,用于调用统一下单接口String mysign = PayUtil.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();//拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去String xml = "<xml>" + "<appid>" + WxPayConfig.appid + "</appid>"+ "<body><![CDATA[" + body + "]]></body>"+ "<mch_id>" + WxPayConfig.mch_id + "</mch_id>"+ "<nonce_str>" + nonce_str + "</nonce_str>"+ "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"+ "<openid>" + openid + "</openid>"+ "<out_trade_no>" + orderNo + "</out_trade_no>"+ "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>"+ "<total_fee>" + money + "</total_fee>"+ "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"+ "<sign>" + mysign + "</sign>"+ "</xml>";//调用统一下单接口,并接受返回的结果String result = PayUtil.httpRequest(WxPayConfig.pay_url, "POST", xml);// 将解析结果存储在HashMap中Map map = PayUtil.doXMLParse(result);String return_code = (String) map.get("return_code");//返回状态码//返回给移动端需要的参数Map<String, Object> responses = new HashMap<String, Object>();if(return_code == "SUCCESS" || return_code.equals(return_code)){// 业务结果String prepay_id = (String) map.get("prepay_id");//返回的预付单信息responses.put("nonceStr", nonce_str);responses.put("package", "prepay_id=" + prepay_id);Long timeStamp = System.currentTimeMillis() / 1000;responses.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=" + WxPayConfig.SIGNTYPE + "&timeStamp=" + timeStamp;//再次签名,这个签名用于小程序端调用wx.requesetPayment方法String paySign = PayUtil.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();responses.put("paySign", paySign);//更新订单信息//业务逻辑代码}responses.put("appid", WxPayConfig.appid);resultMap.put("flag", true);resultMap.put("msg", "发起支付成功");resultMap.put("date",responses);}catch(Exception e){e.printStackTrace();resultMap.put("flag", false);resultMap.put("msg", "发起支付失败");}return resultMap;}/*** @Description:微信支付* @return* @author gxp* @throws Exception* @throws WeixinException*/@RequestMapping(value="/wxNotify")@ResponseBodypublic void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));String line = null;StringBuilder sb = new StringBuilder();while((line = br.readLine())!=null){sb.append(line);}br.close();//sb为微信返回的xmlString notityXml = sb.toString();String resXml = "";Map map = PayUtil.doXMLParse(notityXml);String returnCode = (String) map.get("return_code");String orderNo = (String) map.get("out_trade_no");if("SUCCESS".equals(returnCode)){//收到微信支付成功通知resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";//这里写你自己的业务逻辑代码}else{resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";}System.out.println("--------------微信回调---------------");BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());out.write(resXml.getBytes());out.flush();out.close();}/*** 元转换成分* @param amount* @return*/public static String getMoney(String amount) {if(amount==null){return "";}// 金额转化为分为单位// 处理包含, ¥ 或者$的金额String currency =  amount.replaceAll("\\$|\\¥|\\,", "");int index = currency.indexOf(".");int length = currency.length();Long amLong = 0l;if(index == -1){amLong = Long.valueOf(currency+"00");}else if(length - index >= 3){amLong = Long.valueOf((currency.substring(0, index+3)).replace(".", ""));}else if(length - index == 2){amLong = Long.valueOf((currency.substring(0, index+2)).replace(".", "")+0);}else{amLong = Long.valueOf((currency.substring(0, index+1)).replace(".", "")+"00");}return amLong.toString();}
}

emm....剩下的工具类啥的 我直接发资源包你们下载吧!

https://download.csdn.net/download/qq_19385067/12244077

微信小程序支付 Java后端代码详解相关推荐

  1. java小程序详解_微信小程序登录Java后台接口(详解,附示例代码)

    首先看一下官方文档 地址:微信小程序官方文档API登录接口 我们先对官方给的时序图进行简单的分析 1.当小程序调用wx.login()时,会获得一个code(临时登录凭证),然后我们需要用wx.req ...

  2. 微信小程序api,带代码详解

    微信小程序内置api 1.界面 1.wx.showToast(Object object)显示消息提示框 wx.showToast({title: '你好',icon:"none" ...

  3. 微信小程序篇_01 微信小程序与Java后端接口交互

    微信小程序与Java后端接口交互 准备 创建后端项目 创建小程序项目 本文主要介绍小程序前后端数据的交互,实践演示. 准备 创建后端项目 我这里就创建一个SpringBoot项目作为演示. 在创建项目 ...

  4. 小程序setdata优化_微信小程序 setData的使用方法详解

    微信小程序 setData的使用方法详解 微信小程序 setData的使用方法详解 最近在使用微信小程序的setData时,遇到了以下问题.如下: 官网文档在使用setData()设置数组对象的某个元 ...

  5. 微信小程token_微信小程序url与token设置详解

    微信小程序url与token设置详解 新浪云应用sae的代码里创建一个weixin.php文件,写入以下代码 isValid(); class wechatAPI { public function ...

  6. 微信小程序一键置顶操作详解:

    微信小程序一键置顶操作详解: 第一种方式:采用scroll-view滚动视图实现 第二种方式,直接用view实现 第一种方式:采用scroll-view滚动视图实现 下面是代码简介: wxml文件代码 ...

  7. 微信小程序支付 java

    话不多说,直接开撸. 支付流程步骤: 1)首先调用wx.login方法获取code,通过code获取openid: 2)java后台调用统一下单支付接口(这里会进行第一次签名),用来获取prepay_ ...

  8. 微信小程序支付java服务端集成采坑总结

    先上个微信小程序支付官方文档地址: https://pay.weixin.qq.com/wiki/doc/api/wxa/wxa_api.php?chapter=9_7&index=8 重点看 ...

  9. 微信小程序向java后端发送对象时 ,后端接收不到

    微信小程序前端向后端发送对象接收不到 这里时请求头 这里时data中做的假数据 这是封装好的 post请求 后端的Controller代码 返回的结果 接收结果为null  但是可以接到可以用过 加@ ...

最新文章

  1. 生信服务器 | 防火墙基本配置
  2. matlab怎么跑.cpp程序,MATLAB编译cpp文件
  3. Java定时任务调度工具
  4. Excel VBA中的等价(Eqv)和蕴含(Imp)
  5. java数字转字符串及字符串转数字
  6. Eclipse+pydev+手动安装
  7. NUC972配置为支持NFS
  8. yum命令不能使用的相关错误
  9. 分享30个打动你的摄影师作品集网站
  10. 拦截导弹(CDQ分治,DP)
  11. 8款最受欢迎的HTML5/CSS3应用及源码
  12. 闲置的eSATA接口,会影响Windows 7的启动速度
  13. 网页提示504 gateway time-out是什么意思?如何解决?
  14. 大学计算机基础四大专业课,《大学计算机基础》课程教学大纲.doc
  15. 机器人学与OROCOS-KDL(一)简介
  16. java计算机毕业设计基于web旅游网站的设计与实现源代码+数据库+系统+lw文档
  17. GitHub上传教程,图文并茂
  18. vue2.0分页插件官方_Vue 2的最佳和完整分页插件
  19. myd文件 php项目,MYSQL表引擎与文件.frm,.myd,.myi
  20. yum的配置文件yum.conf详解

热门文章

  1. [BUUCTF]zip伪加密
  2. ultraedit删除重复项_UltraEdit技巧点点滴滴
  3. 彻底删除卸载、删除loaderrunner
  4. Nhiberate了解
  5. python中一切内容都可以称为对象吗_Python中对象的概念很广泛,Python中的一切内容都可以称为 。...
  6. 楼兰图腾 线段树模板
  7. K8s in Action 阅读笔记——【9】Deployments: updating applications declaratively
  8. sinr的值在多少到多少之间
  9. pl_slam配置、运行过程
  10. 什么是linux进程的挂起,linux挂起进程命令