1.首先我们先下载微信支付的服务器端demo得到其中的工具类
2.更改PayConfigUtil.java工具类中的参数
参数配置配ok了基本没问题
3.支付接口代码(这个接口会直接返回一个二维码)
@Inject
private UserService userApplication;
private String weChatStatusCode;
/**
* 微信支付
* @param request
* @param response
* @param modelMap
*/
@ResponseBody
@RequestMapping("/qrcode.do")
public void qrcode(HttpServletRequest request, HttpServletResponse response,
ModelMap modelMap) {
try {
String productId = request.getParameter("productId");
String userId = "user01";
String text = userApplication.weixinPay(userId, productId);
int width = 300;
int height = 300;
//二维码的图片格式
String format = "gif";
Hashtable hints = new Hashtable();
//内容所使用编码
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
BitMatrix bitMatrix;
try {
bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, hints);
QRUtil.writeToStream(bitMatrix, format, response.getOutputStream());
} catch (WriterException e) {
e.printStackTrace();
}
} catch (Exception e) {
}
}
4.回调接口代码(a.注意回调接口必须在微信公众号设置好,要与PayConfigUtil类中的NOTIFY_URL参数一致,b.关于weChatStatusCode这个参数只是我用来保存临时状态,那一块业务逻辑可以自己去改).
/**
* 微信回调
* @param request
* @param response
* @throws JDOMException
* @throws Exception
*/
@ResponseBody
@RequestMapping("/weixinNotify")
public void weixinNotify(HttpServletRequest request, HttpServletResponse response) throws JDOMException, Exception{
//读取参数
InputStream inputStream ;
StringBuffer sb = new StringBuffer();
inputStream = request.getInputStream();
String s ;
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));
while ((s = in.readLine()) != null){
sb.append(s);
}
in.close();
inputStream.close();
//解析xml成map
Map<String, String> m = new HashMap<String, String>();
m = XMLUtil4jdom.doXMLParse(sb.toString());
//过滤空 设置 TreeMap
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
Iterator it = m.keySet().iterator();
while (it.hasNext()) {
String parameter = (String) it.next();
String parameterValue = m.get(parameter);
String v = "";
if(null != parameterValue) {
v = parameterValue.trim();
}
packageParams.put(parameter, v);
}
// 账号信息
String key = PayConfigUtil.API_KEY; //key
//判断签名是否正确
if(PayToolUtil.isTenpaySign("UTF-8", packageParams,key)) {
//------------------------------
//处理业务开始
//------------------------------
String resXml = "";
System.out.println("返回状态:"+packageParams.get("result_code"));
if("SUCCESS".equals((String)packageParams.get("result_code"))){
// 这里是支付成功
//执行自己的业务逻辑
String mch_id = (String)packageParams.get("mch_id");
String openid = (String)packageParams.get("openid");
String is_subscribe = (String)packageParams.get("is_subscribe");
String out_trade_no = (String)packageParams.get("out_trade_no");
String total_fee = (String)packageParams.get("total_fee");
//执行自己的业务逻辑
//暂时使用最简单的业务逻辑来处理:只是将业务处理结果保存到session中
//(根据自己的实际业务逻辑来调整,很多时候,我们会操作业务表,将返回成功的状态保留下来)
//request.getSession().setAttribute("_PAY_RESULT", "OK");
weChatStatusCode = (String) packageParams.get("result_code");
System.out.println("支付成功");
//通知微信.异步确认成功.必写.不然会一直通知后台.八次之后就认为交易失败了.
resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
+ "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
System.out.println("支付成功2");
} else {
weChatStatusCode = "err";
resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
+ "<return_msg><![CDATA[报文为空]]></return_msg>" + "</xml> ";
}
//------------------------------
//处理业务完毕
//------------------------------
BufferedOutputStream out = new BufferedOutputStream(
response.getOutputStream());
out.write(resXml.getBytes());
out.flush();
out.close();
System.out.println("回调成功");
} else{
System.out.println("通知签名验证失败");
}
}
5.查询回调状态(基本上到这一步就搞定了,下面是所需的工具类)
/**
* 查询回调状态
* @param user
* @param request
* @param response
* @param modelMap
* @return
*/
@ResponseBody
@RequestMapping("/hadPay.do")
public Map<String, Object> hadPay(UserVO user, HttpServletRequest request, HttpServletResponse response,
ModelMap modelMap) {
try {
//简单的业务逻辑:在微信的回调接口里面,已经定义了,回调返回成功的话,那么 _PAY_RESULT 不为空
System.out.println("状态码"+weChatStatusCode);
//if(request.getSession().getAttribute("_PAY_RESULT") != null ){
if("SUCCESS".equals(weChatStatusCode)){
return success("支付成功!");
}
return error("没成功");
} catch (Exception e) {
return error(e);
}
}ram response
* @param modelMap
* @return
*/
@ResponseBody
@RequestMapping("/hadPay.do")
public Map<String, Object> hadPay(UserVO user, HttpServletRequest request, HttpServletResponse response,
ModelMap modelMap) {
try {
//简单的业务逻辑:在微信的回调接口里面,已经定义了,回调返回成功的话,那么 _PAY_RESULT 不为空
System.out.println("状态码"+weChatStatusCode);
//if(request.getSession().getAttribute("_PAY_RESULT") != null ){
if("SUCCESS".equals(weChatStatusCode)){
return success("支付成功!");
}
return error("没成功");
} catch (Exception e) {
return error(e);
}
}
2.UserService
package cn.itcast.service;
/**
*
* @author xgchen
*
*/
public interface UserService {
String weixinPay(String userId, String productId) throws Exception;
}
2.UserServiceImpl(这个实现类中的参数可以根据以后需求动态获取)
package cn.itcast.service.impl;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.inject.Named;
import cn.itcast.service.UserService;
import cn.itcast.utils.HttpUtil;
import cn.itcast.utils.PayConfigUtil;
import cn.itcast.utils.PayToolUtil;
import cn.itcast.utils.XMLUtil4jdom;
@Named("userService")
public class UserServiceImpl implements UserService {
@Override
public String weixinPay(String userId, String productId) throws Exception {
String out_trade_no = "" + System.currentTimeMillis(); //订单号 (调整为自己的生产逻辑)
// 账号信息
String appid = PayConfigUtil.APP_ID; // appid
//String appsecret = PayConfigUtil.APP_SECRET; // appsecret
String mch_id = PayConfigUtil.MCH_ID; // 商业号
String key = PayConfigUtil.API_KEY; // key
String currTime = PayToolUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayToolUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// 获取发起电脑 ip
String spbill_create_ip = PayConfigUtil.CREATE_IP;
// 回调接口
String notify_url = PayConfigUtil.NOTIFY_URL;
String trade_type = "NATIVE";
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", appid);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", "可乐"); //(调整为自己的名称)
packageParams.put("out_trade_no", out_trade_no);
packageParams.put("total_fee", "1"); //价格的单位为分
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
String sign = PayToolUtil.createSign("UTF-8", packageParams,key);
packageParams.put("sign", sign);
String requestXML = PayToolUtil.getRequestXml(packageParams);
System.out.println(requestXML);
String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);
Map map = XMLUtil4jdom.doXMLParse(resXml);
String urlCode = (String) map.get("code_url");
return urlCode;
}
}
@Override
public String weixinPay(String userId, String productId) throws Exception {
String out_trade_no = "" + System.currentTimeMillis(); //订单号 (调整为自己的生产逻辑)
// 账号信息
String appid = PayConfigUtil.APP_ID; // appid
//String appsecret = PayConfigUtil.APP_SECRET; // appsecret
String mch_id = PayConfigUtil.MCH_ID; // 商业号
String key = PayConfigUtil.API_KEY; // key
String currTime = PayToolUtil.getCurrTime();
String strTime = currTime.substring(8, currTime.length());
String strRandom = PayToolUtil.buildRandom(4) + "";
String nonce_str = strTime + strRandom;
// 获取发起电脑 ip
String spbill_create_ip = PayConfigUtil.CREATE_IP;
// 回调接口
String notify_url = PayConfigUtil.NOTIFY_URL;
String trade_type = "NATIVE";
SortedMap<Object,Object> packageParams = new TreeMap<Object,Object>();
packageParams.put("appid", appid);
packageParams.put("mch_id", mch_id);
packageParams.put("nonce_str", nonce_str);
packageParams.put("body", "可乐"); //(调整为自己的名称)
packageParams.put("out_trade_no", out_trade_no);
packageParams.put("total_fee", "1"); //价格的单位为分
packageParams.put("spbill_create_ip", spbill_create_ip);
packageParams.put("notify_url", notify_url);
packageParams.put("trade_type", trade_type);
String sign = PayToolUtil.createSign("UTF-8", packageParams,key);
packageParams.put("sign", sign);
String requestXML = PayToolUtil.getRequestXml(packageParams);
System.out.println(requestXML);
String resXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);
Map map = XMLUtil4jdom.doXMLParse(resXml);
String urlCode = (String) map.get("code_url");
return urlCode;
}
}
3.BaseController
package com.demodashi;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.LinkedHashMap;
import java.util.Map;
import javax.servlet.http.HttpServletResponse;
import org.springframework.util.Assert;
@SuppressWarnings("unchecked")
public class BaseController {
public void outPrint(HttpServletResponse response, String result) throws IOException {
PrintWriter out = response.getWriter();
out.print(result);
}
protected Map<String, Object> success(Object data) {
return toMap("data", data, "result", ConstantBean.SUCCESS);
}
protected Map<String, Object> error(Object data) {
return toMap("data", data, "result", ConstantBean.ERROR);
}
protected Map<String, Object> error(Throwable t) {
return toMap("data", t.getMessage(), "result", ConstantBean.ERROR);
}
public static Map toMap(Object... params) {
Map map = new LinkedHashMap();
Assert.notNull(params);
Assert.isTrue(params.length % 2 == 0);
for (int i = 0; i < params.length; i++) {
map.put(params[i++], params[i]);
}
return map;
}
}
4.ConstantBean
package com.demodashi;
/**
*
* @author xgchen
*
*/
public final class ConstantBean {
public final static String SUCCESS = "0";//成功
public final static String ERROR = "1";//失败
public final static String SYSERR = "-1";//系统错误
}
5.UserVO
package com.demodashi;
import java.io.Serializable;
@SuppressWarnings("serial")
public class UserVO implements Serializable {
private String id;
private String name;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
工具类我就不一个一个贴出来了 ,微信官方demo有 以下是我做完后的效果
发起支付
到服务器查看日志
调用查询状态接口
微信扫码支付就搞定了
这是这两年来总结的微信支付宝官方支付的接入代码,流程已全部走通,下载即用:https://download.csdn.net/download/qq_40717036/11866169