JAva微信ウィジェット支払いインタフェース

27210 ワード

利用しているのは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に書いて2ステップ目に書きます)このメソッドは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("    ")
          }
        })

      }
    })

ステップ2支払方法 
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();  

	}
}
以上のロジックは、WeChatウィジェットがjavaバックグラウンドメソッドを呼び出してパラメータを取得する->javaバックグラウンド設定パラメータなど、パラメータをWeChatウィジェットに返す->WeChatウィジェットに支払いに成功する->設定したコールバックアドレスを呼び出す->最後にWeChatウィジェットを呼び出す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
"); } 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()
			+ "        !
\t\t\t :" + e.getClass().getName() + "
\t\t :"+ e.toString()+"
"; } 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(""  + v + "" + k + ">");  
			} else {  
				sb.append("" + v + "" + k + ">");  
			}  
		}  
		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("");  
                   if(!list.isEmpty()) {  
                       sb.append(XMLUtil.getChildrenText(list));  
                   }  
                   sb.append(value);  
                   sb.append("" + name + ">");  
               }  
           }  

           return sb.toString();  
       }  
}

プロジェクトの具体的なダウンロードの住所:クリックしてリンクを開けます