微信小程序调用微信支付接口总结与实现(java)

1,开发前准备

小程序appid,商户id,商户密钥(key),付款用户的(openid)
申请接入微信商户地址:https://pay.weixin.qq.com/static/applyment_guide/applyment_detail_miniapp.shtml

2,开放模式介绍

在进行微信支付开发之前,深刻理解微信支付的账号关系非常有助于你使用微信以及微信支付的能力。微信支付对商户开放的所有面对用户使用的api,都是由appid和mch_id成对使用的。微信支付开放的能力主要分2大类,普通模式和服务商模式(而我们用的是普通模式)

2.1普通模式
最常规的普通模式,适用于有自己开发团队或外包开发商的直连商户收款。开发者申请自己的appid和mch_id,两者需具备绑定关系,以此来使用微信支付提供的开放接口,对用户提供服务。 微信小程序调用微信支付接口总结与实现(java)_第1张图片
微信支付基础账号模型-普通模式

3,调用微信支付接口(流程:首先调用微信统一下单接口,在调用wx.requestPayment(OBJECT)发起微信支付)

3.1:小程序代码

获取openid链接(这个就自己去研究了):https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=4_4

下面展示一些 内联代码片

 payment(openid) {
    var that = this;
    wx.login({
      success: function (res) {
        //if (res.code) {
        wx.request({
          url: http://127.0.0.1:8088/api/WxPayment/payment, 
          data: {
            "openid": openid
          },
          header: {
            "Content-Type": "application/json",
          },
          success: function (ress) {
            wx.requestPayment({
              timeStamp: ress.data.data.timeStamp,
              nonceStr: ress.data.data.nonceStr,
              package: ress.data.data.package,
              signType: 'MD5',
              paySign: ress.data.data.paySign,
              success: function (e) {
                console.log(e.data);
              },
              fail: function (e) {
                console.log("失败");
              }
            })
          }
        })
      }
    })
  }

3.2 java后台

3.2.1 WxPayment.java

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.security.SecureRandom;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Random;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yihe.applet.api.util.common.util.OrderPay;
import com.yihe.applet.api.util.common.util.PayUtil;
import com.yihe.system.utils.Result;


@Controller
@RequestMapping("/api/WxPayment")
public class WxPayment {
	
	 private static final String SYMBOLS = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
	
	 private static final Random RANDOM = new SecureRandom();
	 
	 /**
 * openid这个参数代表用户标识(文章上面有标识在哪里去获取)
 *
 */
	@RequestMapping(value="/payment")
	@ResponseBody
    public Result payment(String openid){
		String nonce_str = generateNonceStr();//随机字符串
		String out_trade_no = getStringToday();//订单编号
		String total_fee="1";//订单总金额,单位为分(这个注意必须String类型)
		String spbill_create_ip=getShowIpv4();//获取当前ip
		String body = "购买商品 小米11";
		String AppId="";//小程序id
		String MchId="";//商户id
		String NotifyUrl="http://www.weixin.qq.com/wxpay/pay.php";//通知地址(微信官方上找的实例能用就行)
		String key="";//商户密钥
		//构造成类
		OrderPay orderPay = new OrderPay(AppId, MchId, nonce_str, body, out_trade_no, total_fee, spbill_create_ip, NotifyUrl, "JSAPI", openid,key,"https://api.mch.weixin.qq.com/pay/unifiedorder");
		//调用方法,得到统一下单地数据
		Map pac = PayUtil.wxPay(orderPay);
		//直接返回给前端,前端调用即可
		return Result.ok(pac);
    }
	
	

    /**
     * 获取随机字符串 Nonce Str
     *
     * @return String 随机字符串
     */
    public static String generateNonceStr() {
        char[] nonceChars = new char[32];
        for (int index = 0; index < nonceChars.length; ++index) {
            nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
        }
        return new String(nonceChars);
    }
    
    
   /**
    * 商户订单号
    * @return
    */
  public static String getStringToday() {
     Date currentTime = new Date();
     SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMddHHmmss");
     String dateString = formatter.format(currentTime);
     
     char[] nonceChars = new char[10];
     for (int index = 0; index < nonceChars.length; ++index) {
         nonceChars[index] = SYMBOLS.charAt(RANDOM.nextInt(SYMBOLS.length()));
     }
     
     return dateString+new String(nonceChars);
  }
  
  
  /**
   * 获取当前ip
   * @return
   */
 public static String getShowIpv4() {
	 try {
			InetAddress ip4 = Inet4Address.getLocalHost();
			 return ip4.getHostAddress();
		} catch (UnknownHostException e) {
			e.printStackTrace();
		}	
    
    return "ip地址错误";
 }
}

3.2.2 OrderPay.java

public class OrderPay {
    private String appid;//正式小程序的appid
    private String mch_id;//商户号的id
    private String nonce_str;//随机字符串
    private String body;//商品主题内容
    private String out_trade_no;//交易号
    private String total_fee;//总的费用
    private String spbill_create_ip;//本地ip,谁调用就是谁的ip
    private String notify_url;//微信回调地址
    private String trade_type="JSAPI";//类型
    private String openid;//用户openid
    private String key;//商户号在平台上设置的密匙,自己设置的
    private String pay_url;//微信支付的地址

    public OrderPay(String appid, String mch_id, String nonce_str, String body, String out_trade_no, String total_fee, String spbill_create_ip, String notify_url, String trade_type, String openid, String key, String pay_url) {
        this.appid = appid;
        this.mch_id = mch_id;
        this.nonce_str = nonce_str;
        this.body = body;
        this.out_trade_no = out_trade_no;
        this.total_fee = total_fee;
        this.spbill_create_ip = spbill_create_ip;
        this.notify_url = notify_url;
        this.trade_type = trade_type;
        this.openid = openid;
        this.key = key;
        this.pay_url = pay_url;
    }

    public String getAppid() {
        return appid;
    }

    public void setAppid(String appid) {
        this.appid = appid;
    }

    public String getMch_id() {
        return mch_id;
    }

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

    public String getNonce_str() {
        return nonce_str;
    }

    public void setNonce_str(String nonce_str) {
        this.nonce_str = nonce_str;
    }

    public String getBody() {
        return body;
    }

    public void setBody(String body) {
        this.body = body;
    }

    public String getOut_trade_no() {
        return out_trade_no;
    }

    public void setOut_trade_no(String out_trade_no) {
        this.out_trade_no = out_trade_no;
    }

    public String getTotal_fee() {
        return total_fee;
    }

    public void setTotal_fee(String total_fee) {
        this.total_fee = total_fee;
    }

    public String getSpbill_create_ip() {
        return spbill_create_ip;
    }

    public void setSpbill_create_ip(String spbill_create_ip) {
        this.spbill_create_ip = spbill_create_ip;
    }

    public String getNotify_url() {
        return notify_url;
    }

    public void setNotify_url(String notify_url) {
        this.notify_url = notify_url;
    }

    public String getTrade_type() {
        return trade_type;
    }

    public void setTrade_type(String trade_type) {
        this.trade_type = trade_type;
    }

    public String getOpenid() {
        return openid;
    }

    public void setOpenid(String openid) {
        this.openid = openid;
    }

    public String getKey() {
        return key;
    }

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

    public String getPay_url() {
        return pay_url;
    }

    public void setPay_url(String pay_url) {
        this.pay_url = pay_url;
    }
}

3.2.3 PayUtil.java

package com.yihe.applet.api.util.common.util;

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

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.*;

/**
  * @ClassName PayUtil.java	
  * @Description 订单支付
  * @Date 2019/8/22 9:20
  * @Version 1.0
  * maven需要的包
  * 

    org.jdom
    jdom2
    2.0.6

 **/
public class PayUtil {
    //调用支付 统一下单 接口,返回Map数据
    public static Map wxPay(OrderPay orderPay){
        try{
            Map packageParams = new HashMap();
            packageParams.put("appid", orderPay.getAppid());
            packageParams.put("mch_id", orderPay.getMch_id());
            packageParams.put("nonce_str", orderPay.getNonce_str());
            packageParams.put("body", orderPay.getBody());
            packageParams.put("out_trade_no", orderPay.getOut_trade_no());//商户订单号
            packageParams.put("total_fee", orderPay.getTotal_fee());
            packageParams.put("spbill_create_ip", orderPay.getSpbill_create_ip());
            packageParams.put("notify_url", orderPay.getNotify_url());
            packageParams.put("trade_type", orderPay.getTrade_type());
            packageParams.put("openid", orderPay.getOpenid());

            // 除去数组中的空值和签名参数
            packageParams = PayUtil.paraFilter(packageParams);
            String prestr = PayUtil.createLinkString(packageParams); // 把数组所有元素,按照“参数=参数值”的模式用“&”字符拼接成字符串

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

            //拼接统一下单接口使用的xml数据,要将上一步生成的签名一起拼接进去
            String xml = "" + "" + orderPay.getAppid() + ""
                    + ""
                    + "" + orderPay.getMch_id() + ""
                    + "" + orderPay.getNonce_str() + ""
                    + "" + orderPay.getNotify_url() + ""
                    + "" + orderPay.getOpenid() + ""
                    + "" + orderPay.getOut_trade_no() + ""
                    + "" + orderPay.getSpbill_create_ip() + ""
                    + "" + orderPay.getTotal_fee() + ""
                    + "" +orderPay.getTrade_type() + ""
                    + "" + mysign + ""
                    + "";

//            System.out.println("调试模式_统一下单接口 请求XML数据:" + xml);


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


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


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


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

            //返回给移动端需要的参数
            Map response = new HashMap();
            if(return_code == "SUCCESS" || return_code.equals(return_code)){
                // 业务结果
                String prepay_id = (String) map.get("prepay_id");//返回的预付单信息
                response.put("nonceStr", orderPay.getNonce_str());
                response.put("package", "prepay_id=" + prepay_id);
                Long timeStamp = System.currentTimeMillis() / 1000;
                response.put("timeStamp", timeStamp + "");//这边要将返回的时间戳转化成字符串,不然小程序端调用wx.requestPayment方法会报签名错误

                String stringSignTemp = "appId=" + orderPay.getAppid() + "&nonceStr=" + orderPay.getNonce_str() + "&package=prepay_id=" + prepay_id+ "&signType=" + "MD5" + "&timeStamp=" + timeStamp;
                //再次签名,这个签名用于小程序端调用wx.requesetPayment方法
                String paySign = PayUtil.sign(stringSignTemp, orderPay.getKey(), "utf-8").toUpperCase();
                response.put("paySign", paySign);
            }
            response.put("appid", orderPay.getOpenid());
            return response;
        }catch(Exception e){
            e.printStackTrace();
        }
        return null;
    }


    public static String sign(String text, String key, String input_charset) {
        text = text + "&key=" + key;
        return DigestUtils.md5Hex(getContentBytes(text, input_charset));
    }

    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;
        }
    }

    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);
        }
    }
    /**
     * 生成6位或10位随机数 param codeLength(多少位)
     * @return
     */
    public static String createCode(int codeLength) {
        String code = "";
        for (int i = 0; i < codeLength; i++) {
            code += (int) (Math.random() * 9);
        }
        return code;
    }
    @SuppressWarnings("unused")
    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 paraFilter(Map sArray) {
        Map result = new HashMap();
        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 params) {
        List keys = new ArrayList(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;
    }

    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;
    }
    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("");
            }
        }
        return sb.toString();
    }
    public static InputStream String2Inputstream(String str) throws UnsupportedEncodingException {
        return new ByteArrayInputStream(str.getBytes("utf-8"));
    }
        //支付成功后调用方法中的执行函数,执行后,得到微信推送的消息,返回map
    public static Map wxNotify(HttpServletRequest request, HttpServletResponse response, String key) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine())!=null){
            sb.append(line);
        }
        br.close();
        //sb为微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的报文:" + notityXml);


        Map map = PayUtil.doXMLParse(notityXml);


        String returnCode = (String) map.get("return_code");
        if("SUCCESS".equals(returnCode)){
            //验证签名是否正确
            if(PayUtil.verify(PayUtil.createLinkString(map), (String)map.get("sign"), key, "utf-8")){
                /**此处添加自己的业务逻辑代码start**/
                /**此处添加自己的业务逻辑代码end**/
                //通知微信服务器已经支付成功
                resXml = ""
                        + " ";
            }
        }else{
            resXml = "" + ""
                    + "" + " ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回调数据结束");


        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
        return map;
    }
}


总结

该文章也是站在巨人的肩膀上完成的,所谓站在巨人的肩膀上有可能比巨人还看的远,这就要看你们的了

你可能感兴趣的:(小程序,java)