java微信小程序支付接口

利用的是java maven 框架ssm

pom.xml


  4.0.0
  cn
  wechatdemo
  war
  0.0.1-SNAPSHOT
  wechatdemo Maven Webapp
  http://maven.apache.org
  
		UTF-8
		UTF-8

		
		4.3.9.RELEASE

		
		3.4.4

		
		6.0.6

		
		1.7.25
		1.2.17
	

	

		
			com.google.code.gson
			gson
			2.3.1
		
		
			org.jdom
			jdom
			1.1.3
		

		
			junit
			junit
			3.8.1
			test
		

		
		
			jstl
			jstl
			1.2
		
		
			redis.clients
			jedis
			2.1.0
		

		
		
		
			org.springframework
			spring-aspects
			${spring.version}
		
		
		

		
			org.springframework
			spring-oxm
			${spring.version}
		
		
			org.springframework
			spring-tx
			${spring.version}
		
		
			org.springframework
			spring-jdbc
			${spring.version}
		
		
			org.springframework
			spring-webmvc
			${spring.version}
		
		

		
			org.springframework
			spring-context-support
			${spring.version}
		

		

		
			org.springframework
			spring-test
			${spring.version}
		

		
		
			org.mybatis
			mybatis
			${mybatis.version}
		

		
		
			org.mybatis
			mybatis-spring
			1.3.0
		

		
		
			mysql
			mysql-connector-java
			${mysql-driver.version}
		

		
		
		
		
		
		

		
		
			com.jolbox
			bonecp-spring
			0.8.0.RELEASE
		

		
		
			log4j
			log4j
			${log4j.version}
		

		
			org.apache.logging.log4j
			log4j-core
			2.8.2
		
		
			org.apache.logging.log4j
			log4j-api
			2.8.2
		

		
			org.slf4j
			slf4j-api
			${slf4j.version}
		

		
			org.slf4j
			slf4j-log4j12
			${slf4j.version}
		


		
			aopalliance
			aopalliance
			1.0
		

		
			org.ow2.asm
			asm
			5.2
		

		
			org.aspectj
			aspectjweaver
			1.8.11
		

		
		
			cglib
			cglib
			3.2.5
		

		
		
			com.fasterxml.jackson.core
			jackson-databind
			2.9.1
		

		
		
			org.javassist
			javassist
			3.22.0-GA
		

		
		
			commons-beanutils
			commons-beanutils
			1.8.3
		

		
		
			commons-io
			commons-io
			2.5
		
		
		
			commons-fileupload
			commons-fileupload
			1.3.1
		

	
	
		
			
			
				org.apache.maven.plugins
				maven-compiler-plugin
				2.3.2
				
					1.7
					1.7
				
			
		
		wechatdemo
		
			
				
				src/main/java
				
				
					**/*.xml
					**/*.properties
				
			
			
				
				src/main/resources
				
				
					**/*.xml
					**/*.properties
				
			
		
	

以下是代码内容

首先微信小程序调用一个方法(这个方法写在java里 第二步会写到) 这个方法要返回paysign等

  wx.request({
      url: "你的IP地址"+ "order/returnparam.action",//调用java后台的方法
      data: {
        'openid': "获取用户的openid",//需要你获取用户的openid
        'title': "shoplist",//订单名称 这里随便定义shoplist
        'price': 0.1* 100,//一毛钱
        'goodsid': 100,///商品ID 这里随便定义成100
      },
      method: 'POST',
      header: {
        "content-type": 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        wx.requestPayment({
          timeStamp: res.data.timeStamp,
          nonceStr: res.data.nonceStr,
          package: res.data.package,
          signType: res.data.signType,
          paySign: res.data.paySign,
          success: function (res) {
            console.log("付款成功")
          },
          fail: function (res) {
            console.log("付款失败")
          }
        })

      }
    })

第二步 支付方法 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.google.gson.Gson;

import cn.myutils.HttpUtil;
import cn.myutils.MyResponseJson;
import cn.myutils.PayCommonUtil;
import cn.myutils.XMLUtil;
import redis.clients.jedis.Jedis;

@Controller
@RequestMapping("order")
public class OrderController {
	private static Logger logger = Logger.getLogger(OrderController.class);
	/*
	 * 购买
	 * @param request
	 * @param response
	 * @return
	 * */
	
	@ResponseBody
	@RequestMapping("returnparam")
	public void doOrder(HttpServletRequest request, HttpServletResponse response) throws Exception{
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		//得到openid(微信用户唯一的openid)
		String openid = request.getParameter("openid");
		//得到价钱(自定义)
		int fee = 0;
		if (null != request.getParameter("price")) {
			fee = Integer.parseInt(request.getParameter("price").toString());
		}
		//得到商品的ID(自定义)
		String goodsid=request.getParameter("goodsid");
		//订单标题(自定义)
		String title = request.getParameter("title");
		//时间戳
		String times = System.currentTimeMillis() + "";
		
		//订单编号(自定义 这里以时间戳+随机数)
		Random random = new Random();
		String did = times+random.nextInt(1000);

		SortedMap packageParams = new TreeMap();
		packageParams.put("appid", "微信小程序ID");//微信小程序ID
		packageParams.put("mch_id", "商户ID");//商户ID
		packageParams.put("nonce_str", times);//随机字符串(32位以内) 这里使用时间戳
		packageParams.put("body", title);//支付主体名称 自定义
		packageParams.put("out_trade_no", did+goodsid);//编号 自定义以时间戳+随机数+商品ID
		packageParams.put("total_fee", fee);//价格 自定义
		//packageParams.put("spbill_create_ip", remoteAddr);
		packageParams.put("notify_url", "http://你的IP地址/order/buy.action");//支付返回地址要外网访问的到, localhost不行,调用下面buy方法。(订单存入数据库)
		packageParams.put("trade_type", "JSAPI");//这个api有,固定的
		packageParams.put("openid", openid);//用户的openid 可以要 可以不要
		//获取sign
		String sign = PayCommonUtil.createSign("UTF-8", packageParams, "32位秘钥");//最后这个是自己在微信商户设置的32位密钥
		packageParams.put("sign", sign);
		System.out.println(sign);
		//转成XML
		String requestXML = PayCommonUtil.getRequestXml(packageParams);
		System.out.println(requestXML);
		//得到含有prepay_id的XML
		String resXml = HttpUtil.postData("https://api.mch.weixin.qq.com/pay/unifiedorder", requestXML);
		System.out.println(resXml);
		//解析XML存入Map
		Map map = XMLUtil.doXMLParse(resXml);
		System.out.println(map);
		// String return_code = (String) map.get("return_code");
		//得到prepay_id
		String prepay_id = (String) map.get("prepay_id");
		SortedMap packageP = new TreeMap();
		packageP.put("appId", "微信小程序ID");//!!!注意,这里是appId,上面是appid
		packageP.put("nonceStr", times);//时间戳
		packageP.put("package", "prepay_id=" + prepay_id);//必须把package写成 "prepay_id="+prepay_id这种形式
		packageP.put("signType", "MD5");//paySign加密
		packageP.put("timeStamp", (System.currentTimeMillis() / 1000) + "");
		//得到paySign
		String paySign = PayCommonUtil.createSign("UTF-8", packageP, "32位秘钥");
		packageP.put("paySign", paySign);
		//将packageP数据返回给小程序
		Gson gson = new Gson();
		String json = gson.toJson(packageP);
		PrintWriter pw = response.getWriter();
		System.out.println(json);
		pw.write(json);
		pw.close();
	}
	//订单存入数据库  上面参数 packageParams.put("notify_url", "http://你的IP地址/order/buy.action");回调的就是这个方法
	@RequestMapping(value="buy")
	@ResponseBody
	public void Buy(HttpServletRequest request,HttpServletResponse response) 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 = "";  
		Map map = XMLUtil.doXMLParse(notityXml);
		String returnCode = (String) map.get("return_code");  

		if("SUCCESS".equals(returnCode)){  
			String out_trade_no=(String) map.get("out_trade_no");
			String timestamp=(String) map.get("nonce_str");
			String goodsid=out_trade_no.substring(out_trade_no.length()-3, out_trade_no.length());
			String openid=(String) map.get("openid");
			/*
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 自己写存入数据库的逻辑
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 
			 * 
			 * */
			resXml = "" + ""  
					+ "" + " ";  
		}else {
			resXml = "" + ""  
					+ "" + " ";  
		}
		BufferedOutputStream out = new BufferedOutputStream(  
				response.getOutputStream());  
		out.write(resXml.getBytes());  
		out.flush();  
		out.close();  

	}
}
以上的逻辑就是 微信小程序调用java后台方法获取参数->java后台设置参数等等并且传参数回去给微信小程序->微信小程序支付成功->调用你设置的回调地址(订单传入数据库)->最后在调用微信小程序的success方法

需要工具类

package cn.myutils;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.net.URLConnection;

public class HttpUtil {
    //private static final Log logger = Logs.get();  
       private final static int CONNECT_TIMEOUT = 5000; // in milliseconds  
       private final static String DEFAULT_ENCODING = "UTF-8";  

       public static String postData(String urlStr, String data){  
           return postData(urlStr, data, null);  
       }  

       public static String postData(String urlStr, String data, String contentType){  
           BufferedReader reader = null;  
           try {  
               URL url = new URL(urlStr);  
               URLConnection conn = url.openConnection();  
               conn.setDoOutput(true);  
               conn.setConnectTimeout(CONNECT_TIMEOUT);  
               conn.setReadTimeout(CONNECT_TIMEOUT);  
               if(contentType != null)  
                   conn.setRequestProperty("content-type", contentType);  
               OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream(), DEFAULT_ENCODING);  
               if(data == null)  
                   data = "";  
               writer.write(data);   
               writer.flush();  
               writer.close();    

               reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), DEFAULT_ENCODING));  
               StringBuilder sb = new StringBuilder();  
               String line = null;  
               while ((line = reader.readLine()) != null) {  
                   sb.append(line);  
                   sb.append("\r\n");  
               }  
               return sb.toString();  
           } catch (IOException e) {  
               //logger.error("Error connecting to " + urlStr + ": " + e.getMessage());  
           } finally {  
               try {  
                   if (reader != null)  
                       reader.close();  
               } catch (IOException e) {  
               }  
           }  
           return null;  
       }  
}
package cn.myutils;

import java.security.MessageDigest;

public class MD5 {
    private static String byteArrayToHexString(byte b[]) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++)
            resultSb.append(byteToHexString(b[i]));

        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if (charsetname == null || "".equals(charsetname))
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes()));
            else
                resultString = byteArrayToHexString(md.digest(resultString
                        .getBytes(charsetname)));
        } catch (Exception exception) {
        }
        return resultString;
    }

    private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5",
        "6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };

}

package cn.myutils;

import java.util.Date;

/**
* @author	lastlySly 
* @create	2018年3月6日 下午10:26:43 
* Description: 
*/
public class MyExceptionOutLog {
	public static String outLog(Exception e) {
		String error = "";
		StackTraceElement[] st = e.getStackTrace();
		for (StackTraceElement stackTraceElement : st) {
			String exclass = stackTraceElement.getClassName();
			String method = stackTraceElement.getMethodName();
			/*new Date() + ":" + */
			error += "\t[类:" + exclass + "]调用"
			+ method + "时在第" + stackTraceElement.getLineNumber()
			+ "行代码处发生异常!\n\t\t\t异常类型:" + e.getClass().getName()
			+ "\n\t\t异常信息为:"+ e.toString()+"\n";
		}
		
		return error;
	}
}

package cn.myutils;

/**
* @author	lastlySly 
* @create	2018年3月5日 下午10:20:25 
* Description: 输出规范
*/
public class MyResponseJson {
	public int code;
	public String tip;
	public Object data;
	
	public MyResponseJson() {
		super();
		// TODO Auto-generated constructor stub
	}
	public MyResponseJson(int code, String tip, Object data) {
		super();
		this.code = code;
		this.tip = tip;
		this.data = data;
	}
	public int getCode() {
		return code;
	}
	public void setCode(int code) {
		this.code = code;
	}
	public String getTip() {
		return tip;
	}
	public void setTip(String tip) {
		this.tip = tip;
	}
	public Object getData() {
		return data;
	}
	public void setData(Object data) {
		this.data = data;
	}

	
}

package cn.myutils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;

public class PayCommonUtil {
	/** 
	 * 是否签名正确,规则是:按参数名称a-z排序,遇到空值的参数不参加签名。 
	 * @return boolean 
	 */  
	public static boolean isTenpaySign(String characterEncoding, SortedMap packageParams, String API_KEY) {  
		StringBuffer sb = new StringBuffer();  
		Set es = packageParams.entrySet();  
		Iterator it = es.iterator();  
		while(it.hasNext()) {  
			Map.Entry entry = (Map.Entry)it.next();  
			String k = (String)entry.getKey();  
			String v = (String)entry.getValue();  
			if(!"sign".equals(k) && null != v && !"".equals(v)) {  
				sb.append(k + "=" + v + "&");  
			}  
		}  

		sb.append("key=" + API_KEY);  

		//算出摘要  
		String mysign = MD5.MD5Encode(sb.toString(), characterEncoding).toLowerCase();  
		String tenpaySign = ((String)packageParams.get("sign")).toLowerCase();  

		//System.out.println(tenpaySign + "    " + mysign);  
		return tenpaySign.equals(mysign);  
	}  

	/** 
	 * @author 
	 * @Description:sign签名 
	 * @param characterEncoding 
	 *            编码格式 
	 * @param parameters 
	 *            请求参数 
	 * @return 
	 */  
	public static String createSign(String characterEncoding, SortedMap packageParams, String API_KEY) {  
		StringBuffer sb = new StringBuffer();  
		Set es = packageParams.entrySet();  
		Iterator it = es.iterator();  
		while (it.hasNext()) {  
			Map.Entry entry = (Map.Entry) it.next();  
			String k = entry.getKey().toString();  
			String v = entry.getValue().toString();  
			if (null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) {  
				sb.append(k + "=" + v + "&");  
			}  
		}  
		sb.append("key=" + API_KEY);  
		String sign = MD5.MD5Encode(sb.toString(), characterEncoding).toUpperCase();  
		return sign;  
	}  
	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;     
	}     
	/** 
	 * @author 
	 * @Description:将请求参数转换为xml格式的string 
	 * @param parameters 
	 *            请求参数 
	 * @return 
	 */  
	public static String getRequestXml(SortedMap parameters) {  
		StringBuffer sb = new StringBuffer();  
		sb.append("");  
		Set es = parameters.entrySet();  
		Iterator it = es.iterator();  
		while (it.hasNext()) {  
			Map.Entry entry = (Map.Entry) it.next();  
			String k = entry.getKey().toString();  
			String v = entry.getValue().toString();   
			if ("attach".equalsIgnoreCase(k) || "body".equalsIgnoreCase(k) || "sign".equalsIgnoreCase(k)) {  
				sb.append("<" + k + ">"  + v + "");  
			} else {  
				sb.append("<" + k + ">" + v + "");  
			}  
		}  
		sb.append("");  
		return sb.toString();  
	}  

	/** 
	 * 取出一个指定长度大小的随机正整数. 
	 *  
	 * @param length 
	 *            int 设定所取出随机数的长度。length小于11 
	 * @return int 返回生成的随机数。 
	 */  
	public static int buildRandom(int length) {  
		int num = 1;  
		double random = Math.random();  
		if (random < 0.1) {  
			random = random + 0.1;  
		}  
		for (int i = 0; i < length; i++) {  
			num = num * 10;  
		}  
		return (int) ((random * num));  
	}  

	/** 
	 * 获取当前时间 yyyyMMddHHmmss 
	 *  
	 * @return String 
	 */  
	public static String getCurrTime() {  
		Date now = new Date();  
		SimpleDateFormat outFormat = new SimpleDateFormat("yyyyMMddHHmmss");  
		String s = outFormat.format(now);  
		return s;  
	}

	public static boolean verify(String text, String sign, String key, String input_charset) {
		text = text + key;     
		String mysign =MD5.MD5Encode(text, input_charset).toUpperCase();  
		System.out.println(mysign);	System.out.println(mysign);	System.out.println(mysign);	System.out.println(mysign);
		if (mysign.equals(sign)) {     
			return true;     
		} else {     
			return false;     
		}     
	}  
}

package cn.myutils;

import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;

public class XMLUtil {
    public static Map doXMLParse(String strxml) throws Exception {  
           strxml = strxml.replaceFirst("encoding=\".*\"", "encoding=\"UTF-8\"");  

           if(null == strxml || "".equals(strxml)) {  
               return null;  
           }  

           Map m = new HashMap();  

           InputStream in = new ByteArrayInputStream(strxml.getBytes("UTF-8"));  
           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 = XMLUtil.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(XMLUtil.getChildrenText(list));  
                   }  
                   sb.append(value);  
                   sb.append("");  
               }  
           }  

           return sb.toString();  
       }  
}

项目具体下载地址: 点击打开链接

你可能感兴趣的:(java微信小程序支付接口)