日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

java后台对接app微信支付

發(fā)布時間:2023/12/20 编程问答 27 豆豆
生活随笔 收集整理的這篇文章主要介紹了 java后台对接app微信支付 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

java后臺對接app微信支付

第一次對接微信支付,找了很多資料,參考很多的案例 最后還是完成了 記錄一下我是怎么完成的,希望能幫到后來者,也有助于自己以后回顧

1:申請微信支付

首先要申請微信支付,申請通過之后會收到一個郵件 里面會有 商戶號和appid等信息

2:獲取必要參數(shù)

到微信的商戶平臺通過安裝證書等一系列操作獲取密鑰key,然后到微信開發(fā)平臺獲取app的APP_SECRET

3:后臺代碼(工具類)

package com.tenpay.util;import java.io.BufferedReader; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.HttpURLConnection; import java.net.URL; import java.security.KeyManagementException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.SecureRandom; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.HashMap; import java.util.Map;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; import javax.net.ssl.TrustManagerFactory;public class HttpClientUtil {/*** http客戶端工具類**/public static final String SunX509 = "SunX509";public static final String JKS = "JKS";public static final String PKCS12 = "PKCS12";public static final String TLS = "TLS";/*** get HttpURLConnection* @param strUrl url地址* @return HttpURLConnection* @throws IOException*/public static HttpURLConnection getHttpURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();return httpURLConnection;}/*** get HttpsURLConnection* @param strUrl url地址?* @return HttpsURLConnection* @throws IOException*/public static HttpsURLConnection getHttpsURLConnection(String strUrl)throws IOException {URL url = new URL(strUrl);HttpsURLConnection httpsURLConnection = (HttpsURLConnection) url.openConnection();return httpsURLConnection;}/*** 獲取不帶查詢串的url* @param strUrl* @return String*/public static String getURL(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(0, indexOf);} return strUrl;}return strUrl;}/*** 獲取查詢串* @param strUrl* @return String*/public static String getQueryString(String strUrl) {if(null != strUrl) {int indexOf = strUrl.indexOf("?");if(-1 != indexOf) {return strUrl.substring(indexOf+1, strUrl.length());} return "";}return strUrl;}/*** 查詢字符串轉(zhuǎn)化為map* name1=key1&name2=key2&...* @param queryString* @return*/public static Map queryString2Map(String queryString) {if(null == queryString || "".equals(queryString)) {return null;}Map m = new HashMap();String[] strArray = queryString.split("&");for(int index = 0; index < strArray.length; index++) {String pair = strArray[index];HttpClientUtil.putMapByPair(pair, m);}return m;}/*** 把鍵值添加到map* pair:name=value* @param pair name=value* @param m*/public static void putMapByPair(String pair, Map m) {if(null == pair || "".equals(pair)) {return;}int indexOf = pair.indexOf("=");if(-1 != indexOf) {String k = pair.substring(0, indexOf);String v = pair.substring(indexOf+1, pair.length());if(null != k && !"".equals(k)) {m.put(k, v);}} else {m.put(pair, "");}}/*** BufferedReader轉(zhuǎn)換成String<br/>* 注意:流關(guān)閉需要自行處理* @param reader* @return* @throws IOException*/public static String bufferedReader2String(BufferedReader reader) throws IOException {StringBuffer buf = new StringBuffer();String line = null;while( (line = reader.readLine()) != null) {buf.append(line);buf.append("\r\n");}return buf.toString();}/*** 處理輸出<br/>* 注意:流關(guān)閉需要自行處理* @param out* @param data* @param len* @throws IOException*/public static void doOutput(OutputStream out, byte[] data, int len)throws IOException {int dataLen = data.length;int off = 0;while (off < data.length) {if (len >= dataLen) {out.write(data, off, dataLen);off += dataLen;} else {out.write(data, off, len);off += len;dataLen -= len;}// ?�?�����out.flush();}}/*** 獲取SSLContext* @param trustFile * @param trustPasswd* @param keyFile* @param keyPasswd* @return* @throws NoSuchAlgorithmException * @throws KeyStoreException * @throws IOException * @throws CertificateException * @throws UnrecoverableKeyException * @throws KeyManagementException */public static SSLContext getSSLContext(FileInputStream trustFileInputStream, String trustPasswd,FileInputStream keyFileInputStream, String keyPasswd)throws NoSuchAlgorithmException, KeyStoreException,CertificateException, IOException, UnrecoverableKeyException,KeyManagementException {// caTrustManagerFactory tmf = TrustManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore trustKeyStore = KeyStore.getInstance(HttpClientUtil.JKS);trustKeyStore.load(trustFileInputStream, HttpClientUtil.str2CharArray(trustPasswd));tmf.init(trustKeyStore);final char[] kp = HttpClientUtil.str2CharArray(keyPasswd);KeyManagerFactory kmf = KeyManagerFactory.getInstance(HttpClientUtil.SunX509);KeyStore ks = KeyStore.getInstance(HttpClientUtil.PKCS12);ks.load(keyFileInputStream, kp);kmf.init(ks, kp);SecureRandom rand = new SecureRandom();SSLContext ctx = SSLContext.getInstance(HttpClientUtil.TLS);ctx.init(kmf.getKeyManagers(), tmf.getTrustManagers(), rand);return ctx;}/*** 字符串轉(zhuǎn)換成char數(shù)組* @param str* @return char[]*/public static char[] str2CharArray(String str) {if(null == str) return null;return str.toCharArray();}public static InputStream String2Inputstream(String str) {return new ByteArrayInputStream(str.getBytes());}/*** InputStream轉(zhuǎn)換成Byte* 注意:流關(guān)閉需要自行處理* @param in* @return byte* @throws Exception*/public static byte[] InputStreamTOByte(InputStream in) throws IOException{ int BUFFER_SIZE = 4096; ByteArrayOutputStream outStream = new ByteArrayOutputStream(); byte[] data = new byte[BUFFER_SIZE]; int count = -1; while((count = in.read(data,0,BUFFER_SIZE)) != -1) outStream.write(data, 0, count); data = null; byte[] outByte = outStream.toByteArray();outStream.close();return outByte; } /*** InputStream轉(zhuǎn)換成String* 注意:流關(guān)閉需要自行處理* @param in* @param encoding 編碼* @return String* @throws Exception*/public static String InputStreamTOString(InputStream in,String encoding) throws IOException{ return new String(InputStreamTOByte(in),encoding);} } package com.tenpay.client;import java.io.BufferedOutputStream; import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection;import javax.net.ssl.HttpsURLConnection; import javax.net.ssl.SSLContext; import javax.net.ssl.SSLSocketFactory;import com.tenpay.util.HttpClientUtil; public class TenpayHttpClient {/** 請求內(nèi)容,無論post和get,都用get方式提供 */private String reqContent;/** 應(yīng)答內(nèi)容 */private String resContent;/** 請求方法 */private String method;/** 錯誤信息 */private String errInfo;/** 超時時間,以秒為單位 */private int timeOut;/** http應(yīng)答編碼 */private int responseCode;/** 字符編碼 */private String charset;private InputStream inputStream;public TenpayHttpClient() {this.reqContent = "";this.resContent = "";this.method = "POST";this.errInfo = "";this.timeOut = 30;//30秒this.responseCode = 0;this.charset = "utf8";this.inputStream = null;}/*** 設(shè)置請求內(nèi)容* @param reqContent 表求內(nèi)容*/public void setReqContent(String reqContent) {this.reqContent = reqContent;}/*** 獲取結(jié)果內(nèi)容* @return String* @throws IOException */public String getResContent() {try {this.doResponse();} catch (IOException e) {this.errInfo = e.getMessage();//return "";}return this.resContent;}/*** 設(shè)置請求方法post或者get* @param method 請求方法post/get*/public void setMethod(String method) {this.method = method;}/*** 獲取錯誤信息* @return String*/public String getErrInfo() {return this.errInfo;}/*** 設(shè)置超時時間,以秒為單位* @param timeOut 超時時間,以秒為單位*/public void setTimeOut(int timeOut) {this.timeOut = timeOut;}/*** 獲取http狀態(tài)碼* @return int*/public int getResponseCode() {return this.responseCode;}protected void callHttp() throws IOException {if("POST".equals(this.method.toUpperCase())) {String url = HttpClientUtil.getURL(this.reqContent);String queryString = HttpClientUtil.getQueryString(this.reqContent);byte[] postData = queryString.getBytes(this.charset);this.httpPostMethod(url, postData);return ;}this.httpGetMethod(this.reqContent);} public boolean callHttpPost(String url, String postdata) {boolean flag = false;byte[] postData;try {postData = postdata.getBytes(this.charset);this.httpPostMethod(url, postData);flag = true;} catch (IOException e1) {e1.printStackTrace();}return flag;}/*** 以http post方式通信* @param url* @param postData* @throws IOException*/protected void httpPostMethod(String url, byte[] postData)throws IOException {HttpURLConnection conn = HttpClientUtil.getHttpURLConnection(url);this.doPost(conn, postData);}/*** 以http get方式通信* * @param url* @throws IOException*/protected void httpGetMethod(String url) throws IOException {HttpURLConnection httpConnection =HttpClientUtil.getHttpURLConnection(url);this.setHttpRequest(httpConnection);httpConnection.setRequestMethod("GET");this.responseCode = httpConnection.getResponseCode();this.inputStream = httpConnection.getInputStream();}/*** 以https get方式通信* @param url* @param sslContext* @throws IOException*/protected void httpsGetMethod(String url, SSLContext sslContext)throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doGet(conn);}protected void httpsPostMethod(String url, byte[] postData,SSLContext sslContext) throws IOException {SSLSocketFactory sf = sslContext.getSocketFactory();HttpsURLConnection conn = HttpClientUtil.getHttpsURLConnection(url);conn.setSSLSocketFactory(sf);this.doPost(conn, postData);}/*** 設(shè)置http請求默認(rèn)屬性* @param httpConnection*/protected void setHttpRequest(HttpURLConnection httpConnection) {//設(shè)置連接超時時間httpConnection.setConnectTimeout(this.timeOut * 1000);//不使用緩存httpConnection.setUseCaches(false);//允許輸入輸出httpConnection.setDoInput(true);httpConnection.setDoOutput(true);}/*** 處理應(yīng)答* @throws IOException*/protected void doResponse() throws IOException {if(null == this.inputStream) {return;}//獲取應(yīng)答內(nèi)容this.resContent=HttpClientUtil.InputStreamTOString(this.inputStream,this.charset); //關(guān)閉輸入流this.inputStream.close();}/*** post方式處理* @param conn* @param postData* @throws IOException*/protected void doPost(HttpURLConnection conn, byte[] postData)throws IOException {// 以post方式通信conn.setRequestMethod("POST");// 設(shè)置請求默認(rèn)屬性this.setHttpRequest(conn);// Content-Typeconn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");BufferedOutputStream out = new BufferedOutputStream(conn.getOutputStream());final int len = 1024; // 1KBHttpClientUtil.doOutput(out, postData, len);// 關(guān)閉流out.close();// 獲取響應(yīng)返回狀態(tài)碼this.responseCode = conn.getResponseCode();// 獲取應(yīng)答輸入流this.inputStream = conn.getInputStream();}/*** get方式處理* @param conn* @throws IOException*/protected void doGet(HttpURLConnection conn) throws IOException {//以GET方式通信conn.setRequestMethod("GET");//設(shè)置請求默認(rèn)屬性this.setHttpRequest(conn);//獲取響應(yīng)返回狀態(tài)碼this.responseCode = conn.getResponseCode();//獲取應(yīng)答輸入流this.inputStream = conn.getInputStream();} } package com.tenpay;import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tenpay.client.TenpayHttpClient; import com.tenpay.util.ConstantUtil; import com.tenpay.util.MD5Util; import com.tenpay.util.XMLUtil;public class PrepayIdRequestHandler extends RequestHandler {public PrepayIdRequestHandler(HttpServletRequest request,HttpServletResponse response) {super(request, response);}public String createMD5Sign() {StringBuffer sb = new StringBuffer();Set es = super.getAllParameters().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();sb.append(k + "=" + v + "&");}String params=sb.append("key="+ConstantUtil.APP_KEY).substring(0);String sign = MD5Util.MD5Encode(params, "utf8");return sign.toUpperCase();}// 提交預(yù)支付public String sendPrepay() throws Exception {String prepayid = "";Set es=super.getAllParameters().entrySet();Iterator it=es.iterator();StringBuffer sb = new StringBuffer("<xml>");while(it.hasNext()){Map.Entry entry = (Map.Entry) it.next();String k = (String) entry.getKey();String v = (String) entry.getValue();sb.append("<"+k+">"+v+"</"+k+">");}sb.append("</xml>");String params=sb.substring(0);System.out.println("請求參數(shù):"+params);String requestUrl = super.getGateUrl();System.out.println("請求url:"+requestUrl);TenpayHttpClient httpClient = new TenpayHttpClient();httpClient.setReqContent(requestUrl);String resContent = "";if (httpClient.callHttpPost(requestUrl, params)) {resContent = httpClient.getResContent();System.out.println("獲取prepayid的返回值:"+resContent);Map<String,String> map=XMLUtil.doXMLParse(resContent);if(map.containsKey("prepay_id"))prepayid=map.get("prepay_id");}return prepayid;} } package com.tenpay.util;import java.util.Random;public class WXUtil {/*** 生成隨機(jī)字符串* @return*/public static String getNonceStr() {Random random = new Random();return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "utf8");}/*** 獲取時間戳* @return*/public static String getTimeStamp() {return String.valueOf(System.currentTimeMillis() / 1000);} } package com.tenpay.util;import java.util.Date;public class UUID {private static Date date = new Date();private static StringBuilder buf = new StringBuilder();private static int seq = 0;private static final int ROTATION = 99999;public static synchronized long next() {if (seq > ROTATION)seq = 0;buf.delete(0, buf.length());date.setTime(System.currentTimeMillis());String str = String.format("%1$tY%1$tm%1$td%1$tk%1$tM%1$tS%2$05d", date, seq++);return Long.parseLong(str);}private UUID(){} } package com.tenpay.util;import java.security.MessageDigest;public class MD5Util {/*** MD5加密* @param b* @return*/private static String byteArrayToHexString(byte b[]) {StringBuffer resultSb = new StringBuffer();for (int i = 0; i < b.length; i++)resultSb.append(byteToHexString(b[i]));return resultSb.toString();}private static String byteToHexString(byte b) {int n = b;if (n < 0)n += 256;int d1 = n / 16;int d2 = n % 16;return hexDigits[d1] + hexDigits[d2];}public static String MD5Encode(String origin, String charsetname) {String resultString = null;try {resultString = new String(origin);MessageDigest md = MessageDigest.getInstance("MD5");if (charsetname == null || "".equals(charsetname))resultString = byteArrayToHexString(md.digest(resultString.getBytes()));elseresultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));} catch (Exception exception) {}return resultString;}private static final String hexDigits[] = { "0", "1", "2", "3", "4", "5","6", "7", "8", "9", "a", "b", "c", "d", "e", "f" };} package com.tenpay.util;public class ConstantUtil {/*** 微信開發(fā)平臺應(yīng)用ID*/public static final String APP_ID="wx1ebc0edb8656a12d";//wx1ebc0edb8656a12e/*** 應(yīng)用對應(yīng)的憑證*/public static final String APP_SECRET="0e99e39f85e566a35f31b7bbd7cfd161";//0e99e39f85e566a35f31b7bbd7cfd169/*** 應(yīng)用對應(yīng)的密鑰*/public static final String APP_KEY="dfsfdvdfvgk32423423oGdfsfdsvBO68";//dfsfdvdfvgk56423423oGdfsfdsvBO66/*** 微信支付商戶號*/public static final String MCH_ID="1517726062";//1517726061/*** 商品描述*/public static final String BODY="pay"; /*** 商戶id*/public static final String PARTNER_ID="1517726062";//這個不一定相同/*** 獲取預(yù)支付id的接口url*/public static String GATEURL = "https://api.mch.weixin.qq.com/pay/unifiedorder";/*** 微信服務(wù)器回調(diào)通知url*/public static String NOTIFY_URL="http://localhost/control/app_weixpayCallBack"; }

3:前面基本都是工具類,在這里做業(yè)務(wù)實現(xiàn)返回給前端吊起支付

// An highlighted block package com.huabang.ofo.utils.weixin.Utils; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.lang.RandomStringUtils; import com.alibaba.fastjson.JSONObject; import com.huabang.ofo.domain.HbOrder; import com.huabang.ofo.domain.HbUser; import com.huabang.ofo.domain.HbUserCash; import com.huabang.ofo.service.UsersService; import com.tenpay.PrepayIdRequestHandler; import com.tenpay.util.ConstantUtil; import com.tenpay.util.MD5Util; import com.tenpay.util.UUID; import com.tenpay.util.WXUtil;/*** 微信支付測試*/ public class WeixinPayUtil {private UsersService userServiceImpl;private String out_trade_no = "";public WeixinPayUtil(UsersService userServiceImpl) {this.userServiceImpl = userServiceImpl;}public JSONObject pay(HttpServletRequest request, HttpServletResponse response) {JSONObject object = new JSONObject();HashMap<String,Object> mymap=new HashMap<>();Map<String, Object> map = new HashMap<String, Object>();// 獲取生成預(yù)支付訂單的請求類PrepayIdRequestHandler prepayReqHandler = new PrepayIdRequestHandler(request, response);String totalFee =request.getAttribute("totalMoney").toString();int total_fee=(int) (Float.valueOf(totalFee)*100);//金額單位默認(rèn)是分prepayReqHandler.setParameter("appid", ConstantUtil.APP_ID);prepayReqHandler.setParameter("body", ConstantUtil.BODY);prepayReqHandler.setParameter("mch_id", ConstantUtil.MCH_ID);String nonce_str = WXUtil.getNonceStr();prepayReqHandler.setParameter("nonce_str", nonce_str);prepayReqHandler.setParameter("notify_url", ConstantUtil.NOTIFY_URL);out_trade_no = String.valueOf(UUID.next());prepayReqHandler.setParameter("out_trade_no", out_trade_no);prepayReqHandler.setParameter("spbill_create_ip", request.getRemoteAddr());String timestamp = WXUtil.getTimeStamp();prepayReqHandler.setParameter("time_start", timestamp);System.out.println(String.valueOf(total_fee));prepayReqHandler.setParameter("total_fee", String.valueOf(total_fee));prepayReqHandler.setParameter("trade_type", "APP");prepayReqHandler.setParameter("sign", prepayReqHandler.createMD5Sign());prepayReqHandler.setGateUrl(ConstantUtil.GATEURL);/*** 注意簽名(sign)的生成方式,具體見官方文檔(傳參都要參與生成簽名,且參數(shù)名按照字典序排序,最后接上APP_KEY,轉(zhuǎn)化成大寫)*/try {HbUser user = this.userServiceImpl.selectUserObject(String.valueOf(request.getAttribute("telephone")));if(user==null){object.put("msg", "該手機(jī)用戶不存在");object.put("code", "400");return object;}String numeric = System.currentTimeMillis() + RandomStringUtils.randomNumeric(6);String type = String.valueOf(request.getAttribute("type"));HbOrder order = new HbOrder();if (type.equals("0")) { // 押金HbUserCash cash = new HbUserCash();cash.setUserId(user.getUserId());cash.setUserAccountMoney(String.valueOf(request.getAttribute("money")));cash.setUserCash(Double.parseDouble(String.valueOf(request.getAttribute("cashMoney"))));cash.setUserCashType(Integer.parseInt(String.valueOf(request.getAttribute("cashType"))));cash.setUserCashStatus(2);//保存押金信息this.userServiceImpl.saveUserCash(cash);order.setOrderType(0);order.setOrderCashId(user.getUserId());}else{//充值order.setOrderType(1);order.setOrderCashId(null);}order.setOrderId(numeric);SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");order.setOrderCreatetime(format.parse(format.format(new Date())));order.setOrderPrice(Double.parseDouble(String.valueOf(request.getAttribute("totalMoney"))));order.setOrderUserid(user.getUserId());this.userServiceImpl.saveOrder(order);String prepayid = prepayReqHandler.sendPrepay();// 若獲取prepayid成功,將相關(guān)信息返回客戶端if (prepayid != null && !prepayid.equals("")) {String signs = "appid=" + ConstantUtil.APP_ID + "&noncestr=" + nonce_str + "&package=Sign=WXPay&partnerid="+ ConstantUtil.PARTNER_ID + "&prepayid=" + prepayid + "&timestamp=" + timestamp + "&key="+ ConstantUtil.APP_KEY;map.put("code", 0);map.put("info", "success");map.put("prepayid", prepayid);/*** 簽名方式與上面類似*/map.put("sign", MD5Util.MD5Encode(signs, "utf8").toUpperCase());map.put("appid", ConstantUtil.APP_ID);map.put("timestamp", timestamp); //等于請求prepayId時的time_startmap.put("noncestr", nonce_str); //與請求prepayId時值一致map.put("package", "Sign=WXPay"); //固定常量map.put("partnerid", ConstantUtil.PARTNER_ID);mymap.put("sdk",map);object.put("data", mymap);object.put("code", "200");object.put("msg", "獲取簽名成功");} else {object.put("code", "400");object.put("msg", "獲取簽名失敗");}} catch (Exception e) {e.printStackTrace();object.put("code", "400");object.put("msg", "獲取簽名失敗");}return object;} }

微信支付回調(diào)方法 (這里可以寫自己的業(yè)務(wù)處理,重點是要回一個支付成功的信息)

@Override@Transactional(propagation=Propagation.REQUIRED)public void weixhuiDiao(HttpServletRequest request,HttpServletResponse response) throws Exception{System.out.println("微信支付回調(diào)");PrintWriter writer = response.getWriter();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");System.out.println("微信支付通知結(jié)果:" + result);Map<String, String> map = null;try {/*** 解析微信通知返回的信息*/map = XMLUtil.doXMLParse(result);} catch (JDOMException e) {// TODO Auto-generated catch blocke.printStackTrace();}System.out.println("=========:"+result);// 若支付成功,則告知微信服務(wù)器收到通知if (map.get("return_code").equals("SUCCESS")) {if (map.get("result_code").equals("SUCCESS")) {System.out.println("充值成功!");//通過自定義的訂單號將該訂單查詢出來String string = Long.valueOf(map.get("out_trade_no")).toString();HbOrder order = this.hbOrdersMapper.selectByPrimaryKey(string);if(order.getOrderCashId() == null){//充值HbUser user = this.hbuserMapper.selectByPrimaryKey(order.getOrderUserid());HbAccount account = this.hbAccountMapper.selectByUserId(user.getUserId());account.setAccountTotel(String.valueOf(Double.parseDouble(account.getAccountTotel())+order.getOrderPrice()));account.setAccountPay(Double.parseDouble(account.getAccountTotel()));this.hbAccountMapper.updateByPrimaryKey(account);//修改訂單狀態(tài)hbOrdersMapper.updateStatus(request.getParameter("out_trade_no"),"1");}else{ // 押金//押金的修改String orderCashId = order.getOrderCashId();HbUserCash cash = this.hbUserCashMapper.selectByPrimaryKey(orderCashId);cash.setUserCashStatus(0);this.hbUserCashMapper.updateByPrimaryKeySelective(cash);//用戶賬戶余額的修改if(cash.getUserAccountMoney()!=null ||cash.getUserAccountMoney().equals("") ){HbAccount account = this.hbAccountMapper.selectByUserId(order.getOrderUserid());account.setAccountTotel(String.valueOf(Double.parseDouble(account.getAccountTotel())+Double.parseDouble(cash.getUserAccountMoney())));account.setAccountPay(Double.parseDouble(account.getAccountTotel()));// this.hbAccountMapper.updateByPrimaryKeySelective(account);}//修改訂單狀態(tài)hbOrdersMapper.updateStatus(request.getParameter("out_trade_no"),"1");//修改用戶的認(rèn)證狀態(tài)HbUser user = this.hbuserMapper.selectByPrimaryKey(orderCashId);user.setUserApprove(1);this.hbuserMapper.updateByPrimaryKeySelective(user);}System.out.println("訂單號:"+Long.valueOf(map.get("out_trade_no")));System.out.println("通知微信后臺");String notifyStr = XMLUtil.setXML("SUCCESS", "");writer.write(notifyStr);writer.flush();}}}

到這里就基本完成了

總結(jié)

以上是生活随笔為你收集整理的java后台对接app微信支付的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。