java開發Demo~微信掃碼支付,java開發示例

開發所需工具類


開發所需jar

具體的代碼不貼了,說明下PayConfigUtil中的參數


APP_ID和APP_SECRET在公眾平臺?

MCH_ID和API_KEY在商戶平臺,其中API_KEY是自己設置的,并不是自動生成的。

Controller

通過此方法,前往可以生成二維碼的頁面

//微信前往支付頁面

? ? @RequestMapping(value = "towxPay")

? ? public ModelAndView towxPay(ModelMap map,HttpServletRequest request,String chapterId,String chapterName,String price) throws IOException{

? ? ? ? ModelAndView mav = new ModelAndView();

? ? ? ? mav.setViewName("jsp/pay/weixinpayma");

? ? ? ? HttpSession session = request.getSession();

? ? ? ? session.setAttribute("chapterId", chapterId);

? ? ? ? session.setAttribute("chapterName", chapterName);

? ? ? ? session.setAttribute("price", price);

? ? ? ? return mav;

? ? }

返回的頁面如下

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>

? ? ? ? ? ? ? ? <%

? ? String path = request.getContextPath();

? ? String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()

? ? ? ? ? ? + path + "/";

%>

Insert title here

? ?



? ?

? ? /* ajax輪回,不停的訪問Controller,直到wxPayType=1時,付款成功 */

? ? ? ? var num = 0;

? ? ? ? $(function(){

? ? ? ? ? ? panduanWXPay();

? ? ? ? });

? ? ? ? function panduanWXPay(){

? ? ? ? ? ? $.post("<%=basePath%>index/panduanPay",function(data){

? ? ? ? ? ? ? ? var wxPayType = data.wxPayType;

? ? ? ? ? ? ? ? if(wxPayType==1){

? ? ? ? ? ? ? ? /* 成功 */

? ? ? ? ? ? ? ? ? ? window.location.href='<%=basePath%>index/gouMai';

? ? ? ? ? ? ? ? }else if(wxPayType==0 && num!=400){

? ? ? ? ? ? ? ? ? ? num++;

? ? ? ? ? ? ? ? ? ? panduanWXPay();

? ? ? ? ? ? ? ? }else{

? ? ? ? ? ? ? ? ? ? alert("支付超時");

? ? ? ? ? ? ? ? }

? ? ? ? ? ? });

? ? ? ? }?


payImg方法

//微信支付,生成二維碼

? ? @RequestMapping(value = "payImg")

? ? public? void payImg(HttpServletRequest request, HttpServletResponse response) throws IOException{

? ? ? ? HttpSession session = request.getSession();

? ? ? ? String chapterName=(String)session.getAttribute("chapterName");

? ? ? ? String price=(String)session.getAttribute("price");

? ? ? ? int defaultWidthAndHeight=200;

? ? ? ? String nonce_str = PayCommonUtil.getNonce_str();

? ? ? ? long time_stamp = System.currentTimeMillis() / 1000;

? ? ? ? String product_id = chapterName+"*"+price;//訂單名字和價錢,拼到了一起,后面用到的時候再拆

? ? ? ? String key = PayConfigUtil.API_KEY; // key

? ? ? ? SortedMap packageParams = new TreeMap();

? ? ? ? packageParams.put("appid", PayConfigUtil.APP_ID);

? ? ? ? packageParams.put("mch_id", PayConfigUtil.MCH_ID);

? ? ? ? packageParams.put("time_stamp", String.valueOf(time_stamp));

? ? ? ? packageParams.put("nonce_str", nonce_str);

? ? ? ? packageParams.put("product_id", product_id);

//? ? ? packageParams.put("chapterId", chapterId);

//? ? ? packageParams.put("price", price);

? ? ? ? String sign = PayCommonUtil.createSign("UTF-8", packageParams,key);//MD5哈希

? ? ? ? packageParams.put("sign", sign);

? ? ? ? //生成參數

? ? ? ? String str = ToUrlParams(packageParams);

? ? ? ? String payurl = "weixin://wxpay/bizpayurl?" + str;

//? ? ? logger.info("payurl:"+payurl);

? ? ? ? //生成二維碼

? ? ? ? Map? hints=new HashMap();

? ? ? ? // 指定糾錯等級?

? ? ? ? hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);?

? ? ? ? // 指定編碼格式?

? ? ? ? hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");?

? ? ? ? hints.put(EncodeHintType.MARGIN, 1);

? ? ? ? try {

? ? ? ? ? ? BitMatrix bitMatrix = new MultiFormatWriter().encode(payurl,BarcodeFormat.QR_CODE, defaultWidthAndHeight, defaultWidthAndHeight, hints);

? ? ? ? ? ? OutputStream out = response.getOutputStream();

? ? ? ? ? ? MatrixToImageWriter.writeToStream(bitMatrix, "png", out);//輸出二維碼

? ? ? ? ? ? out.flush();

? ? ? ? ? ? out.close();

? ? ? ? } catch (WriterException e) {

? ? ? ? ? ? // TODO Auto-generated catch block

? ? ? ? ? ? e.printStackTrace();

? ? ? ? }

? ? }

public String ToUrlParams(SortedMap packageParams){

? ? ? ? //實際可以不排序

? ? ? ? StringBuffer sb = new StringBuffer();?

? ? ? ? Set es = packageParams.entrySet();?

? ? ? ? Iterator it = es.iterator();?

? ? ? ? while (it.hasNext()) {?

? ? ? ? ? ? Map.Entry entry = (Map.Entry) it.next();?

? ? ? ? ? ? String k = (String) entry.getKey();?

? ? ? ? ? ? String v = (String) entry.getValue();?

? ? ? ? ? ? if (null != v && !"".equals(v)) {?

? ? ? ? ? ? ? ? sb.append(k + "=" + v + "&");?

? ? ? ? ? ? }?

? ? ? ? }

? ? ? ? sb.deleteCharAt(sb.length()-1);//刪掉最后一個&

? ? ? ? return sb.toString();

? ? }

掃碼時觸動此方法,會在手機端顯示付款信息

要將此方法的路徑配置到回調url里,微信公眾平臺–>微信支付–>開發配置?


//微信掃碼的時候,觸發此方法

? ? @RequestMapping(value = "Re_notify")

? ? public void Re_notify(HttpServletRequest request, HttpServletResponse response) throws IOException{

? ? ? ? HttpSession session = request.getSession();

? ? ? ? String chapterId=(String)session.getAttribute("chapterId");

? ? ? ? String chapterName=(String)session.getAttribute("chapterName");

? ? ? ? String price=(String)session.getAttribute("price");

? ? ? ? System.out.println(chapterId+":"+chapterName+":"+price);

? ? ? ? // 讀取xml

? ? ? ? ? ? ? ? InputStream inputStream;

? ? ? ? ? ? ? ? StringBuffer sb = new StringBuffer();

? ? ? ? ? ? ? ? inputStream = request.getInputStream();

? ? ? ? ? ? ? ? String s;

? ? ? ? ? ? ? ? BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

? ? ? ? ? ? ? ? while ((s = in.readLine()) != null) {

? ? ? ? ? ? ? ? ? ? sb.append(s);

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? in.close();

? ? ? ? ? ? ? ? inputStream.close();

? ? ? ? ? ? ? ? SortedMap packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());

//? ? ? ? ? ? ? logger.info(packageParams);

? ? ? ? ? ? ? ? // 賬號信息

? ? ? ? ? ? ? ? String key = PayConfigUtil.API_KEY; // key

? ? ? ? ? ? ? ? String resXml="";//反饋給微信服務器

? ? ? ? ? ? ? ? // 驗簽

? ? ? ? ? ? ? ? if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {

? ? ? ? ? ? ? ? ? ? //appid openid mch_id is_subscribe nonce_str product_id sign

? ? ? ? ? ? ? ? ? ? //統一下單

? ? ? ? ? ? ? ? ? ? String openid = (String)packageParams.get("openid");

? ? ? ? ? ? ? ? ? ? String product_id = (String)packageParams.get("product_id");

? ? ? ? ? ? ? ? ? ? //解析product_id,計算價格等

? ? ? ? ? ? ? ? ? ? String thePricce = product_id.substring(product_id.lastIndexOf("*")+1);

? ? ? ? ? ? ? ? ? ? String newProductId = product_id.substring(0, product_id.indexOf("*"));

? ? ? ? ? ? ? ? ? ? String out_trade_no = String.valueOf(System.currentTimeMillis()); // 訂單號?

? ? ? ? ? ? ? ? ? ? String order_price = thePricce; // 價格"1"? 注意:價格的單位是分?

? ? ? ? ? ? ? ? ? ? String body = newProductId;? // 商品名稱product_id? 這里設置為product_id

? ? ? ? ? ? ? ? ? ? String attach = "十倍課"; //附加數據

? ? ? ? ? ? ? ? ? ? String nonce_str0 = PayCommonUtil.getNonce_str();

? ? ? ? ? ? ? ? ? ? // 獲取發起電腦 ip?

? ? ? ? ? ? ? ? ? ? String spbill_create_ip = PayConfigUtil.CREATE_IP;? ?

? ? ? ? ? ? ? ? ? ? String trade_type = "NATIVE";

? ? ? ? ? ? ? ? ? ? SortedMap unifiedParams = new TreeMap();?

? ? ? ? ? ? ? ? ? ? unifiedParams.put("appid", PayConfigUtil.APP_ID); // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("mch_id", PayConfigUtil.MCH_ID); // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("out_trade_no", out_trade_no); // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("product_id", product_id);

? ? ? ? ? ? ? ? ? ? unifiedParams.put("body", body); // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("attach", attach);

? ? ? ? ? ? ? ? ? ? unifiedParams.put("total_fee", order_price);? // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("nonce_str", nonce_str0);? // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("spbill_create_ip", spbill_create_ip); // 必須

? ? ? ? ? ? ? ? ? ? unifiedParams.put("trade_type", trade_type); // 必須?

? ? ? ? ? ? ? ? ? ? unifiedParams.put("openid", openid);?

? ? ? ? ? ? ? ? ? ? unifiedParams.put("notify_url", PayConfigUtil.NOTIFY_URL);//異步通知url

? ? ? ? ? ? ? ? ? ? String sign0 = PayCommonUtil.createSign("UTF-8", unifiedParams,key);?

? ? ? ? ? ? ? ? ? ? unifiedParams.put("sign", sign0); //簽名

? ? ? ? ? ? ? ? ? ? String requestXML = PayCommonUtil.getRequestXml(unifiedParams);?

//? ? ? ? ? ? ? ? ? logger.info(requestXML);

? ? ? ? ? ? ? ? ? ? //統一下單接口

? ? ? ? ? ? ? ? ? ? String rXml = HttpUtil.postData(PayConfigUtil.UFDODER_URL, requestXML);?

? ? ? ? ? ? ? ? ? ? //統一下單響應

? ? ? ? ? ? ? ? ? ? SortedMap reParams = PayCommonUtil.xmlConvertToMap(rXml);

//? ? ? ? ? ? ? ? ? logger.info(reParams);

? ? ? ? ? ? ? ? ? ? //驗簽

? ? ? ? ? ? ? ? ? ? if (PayCommonUtil.isTenpaySign("UTF-8", reParams, key)) {

? ? ? ? ? ? ? ? ? ? ? ? // 統一下單返回的參數

? ? ? ? ? ? ? ? ? ? ? ? String prepay_id = (String)reParams.get("prepay_id");//交易會話標識? 2小時內有效

? ? ? ? ? ? ? ? ? ? ? ? String nonce_str1 = PayCommonUtil.getNonce_str();

? ? ? ? ? ? ? ? ? ? ? ? SortedMap resParams = new TreeMap();?

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("return_code", "SUCCESS"); // 必須

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("return_msg", "OK");

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("appid", PayConfigUtil.APP_ID); // 必須

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("mch_id", PayConfigUtil.MCH_ID);

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("nonce_str", nonce_str1); // 必須

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("prepay_id", prepay_id); // 必須

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("result_code", "SUCCESS"); // 必須

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("err_code_des", "OK");

? ? ? ? ? ? ? ? ? ? ? ? String sign1 = PayCommonUtil.createSign("UTF-8", resParams,key);?

? ? ? ? ? ? ? ? ? ? ? ? resParams.put("sign", sign1); //簽名

? ? ? ? ? ? ? ? ? ? ? ? resXml = PayCommonUtil.getRequestXml(resParams);

//? ? ? ? ? ? ? ? ? ? ? logger.info(resXml);

? ? ? ? ? ? ? ? ? ? }else{

//? ? ? ? ? ? ? ? ? ? ? logger.info("簽名驗證錯誤");

? ? ? ? ? ? ? ? ? ? ? ? resXml = "" + ""?

? ? ? ? ? ? ? ? ? ? ? ? ? ? ? ? + "" + " ";

? ? ? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? }else{

//? ? ? ? ? ? ? ? ? logger.info("簽名驗證錯誤");

? ? ? ? ? ? ? ? ? ? resXml = "" + ""?

? ? ? ? ? ? ? ? ? ? ? ? ? ? + "" + " ";

? ? ? ? ? ? ? ? }

? ? ? ? ? ? ? ? //------------------------------?

? ? ? ? ? ? ? ? //處理業務完畢?

? ? ? ? ? ? ? ? //------------------------------?

? ? ? ? ? ? ? ? BufferedOutputStream out = new BufferedOutputStream(?

? ? ? ? ? ? ? ? ? ? ? ? response.getOutputStream());?

? ? ? ? ? ? ? ? out.write(resXml.getBytes());?

? ? ? ? ? ? ? ? out.flush();?

? ? ? ? ? ? ? ? out.close();?

? ? }

微信支付成功時訪問的方法

密碼錯誤等未支付成功的情況下,不會訪問。?

此路徑是PayConfigUtil中配置的

int wxPayType = 0;

? ? //微信掃碼支付回調

? ? @RequestMapping(value = "Notify1")

? ? public void Notify1(HttpServletRequest request, HttpServletResponse response) throws IOException{

? ? ? ? InputStream inputStream;

? ? ? ? StringBuffer sb = new StringBuffer();

? ? ? ? inputStream = request.getInputStream();

? ? ? ? String s;

? ? ? ? BufferedReader in = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"));

? ? ? ? while ((s = in.readLine()) != null) {

? ? ? ? ? ? sb.append(s);

? ? ? ? }

? ? ? ? in.close();

? ? ? ? inputStream.close();

? ? ? ? SortedMap packageParams = PayCommonUtil.xmlConvertToMap(sb.toString());

//? ? ? logger.info(packageParams);

? ? ? ? // 賬號信息

? ? ? ? String key = PayConfigUtil.API_KEY; // key

? ? ? ? String resXml = ""; // 反饋給微信服務器

? ? ? ? // 判斷簽名是否正確

? ? ? ? if (PayCommonUtil.isTenpaySign("UTF-8", packageParams, key)) {

? ? ? ? ? ? // ------------------------------

? ? ? ? ? ? // 處理業務開始

? ? ? ? ? ? // ------------------------------

? ? ? ? ? ? if ("SUCCESS".equals((String) packageParams.get("result_code"))) {

? ? ? ? ? ? ? ? // 這里是支付成功

? ? ? ? ? ? ? ? ////////// 執行自己的業務邏輯////////////////

? ? ? ? ? ? ? ? String mch_id = (String) packageParams.get("mch_id");

? ? ? ? ? ? ? ? String openid = (String) packageParams.get("openid");

? ? ? ? ? ? ? ? String is_subscribe = (String) packageParams.get("is_subscribe");

? ? ? ? ? ? ? ? String out_trade_no = (String) packageParams.get("out_trade_no");

? ? ? ? ? ? ? ? String total_fee = (String) packageParams.get("total_fee");

//// 將用于標記是否成功的全局變量wxPayType設置為1,ajax輪回時,可以獲取到其變化,從而進行頁面跳轉////

? ? ? ? ? ? ? ? wxPayType=1;

? ? ? ? ? ? ? ? System.out.println("33333333333333333333333333333:"+wxPayType);

//? ? ? ? ? "支付成功"

// 通知微信.異步確認成功.必寫.不然會一直通知后臺.八次之后就認為交易失敗了.

? ? ? ? ? ? ? ? resXml = "" + ""

? ? ? ? ? ? ? ? ? ? ? ? + "" + " ";

? ? ? ? ? ? } else {

//? ? ? ? ? ? ? logger.info("支付失敗,錯誤信息:" + packageParams.get("err_code"));

? ? ? ? ? ? ? ? resXml = "" + ""

? ? ? ? ? ? ? ? ? ? ? ? + "" + " ";

? ? ? ? ? ? }

? ? ? ? } else {

//? ? ? ? ? logger.info("簽名驗證錯誤");

? ? ? ? ? ? resXml = "" + ""?

? ? ? ? ? ? ? ? ? ? + "" + " ";

? ? ? ? }

? ? ? ? // ------------------------------

? ? ? ? // 處理業務完畢

? ? ? ? // ------------------------------

? ? ? ? BufferedOutputStream out = new BufferedOutputStream(response.getOutputStream());

? ? ? ? out.write(resXml.getBytes());

? ? ? ? out.flush();

? ? ? ? out.close();

? ? }

ajax不停輪回,判斷是否登錄成功的方法

@RequestMapping(value = "panduanPay")

? ? ? ? @ResponseBody

? ? ? ? public Map panduanPay(HttpServletRequest request) throws IOException{

? ? ? ? ? ? Map map = new HashMap();

? ? ? ? ? ? try {

? ? ? ? ? ? ? ? Thread.sleep(500);

? ? ? ? ? ? } catch (InterruptedException e) {

? ? ? ? ? ? ? ? // TODO Auto-generated catch block

? ? ? ? ? ? ? ? e.printStackTrace();

? ? ? ? ? ? }

? ? ? ? ? ? //給頁面返回wxPayType值,成功是返回的是1;還未支付成功,返回的是初始值0

? ? ? ? ? ? map.put("wxPayType",wxPayType);

? ? ? ? ? ? return map;

? ? ? ? }

成功后頁面跳轉的方法

//購買成功,存入購買表中

? ? @RequestMapping(value="gouMai")

? ? @ResponseBody

? ? public ModelAndView gouMai(HttpServletRequest req,String a,String urlName,String couName,ModelMap map){

? ? ? ? ModelAndView mav = new ModelAndView();

? ? ? ? Map mapp1 = new HashMap();

//? ? ? SysUserTab login_user = sysuserService.getSysUserById(userId);

? ? ? ? HttpSession session = req.getSession();

? ? ? ? SysUserTab login_user1 = (SysUserTab) session.getAttribute("login_user");

? ? ? ? String userId = login_user1.getUserId();

//? ? ? session.setAttribute("login_user", login_user);

? ? ? ? String chapterId = (String) session.getAttribute("chapterId");

? ? ? ? mapp1.put("userId", userId);

? ? ? ? mapp1.put("chapterId", chapterId);

? ? ? ? int num = sysBuyService.getBuyCount(mapp1);

? ? ? ? if(num==0){

? ? ? ? ? ? mapp1.put("buyId", UUID.randomUUID().toString().replace("-", ""));

? ? ? ? ? ? sysBuyService.insertBuy(mapp1);

? ? ? ? }

Java高架構師、分布式架構、高可擴展、高性能、高并發、性能優化、Spring boot、Redis、ActiveMQ、Nginx、Mycat、Netty、Jvm大型分布式項目實戰學習架構師視頻免費學習加群:835638062 點擊鏈接加入群聊【Java高級架構】:https://jq.qq.com/?_wv=1027&k=5S3kL3v

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容

  • Overview The ccxt library is a collection of available cr...
    郭蟈兒蟈兒閱讀 3,809評論 0 1
  • 這篇文章主要記錄我自己在醫院旁邊的床位來看病人的三波。第一波,親戚,關心后給錢。第二波,打電話給朋友,給紅包。第三...
    邊境游騎閱讀 142評論 0 0
  • 就一卒子 牢守邊疆 一盤大戰勝敗已成定局 從未移動半步 一開局 就粉身碎骨 血染楚河漢界 屬勝屬敗不得而知 高手決...
    洛水秦韻閱讀 346評論 2 15
  • 有時候吧,負能量就突發性的爆炸 每一次以為的轉機都是新一輪的噩夢,以前算命的說,我感情不順,事業很好,哎,都是騙人...
    維爭青青閱讀 120評論 0 0
  • 還來不及回想人生路,大學畢業已經匆匆十年了,就在上周末,同學們蓄謀已久的十年聚會完美的落下了帷幕。有很多同學都感慨...
    歐陽風影閱讀 441評論 0 0