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
m = XMLUtil4jdom.doXMLParse(sb.toString());
//过滤空 设置 TreeMap
SortedMap
5.查询回调状态(基本上到这一步就搞定了,下面是所需的工具类)
/**
* 查询回调状态
* @param user
* @param request
* @param response
* @param modelMap
* @return
*/
@ResponseBody
@RequestMapping("/hadPay.do")
public Map
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
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
@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"; SortedMappackageParams = new TreeMap (); 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; } } packageParams = new TreeMap (); 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 success(Object data) {
return toMap("data", data, "result", ConstantBean.SUCCESS);
}
protected Map error(Object data) {
return toMap("data", data, "result", ConstantBean.ERROR);
}
protected Map 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