2 編寫一個(gè)servlet用于通過Oauth獲取code<\/p>
package com.debug.weixin.servlet; \r\n \r\nimport java.io.IOException; \r\nimport java.io.PrintWriter; \r\n \r\nimport javax.servlet.RequestDispatcher; \r\nimport javax.servlet.ServletException; \r\nimport javax.servlet.http.HttpServlet; \r\nimport javax.servlet.http.HttpServletRequest; \r\nimport javax.servlet.http.HttpServletResponse; \r\n \r\nimport com.debug.weixin.util.CommonUtil; \r\nimport com.debug.weixin.util.ServerConfig; \r\n \r\npublic class OauthServlet extends HttpServlet { \r\n \r\n \r\n public void doGet(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n \r\n this.doPost(request, response); \r\n } \r\n \r\n public void doPost(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n \r\n String orderNo=request.getParameter(\"orderNo\"); \r\n \/\/調(diào)用微信Oauth2.0獲取openid \r\n String redirectURL=ServerConfig.SERVERDOMAIN+\"\/BasicWeixin\/payServletForH5?orderNo=\"+orderNo; \r\n String redirectURI=\"\"; \r\n try { \r\n redirectURI=CommonUtil.initOpenId(redirectURL); \r\n } catch (Exception e) { \r\n \/\/ TODO Auto-generated catch block \r\n e.printStackTrace(); \r\n } \r\n \/\/System.out.println(redirectURI); \r\n \/\/RequestDispatcher dis= request.getRequestDispatcher(redirectURI); \r\n \/\/dis.forward(request, response); \r\n response.sendRedirect(redirectURI); \r\n } \r\n \r\n}<\/pre>3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口<\/p>package com.debug.weixin.servlet; \r\n \r\nimport java.io.IOException; \r\nimport java.io.PrintWriter; \r\nimport java.util.SortedMap; \r\nimport java.util.TreeMap; \r\n \r\nimport javax.servlet.RequestDispatcher; \r\nimport javax.servlet.ServletException; \r\nimport javax.servlet.http.HttpServlet; \r\nimport javax.servlet.http.HttpServletRequest; \r\nimport javax.servlet.http.HttpServletResponse; \r\n \r\nimport com.debug.weixin.pojo.WeixinOauth2Token; \r\nimport com.debug.weixin.pojo.WeixinQRCode; \r\nimport com.debug.weixin.util.AdvancedUtil; \r\nimport com.debug.weixin.util.CommonUtil; \r\nimport com.debug.weixin.util.ConfigUtil; \r\nimport com.debug.weixin.util.PayCommonUtil; \r\n \r\npublic class PayServletForH5 extends HttpServlet { \r\n \r\n \r\n public void doGet(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n \r\n this.doPost(request, response); \r\n } \r\n \r\n public void doPost(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n String orderNo=request.getParameter(\"orderNo\"); \r\n String code=request.getParameter(\"code\"); \r\n \r\n \/\/獲取AccessToken \r\n \r\n WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); \r\n \r\n String openId=token.getOpenId(); \r\n \r\n \/\/調(diào)用微信統(tǒng)一支付接口 \r\n SortedMap parameters = new TreeMap(); \r\n parameters.put(\"appid\", ConfigUtil.APPID); \r\n \r\n parameters.put(\"mch_id\", ConfigUtil.MCH_ID); \r\n parameters.put(\"device_info\", \"1000\"); \r\n parameters.put(\"body\", \"我的測(cè)試訂單\"); \r\n parameters.put(\"nonce_str\", PayCommonUtil.CreateNoncestr()); \r\n \r\n \r\n parameters.put(\"out_trade_no\", orderNo); \r\n \/\/parameters.put(\"total_fee\", String.valueOf(total)); \r\n parameters.put(\"total_fee\", \"1\"); \r\n parameters.put(\"spbill_create_ip\", request.getRemoteAddr()); \r\n parameters.put(\"notify_url\", ConfigUtil.NOTIFY_URL); \r\n parameters.put(\"trade_type\", \"JSAPI\"); \r\n parameters.put(\"openid\", openId); \r\n \r\n String sign = PayCommonUtil.createSign(\"UTF-8\", parameters); \r\n parameters.put(\"sign\", sign); \r\n \r\n String requestXML = PayCommonUtil.getRequestXml(parameters); \r\n \r\n String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,\"POST\", requestXML); \r\n System.out.println(\"----------------------------------\"); \r\n System.out.println(result); \r\n System.out.println(\"----------------------------------\"); \r\n \r\n request.setAttribute(\"orderNo\", orderNo); \r\n request.setAttribute(\"totalPrice\", \"0.01\"); \r\n String payJSON=\"\"; \r\n try { \r\n payJSON=CommonUtil.getH5PayStr(result,request); \r\n \r\n } catch (Exception e) { \r\n \/\/ TODO Auto-generated catch block \r\n e.printStackTrace(); \r\n } \r\n \/\/System.out.println(payJSON); \r\n request.setAttribute(\"unifiedOrder\",payJSON); \r\n \r\n RequestDispatcher dis= request.getRequestDispatcher(\"h5Pay.jsp\"); \r\n dis.forward(request, response); \r\n } \r\n \r\n}<\/pre>調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付<\/p>public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ \r\n \r\n Map map = XMLUtil.doXMLParse(result); \r\n \r\n \r\n SortedMap params = new TreeMap(); \r\n params.put(\"appId\", ConfigUtil.APPID); \r\n params.put(\"timeStamp\", Long.toString(new Date().getTime())); \r\n params.put(\"nonceStr\", PayCommonUtil.CreateNoncestr()); \r\n params.put(\"package\", \"prepay_id=\"+map.get(\"prepay_id\")); \r\n params.put(\"signType\", ConfigUtil.SIGN_TYPE); \r\n String paySign = PayCommonUtil.createSign(\"UTF-8\", params); \r\n \r\n params.put(\"paySign\", paySign); \/\/paySign的生成規(guī)則和Sign的生成規(guī)則一致 \r\n \r\n String json = JSONObject.fromObject(params).toString(); \r\n \r\n return json; \r\n }<\/pre> 4 編寫最終的支付界面調(diào)起微信H5支付<\/p><%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%> \r\n<% \r\nString path = request.getContextPath(); \r\nString basePath = request.getScheme()+\":\/\/\"+request.getServerName()+\":\"+request.getServerPort()+path+\"\/\"; \r\n%> \r\n \r\n \r\n \r\n \r\n \"> \r\n \r\n 微信H5支付<\/title> \r\n \r\n \r\n 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂 masyarakat Artikel Topik Soal Jawab Belajar Kursus Kamus Pengaturcaraan Perpustakaan Alatan Alat pembangunan Kod sumber laman web Perpustakaan PHP Kesan khas JS Bahan laman web Pemalam sambungan Alat AI Masa lapang Muat Turun Permainan Tutorial Permainan Melayu 簡(jiǎn)體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Rumah applet WeChat pembangunan WeChat Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 高洛峰 Feb 04, 2017 am 11:30 AM 微信支付現(xiàn)在已經(jīng)變得越來越流行了,隨之也出現(xiàn)了很多以可以快速接入微信支付為噱頭的產(chǎn)品,不過方便之余也使得我們做東西慢慢依賴第三方,喪失了獨(dú)立思考的能力,這次打算分享下我之前開發(fā)過的微信支付。 一 、H5公眾號(hào)支付 要點(diǎn):正確獲取openId以及統(tǒng)一下單接口,正確處理支付結(jié)果通知,正確配置支付授權(quán)目錄 H5的支付方式是使用較為廣泛的方式,這種支付方式主要用于微信內(nèi)自定義菜單的網(wǎng)頁,依賴手機(jī)上安裝的微信客戶端,高版本的微信才支持微信支付,下面按我的流程注意說明 1? 編寫用于支付的頁面,由于是測(cè)試用就寫的簡(jiǎn)單了點(diǎn)<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信支付樣例</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="oauthServlet" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="H5支付"/> </form> </br></br> <form action="scanCodePayServlet?flag=createCode" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="掃碼支付"/> </form> </body> </html>2 編寫一個(gè)servlet用于通過Oauth獲取codepackage com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ServerConfig; public class OauthServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); //調(diào)用微信Oauth2.0獲取openid String redirectURL=ServerConfig.SERVERDOMAIN+"/BasicWeixin/payServletForH5?orderNo="+orderNo; String redirectURI=""; try { redirectURI=CommonUtil.initOpenId(redirectURL); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(redirectURI); //RequestDispatcher dis= request.getRequestDispatcher(redirectURI); //dis.forward(request, response); response.sendRedirect(redirectURI); } }3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.pojo.WeixinOauth2Token; import com.debug.weixin.pojo.WeixinQRCode; import com.debug.weixin.util.AdvancedUtil; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.PayCommonUtil; public class PayServletForH5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); String code=request.getParameter("code"); //獲取AccessToken WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); String openId=token.getOpenId(); //調(diào)用微信統(tǒng)一支付接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "我的測(cè)試訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", orderNo); //parameters.put("total_fee", String.valueOf(total)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "JSAPI"); parameters.put("openid", openId); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("----------------------------------"); System.out.println(result); System.out.println("----------------------------------"); request.setAttribute("orderNo", orderNo); request.setAttribute("totalPrice", "0.01"); String payJSON=""; try { payJSON=CommonUtil.getH5PayStr(result,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(payJSON); request.setAttribute("unifiedOrder",payJSON); RequestDispatcher dis= request.getRequestDispatcher("h5Pay.jsp"); dis.forward(request, response); } }調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); SortedMap<Object,Object> params = new TreeMap<Object,Object>(); params.put("appId", ConfigUtil.APPID); params.put("timeStamp", Long.toString(new Date().getTime())); params.put("nonceStr", PayCommonUtil.CreateNoncestr()); params.put("package", "prepay_id="+map.get("prepay_id")); params.put("signType", ConfigUtil.SIGN_TYPE); String paySign = PayCommonUtil.createSign("UTF-8", params); params.put("paySign", paySign); //paySign的生成規(guī)則和Sign的生成規(guī)則一致 String json = JSONObject.fromObject(params).toString(); return json; } 4 編寫最終的支付界面調(diào)起微信H5支付<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信H5支付</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <script type="text/javascript"> function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest',<%=(String)request.getAttribute("unifiedOrder")%>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("恭喜你,支付成功!"); }else{ alert(res.err_code+res.err_desc+res.err_msg); } } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body> <input type="button" value="支付" onclick="callpay()"/> </body> </html>5 處理微信支付結(jié)果通知package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; public class PayHandlerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) { //對(duì)訂單進(jìn)行業(yè)務(wù)操作 System.out.println("-------------OK"); response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); //告訴微信服務(wù)器,我收到信息了,不要在調(diào)用回調(diào)action了 } } }對(duì)于上面的代碼,有很多都是參考http://blog.csdn.net/u011160656/article/details/41759195,因此這部分的代碼就不貼出來了,需要的話看這個(gè)博客就知道了。二 微信掃碼支付(模式一)要點(diǎn):必須調(diào)用長(zhǎng)鏈接轉(zhuǎn)短鏈接接口、正確配置掃碼支付回調(diào)URL1 根據(jù)訂單號(hào)生成微信支付二維碼下面是幾個(gè)生成二維碼的方法:package com.debug.weixin.util; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } } 這個(gè)算是工具類,還有一個(gè)就是把二維碼顯示在界面上的方法,CreateQRCode主要用到代碼塊:public static void createCodeStream(String text,HttpServletResponse response) throws Exception{ // response.setContentType("image/jpeg"); ServletOutputStream sos = response.getOutputStream(); int width = 500; int height = 500; //二維碼的圖片格式 String format = "jpg"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); //內(nèi)容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼 MatrixToImageWriter.writeToStream(bitMatrix, format,sos); sos.close(); }2 長(zhǎng)鏈接轉(zhuǎn)短鏈接生成二維碼,編寫掃碼支付回調(diào)方法并調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.CreateQRCode; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; import com.mongodb.DBObject; public class ScanCodePayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flag=request.getParameter("flag"); if("createCode".equals(flag)){ createPayCode(request,response); }else{ try { wxScanCodeHandler(request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void createPayCode(HttpServletRequest request,HttpServletResponse response){ String orderNo=request.getParameter("orderNo"); SortedMap<Object,Object> paras = new TreeMap<Object,Object>(); paras.put("appid", ConfigUtil.APPID); paras.put("mch_id", ConfigUtil.MCH_ID); paras.put("time_stamp", Long.toString(new Date().getTime())); paras.put("nonce_str", PayCommonUtil.CreateNoncestr()); paras.put("product_id", orderNo);//商品號(hào)要唯一 String sign = PayCommonUtil.createSign("UTF-8", paras); paras.put("sign", sign); String url = "weixin://wxpay/bizpayurl?sign=SIGN&appid=APPID&mch_id=MCHID&product_id=PRODUCTID&time_stamp=TIMESTAMP&nonce_str=NOCESTR"; String nativeUrl = url.replace("SIGN", sign).replace("APPID", ConfigUtil.APPID).replace("MCHID", ConfigUtil.MCH_ID).replace("PRODUCTID", (String)paras.get("product_id")).replace("TIMESTAMP", (String)paras.get("time_stamp")).replace("NOCESTR", (String)paras.get("nonce_str")); SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("long_url", CommonUtil.urlEncodeUTF8(nativeUrl)); String sign2 = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign2); String requestXML = PayCommonUtil.getRequestXml(parameters); String result =CommonUtil.httpsRequestForStr(ConfigUtil.SHORT_URL, "POST", requestXML); Map<String, String> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String returnCode = map.get("return_code"); String resultCode = map.get("result_code"); if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){ String shortUrl = map.get("short_url"); //TODO 拿到shortUrl,寫代碼生成二維碼 System.out.println("shortUrl="+shortUrl); try { CreateQRCode.createCodeStream(shortUrl,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void wxScanCodeHandler(HttpServletRequest request,HttpServletResponse response) throws Exception { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } String orderNo=map.get("product_id").toString(); //接收到請(qǐng)求參數(shù)后調(diào)用統(tǒng)一下單接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "測(cè)試掃碼支付訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", map.get("product_id")); //parameters.put("total_fee", String.valueOf(totalPrice)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "NATIVE"); parameters.put("openid", map.get("openid")); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result2 = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("-----------------------------統(tǒng)一下單結(jié)果---------------------------"); System.out.println(result2); Map<String, String> mm=null; try { mm=getH5PayMap(result2,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String prepayId=getPrepayId(result2,request); //String returnNoneStr=getReturnNoneStr(result2,request); String prepayId=mm.get("prepay_id"); String returnNoneStr=mm.get("nonce_str");; SortedMap<Object, Object> lastSign = new TreeMap<Object, Object>(); lastSign.put("return_code", "SUCCESS"); lastSign.put("appid", ConfigUtil.APPID); lastSign.put("mch_id", ConfigUtil.MCH_ID); lastSign.put("nonce_str", returnNoneStr); lastSign.put("prepay_id", prepayId); lastSign.put("result_code", "SUCCESS"); lastSign.put("key", ConfigUtil.API_KEY); String lastSignpara = PayCommonUtil.createSign("UTF-8", lastSign); StringBuffer buf=new StringBuffer(); buf.append("<xml>"); buf.append("<return_code>SUCCESS</return_code>"); buf.append("<appid>"+ConfigUtil.APPID+"</appid>"); buf.append("<mch_id>"+ConfigUtil.MCH_ID+"</mch_id>"); buf.append("<nonce_str>"+returnNoneStr+"</nonce_str>"); buf.append("<prepay_id>"+prepayId+"</prepay_id>"); buf.append("<result_code>SUCCESS</result_code>"); buf.append("<sign>"+lastSignpara+"</sign>"); buf.append("</xml>"); response.getWriter().print(buf.toString()); } public Map<String, String> getH5PayMap(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); return map; } }最終看下公眾號(hào)支付和掃碼支付的微信配置: 希望通過這篇文章,大家能明白就算通過Java來做微信公眾號(hào)、微信支付而不借助github提供的那些坑人的代碼也可以開發(fā)出另自己和客戶滿意的微信應(yīng)用。雖然微信給出的demo都是PHP的,但這些都是浮云,開發(fā)語言是其次,理解接口調(diào)用需具備的底層只是才是程序員的必修課。 更多Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)! Kenyataan Laman Web ini Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn Alat AI Hot Undress AI Tool Gambar buka pakaian secara percuma Undresser.AI Undress Apl berkuasa AI untuk mencipta foto bogel yang realistik AI Clothes Remover Alat AI dalam talian untuk mengeluarkan pakaian daripada foto. Clothoff.io Penyingkiran pakaian AI Video Face Swap Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami! Tunjukkan Lagi Artikel Panas Panduan Membina Rumput Wonder | Uma Musume Pretty Derby 1 bulan yang lalu By Jack chen <??>: 99 Malam di Hutan - Semua Lencana Dan Cara Membuka Kunci Mereka 1 bulan yang lalu By DDD Panduan Suhu Rimworld Odyssey untuk Kapal dan Gravtech 3 minggu yang lalu By Jack chen Mejiro Ryan Build Guide | Uma Musume Pretty Derby 4 minggu yang lalu By Jack chen Rimworld Odyssey Cara Ikan 3 minggu yang lalu By Jack chen Tunjukkan Lagi Alat panas Notepad++7.3.1 Editor kod yang mudah digunakan dan percuma SublimeText3 versi Cina Versi Cina, sangat mudah digunakan Hantar Studio 13.0.1 Persekitaran pembangunan bersepadu PHP yang berkuasa Dreamweaver CS6 Alat pembangunan web visual SublimeText3 versi Mac Perisian penyuntingan kod peringkat Tuhan (SublimeText3) Tunjukkan Lagi Topik panas Tutorial Laravel 1601 29 Tutorial PHP 1502 276 Tunjukkan Lagi
3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口<\/p>
package com.debug.weixin.servlet; \r\n \r\nimport java.io.IOException; \r\nimport java.io.PrintWriter; \r\nimport java.util.SortedMap; \r\nimport java.util.TreeMap; \r\n \r\nimport javax.servlet.RequestDispatcher; \r\nimport javax.servlet.ServletException; \r\nimport javax.servlet.http.HttpServlet; \r\nimport javax.servlet.http.HttpServletRequest; \r\nimport javax.servlet.http.HttpServletResponse; \r\n \r\nimport com.debug.weixin.pojo.WeixinOauth2Token; \r\nimport com.debug.weixin.pojo.WeixinQRCode; \r\nimport com.debug.weixin.util.AdvancedUtil; \r\nimport com.debug.weixin.util.CommonUtil; \r\nimport com.debug.weixin.util.ConfigUtil; \r\nimport com.debug.weixin.util.PayCommonUtil; \r\n \r\npublic class PayServletForH5 extends HttpServlet { \r\n \r\n \r\n public void doGet(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n \r\n this.doPost(request, response); \r\n } \r\n \r\n public void doPost(HttpServletRequest request, HttpServletResponse response) \r\n throws ServletException, IOException { \r\n String orderNo=request.getParameter(\"orderNo\"); \r\n String code=request.getParameter(\"code\"); \r\n \r\n \/\/獲取AccessToken \r\n \r\n WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); \r\n \r\n String openId=token.getOpenId(); \r\n \r\n \/\/調(diào)用微信統(tǒng)一支付接口 \r\n SortedMap parameters = new TreeMap(); \r\n parameters.put(\"appid\", ConfigUtil.APPID); \r\n \r\n parameters.put(\"mch_id\", ConfigUtil.MCH_ID); \r\n parameters.put(\"device_info\", \"1000\"); \r\n parameters.put(\"body\", \"我的測(cè)試訂單\"); \r\n parameters.put(\"nonce_str\", PayCommonUtil.CreateNoncestr()); \r\n \r\n \r\n parameters.put(\"out_trade_no\", orderNo); \r\n \/\/parameters.put(\"total_fee\", String.valueOf(total)); \r\n parameters.put(\"total_fee\", \"1\"); \r\n parameters.put(\"spbill_create_ip\", request.getRemoteAddr()); \r\n parameters.put(\"notify_url\", ConfigUtil.NOTIFY_URL); \r\n parameters.put(\"trade_type\", \"JSAPI\"); \r\n parameters.put(\"openid\", openId); \r\n \r\n String sign = PayCommonUtil.createSign(\"UTF-8\", parameters); \r\n parameters.put(\"sign\", sign); \r\n \r\n String requestXML = PayCommonUtil.getRequestXml(parameters); \r\n \r\n String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,\"POST\", requestXML); \r\n System.out.println(\"----------------------------------\"); \r\n System.out.println(result); \r\n System.out.println(\"----------------------------------\"); \r\n \r\n request.setAttribute(\"orderNo\", orderNo); \r\n request.setAttribute(\"totalPrice\", \"0.01\"); \r\n String payJSON=\"\"; \r\n try { \r\n payJSON=CommonUtil.getH5PayStr(result,request); \r\n \r\n } catch (Exception e) { \r\n \/\/ TODO Auto-generated catch block \r\n e.printStackTrace(); \r\n } \r\n \/\/System.out.println(payJSON); \r\n request.setAttribute(\"unifiedOrder\",payJSON); \r\n \r\n RequestDispatcher dis= request.getRequestDispatcher(\"h5Pay.jsp\"); \r\n dis.forward(request, response); \r\n } \r\n \r\n}<\/pre>調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付<\/p>public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ \r\n \r\n Map map = XMLUtil.doXMLParse(result); \r\n \r\n \r\n SortedMap params = new TreeMap(); \r\n params.put(\"appId\", ConfigUtil.APPID); \r\n params.put(\"timeStamp\", Long.toString(new Date().getTime())); \r\n params.put(\"nonceStr\", PayCommonUtil.CreateNoncestr()); \r\n params.put(\"package\", \"prepay_id=\"+map.get(\"prepay_id\")); \r\n params.put(\"signType\", ConfigUtil.SIGN_TYPE); \r\n String paySign = PayCommonUtil.createSign(\"UTF-8\", params); \r\n \r\n params.put(\"paySign\", paySign); \/\/paySign的生成規(guī)則和Sign的生成規(guī)則一致 \r\n \r\n String json = JSONObject.fromObject(params).toString(); \r\n \r\n return json; \r\n }<\/pre> 4 編寫最終的支付界面調(diào)起微信H5支付<\/p><%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%> \r\n<% \r\nString path = request.getContextPath(); \r\nString basePath = request.getScheme()+\":\/\/\"+request.getServerName()+\":\"+request.getServerPort()+path+\"\/\"; \r\n%> \r\n \r\n \r\n \r\n \r\n \"> \r\n \r\n 微信H5支付<\/title> \r\n \r\n \r\n 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂 masyarakat Artikel Topik Soal Jawab Belajar Kursus Kamus Pengaturcaraan Perpustakaan Alatan Alat pembangunan Kod sumber laman web Perpustakaan PHP Kesan khas JS Bahan laman web Pemalam sambungan Alat AI Masa lapang Muat Turun Permainan Tutorial Permainan Melayu 簡(jiǎn)體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Rumah applet WeChat pembangunan WeChat Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 高洛峰 Feb 04, 2017 am 11:30 AM 微信支付現(xiàn)在已經(jīng)變得越來越流行了,隨之也出現(xiàn)了很多以可以快速接入微信支付為噱頭的產(chǎn)品,不過方便之余也使得我們做東西慢慢依賴第三方,喪失了獨(dú)立思考的能力,這次打算分享下我之前開發(fā)過的微信支付。 一 、H5公眾號(hào)支付 要點(diǎn):正確獲取openId以及統(tǒng)一下單接口,正確處理支付結(jié)果通知,正確配置支付授權(quán)目錄 H5的支付方式是使用較為廣泛的方式,這種支付方式主要用于微信內(nèi)自定義菜單的網(wǎng)頁,依賴手機(jī)上安裝的微信客戶端,高版本的微信才支持微信支付,下面按我的流程注意說明 1? 編寫用于支付的頁面,由于是測(cè)試用就寫的簡(jiǎn)單了點(diǎn)<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信支付樣例</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="oauthServlet" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="H5支付"/> </form> </br></br> <form action="scanCodePayServlet?flag=createCode" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="掃碼支付"/> </form> </body> </html>2 編寫一個(gè)servlet用于通過Oauth獲取codepackage com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ServerConfig; public class OauthServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); //調(diào)用微信Oauth2.0獲取openid String redirectURL=ServerConfig.SERVERDOMAIN+"/BasicWeixin/payServletForH5?orderNo="+orderNo; String redirectURI=""; try { redirectURI=CommonUtil.initOpenId(redirectURL); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(redirectURI); //RequestDispatcher dis= request.getRequestDispatcher(redirectURI); //dis.forward(request, response); response.sendRedirect(redirectURI); } }3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.pojo.WeixinOauth2Token; import com.debug.weixin.pojo.WeixinQRCode; import com.debug.weixin.util.AdvancedUtil; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.PayCommonUtil; public class PayServletForH5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); String code=request.getParameter("code"); //獲取AccessToken WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); String openId=token.getOpenId(); //調(diào)用微信統(tǒng)一支付接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "我的測(cè)試訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", orderNo); //parameters.put("total_fee", String.valueOf(total)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "JSAPI"); parameters.put("openid", openId); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("----------------------------------"); System.out.println(result); System.out.println("----------------------------------"); request.setAttribute("orderNo", orderNo); request.setAttribute("totalPrice", "0.01"); String payJSON=""; try { payJSON=CommonUtil.getH5PayStr(result,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(payJSON); request.setAttribute("unifiedOrder",payJSON); RequestDispatcher dis= request.getRequestDispatcher("h5Pay.jsp"); dis.forward(request, response); } }調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); SortedMap<Object,Object> params = new TreeMap<Object,Object>(); params.put("appId", ConfigUtil.APPID); params.put("timeStamp", Long.toString(new Date().getTime())); params.put("nonceStr", PayCommonUtil.CreateNoncestr()); params.put("package", "prepay_id="+map.get("prepay_id")); params.put("signType", ConfigUtil.SIGN_TYPE); String paySign = PayCommonUtil.createSign("UTF-8", params); params.put("paySign", paySign); //paySign的生成規(guī)則和Sign的生成規(guī)則一致 String json = JSONObject.fromObject(params).toString(); return json; } 4 編寫最終的支付界面調(diào)起微信H5支付<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信H5支付</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <script type="text/javascript"> function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest',<%=(String)request.getAttribute("unifiedOrder")%>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("恭喜你,支付成功!"); }else{ alert(res.err_code+res.err_desc+res.err_msg); } } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body> <input type="button" value="支付" onclick="callpay()"/> </body> </html>5 處理微信支付結(jié)果通知package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; public class PayHandlerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) { //對(duì)訂單進(jìn)行業(yè)務(wù)操作 System.out.println("-------------OK"); response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); //告訴微信服務(wù)器,我收到信息了,不要在調(diào)用回調(diào)action了 } } }對(duì)于上面的代碼,有很多都是參考http://blog.csdn.net/u011160656/article/details/41759195,因此這部分的代碼就不貼出來了,需要的話看這個(gè)博客就知道了。二 微信掃碼支付(模式一)要點(diǎn):必須調(diào)用長(zhǎng)鏈接轉(zhuǎn)短鏈接接口、正確配置掃碼支付回調(diào)URL1 根據(jù)訂單號(hào)生成微信支付二維碼下面是幾個(gè)生成二維碼的方法:package com.debug.weixin.util; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } } 這個(gè)算是工具類,還有一個(gè)就是把二維碼顯示在界面上的方法,CreateQRCode主要用到代碼塊:public static void createCodeStream(String text,HttpServletResponse response) throws Exception{ // response.setContentType("image/jpeg"); ServletOutputStream sos = response.getOutputStream(); int width = 500; int height = 500; //二維碼的圖片格式 String format = "jpg"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); //內(nèi)容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼 MatrixToImageWriter.writeToStream(bitMatrix, format,sos); sos.close(); }2 長(zhǎng)鏈接轉(zhuǎn)短鏈接生成二維碼,編寫掃碼支付回調(diào)方法并調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.CreateQRCode; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; import com.mongodb.DBObject; public class ScanCodePayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flag=request.getParameter("flag"); if("createCode".equals(flag)){ createPayCode(request,response); }else{ try { wxScanCodeHandler(request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void createPayCode(HttpServletRequest request,HttpServletResponse response){ String orderNo=request.getParameter("orderNo"); SortedMap<Object,Object> paras = new TreeMap<Object,Object>(); paras.put("appid", ConfigUtil.APPID); paras.put("mch_id", ConfigUtil.MCH_ID); paras.put("time_stamp", Long.toString(new Date().getTime())); paras.put("nonce_str", PayCommonUtil.CreateNoncestr()); paras.put("product_id", orderNo);//商品號(hào)要唯一 String sign = PayCommonUtil.createSign("UTF-8", paras); paras.put("sign", sign); String url = "weixin://wxpay/bizpayurl?sign=SIGN&appid=APPID&mch_id=MCHID&product_id=PRODUCTID&time_stamp=TIMESTAMP&nonce_str=NOCESTR"; String nativeUrl = url.replace("SIGN", sign).replace("APPID", ConfigUtil.APPID).replace("MCHID", ConfigUtil.MCH_ID).replace("PRODUCTID", (String)paras.get("product_id")).replace("TIMESTAMP", (String)paras.get("time_stamp")).replace("NOCESTR", (String)paras.get("nonce_str")); SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("long_url", CommonUtil.urlEncodeUTF8(nativeUrl)); String sign2 = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign2); String requestXML = PayCommonUtil.getRequestXml(parameters); String result =CommonUtil.httpsRequestForStr(ConfigUtil.SHORT_URL, "POST", requestXML); Map<String, String> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String returnCode = map.get("return_code"); String resultCode = map.get("result_code"); if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){ String shortUrl = map.get("short_url"); //TODO 拿到shortUrl,寫代碼生成二維碼 System.out.println("shortUrl="+shortUrl); try { CreateQRCode.createCodeStream(shortUrl,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void wxScanCodeHandler(HttpServletRequest request,HttpServletResponse response) throws Exception { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } String orderNo=map.get("product_id").toString(); //接收到請(qǐng)求參數(shù)后調(diào)用統(tǒng)一下單接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "測(cè)試掃碼支付訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", map.get("product_id")); //parameters.put("total_fee", String.valueOf(totalPrice)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "NATIVE"); parameters.put("openid", map.get("openid")); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result2 = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("-----------------------------統(tǒng)一下單結(jié)果---------------------------"); System.out.println(result2); Map<String, String> mm=null; try { mm=getH5PayMap(result2,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String prepayId=getPrepayId(result2,request); //String returnNoneStr=getReturnNoneStr(result2,request); String prepayId=mm.get("prepay_id"); String returnNoneStr=mm.get("nonce_str");; SortedMap<Object, Object> lastSign = new TreeMap<Object, Object>(); lastSign.put("return_code", "SUCCESS"); lastSign.put("appid", ConfigUtil.APPID); lastSign.put("mch_id", ConfigUtil.MCH_ID); lastSign.put("nonce_str", returnNoneStr); lastSign.put("prepay_id", prepayId); lastSign.put("result_code", "SUCCESS"); lastSign.put("key", ConfigUtil.API_KEY); String lastSignpara = PayCommonUtil.createSign("UTF-8", lastSign); StringBuffer buf=new StringBuffer(); buf.append("<xml>"); buf.append("<return_code>SUCCESS</return_code>"); buf.append("<appid>"+ConfigUtil.APPID+"</appid>"); buf.append("<mch_id>"+ConfigUtil.MCH_ID+"</mch_id>"); buf.append("<nonce_str>"+returnNoneStr+"</nonce_str>"); buf.append("<prepay_id>"+prepayId+"</prepay_id>"); buf.append("<result_code>SUCCESS</result_code>"); buf.append("<sign>"+lastSignpara+"</sign>"); buf.append("</xml>"); response.getWriter().print(buf.toString()); } public Map<String, String> getH5PayMap(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); return map; } }最終看下公眾號(hào)支付和掃碼支付的微信配置: 希望通過這篇文章,大家能明白就算通過Java來做微信公眾號(hào)、微信支付而不借助github提供的那些坑人的代碼也可以開發(fā)出另自己和客戶滿意的微信應(yīng)用。雖然微信給出的demo都是PHP的,但這些都是浮云,開發(fā)語言是其次,理解接口調(diào)用需具備的底層只是才是程序員的必修課。 更多Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)! Kenyataan Laman Web ini Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn Alat AI Hot Undress AI Tool Gambar buka pakaian secara percuma Undresser.AI Undress Apl berkuasa AI untuk mencipta foto bogel yang realistik AI Clothes Remover Alat AI dalam talian untuk mengeluarkan pakaian daripada foto. Clothoff.io Penyingkiran pakaian AI Video Face Swap Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami! Tunjukkan Lagi Artikel Panas Panduan Membina Rumput Wonder | Uma Musume Pretty Derby 1 bulan yang lalu By Jack chen <??>: 99 Malam di Hutan - Semua Lencana Dan Cara Membuka Kunci Mereka 1 bulan yang lalu By DDD Panduan Suhu Rimworld Odyssey untuk Kapal dan Gravtech 3 minggu yang lalu By Jack chen Mejiro Ryan Build Guide | Uma Musume Pretty Derby 4 minggu yang lalu By Jack chen Rimworld Odyssey Cara Ikan 3 minggu yang lalu By Jack chen Tunjukkan Lagi Alat panas Notepad++7.3.1 Editor kod yang mudah digunakan dan percuma SublimeText3 versi Cina Versi Cina, sangat mudah digunakan Hantar Studio 13.0.1 Persekitaran pembangunan bersepadu PHP yang berkuasa Dreamweaver CS6 Alat pembangunan web visual SublimeText3 versi Mac Perisian penyuntingan kod peringkat Tuhan (SublimeText3) Tunjukkan Lagi Topik panas Tutorial Laravel 1601 29 Tutorial PHP 1502 276 Tunjukkan Lagi
調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付<\/p>
public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ \r\n \r\n Map map = XMLUtil.doXMLParse(result); \r\n \r\n \r\n SortedMap params = new TreeMap(); \r\n params.put(\"appId\", ConfigUtil.APPID); \r\n params.put(\"timeStamp\", Long.toString(new Date().getTime())); \r\n params.put(\"nonceStr\", PayCommonUtil.CreateNoncestr()); \r\n params.put(\"package\", \"prepay_id=\"+map.get(\"prepay_id\")); \r\n params.put(\"signType\", ConfigUtil.SIGN_TYPE); \r\n String paySign = PayCommonUtil.createSign(\"UTF-8\", params); \r\n \r\n params.put(\"paySign\", paySign); \/\/paySign的生成規(guī)則和Sign的生成規(guī)則一致 \r\n \r\n String json = JSONObject.fromObject(params).toString(); \r\n \r\n return json; \r\n }<\/pre> 4 編寫最終的支付界面調(diào)起微信H5支付<\/p><%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%> \r\n<% \r\nString path = request.getContextPath(); \r\nString basePath = request.getScheme()+\":\/\/\"+request.getServerName()+\":\"+request.getServerPort()+path+\"\/\"; \r\n%> \r\n \r\n \r\n \r\n \r\n \"> \r\n \r\n 微信H5支付<\/title> \r\n \r\n \r\n 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂 masyarakat Artikel Topik Soal Jawab Belajar Kursus Kamus Pengaturcaraan Perpustakaan Alatan Alat pembangunan Kod sumber laman web Perpustakaan PHP Kesan khas JS Bahan laman web Pemalam sambungan Alat AI Masa lapang Muat Turun Permainan Tutorial Permainan Melayu 簡(jiǎn)體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Rumah applet WeChat pembangunan WeChat Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 高洛峰 Feb 04, 2017 am 11:30 AM 微信支付現(xiàn)在已經(jīng)變得越來越流行了,隨之也出現(xiàn)了很多以可以快速接入微信支付為噱頭的產(chǎn)品,不過方便之余也使得我們做東西慢慢依賴第三方,喪失了獨(dú)立思考的能力,這次打算分享下我之前開發(fā)過的微信支付。 一 、H5公眾號(hào)支付 要點(diǎn):正確獲取openId以及統(tǒng)一下單接口,正確處理支付結(jié)果通知,正確配置支付授權(quán)目錄 H5的支付方式是使用較為廣泛的方式,這種支付方式主要用于微信內(nèi)自定義菜單的網(wǎng)頁,依賴手機(jī)上安裝的微信客戶端,高版本的微信才支持微信支付,下面按我的流程注意說明 1? 編寫用于支付的頁面,由于是測(cè)試用就寫的簡(jiǎn)單了點(diǎn)<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信支付樣例</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="oauthServlet" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="H5支付"/> </form> </br></br> <form action="scanCodePayServlet?flag=createCode" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="掃碼支付"/> </form> </body> </html>2 編寫一個(gè)servlet用于通過Oauth獲取codepackage com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ServerConfig; public class OauthServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); //調(diào)用微信Oauth2.0獲取openid String redirectURL=ServerConfig.SERVERDOMAIN+"/BasicWeixin/payServletForH5?orderNo="+orderNo; String redirectURI=""; try { redirectURI=CommonUtil.initOpenId(redirectURL); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(redirectURI); //RequestDispatcher dis= request.getRequestDispatcher(redirectURI); //dis.forward(request, response); response.sendRedirect(redirectURI); } }3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.pojo.WeixinOauth2Token; import com.debug.weixin.pojo.WeixinQRCode; import com.debug.weixin.util.AdvancedUtil; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.PayCommonUtil; public class PayServletForH5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); String code=request.getParameter("code"); //獲取AccessToken WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); String openId=token.getOpenId(); //調(diào)用微信統(tǒng)一支付接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "我的測(cè)試訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", orderNo); //parameters.put("total_fee", String.valueOf(total)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "JSAPI"); parameters.put("openid", openId); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("----------------------------------"); System.out.println(result); System.out.println("----------------------------------"); request.setAttribute("orderNo", orderNo); request.setAttribute("totalPrice", "0.01"); String payJSON=""; try { payJSON=CommonUtil.getH5PayStr(result,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(payJSON); request.setAttribute("unifiedOrder",payJSON); RequestDispatcher dis= request.getRequestDispatcher("h5Pay.jsp"); dis.forward(request, response); } }調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); SortedMap<Object,Object> params = new TreeMap<Object,Object>(); params.put("appId", ConfigUtil.APPID); params.put("timeStamp", Long.toString(new Date().getTime())); params.put("nonceStr", PayCommonUtil.CreateNoncestr()); params.put("package", "prepay_id="+map.get("prepay_id")); params.put("signType", ConfigUtil.SIGN_TYPE); String paySign = PayCommonUtil.createSign("UTF-8", params); params.put("paySign", paySign); //paySign的生成規(guī)則和Sign的生成規(guī)則一致 String json = JSONObject.fromObject(params).toString(); return json; } 4 編寫最終的支付界面調(diào)起微信H5支付<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信H5支付</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <script type="text/javascript"> function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest',<%=(String)request.getAttribute("unifiedOrder")%>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("恭喜你,支付成功!"); }else{ alert(res.err_code+res.err_desc+res.err_msg); } } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body> <input type="button" value="支付" onclick="callpay()"/> </body> </html>5 處理微信支付結(jié)果通知package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; public class PayHandlerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) { //對(duì)訂單進(jìn)行業(yè)務(wù)操作 System.out.println("-------------OK"); response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); //告訴微信服務(wù)器,我收到信息了,不要在調(diào)用回調(diào)action了 } } }對(duì)于上面的代碼,有很多都是參考http://blog.csdn.net/u011160656/article/details/41759195,因此這部分的代碼就不貼出來了,需要的話看這個(gè)博客就知道了。二 微信掃碼支付(模式一)要點(diǎn):必須調(diào)用長(zhǎng)鏈接轉(zhuǎn)短鏈接接口、正確配置掃碼支付回調(diào)URL1 根據(jù)訂單號(hào)生成微信支付二維碼下面是幾個(gè)生成二維碼的方法:package com.debug.weixin.util; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } } 這個(gè)算是工具類,還有一個(gè)就是把二維碼顯示在界面上的方法,CreateQRCode主要用到代碼塊:public static void createCodeStream(String text,HttpServletResponse response) throws Exception{ // response.setContentType("image/jpeg"); ServletOutputStream sos = response.getOutputStream(); int width = 500; int height = 500; //二維碼的圖片格式 String format = "jpg"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); //內(nèi)容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼 MatrixToImageWriter.writeToStream(bitMatrix, format,sos); sos.close(); }2 長(zhǎng)鏈接轉(zhuǎn)短鏈接生成二維碼,編寫掃碼支付回調(diào)方法并調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.CreateQRCode; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; import com.mongodb.DBObject; public class ScanCodePayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flag=request.getParameter("flag"); if("createCode".equals(flag)){ createPayCode(request,response); }else{ try { wxScanCodeHandler(request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void createPayCode(HttpServletRequest request,HttpServletResponse response){ String orderNo=request.getParameter("orderNo"); SortedMap<Object,Object> paras = new TreeMap<Object,Object>(); paras.put("appid", ConfigUtil.APPID); paras.put("mch_id", ConfigUtil.MCH_ID); paras.put("time_stamp", Long.toString(new Date().getTime())); paras.put("nonce_str", PayCommonUtil.CreateNoncestr()); paras.put("product_id", orderNo);//商品號(hào)要唯一 String sign = PayCommonUtil.createSign("UTF-8", paras); paras.put("sign", sign); String url = "weixin://wxpay/bizpayurl?sign=SIGN&appid=APPID&mch_id=MCHID&product_id=PRODUCTID&time_stamp=TIMESTAMP&nonce_str=NOCESTR"; String nativeUrl = url.replace("SIGN", sign).replace("APPID", ConfigUtil.APPID).replace("MCHID", ConfigUtil.MCH_ID).replace("PRODUCTID", (String)paras.get("product_id")).replace("TIMESTAMP", (String)paras.get("time_stamp")).replace("NOCESTR", (String)paras.get("nonce_str")); SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("long_url", CommonUtil.urlEncodeUTF8(nativeUrl)); String sign2 = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign2); String requestXML = PayCommonUtil.getRequestXml(parameters); String result =CommonUtil.httpsRequestForStr(ConfigUtil.SHORT_URL, "POST", requestXML); Map<String, String> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String returnCode = map.get("return_code"); String resultCode = map.get("result_code"); if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){ String shortUrl = map.get("short_url"); //TODO 拿到shortUrl,寫代碼生成二維碼 System.out.println("shortUrl="+shortUrl); try { CreateQRCode.createCodeStream(shortUrl,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void wxScanCodeHandler(HttpServletRequest request,HttpServletResponse response) throws Exception { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } String orderNo=map.get("product_id").toString(); //接收到請(qǐng)求參數(shù)后調(diào)用統(tǒng)一下單接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "測(cè)試掃碼支付訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", map.get("product_id")); //parameters.put("total_fee", String.valueOf(totalPrice)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "NATIVE"); parameters.put("openid", map.get("openid")); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result2 = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("-----------------------------統(tǒng)一下單結(jié)果---------------------------"); System.out.println(result2); Map<String, String> mm=null; try { mm=getH5PayMap(result2,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String prepayId=getPrepayId(result2,request); //String returnNoneStr=getReturnNoneStr(result2,request); String prepayId=mm.get("prepay_id"); String returnNoneStr=mm.get("nonce_str");; SortedMap<Object, Object> lastSign = new TreeMap<Object, Object>(); lastSign.put("return_code", "SUCCESS"); lastSign.put("appid", ConfigUtil.APPID); lastSign.put("mch_id", ConfigUtil.MCH_ID); lastSign.put("nonce_str", returnNoneStr); lastSign.put("prepay_id", prepayId); lastSign.put("result_code", "SUCCESS"); lastSign.put("key", ConfigUtil.API_KEY); String lastSignpara = PayCommonUtil.createSign("UTF-8", lastSign); StringBuffer buf=new StringBuffer(); buf.append("<xml>"); buf.append("<return_code>SUCCESS</return_code>"); buf.append("<appid>"+ConfigUtil.APPID+"</appid>"); buf.append("<mch_id>"+ConfigUtil.MCH_ID+"</mch_id>"); buf.append("<nonce_str>"+returnNoneStr+"</nonce_str>"); buf.append("<prepay_id>"+prepayId+"</prepay_id>"); buf.append("<result_code>SUCCESS</result_code>"); buf.append("<sign>"+lastSignpara+"</sign>"); buf.append("</xml>"); response.getWriter().print(buf.toString()); } public Map<String, String> getH5PayMap(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); return map; } }最終看下公眾號(hào)支付和掃碼支付的微信配置: 希望通過這篇文章,大家能明白就算通過Java來做微信公眾號(hào)、微信支付而不借助github提供的那些坑人的代碼也可以開發(fā)出另自己和客戶滿意的微信應(yīng)用。雖然微信給出的demo都是PHP的,但這些都是浮云,開發(fā)語言是其次,理解接口調(diào)用需具備的底層只是才是程序員的必修課。 更多Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)! Kenyataan Laman Web ini Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn Alat AI Hot Undress AI Tool Gambar buka pakaian secara percuma Undresser.AI Undress Apl berkuasa AI untuk mencipta foto bogel yang realistik AI Clothes Remover Alat AI dalam talian untuk mengeluarkan pakaian daripada foto. Clothoff.io Penyingkiran pakaian AI Video Face Swap Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami! Tunjukkan Lagi Artikel Panas Panduan Membina Rumput Wonder | Uma Musume Pretty Derby 1 bulan yang lalu By Jack chen <??>: 99 Malam di Hutan - Semua Lencana Dan Cara Membuka Kunci Mereka 1 bulan yang lalu By DDD Panduan Suhu Rimworld Odyssey untuk Kapal dan Gravtech 3 minggu yang lalu By Jack chen Mejiro Ryan Build Guide | Uma Musume Pretty Derby 4 minggu yang lalu By Jack chen Rimworld Odyssey Cara Ikan 3 minggu yang lalu By Jack chen Tunjukkan Lagi Alat panas Notepad++7.3.1 Editor kod yang mudah digunakan dan percuma SublimeText3 versi Cina Versi Cina, sangat mudah digunakan Hantar Studio 13.0.1 Persekitaran pembangunan bersepadu PHP yang berkuasa Dreamweaver CS6 Alat pembangunan web visual SublimeText3 versi Mac Perisian penyuntingan kod peringkat Tuhan (SublimeText3) Tunjukkan Lagi Topik panas Tutorial Laravel 1601 29 Tutorial PHP 1502 276 Tunjukkan Lagi
4 編寫最終的支付界面調(diào)起微信H5支付<\/p>
<%@ page language=\"java\" import=\"java.util.*\" pageEncoding=\"UTF-8\"%> \r\n<% \r\nString path = request.getContextPath(); \r\nString basePath = request.getScheme()+\":\/\/\"+request.getServerName()+\":\"+request.getServerPort()+path+\"\/\"; \r\n%> \r\n \r\n \r\n \r\n \r\n \"> \r\n \r\n 微信H5支付<\/title> \r\n \r\n \r\n 国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂 masyarakat Artikel Topik Soal Jawab Belajar Kursus Kamus Pengaturcaraan Perpustakaan Alatan Alat pembangunan Kod sumber laman web Perpustakaan PHP Kesan khas JS Bahan laman web Pemalam sambungan Alat AI Masa lapang Muat Turun Permainan Tutorial Permainan Melayu 簡(jiǎn)體中文 English 繁體中文 日本語 ??? Melayu Fran?ais Deutsch Login singup Rumah applet WeChat pembangunan WeChat Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例 高洛峰 Feb 04, 2017 am 11:30 AM 微信支付現(xiàn)在已經(jīng)變得越來越流行了,隨之也出現(xiàn)了很多以可以快速接入微信支付為噱頭的產(chǎn)品,不過方便之余也使得我們做東西慢慢依賴第三方,喪失了獨(dú)立思考的能力,這次打算分享下我之前開發(fā)過的微信支付。 一 、H5公眾號(hào)支付 要點(diǎn):正確獲取openId以及統(tǒng)一下單接口,正確處理支付結(jié)果通知,正確配置支付授權(quán)目錄 H5的支付方式是使用較為廣泛的方式,這種支付方式主要用于微信內(nèi)自定義菜單的網(wǎng)頁,依賴手機(jī)上安裝的微信客戶端,高版本的微信才支持微信支付,下面按我的流程注意說明 1? 編寫用于支付的頁面,由于是測(cè)試用就寫的簡(jiǎn)單了點(diǎn)<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信支付樣例</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="oauthServlet" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="H5支付"/> </form> </br></br> <form action="scanCodePayServlet?flag=createCode" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="掃碼支付"/> </form> </body> </html>2 編寫一個(gè)servlet用于通過Oauth獲取codepackage com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ServerConfig; public class OauthServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); //調(diào)用微信Oauth2.0獲取openid String redirectURL=ServerConfig.SERVERDOMAIN+"/BasicWeixin/payServletForH5?orderNo="+orderNo; String redirectURI=""; try { redirectURI=CommonUtil.initOpenId(redirectURL); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(redirectURI); //RequestDispatcher dis= request.getRequestDispatcher(redirectURI); //dis.forward(request, response); response.sendRedirect(redirectURI); } }3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.pojo.WeixinOauth2Token; import com.debug.weixin.pojo.WeixinQRCode; import com.debug.weixin.util.AdvancedUtil; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.PayCommonUtil; public class PayServletForH5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); String code=request.getParameter("code"); //獲取AccessToken WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); String openId=token.getOpenId(); //調(diào)用微信統(tǒng)一支付接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "我的測(cè)試訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", orderNo); //parameters.put("total_fee", String.valueOf(total)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "JSAPI"); parameters.put("openid", openId); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("----------------------------------"); System.out.println(result); System.out.println("----------------------------------"); request.setAttribute("orderNo", orderNo); request.setAttribute("totalPrice", "0.01"); String payJSON=""; try { payJSON=CommonUtil.getH5PayStr(result,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(payJSON); request.setAttribute("unifiedOrder",payJSON); RequestDispatcher dis= request.getRequestDispatcher("h5Pay.jsp"); dis.forward(request, response); } }調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); SortedMap<Object,Object> params = new TreeMap<Object,Object>(); params.put("appId", ConfigUtil.APPID); params.put("timeStamp", Long.toString(new Date().getTime())); params.put("nonceStr", PayCommonUtil.CreateNoncestr()); params.put("package", "prepay_id="+map.get("prepay_id")); params.put("signType", ConfigUtil.SIGN_TYPE); String paySign = PayCommonUtil.createSign("UTF-8", params); params.put("paySign", paySign); //paySign的生成規(guī)則和Sign的生成規(guī)則一致 String json = JSONObject.fromObject(params).toString(); return json; } 4 編寫最終的支付界面調(diào)起微信H5支付<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信H5支付</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <script type="text/javascript"> function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest',<%=(String)request.getAttribute("unifiedOrder")%>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("恭喜你,支付成功!"); }else{ alert(res.err_code+res.err_desc+res.err_msg); } } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body> <input type="button" value="支付" onclick="callpay()"/> </body> </html>5 處理微信支付結(jié)果通知package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; public class PayHandlerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) { //對(duì)訂單進(jìn)行業(yè)務(wù)操作 System.out.println("-------------OK"); response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); //告訴微信服務(wù)器,我收到信息了,不要在調(diào)用回調(diào)action了 } } }對(duì)于上面的代碼,有很多都是參考http://blog.csdn.net/u011160656/article/details/41759195,因此這部分的代碼就不貼出來了,需要的話看這個(gè)博客就知道了。二 微信掃碼支付(模式一)要點(diǎn):必須調(diào)用長(zhǎng)鏈接轉(zhuǎn)短鏈接接口、正確配置掃碼支付回調(diào)URL1 根據(jù)訂單號(hào)生成微信支付二維碼下面是幾個(gè)生成二維碼的方法:package com.debug.weixin.util; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } } 這個(gè)算是工具類,還有一個(gè)就是把二維碼顯示在界面上的方法,CreateQRCode主要用到代碼塊:public static void createCodeStream(String text,HttpServletResponse response) throws Exception{ // response.setContentType("image/jpeg"); ServletOutputStream sos = response.getOutputStream(); int width = 500; int height = 500; //二維碼的圖片格式 String format = "jpg"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); //內(nèi)容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼 MatrixToImageWriter.writeToStream(bitMatrix, format,sos); sos.close(); }2 長(zhǎng)鏈接轉(zhuǎn)短鏈接生成二維碼,編寫掃碼支付回調(diào)方法并調(diào)用統(tǒng)一下單接口package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.CreateQRCode; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; import com.mongodb.DBObject; public class ScanCodePayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flag=request.getParameter("flag"); if("createCode".equals(flag)){ createPayCode(request,response); }else{ try { wxScanCodeHandler(request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void createPayCode(HttpServletRequest request,HttpServletResponse response){ String orderNo=request.getParameter("orderNo"); SortedMap<Object,Object> paras = new TreeMap<Object,Object>(); paras.put("appid", ConfigUtil.APPID); paras.put("mch_id", ConfigUtil.MCH_ID); paras.put("time_stamp", Long.toString(new Date().getTime())); paras.put("nonce_str", PayCommonUtil.CreateNoncestr()); paras.put("product_id", orderNo);//商品號(hào)要唯一 String sign = PayCommonUtil.createSign("UTF-8", paras); paras.put("sign", sign); String url = "weixin://wxpay/bizpayurl?sign=SIGN&appid=APPID&mch_id=MCHID&product_id=PRODUCTID&time_stamp=TIMESTAMP&nonce_str=NOCESTR"; String nativeUrl = url.replace("SIGN", sign).replace("APPID", ConfigUtil.APPID).replace("MCHID", ConfigUtil.MCH_ID).replace("PRODUCTID", (String)paras.get("product_id")).replace("TIMESTAMP", (String)paras.get("time_stamp")).replace("NOCESTR", (String)paras.get("nonce_str")); SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("long_url", CommonUtil.urlEncodeUTF8(nativeUrl)); String sign2 = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign2); String requestXML = PayCommonUtil.getRequestXml(parameters); String result =CommonUtil.httpsRequestForStr(ConfigUtil.SHORT_URL, "POST", requestXML); Map<String, String> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String returnCode = map.get("return_code"); String resultCode = map.get("result_code"); if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){ String shortUrl = map.get("short_url"); //TODO 拿到shortUrl,寫代碼生成二維碼 System.out.println("shortUrl="+shortUrl); try { CreateQRCode.createCodeStream(shortUrl,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void wxScanCodeHandler(HttpServletRequest request,HttpServletResponse response) throws Exception { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } String orderNo=map.get("product_id").toString(); //接收到請(qǐng)求參數(shù)后調(diào)用統(tǒng)一下單接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "測(cè)試掃碼支付訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", map.get("product_id")); //parameters.put("total_fee", String.valueOf(totalPrice)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "NATIVE"); parameters.put("openid", map.get("openid")); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result2 = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("-----------------------------統(tǒng)一下單結(jié)果---------------------------"); System.out.println(result2); Map<String, String> mm=null; try { mm=getH5PayMap(result2,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String prepayId=getPrepayId(result2,request); //String returnNoneStr=getReturnNoneStr(result2,request); String prepayId=mm.get("prepay_id"); String returnNoneStr=mm.get("nonce_str");; SortedMap<Object, Object> lastSign = new TreeMap<Object, Object>(); lastSign.put("return_code", "SUCCESS"); lastSign.put("appid", ConfigUtil.APPID); lastSign.put("mch_id", ConfigUtil.MCH_ID); lastSign.put("nonce_str", returnNoneStr); lastSign.put("prepay_id", prepayId); lastSign.put("result_code", "SUCCESS"); lastSign.put("key", ConfigUtil.API_KEY); String lastSignpara = PayCommonUtil.createSign("UTF-8", lastSign); StringBuffer buf=new StringBuffer(); buf.append("<xml>"); buf.append("<return_code>SUCCESS</return_code>"); buf.append("<appid>"+ConfigUtil.APPID+"</appid>"); buf.append("<mch_id>"+ConfigUtil.MCH_ID+"</mch_id>"); buf.append("<nonce_str>"+returnNoneStr+"</nonce_str>"); buf.append("<prepay_id>"+prepayId+"</prepay_id>"); buf.append("<result_code>SUCCESS</result_code>"); buf.append("<sign>"+lastSignpara+"</sign>"); buf.append("</xml>"); response.getWriter().print(buf.toString()); } public Map<String, String> getH5PayMap(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); return map; } }最終看下公眾號(hào)支付和掃碼支付的微信配置: 希望通過這篇文章,大家能明白就算通過Java來做微信公眾號(hào)、微信支付而不借助github提供的那些坑人的代碼也可以開發(fā)出另自己和客戶滿意的微信應(yīng)用。雖然微信給出的demo都是PHP的,但這些都是浮云,開發(fā)語言是其次,理解接口調(diào)用需具備的底層只是才是程序員的必修課。 更多Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)! Kenyataan Laman Web ini Kandungan artikel ini disumbangkan secara sukarela oleh netizen, dan hak cipta adalah milik pengarang asal. Laman web ini tidak memikul tanggungjawab undang-undang yang sepadan. Jika anda menemui sebarang kandungan yang disyaki plagiarisme atau pelanggaran, sila hubungi admin@php.cn Alat AI Hot Undress AI Tool Gambar buka pakaian secara percuma Undresser.AI Undress Apl berkuasa AI untuk mencipta foto bogel yang realistik AI Clothes Remover Alat AI dalam talian untuk mengeluarkan pakaian daripada foto. Clothoff.io Penyingkiran pakaian AI Video Face Swap Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami! Tunjukkan Lagi Artikel Panas Panduan Membina Rumput Wonder | Uma Musume Pretty Derby 1 bulan yang lalu By Jack chen <??>: 99 Malam di Hutan - Semua Lencana Dan Cara Membuka Kunci Mereka 1 bulan yang lalu By DDD Panduan Suhu Rimworld Odyssey untuk Kapal dan Gravtech 3 minggu yang lalu By Jack chen Mejiro Ryan Build Guide | Uma Musume Pretty Derby 4 minggu yang lalu By Jack chen Rimworld Odyssey Cara Ikan 3 minggu yang lalu By Jack chen Tunjukkan Lagi Alat panas Notepad++7.3.1 Editor kod yang mudah digunakan dan percuma SublimeText3 versi Cina Versi Cina, sangat mudah digunakan Hantar Studio 13.0.1 Persekitaran pembangunan bersepadu PHP yang berkuasa Dreamweaver CS6 Alat pembangunan web visual SublimeText3 versi Mac Perisian penyuntingan kod peringkat Tuhan (SublimeText3) Tunjukkan Lagi Topik panas Tutorial Laravel 1601 29 Tutorial PHP 1502 276 Tunjukkan Lagi
微信支付現(xiàn)在已經(jīng)變得越來越流行了,隨之也出現(xiàn)了很多以可以快速接入微信支付為噱頭的產(chǎn)品,不過方便之余也使得我們做東西慢慢依賴第三方,喪失了獨(dú)立思考的能力,這次打算分享下我之前開發(fā)過的微信支付。
一 、H5公眾號(hào)支付
要點(diǎn):正確獲取openId以及統(tǒng)一下單接口,正確處理支付結(jié)果通知,正確配置支付授權(quán)目錄
H5的支付方式是使用較為廣泛的方式,這種支付方式主要用于微信內(nèi)自定義菜單的網(wǎng)頁,依賴手機(jī)上安裝的微信客戶端,高版本的微信才支持微信支付,下面按我的流程注意說明
1? 編寫用于支付的頁面,由于是測(cè)試用就寫的簡(jiǎn)單了點(diǎn)
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信支付樣例</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="oauthServlet" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="H5支付"/> </form> </br></br> <form action="scanCodePayServlet?flag=createCode" method="POST"> 訂單號(hào):<input type="text" name="orderNo" /> <input type="submit" value="掃碼支付"/> </form> </body> </html>
2 編寫一個(gè)servlet用于通過Oauth獲取code
package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ServerConfig; public class OauthServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); //調(diào)用微信Oauth2.0獲取openid String redirectURL=ServerConfig.SERVERDOMAIN+"/BasicWeixin/payServletForH5?orderNo="+orderNo; String redirectURI=""; try { redirectURI=CommonUtil.initOpenId(redirectURL); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(redirectURI); //RequestDispatcher dis= request.getRequestDispatcher(redirectURI); //dis.forward(request, response); response.sendRedirect(redirectURI); } }
3 獲取到code后,通過REDIRECTURI獲取openId,調(diào)用統(tǒng)一下單接口
package com.debug.weixin.servlet; import java.io.IOException; import java.io.PrintWriter; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.RequestDispatcher; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.debug.weixin.pojo.WeixinOauth2Token; import com.debug.weixin.pojo.WeixinQRCode; import com.debug.weixin.util.AdvancedUtil; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.PayCommonUtil; public class PayServletForH5 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String orderNo=request.getParameter("orderNo"); String code=request.getParameter("code"); //獲取AccessToken WeixinOauth2Token token=AdvancedUtil.getOauth2AccessToken(ConfigUtil.APPID, ConfigUtil.APP_SECRECT, code); String openId=token.getOpenId(); //調(diào)用微信統(tǒng)一支付接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "我的測(cè)試訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", orderNo); //parameters.put("total_fee", String.valueOf(total)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "JSAPI"); parameters.put("openid", openId); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("----------------------------------"); System.out.println(result); System.out.println("----------------------------------"); request.setAttribute("orderNo", orderNo); request.setAttribute("totalPrice", "0.01"); String payJSON=""; try { payJSON=CommonUtil.getH5PayStr(result,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //System.out.println(payJSON); request.setAttribute("unifiedOrder",payJSON); RequestDispatcher dis= request.getRequestDispatcher("h5Pay.jsp"); dis.forward(request, response); } }
調(diào)用微信統(tǒng)一下單接口,需要注意簽名算法,只有簽名計(jì)算正確才能順利支付
public static String getH5PayStr(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); SortedMap<Object,Object> params = new TreeMap<Object,Object>(); params.put("appId", ConfigUtil.APPID); params.put("timeStamp", Long.toString(new Date().getTime())); params.put("nonceStr", PayCommonUtil.CreateNoncestr()); params.put("package", "prepay_id="+map.get("prepay_id")); params.put("signType", ConfigUtil.SIGN_TYPE); String paySign = PayCommonUtil.createSign("UTF-8", params); params.put("paySign", paySign); //paySign的生成規(guī)則和Sign的生成規(guī)則一致 String json = JSONObject.fromObject(params).toString(); return json; }
4 編寫最終的支付界面調(diào)起微信H5支付
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <base href="<%=basePath%>"> <title>微信H5支付</title> <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0"> <script type="text/javascript"> function jsApiCall(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest',<%=(String)request.getAttribute("unifiedOrder")%>, function(res){ WeixinJSBridge.log(res.err_msg); //alert(res.err_code+res.err_desc+res.err_msg); if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("恭喜你,支付成功!"); }else{ alert(res.err_code+res.err_desc+res.err_msg); } } ); } function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', jsApiCall, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', jsApiCall); document.attachEvent('onWeixinJSBridgeReady', jsApiCall); } }else{ jsApiCall(); } } </script> </head> <body> <input type="button" value="支付" onclick="callpay()"/> </body> </html>
5 處理微信支付結(jié)果通知
package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Map; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; public class PayHandlerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } if (map.get("result_code").toString().equalsIgnoreCase("SUCCESS")) { //對(duì)訂單進(jìn)行業(yè)務(wù)操作 System.out.println("-------------OK"); response.getWriter().write(PayCommonUtil.setXML("SUCCESS", "")); //告訴微信服務(wù)器,我收到信息了,不要在調(diào)用回調(diào)action了 } } }
對(duì)于上面的代碼,有很多都是參考http://blog.csdn.net/u011160656/article/details/41759195,因此這部分的代碼就不貼出來了,需要的話看這個(gè)博客就知道了。
二 微信掃碼支付(模式一)
要點(diǎn):必須調(diào)用長(zhǎng)鏈接轉(zhuǎn)短鏈接接口、正確配置掃碼支付回調(diào)URL
1 根據(jù)訂單號(hào)生成微信支付二維碼
下面是幾個(gè)生成二維碼的方法:
package com.debug.weixin.util; import com.google.zxing.common.BitMatrix; import javax.imageio.ImageIO; import java.io.File; import java.io.OutputStream; import java.io.IOException; import java.awt.image.BufferedImage; public final class MatrixToImageWriter { private static final int BLACK = 0xFF000000; private static final int WHITE = 0xFFFFFFFF; private MatrixToImageWriter() {} public static BufferedImage toBufferedImage(BitMatrix matrix) { int width = matrix.getWidth(); int height = matrix.getHeight(); BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); for (int x = 0; x < width; x++) { for (int y = 0; y < height; y++) { image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE); } } return image; } public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, file)) { throw new IOException("Could not write an image of format " + format + " to " + file); } } public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException { BufferedImage image = toBufferedImage(matrix); if (!ImageIO.write(image, format, stream)) { throw new IOException("Could not write an image of format " + format); } } }
這個(gè)算是工具類,還有一個(gè)就是把二維碼顯示在界面上的方法,CreateQRCode主要用到代碼塊:
public static void createCodeStream(String text,HttpServletResponse response) throws Exception{ // response.setContentType("image/jpeg"); ServletOutputStream sos = response.getOutputStream(); int width = 500; int height = 500; //二維碼的圖片格式 String format = "jpg"; MultiFormatWriter multiFormatWriter = new MultiFormatWriter(); Map hints = new HashMap(); //內(nèi)容所使用編碼 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); BitMatrix bitMatrix = multiFormatWriter.encode(text, BarcodeFormat.QR_CODE, width, height, hints); //生成二維碼 MatrixToImageWriter.writeToStream(bitMatrix, format,sos); sos.close(); }
2 長(zhǎng)鏈接轉(zhuǎn)短鏈接生成二維碼,編寫掃碼支付回調(diào)方法并調(diào)用統(tǒng)一下單接口
package com.debug.weixin.servlet; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.PrintWriter; import java.util.Date; import java.util.Map; import java.util.SortedMap; import java.util.TreeMap; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.jdom.JDOMException; import com.debug.weixin.util.CommonUtil; import com.debug.weixin.util.ConfigUtil; import com.debug.weixin.util.CreateQRCode; import com.debug.weixin.util.PayCommonUtil; import com.debug.weixin.util.XMLUtil; import com.mongodb.DBObject; public class ScanCodePayServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { this.doPost(request, response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String flag=request.getParameter("flag"); if("createCode".equals(flag)){ createPayCode(request,response); }else{ try { wxScanCodeHandler(request,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void createPayCode(HttpServletRequest request,HttpServletResponse response){ String orderNo=request.getParameter("orderNo"); SortedMap<Object,Object> paras = new TreeMap<Object,Object>(); paras.put("appid", ConfigUtil.APPID); paras.put("mch_id", ConfigUtil.MCH_ID); paras.put("time_stamp", Long.toString(new Date().getTime())); paras.put("nonce_str", PayCommonUtil.CreateNoncestr()); paras.put("product_id", orderNo);//商品號(hào)要唯一 String sign = PayCommonUtil.createSign("UTF-8", paras); paras.put("sign", sign); String url = "weixin://wxpay/bizpayurl?sign=SIGN&appid=APPID&mch_id=MCHID&product_id=PRODUCTID&time_stamp=TIMESTAMP&nonce_str=NOCESTR"; String nativeUrl = url.replace("SIGN", sign).replace("APPID", ConfigUtil.APPID).replace("MCHID", ConfigUtil.MCH_ID).replace("PRODUCTID", (String)paras.get("product_id")).replace("TIMESTAMP", (String)paras.get("time_stamp")).replace("NOCESTR", (String)paras.get("nonce_str")); SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("long_url", CommonUtil.urlEncodeUTF8(nativeUrl)); String sign2 = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign2); String requestXML = PayCommonUtil.getRequestXml(parameters); String result =CommonUtil.httpsRequestForStr(ConfigUtil.SHORT_URL, "POST", requestXML); Map<String, String> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } String returnCode = map.get("return_code"); String resultCode = map.get("result_code"); if(returnCode.equalsIgnoreCase("SUCCESS")&&resultCode.equalsIgnoreCase("SUCCESS")){ String shortUrl = map.get("short_url"); //TODO 拿到shortUrl,寫代碼生成二維碼 System.out.println("shortUrl="+shortUrl); try { CreateQRCode.createCodeStream(shortUrl,response); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } } public void wxScanCodeHandler(HttpServletRequest request,HttpServletResponse response) throws Exception { 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 result = new String(outSteam.toByteArray(),"utf-8");//獲取微信調(diào)用我們notify_url的返回信息 Map<Object, Object> map=null; try { map = XMLUtil.doXMLParse(result); } catch (JDOMException e) { // TODO Auto-generated catch block e.printStackTrace(); } for(Object keyValue : map.keySet()){ System.out.println(keyValue+"="+map.get(keyValue)); } String orderNo=map.get("product_id").toString(); //接收到請(qǐng)求參數(shù)后調(diào)用統(tǒng)一下單接口 SortedMap<Object, Object> parameters = new TreeMap<Object, Object>(); parameters.put("appid", ConfigUtil.APPID); parameters.put("mch_id", ConfigUtil.MCH_ID); parameters.put("device_info", "1000"); parameters.put("body", "測(cè)試掃碼支付訂單"); parameters.put("nonce_str", PayCommonUtil.CreateNoncestr()); parameters.put("out_trade_no", map.get("product_id")); //parameters.put("total_fee", String.valueOf(totalPrice)); parameters.put("total_fee", "1"); parameters.put("spbill_create_ip", request.getRemoteAddr()); parameters.put("notify_url", ConfigUtil.NOTIFY_URL); parameters.put("trade_type", "NATIVE"); parameters.put("openid", map.get("openid")); String sign = PayCommonUtil.createSign("UTF-8", parameters); parameters.put("sign", sign); String requestXML = PayCommonUtil.getRequestXml(parameters); String result2 = CommonUtil.httpsRequestForStr(ConfigUtil.UNIFIED_ORDER_URL,"POST", requestXML); System.out.println("-----------------------------統(tǒng)一下單結(jié)果---------------------------"); System.out.println(result2); Map<String, String> mm=null; try { mm=getH5PayMap(result2,request); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } //String prepayId=getPrepayId(result2,request); //String returnNoneStr=getReturnNoneStr(result2,request); String prepayId=mm.get("prepay_id"); String returnNoneStr=mm.get("nonce_str");; SortedMap<Object, Object> lastSign = new TreeMap<Object, Object>(); lastSign.put("return_code", "SUCCESS"); lastSign.put("appid", ConfigUtil.APPID); lastSign.put("mch_id", ConfigUtil.MCH_ID); lastSign.put("nonce_str", returnNoneStr); lastSign.put("prepay_id", prepayId); lastSign.put("result_code", "SUCCESS"); lastSign.put("key", ConfigUtil.API_KEY); String lastSignpara = PayCommonUtil.createSign("UTF-8", lastSign); StringBuffer buf=new StringBuffer(); buf.append("<xml>"); buf.append("<return_code>SUCCESS</return_code>"); buf.append("<appid>"+ConfigUtil.APPID+"</appid>"); buf.append("<mch_id>"+ConfigUtil.MCH_ID+"</mch_id>"); buf.append("<nonce_str>"+returnNoneStr+"</nonce_str>"); buf.append("<prepay_id>"+prepayId+"</prepay_id>"); buf.append("<result_code>SUCCESS</result_code>"); buf.append("<sign>"+lastSignpara+"</sign>"); buf.append("</xml>"); response.getWriter().print(buf.toString()); } public Map<String, String> getH5PayMap(String result,HttpServletRequest request) throws Exception{ Map<String, String> map = XMLUtil.doXMLParse(result); return map; } }
最終看下公眾號(hào)支付和掃碼支付的微信配置:
希望通過這篇文章,大家能明白就算通過Java來做微信公眾號(hào)、微信支付而不借助github提供的那些坑人的代碼也可以開發(fā)出另自己和客戶滿意的微信應(yīng)用。雖然微信給出的demo都是PHP的,但這些都是浮云,開發(fā)語言是其次,理解接口調(diào)用需具備的底層只是才是程序員的必修課。
更多Java微信支付之公眾號(hào)支付、掃碼支付實(shí)例相關(guān)文章請(qǐng)關(guān)注PHP中文網(wǎng)!
Gambar buka pakaian secara percuma
Apl berkuasa AI untuk mencipta foto bogel yang realistik
Alat AI dalam talian untuk mengeluarkan pakaian daripada foto.
Penyingkiran pakaian AI
Tukar muka dalam mana-mana video dengan mudah menggunakan alat tukar muka AI percuma kami!
Editor kod yang mudah digunakan dan percuma
Versi Cina, sangat mudah digunakan
Persekitaran pembangunan bersepadu PHP yang berkuasa
Alat pembangunan web visual
Perisian penyuntingan kod peringkat Tuhan (SublimeText3)