微信官方文档
建议大家先看下流程图:
大概的流程是先获取openid –>统一下单 –> 返回预支付交易会话标识 prepay_id等参数 –>然后返回页面h5调用微信支付的页面
获取openid
代码如下:
package com.shine.house.controller;
import com.alibaba.fastjson.JSONObject;
import com.github.wxpay.sdk.WXPay;
import com.github.wxpay.sdk.WXPayConstants;
import com.github.wxpay.sdk.WXPayUtil;
import com.shine.house.util.Constants;
import com.shine.house.util.HttpUtil;
import com.shine.house.util.IpUtil;
import com.shine.house.util.MyConfig;
import com.shine.house.util.OnlyId;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
@Controller
public class WxPayController {
/**
* @Description : 前往微信获取openId
* @Author : 高冷的美男子
* @Date : Created in 8:52 2018/5/25
*/
@RequestMapping(value = {
"/toGetOpenID", "/"})
public void toWeChat(HttpServletRequest request, HttpServletResponse response) throws Exception {
//第一步:用户同意授权,获取code,会重定向到backUrl
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" + Constants.APP_ID
+ "&redirect_uri=" + URLEncoder.encode(Constants.BACKURL)
+ "&response_type=code"
+ "&scope=snsapi_base"
+ "&state=STATE#wechat_redirect";
response.sendRedirect(url);
}
/**
* 微信网页授权获得微信详情
*
* @param code
* @param state
* @throws ServletException
* @throws IOException
*/
@RequestMapping("/getOpenInfo")
public String getOpenInfo(HttpServletRequest request, HttpServletResponse response, Model model) throws Exception {
String code=request.getParameter("code");
if(code==null) {
System.out.println("未获取到微信授权,返回参数如下:");
Map<String, String[]> params=request.getParameterMap();
for (Entry<String, String[]> entry: params.entrySet()) {
System.out.println("key:"+entry.getKey()+" Value:"+entry.getValue());
}
return "wepay";
}
//用户同意
JSONObject result = getAccess_token(code);
if (result.get("errcode") == null) {
//成功 返回到首页
String openid = (String) result.get("openid");
String access_token = (String) result.get("access_token");
HttpSession session = request.getSession();
session.setAttribute("openid", openid);
session.setAttribute("access_token", access_token);
if (openid==null){
model.addAttribute("errmsg","openid为空");
}
if (access_token==null){
model.addAttribute("errmsg","access_token为空");
}
System.out.println("openid:"+openid);
return "wepay";
} else {
//失败
model.addAttribute("errmsg","获取openid失败,请重新尝试");
}
return "wepay";
}
/**
* @Description : 统一下单
* @Author : 高冷的美男子
* @Date : Created in 9:20 2018/5/25
*/
@RequestMapping("/unifiedOrder")
public String unifiedOrder(@RequestParam("total_fee") Double total_fee,HttpServletRequest request,Model model) throws Exception {
HttpSession session=request.getSession();
String spbill_create_ip=IpUtil.getIp(request);
//统一下单
MyConfig config = new MyConfig();
WXPay wxpay = new WXPay(config);
Map<String, String> data = new HashMap<String, String>();
//商品描述
data.put("body", "test充钱");
//商户订单号
data.put("out_trade_no", OnlyId.getOnlyOrderNo());
int fee=(int) (total_fee*100);
//标价金额 付款金额
data.put("total_fee", String.valueOf(fee));
//客户终端IP
data.put("spbill_create_ip", spbill_create_ip);
//异步接收微信支付结果通知的回调地址,通知url必须为外网可访问的url,不能携带参数。
data.put("notify_url", Constants.NOTIFY_URL);
//交易类型 公众号支付
data.put("trade_type", "JSAPI");
//用户标识
data.put("openid",(String) session.getAttribute("openid"));
Map<String, String> resp=null;
try {
resp = wxpay.unifiedOrder(data);
for (Entry<String, String> entry: resp.entrySet()) {
System.out.println("key:"+entry.getKey()+" Value:"+entry.getValue());
}
} catch (Exception e) {
e.printStackTrace();
}
if (resp.get("return_code").equals("SUCCESS")){
if (resp.get("result_code").equals("SUCCESS")){
Map<String, String> Param = new HashMap<String, String>();
Param.put("appId", Constants.APP_ID);
Param.put("timeStamp", String.valueOf(System.currentTimeMillis() / 1000));
Param.put("nonceStr", WXPayUtil.generateNonceStr());
Param.put("package", "prepay_id=" + resp.get("prepay_id"));
Param.put("signType", Constants.SIGN_TYPE);
String sign=WXPayUtil.generateSignature(Param,config.getKey(),WXPayConstants.SignType.MD5);
Param.put("paySign",sign);
model.addAttribute(