微信小程序支付(JAVA)

一、步骤

1、小程序调用wx.login获取code;

2、利用第一步中code,获取用户标识openid,接口地址

https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code

3、调用server商户下单,获取小程序支付所需参数;

4、取第三步返回参数,小程序调用wx.requestPayment拉起微信支付

5、回调,告知微信支付状态

二、代码展示

1、微信登录:

 wx.login({
      success: function (res) {
        if (res.code) {
          console.log('code:'+res.code);
          that.getOpenId(res.code)
        } else {
          console.log('登录失败!' + res.errMsg)
        }
      }

    });

2、获取用户标识openid:

 getOpenId:function(code){
    var that = this;
    wx.request({
      url: 'https://api.weixin.qq.com/sns/jscode2session?appid=wx296570050860e065&secret=7ce61e99bf90a6080af77113ea1278dc&js_code='+code+'&grant_type=authorization_code',
      data:{},
      method:'GET',
      success:function(res){
        console.log('openid:'+res.data.openid)
        that.order(res.data.openid);
        // that.refund(res.data.openid);
      },
      fail:function(){


      },
      complete:function(){


      }
    })

  }

3、调用server商户下单

(1)小程序

    order:function(openId){
    var that = this;
    wx.request({
      url: 'http://t7hhri.natappfree.cc/wechat/pay',
      header:{
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:'POST',
      data:{
        'openid': openId,
        'orderId':'036b2f8a56904804b3eb1da907735bc1',
        'orderNumber':'00630001201805230301000004',
        'deposit':'1'
      },
      success:function(res){
        console.log('sign:'+JSON.stringify(res.data));
        that.pay(res.data.data);
      }
    })
  }

(2)server:

 @RequestMapping(value = "/pay")
    @ResponseBody
    public Object pay(HttpServletRequest request) throws Exception {
        JsonResult jsonResult = new JsonResult();
        String code = MessageUtil.CODE_SUCCESS;//状态码
        String msg = MessageUtil.MSG_00;//提示信息
        PageData pd = new PageData();
        try {
            pd = this.getPageData();
            if (!pd.containsKey("orderId") || StringUtils.isEmpty(pd.getString("orderId"))){
                code = MessageUtil.CODE_ERROR;
                msg = MessageUtil.MSG_NULL;
            } if (!pd.containsKey("orderNumber") || StringUtils.isEmpty(pd.getString("orderNumber"))){
                code = MessageUtil.CODE_ERROR;
                msg = MessageUtil.MSG_NULL;
            }else  if (!pd.containsKey("openid") || StringUtils.isEmpty(pd.getString("openid"))){
                code = MessageUtil.CODE_ERROR;
                msg = MessageUtil.MSG_NULL;
            }else  if (!pd.containsKey("deposit") || StringUtils.isEmpty(pd.getString("deposit"))){
                code = MessageUtil.CODE_ERROR;
                msg = MessageUtil.MSG_NULL;
            }else {
                /******************商户下单******************/
                String openid = pd.getString("openid");
                String orderId = pd.getString("orderId");
                String orderNumber =  pd.getString("orderNumber");
                Long deposit = Long.parseLong(pd.getString("deposit"));
                int total_fee = (int) (deposit*100);
                //生成的随机字符串
                String nonce_str = getRandomStringByLength(32);
                //商品名称
                String body = "微潜订单-"+orderNumber;
                //获取客户端的ip地址
                String spbill_create_ip = getIpAddr(request);

                //组装参数,用户生成统一下单接口的签名
                PageData data = new PageData();
                data.put("appid", Configure.getAppID());
                data.put("body",body);
                data.put("mch_id", Configure.getMch_id());
                data.put("nonce_str", nonce_str);
                data.put("notify_url", Configure.getNotify_url_pay());//支付成功后的回调地址
                data.put("openid", openid);
                data.put("out_trade_no", orderId);//商户订单号
                data.put("spbill_create_ip", spbill_create_ip);
//            data.put("total_fee", total_fee);//支付金额,这边需要转成字符串类型,否则后面的签名会失败
                data.put("total_fee", "1");//支付金额,这边需要转成字符串类型,否则后面的签名会失败
                data.put("trade_type", "JSAPI");//支付方式

                String prestr = PayUtil.createLinkString(data); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串

                //MD5运算生成签名,这里是第一次签名,用于调用统一下单接口
                String mysign = PayUtil.sign(prestr, Configure.getKey(), "utf-8").toUpperCase();
                data.put("sign", mysign);//支付方式

                //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
                System.out.println("调试模式_统一下单接口 请求XML数据:" + PayUtil.GetMapToXML(data));

                //调用统一下单接口,并接受返回的结果
                String result = PayUtil.httpRequest(Configure.getOrderPath(), "POST", PayUtil.GetMapToXML(data));

                System.out.println("调试模式_统一下单接口 返回XML数据:" + result);

                // 将解析结果存储在HashMap中
                Map map = PayUtil.doXMLParse(result);

                String return_code = (String) map.get("return_code");//返回状态码

                if (return_code == "SUCCESS" || return_code.equals(return_code)) {
                    String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                    Long timeStamp = System.currentTimeMillis() / 1000;
                    //拼接签名需要的参数
                    String stringSignTemp = "appId=" + Configure.getAppID() + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id + "&signType=MD5&timeStamp=" + timeStamp;
                    //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                    String paySign = PayUtil.sign(stringSignTemp, Configure.getKey(), "utf-8").toUpperCase();
                    PageData signInfo = new PageData();
                    signInfo.put("appid",Configure.getAppID());
                    signInfo.put("nonceStr",nonce_str);
                    signInfo.put("package","prepay_id="+prepay_id);
                    signInfo.put("signType","MD5");
                    signInfo.put("timeStamp",String.valueOf(timeStamp));
                    signInfo.put("paySign", paySign);
                    jsonResult.setData(signInfo);
                    code = MessageUtil.CODE_SUCCESS;
                    msg = MessageUtil.MSG_00;
                }else {
                    code = MessageUtil.CODE_ERROR;
                    msg = MessageUtil.MSG_01;
                }
            }
            jsonResult.setCode(code);
            jsonResult.setMessage(msg);
        }catch (Exception e) {
            jsonResult.setCode(MessageUtil.CODE_ERROR);
            jsonResult.setMessage(MessageUtil.MSG_01);
            logger.error(e.toString(), e);
        }
        return  jsonResult;
    }
public static String getRandomStringByLength(int length) {
    String base = "abcdefghijklmnopqrstuvwxyz0123456789";
    Random random = new Random();
    StringBuffer sb = new StringBuffer();
    for (int i = 0; i < length; i++) {
        int number = random.nextInt(base.length());
        sb.append(base.charAt(number));
    }
    return sb.toString();
}
public static String getIpAddr(HttpServletRequest request) {
    String ip = request.getHeader("X-Forwarded-For");
    if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
        //多次反向代理后会有多个ip值,第一个ip才是真实ip
        int index = ip.indexOf(",");
        if(index != -1){
            return ip.substring(0,index);
        }else{
            return ip;
        }
    }
    ip = request.getHeader("X-Real-IP");
    if(StringUtils.isNotEmpty(ip) && !"unKnown".equalsIgnoreCase(ip)){
        return ip;
    }
    return request.getRemoteAddr();
}
public class Configure {
    //商户号
    private static String mch_id = "mch_id";
    //商户号密钥
    private static String key = "key";

    //小程序ID
    private static String appID = "appID";
    //小程序密钥
    private static String secret = "secret";

    private static String notify_url_pay = "http://t7hhri.natappfree.cc/wechat/payResult";

    private static String notify_url_refund = "http://t7hhri.natappfree.cc/wechat/refundResult";

    private static String certPath = "\\apiclient_cert.p12";

    private static String orderPath = "https://api.mch.weixin.qq.com/pay/unifiedorder";

    private static String refundPath = "https://api.mch.weixin.qq.com/secapi/pay/refund";


    public static String getAppID() {
        return appID;
    }

    public static void setAppID(String appID) {
        Configure.appID = appID;
    }

    public static String getMch_id() {
        return mch_id;
    }

    public static void setMch_id(String mch_id) {
        Configure.mch_id = mch_id;
    }

    public static String getSecret() {
        return secret;
    }

    public static void setSecret(String secret) {
        Configure.secret = secret;
    }

    public static String getKey() {
        return key;
    }

    public static void setKey(String key) {
        Configure.key = key;
    }

    public static String getNotify_url_pay() {
        return notify_url_pay;
    }

    public static void setNotify_url_pay(String notify_url_pay) {
        Configure.notify_url_pay = notify_url_pay;
    }

    public static String getNotify_url_refund() {
        return notify_url_refund;
    }

    public static void setNotify_url_refund(String notify_url_refund) {
        Configure.notify_url_refund = notify_url_refund;
    }

    public static String getCertPath() {
        return certPath;
    }

    public static void setCertPath(String certPath) {
        Configure.certPath = certPath;
    }

    public static String getOrderPath() {
        return orderPath;
    }

    public static void setOrderPath(String orderPath) {
        Configure.orderPath = orderPath;
    }

    public static String getRefundPath() {
        return refundPath;
    }

    public static void setRefundPath(String refundPath) {
        Configure.refundPath = refundPath;
    }
}

package com.fh.wx;


import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.security.SignatureException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.commons.codec.digest.DigestUtils;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.JDOMException;
import org.jdom.input.SAXBuilder;

/**
 * Created by 菜园子 on 2018/7/3.
 */
public class PayUtil {
    /**
     * 签名字符串
     * @param text 需要签名的字符串
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static String sign(String text, String key, String input_charset) {
        text = text + "&key=" + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }
    /**
     * 签名字符串
     *  @param text 需要签名的字符串
     * @param sign 签名结果
     * @param key 密钥
     * @param input_charset 编码格式
     * @return 签名结果
     */
    public static boolean verify(String text, String sign, String key, String input_charset) {
        text = text + key;
        String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
        if (mysign.equals(sign)) {
            return true;
        } else {
            return false;
        }
    }
    /**
     * @param content
     * @param charset
     * @return
     * @throws SignatureException
     * @throws UnsupportedEncodingException
     */
    public static byte[] getContentBytes(String content, String charset) {
        if (charset == null || "".equals(charset)) {
            return content.getBytes();
        }
        try {
            return content.getBytes(charset);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误,指定的编码集不对,您目前指定的编码集是:" + charset);
        }
    }

    private static boolean isValidChar(char ch) {
        if ((ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z'))
            return true;
        if ((ch >= 0x4e00 && ch <= 0x7fff) || (ch >= 0x8000 && ch <= 0x952f))
            return true;// 简体中文汉字编码
        return false;
    }
    /**
     * 除去数组中的空值和签名参数
     * @param sArray 签名参数组
     * @return 去掉空值与签名参数后的新签名参数组
     */
    public static Map<String, String> paraFilter(Map<String, String> sArray) {
        Map<String, String> result = new HashMap<String, String>();
        if (sArray == null || sArray.size() <= 0) {
            return result;
        }
        for (String key : sArray.keySet()) {
            String value = sArray.get(key);
            if (value == null || value.equals("") || key.equalsIgnoreCase("sign")
                    || key.equalsIgnoreCase("sign_type")) {
                continue;
            }
            result.put(key, value);
        }
        return result;
    }
    /**
     * 把数组所有元素排序,并按照“参数=参数值”的模式用“&”字符拼接成字符串
     * @param params 需要排序并参与字符拼接的参数组
     * @return 拼接后字符串
     */
    public static String createLinkString(Map<String, String> params) {
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        String prestr = "";
        for (int i = 0; i < keys.size(); i++) {
            String key = keys.get(i);
            String value = params.get(key);
            if (i == keys.size() - 1) {// 拼接时,不包括最后一个&字符
                prestr = prestr + key + "=" + value;
            } else {
                prestr = prestr + key + "=" + value + "&";
            }
        }
        return prestr;
    }
    /**
     *
     * @param requestUrl 请求地址
     * @param requestMethod 请求方法
     * @param outputStr 参数
     */
    public static String httpRequest(String requestUrl,String requestMethod,String outputStr){
        // 创建SSLContext
        StringBuffer buffer = null;
        try{
            URL url = new URL(requestUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod(requestMethod);
            conn.setDoOutput(true);
            conn.setDoInput(true);
            conn.connect();
            //往服务器端写内容
            if(null !=outputStr){
                OutputStream os=conn.getOutputStream();
                os.write(outputStr.getBytes("utf-8"));
                os.close();
            }
            // 读取服务器端返回的内容
            InputStream is = conn.getInputStream();
            InputStreamReader isr = new InputStreamReader(is, "utf-8");
            BufferedReader br = new BufferedReader(isr);
            buffer = new StringBuffer();
            String line = null;
            while ((line = br.readLine()) != null) {
                buffer.append(line);
            }
            br.close();
        }catch(Exception e){
            e.printStackTrace();
        }
        return buffer.toString();
    }
    public static String urlEncodeUTF8(String source){
        String result=source;
        try {
            result=java.net.URLEncoder.encode(source, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 解析xml,返回第一级元素键值对。如果第一级元素有子节点,则此节点的值是子节点的xml数据。
     * @param strxml
     * @return
     * @throws JDOMException
     * @throws IOException
     */
    public static Map doXMLParse(String strxml) throws Exception {
        if(null == strxml || "".equals(strxml)) {
            return null;
        }

        Map m = new HashMap();
        InputStream in = String2Inputstream(strxml);
        SAXBuilder builder = new SAXBuilder();
        Document doc = builder.build(in);
        Element root = doc.getRootElement();
        List list = root.getChildren();
        Iterator it = list.iterator();
        while(it.hasNext()) {
            Element e = (Element) it.next();
            String k = e.getName();
            String v = "";
            List children = e.getChildren();
            if(children.isEmpty()) {
                v = e.getTextNormalize();
            } else {
                v = getChildrenText(children);
            }

            m.put(k, v);
        }

        //关闭流
        in.close();

        return m;
    }
    /**
     * 获取子结点的xml
     * @param children
     * @return String
     */
    public static String getChildrenText(List children) {
        StringBuffer sb = new StringBuffer();
        if(!children.isEmpty()) {
            Iterator it = children.iterator();
            while(it.hasNext()) {
                Element e = (Element) it.next();
                String name = e.getName();
                String value = e.getTextNormalize();
                List list = e.getChildren();
                sb.append("<" + name + ">");
                if(!list.isEmpty()) {
                    sb.append(getChildrenText(list));
                }
                sb.append(value);
                sb.append("</" + name + ">");
            }
        }

        return sb.toString();
    }
    public static InputStream String2Inputstream(String str) {
        return new ByteArrayInputStream(str.getBytes());
    }


    public static String GetMapToXML(Map<String,String> param){
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        for (Map.Entry<String,String> entry : param.entrySet()) {
            sb.append("<"+ entry.getKey() +">");
            sb.append(entry.getValue());
            sb.append("</"+ entry.getKey() +">");
        }
        sb.append("</xml>");
        return sb.toString();
    }

}

4、小程序拉起微信支付

pay:function(obj){     wx.requestPayment({       'timeStamp': obj.timeStamp,       'nonceStr': obj.nonceStr,       'package': obj.package,       'signType': obj.signType,       'paySign': obj.paySign,       'success':function(res){         console.log('pay:'+JSON.stringify(res));       },       'fail':function(res){         console.log('fail'+JSON.stringify(res))       }     })   }

5、支付回调

@RequestMapping(value = "/payResult")
@ResponseBody
public void payResult(HttpServletRequest request, HttpServletResponse response) throws Exception {
    String reqParams = StreamUtil.read(request.getInputStream());
    Map result = PayUtil.doXMLParse(reqParams);
    String return_code = (String) result.get("return_code");//返回状态码
    if (return_code.equals("SUCCESS")) {
       
    }
    StringBuffer sb = new StringBuffer("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    response.getWriter().write(sb.toString());
}



猜你喜欢

转载自blog.csdn.net/qq_34479912/article/details/80916556