微信公众号支付开发Demo

微信官方文档
建议大家先看下流程图:
微信公众号支付开发Demo_第1张图片

大概的流程是先获取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 params=request.getParameterMap();
                         for (Entry 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 data = new HashMap();
        //商品描述
        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 resp=null;
        try {

           resp = wxpay.unifiedOrder(data);
           for (Entry 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 Param = new HashMap();
            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("appId", Param.get("appId"));
                      model.addAttribute("timeStamp", Param.get("timeStamp"));
                      model.addAttribute("nonceStr",Param.get("nonceStr"));
                      model.addAttribute("pa", Param.get("package"));
                      model.addAttribute("signType",Param.get("signType"));
                      model.addAttribute("paySign",sign);

          return  "wxpay";
        }else {
            model.addAttribute("errmsg",resp.get("err_code"));
        }
        }else {
            //通信失败,请检查网络
            model.addAttribute("errmsg",resp.get("return_msg"));
        }

        return "wxpay";
    }



    /**
     * @Description : 支付结果通知
     * @Author : 高冷的美男子
     * @Date : Created in 10:51 2018/5/25
     */
    @RequestMapping("/notify_url1")
    public void payNotify(HttpServletRequest request,HttpServletResponse response){
    Mapmap=new HashMap();
        String out_trade_no=null;
        String return_code =null;
        try {
            InputStream inStream = request.getInputStream();
            ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = inStream.read(buffer)) != -1) {
                outSteam.write(buffer, 0, len);
            }
            outSteam.close();
            inStream.close();
            String resultStr  = new String(outSteam.toByteArray(),"utf-8");
           System.out.print("支付成功的回调:"+resultStr);
            Map resultMap =WXPayUtil.xmlToMap(resultStr);
            String result_code = (String) resultMap.get("result_code");
            String is_subscribe = (String) resultMap.get("is_subscribe");
            String transaction_id = (String) resultMap.get("transaction_id");
            String sign = (String) resultMap.get("sign");
            String time_end = (String) resultMap.get("time_end");
            String bank_type = (String) resultMap.get("bank_type");

            out_trade_no = (String) resultMap.get("out_trade_no");
            return_code = (String) resultMap.get("return_code");

            request.setAttribute("out_trade_no", out_trade_no);
            //通知微信.异步确认成功了.
            map.put("SUCCESS","SUCCESS");
            response.getWriter().write(WXPayUtil.mapToXml(map));
        }  catch (Exception e) {
            System.out.print("微信回调接口出现错误:");
            try {
                map.put("FAIL","error");
                response.getWriter().write(WXPayUtil.mapToXml(map));
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        }
        if(return_code.equals("SUCCESS")){
            //支付成功的业务逻辑
System.out.println(">>>>>>>>>>>>>>>>>>支付成功了");

        }else{
            //支付失败的业务逻辑
        }

    }

    public JSONObject getAccess_token(String code) {
        String url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + Constants.APP_ID + "&secret=" + Constants.APP_SECRET + "&code=" + code + "&grant_type=authorization_code";

        JSONObject jsonObject = HttpUtil.httpRequest(url, "GET", null);

        return jsonObject;

    }


}

配置类MyConfig 继承微信给SDK的配置类

package com.shine.house.util;

import com.github.wxpay.sdk.WXPayConfig;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;

public class MyConfig implements WXPayConfig {
    private byte[] certData;

    public MyConfig() throws Exception {
        String certPath = "D:/cert/apiclient_cert.p12";
        File file = new File(certPath);
        InputStream certStream = new FileInputStream(file);
        this.certData = new byte[(int) file.length()];
        certStream.read(this.certData);
        certStream.close();
    }
    //APPID
    public String getAppID() {
        return "000000000000000000";
    }
    //商户ID
    public String getMchID() {
        return "00000000000000000";
    }
    //获取接口秘钥
    public String getKey() {
        return "0000000000000000000000000000000";
    }
    //获取商户证书内容
    public InputStream getCertStream() {
        ByteArrayInputStream certBis = new ByteArrayInputStream(this.certData);
        return certBis;
    }

    public int getHttpConnectTimeoutMs() {
        return 8000;
    }

    public int getHttpReadTimeoutMs() {
        return 10000;
    }

}

工具类IpUtil 获取IP

/**
 * 
 */
package com.shine.house.util;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * @Description : IP 相关操作
 * @Author : 高冷的叶子
 * @Date : Created in 2018年3月10日 下午4:55:46
 */
public class IpUtil {

static Logger LOGGER= LoggerFactory.getLogger(IpUtil.class);


    /**
     * @Description : 获取IP
     * @Author : 高冷的叶子
     * @Date : Created in 2018年3月10日 下午5:00:20
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request) {
        String ipAddress = request.getHeader("x-forwarded-for");
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("Proxy-Client-IP");
        }
        if (ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getHeader("WL-Proxy-Client-IP");
        }
        if (StringUtils.isBlank(ipAddress) || "unknown".equalsIgnoreCase(ipAddress)) {
        ipAddress = request.getRemoteAddr();
        if (ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")) {
        //根据网卡取本机配置的IP
        InetAddress inet = null;
        try {
        inet = InetAddress.getLocalHost();
        } catch (UnknownHostException e) {
        e.printStackTrace();
        }
        ipAddress = inet.getHostAddress();
        }
        }
        //对于通过多个代理的情况,第一个IP为客户端真实IP,多个IP按照','分割
        if (ipAddress != null && ipAddress.length() > 15) { //"...".length() = 15
        if (ipAddress.indexOf(",") > 0) {
        ipAddress = ipAddress.substring(0, ipAddress.indexOf(","));
        }
        }
        return ipAddress;
        }





}

工具类 HttpUtil 以及 MyX509TrustManager

package com.shine.house.util;

import com.alibaba.fastjson.JSONObject;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;

public class HttpUtil {


    /**
     * 发起https请求并获取结果
     * @param requestUrl 请求地址
     * @param requestMethod 请求方式(GET、POST)
     * @param outputStr 提交的数据
     * @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
     */
    public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
        JSONObject jsonObject = null;
        StringBuffer buffer = new StringBuffer();
        try {
            // 创建SSLContext对象,并使用我们指定的信任管理器初始化
            TrustManager[] tm = { new MyX509TrustManager() };
            SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
            sslContext.init(null, tm, new java.security.SecureRandom());
            // 从上述SSLContext对象中得到SSLSocketFactory对象
            SSLSocketFactory ssf = sslContext.getSocketFactory();
            URL url = new URL(requestUrl);
            HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
            httpUrlConn.setSSLSocketFactory(ssf);
            httpUrlConn.setDoOutput(true);
            httpUrlConn.setDoInput(true);
            httpUrlConn.setUseCaches(false);
            // 设置请求方式(GET/POST)
            httpUrlConn.setRequestMethod(requestMethod);
            if ("GET".equalsIgnoreCase(requestMethod))
                httpUrlConn.connect();
            // 当有数据需要提交时
            if (null != outputStr) {
                OutputStream outputStream = httpUrlConn.getOutputStream();
                // 注意编码格式,防止中文乱码
                outputStream.write(outputStr.getBytes("UTF-8"));
                outputStream.close();
            }
            // 将返回的输入流转换成字符串
            InputStream inputStream = httpUrlConn.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
            BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
            String str = null;
            while ((str = bufferedReader.readLine()) != null) {
                buffer.append(str);
            }
            bufferedReader.close();
            inputStreamReader.close();
            // 释放资源
            inputStream.close();
            inputStream = null;
            httpUrlConn.disconnect();
            jsonObject = JSONObject.parseObject(buffer.toString());
        } catch (ConnectException ce) {
            ce.printStackTrace();
        } catch (Exception e) {
        e.printStackTrace();
        }
        return jsonObject;
    }


}

package com.shine.house.util;


import javax.net.ssl.X509TrustManager;
import java.security.cert.CertificateException;
import java.security.cert.X509Certificate;

public class MyX509TrustManager implements X509TrustManager {
    public void checkClientTrusted(X509Certificate[] chain, String authType)
            throws CertificateException
    {
    }

    public void checkServerTrusted(X509Certificate[] chain, String authType)
            throws CertificateException
    {
    }

    public X509Certificate[] getAcceptedIssuers()
    {
        return null;
    }
}

JSP页面 wxpay.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
head>
<script src="/js/jquery.min.js"/>

                    
                    

你可能感兴趣的:(技术小白,微信支付)