您好,登錄后才能下訂單哦!
小編給大家分享一下如何使用java實現微信支付的公眾號支付,希望大家閱讀完這篇文章之后都有所收獲,下面讓我們一起去探討吧!
最近兩周實現了調用微信接口使用微信進行支付的需求,包含公眾號支付及掃碼支付兩種方式,由于微信文檔寫的較為簡略,現將調用微信接口進行支付流程進行記錄及分享。
本文旨在對公眾號支付的實現流程進行介紹,即微信用戶從公眾號中點擊鏈接進入商品h6頁面,選擇商品后點擊支付按鈕后彈出微信支付頁面、輸入支付密碼、支付成功后跳轉到全部商品頁面的整個過程。微信掃碼支付請參看后續文章。
1、首先,商戶需申請微信公眾號、微信商戶號及微信支付權限。開發過程中需參照公眾號及商戶平臺提供如下參數:
① appid:公眾號id,登錄微信公眾號–開發–基本配置中獲得; ② mch_id:收款商家商戶號; ③ APP_SECRET:第三方唯一憑證密碼; ④ key:收款商戶后臺進行配置,登錄微信商戶平臺–賬戶設置–安全設置–api安全,設置32位key值。
2、登錄微信公眾號,進行開發相關設置:
① 獲取用戶基本信息(主要是openid)權限配置:微信公眾平臺–開發–接口權限–網頁授權–網頁授權域名(不接受IP地址,需通過ICP備案驗證,不帶http):
② 支付測試目錄及測試白名單設置:微信公眾平臺–微信支付–開發配置,測試授權目錄具體到最后一級。
3、獲取用戶openid,OpenID是公眾號一對一對應用戶身份的標識:
① 微信網頁授權獲取用戶信息文檔:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/userinfo.html。根據文檔拼裝url,引導用戶在微信上點擊該鏈接,獲取用戶openid等基本信息;
② 引導用戶點擊url(例如公眾號推送該鏈接),形式如下: https://open.weixin.qq.com/connect/oauth3/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
各個參數需替換,含義如下: REDIRECT_URI:重定向URL,可為商品列表頁面或商品頁面,用戶授權成功即轉到該URL指向頁面 scope:snsapi_base和snsapi_userinfo兩種,snsapi_base為用戶靜默授權,snsapi_userinfo需要用戶進行授權確認,可以獲得更多用戶信息。本文選擇后者 state:重定向后會帶上此參數
③ 用戶授權后,重定向的頁面獲得code參數(若用戶禁止授權,則重定向后不會帶上code參數,僅會帶上state參數redirect_uri?state=STATE ),官方對于code參數的說明如下:
code作為換取access_token的票據,每次用戶授權帶上的code將不一樣,code只能使用一次,5分鐘未被使用自動過期。
重定向頁面對應controller中通過String code = getPara("code");
獲取code參數。
④ contoller中同時利用WxPayUtil中方法,調用微信接口,獲取當前用戶openid,將該openid存入session:
setSessionAttr("openid", (WxPayUtil.getOpenIdByCode(code)).get("openid"));
4、用戶選擇商品點擊付款,在商家提供h6頁面確認支付對應controller中,進行統一下單,獲得prepay_id(這里需要注意,訂單金額轉換成以分為單位)。統一下單的官方文檔地址為:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
//統一下單,返回xml,用return_code判斷統一下單結果,獲取prepay_id等預支付成功信息String prePayInfoXml = WxPayUtil.unifiedOrder("WxPay", userOrder.getStr("orderNo"), (entity.getBigDecimal("orderMoney").multiply(new BigDecimal(100))).intValue(), WxPayUtil.getIpAddr(getRequest()), getSessionAttr("openid").toString());//生成包含prepay_id的map,map傳入前端map = WxPayUtil.getPayMap(prePayInfoXml);//將訂單號放入map,用以支付后處理map.put("orderNo",userOrder.getStr("orderNo"));
5、前端獲得上一步中的map后,調用微信支付JSAPI,前端js代碼如下所示:
<script type="text/javascript">function payPublic(){ Common.AjaxSubmitBind("saveForm",function(){ saveIndex=Common.Loading("正在付款中"); },function(data){ prepay_id = data.prepay_id; paySign = data.paySign; appId = data.appId; timeStamp = data.timeStamp; nonceStr = data.nonceStr; packageStr = data.packageStr; signType = data.signType; orderNo = data.orderNo; callpay(); },function(errMsg,errCode){ Common.Alert(errMsg); });}var prepay_id;var paySign;var appId;var timeStamp;var nonceStr;var packageStr;var signType;var orderNo;function onBridgeReady(){ WeixinJSBridge.invoke( 'getBrandWCPayRequest', { "appId" : appId, //公眾號名稱,由商戶傳入 "timeStamp" : timeStamp, //時間戳,自1970年以來的秒數 "nonceStr" : nonceStr , //隨機串 "package" : packageStr, "signType" : signType, //微信簽名方式: "paySign" : paySign //微信簽名 }, function(res){ if(res.err_msg == "get_brand_wcpay_request:ok" ) { alert("交易成功"); window.location.href="${base}/test/paySuccess" rel="external nofollow" ; } if (res.err_msg == "get_brand_wcpay_request:cancel") { alert("交易取消"); window.location.href="${base}/test/cancel" rel="external nofollow" ; } if (res.err_msg == "get_brand_wcpay_request:fail") { alert("支付失敗"); window.location.href="${base}/test/fail" rel="external nofollow" ; } } );}function callpay(){ if (typeof WeixinJSBridge == "undefined"){ if( document.addEventListener ){ document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false); }else if (document.attachEvent){ document.attachEvent('WeixinJSBridgeReady', onBridgeReady); document.attachEvent('onWeixinJSBridgeReady', onBridgeReady); } }else{ onBridgeReady(); }}</script>
6、用戶完成支付,后臺等待微信支付回調,進行支付成功后操作:
① 用戶輸入密碼完成支付。后臺回調地址(統一下單中設定的notify_url)接收微信支付結果,對支付結果進行判斷并進行對應操作:
public void notify(){ System.out.print("微信支付回調獲取數據開始"); HttpServletRequest request = getRequest(); String resXml = WxPayUtil.getNotifyResult(request); //向微信輸出處理結果,如果成功(SUCCESS),微信就不會繼續調用了,否則微信會連續調用8次 renderText(resXml, "text/xml");}
相關工具及常量類如下:
① WxPayUtil類(支付工具類):
public class WxPayUtil { private static Logger logger = Logger.getLogger(WxPayUtil.class); /** * 根據code獲取openid * @param code * @return * @throws IOException */ public static Map<String,Object> getOpenIdByCode(String code) throws IOException { //請求該鏈接獲取access_token HttpPost httppost = new HttpPost("https://api.weixin.qq.com/sns/oauth3/access_token"); //組裝請求參數 String reqEntityStr = "appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code"; reqEntityStr = reqEntityStr.replace("APPID", WxPayConstants.APPID); reqEntityStr = reqEntityStr.replace("SECRET", WxPayConstants.APP_SECRET); reqEntityStr = reqEntityStr.replace("CODE", code); StringEntity reqEntity = new StringEntity(reqEntityStr); //設置參數 httppost.setEntity(reqEntity); //設置瀏覽器 CloseableHttpClient httpclient = HttpClients.createDefault(); //發起請求 CloseableHttpResponse response = httpclient.execute(httppost); //獲得請求內容 String strResult = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8")); //獲取openid JSONObject jsonObject = new JSONObject(strResult); Map<String,Object> map = new HashMap<String,Object>(); map.put("openid",jsonObject.get("openid")); map.put("access_token",jsonObject.get("access_token")); map.put("refresh_token",jsonObject.get("refresh_token")); return map; } /** * 統一下單 * @param body * @param out_trade_no * @param total_fee * @param IP * @param notify_url * @param openid * @return * @throws IOException */ public static String unifiedOrder(String body,String out_trade_no,Integer total_fee,String IP,String openid)throws IOException { //設置訪問路徑 HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); String nonce_str = getNonceStr().toUpperCase();//隨機 //組裝請求參數,按照ASCII排序 String sign = "appid=" + WxPayConstants.APPID + "&body=" + body + "&mch_id=" + WxPayConstants.MCH_ID + "&nonce_str=" + nonce_str + "¬ify_url=" + WxPayConstants.NOTIFY_URL + "&openid=" + openid + "&out_trade_no=" + out_trade_no + "&spbill_create_ip=" + IP + "&total_fee=" + total_fee.toString() + "&trade_type=" + WxPayConstants.TRADE_TYPE_JS + "&key=" + WxPayConstants.KEY;//這個字段是用于之后MD5加密的,字段要按照ascii碼順序排序 sign = ToolMD5.MD5Encode(sign,"").toUpperCase(); //組裝包含openid用于請求統一下單返回結果的XML StringBuilder sb = new StringBuilder(""); sb.append("<xml>"); setXmlKV(sb,"appid",WxPayConstants.APPID); setXmlKV(sb,"body",body); setXmlKV(sb,"mch_id",WxPayConstants.MCH_ID); setXmlKV(sb,"nonce_str",nonce_str); setXmlKV(sb,"notify_url",WxPayConstants.NOTIFY_URL); setXmlKV(sb,"openid",openid); setXmlKV(sb,"out_trade_no",out_trade_no); setXmlKV(sb,"spbill_create_ip",IP); setXmlKV(sb,"total_fee",total_fee.toString()); setXmlKV(sb,"trade_type",WxPayConstants.TRADE_TYPE_JS); setXmlKV(sb,"sign",sign); sb.append("</xml>"); System.out.println("統一下單請求:" + sb); StringEntity reqEntity = new StringEntity(new String (sb.toString().getBytes("UTF-8"),"ISO8859-1"));//這個處理是為了防止傳中文的時候出現簽名錯誤 httppost.setEntity(reqEntity); CloseableHttpClient httpclient = HttpClients.createDefault(); CloseableHttpResponse response = httpclient.execute(httppost); String strResult = EntityUtils.toString(response.getEntity(), Charset.forName("utf-8")); System.out.println("統一下單返回xml:" + strResult); return strResult; } /** * 根據統一下單返回預支付訂單的id和其他信息生成簽名并拼裝為map(調用微信支付) * @param prePayInfoXml * @return */ public static Map<String,Object> getPayMap(String prePayInfoXml){ Map<String,Object> map = new HashMap<String,Object>(); String prepay_id = getXmlPara(prePayInfoXml,"prepay_id");//統一下單返回xml中prepay_id String timeStamp = String.valueOf((System.currentTimeMillis()/1000));//1970年到現在的秒數 String nonceStr = getNonceStr().toUpperCase();//隨機數據字符串 String packageStr = "prepay_id=" + prepay_id; String signType = "MD5"; String paySign = "appId=" + WxPayConstants.APPID + "&nonceStr=" + nonceStr + "&package=prepay_id=" + prepay_id + "&signType=" + signType + "&timeStamp=" + timeStamp + "&key="+ WxPayConstants.KEY;//注意這里的參數要根據ASCII碼 排序 paySign = ToolMD5.MD5Encode(paySign,"").toUpperCase();//將數據MD5加密 map.put("appId",WxPayConstants.APPID); map.put("timeStamp",timeStamp); map.put("nonceStr",nonceStr); map.put("packageStr",packageStr); map.put("signType",signType); map.put("paySign",paySign); map.put("prepay_id",prepay_id); return map; } /** * 修改訂單狀態,獲取微信回調結果 * @param request * @return */ public static String getNotifyResult(HttpServletRequest request){ String inputLine; String notifyXml = ""; String resXml = ""; try { while ((inputLine = request.getReader().readLine()) != null){ notifyXml += inputLine; } request.getReader().close(); } catch (Exception e) { logger.debug("xml獲取失敗:" + e); e.printStackTrace(); } System.out.println("接收到的xml:" + notifyXml); logger.debug("收到微信異步回調:"); logger.debug(notifyXml); if(ToolString.isEmpty(notifyXml)){ logger.debug("xml為空:"); } String appid = getXmlPara(notifyXml,"appid");; String bank_type = getXmlPara(notifyXml,"bank_type"); String cash_fee = getXmlPara(notifyXml,"cash_fee"); String fee_type = getXmlPara(notifyXml,"fee_type"); String is_subscribe = getXmlPara(notifyXml,"is_subscribe"); String mch_id = getXmlPara(notifyXml,"mch_id"); String nonce_str = getXmlPara(notifyXml,"nonce_str"); String openid = getXmlPara(notifyXml,"openid"); String out_trade_no = getXmlPara(notifyXml,"out_trade_no"); String result_code = getXmlPara(notifyXml,"result_code"); String return_code = getXmlPara(notifyXml,"return_code"); String sign = getXmlPara(notifyXml,"sign"); String time_end = getXmlPara(notifyXml,"time_end"); String total_fee = getXmlPara(notifyXml,"total_fee"); String trade_type = getXmlPara(notifyXml,"trade_type"); String transaction_id = getXmlPara(notifyXml,"transaction_id"); //根據返回xml計算本地簽名 String localSign = "appid=" + appid + "&bank_type=" + bank_type + "&cash_fee=" + cash_fee + "&fee_type=" + fee_type + "&is_subscribe=" + is_subscribe + "&mch_id=" + mch_id + "&nonce_str=" + nonce_str + "&openid=" + openid + "&out_trade_no=" + out_trade_no + "&result_code=" + result_code + "&return_code=" + return_code + "&time_end=" + time_end + "&total_fee=" + total_fee + "&trade_type=" + trade_type + "&transaction_id=" + transaction_id + "&key=" + WxPayConstants.KEY;//注意這里的參數要根據ASCII碼 排序 localSign = ToolMD5.MD5Encode(localSign,"").toUpperCase();//將數據MD5加密 System.out.println("本地簽名是:" + localSign); logger.debug("本地簽名是:" + localSign); logger.debug("微信支付簽名是:" + sign); //本地計算簽名與微信返回簽名不同||返回結果為不成功 if(!sign.equals(localSign) || !"SUCCESS".equals(result_code) || !"SUCCESS".equals(return_code)){ System.out.println("驗證簽名失敗或返回錯誤結果碼"); logger.error("驗證簽名失敗或返回錯誤結果碼"); resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>" + "<return_msg><![CDATA[FAIL]]></return_msg>" + "</xml> "; }else{ System.out.println("支付成功"); logger.debug("公眾號支付成功,out_trade_no(訂單號)為:" + out_trade_no); resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>" + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> "; } return resXml; } /** * 獲取32位隨機字符串 * @return */ public static String getNonceStr(){ String str = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; StringBuilder sb = new StringBuilder(); Random rd = new Random(); for(int i = 0 ; i < 32 ; i ++ ){ sb.append(str.charAt(rd.nextInt(str.length()))); } return sb.toString(); } /** * 插入XML標簽 * @param sb * @param Key * @param value * @return */ public static StringBuilder setXmlKV(StringBuilder sb,String Key,String value){ sb.append("<"); sb.append(Key); sb.append(">"); sb.append(value); sb.append("</"); sb.append(Key); sb.append(">"); return sb; } /** * 解析XML 獲得名稱為para的參數值 * @param xml * @param para * @return */ public static String getXmlPara(String xml,String para){ int start = xml.indexOf("<"+para+">"); int end = xml.indexOf("</"+para+">"); if(start < 0 && end < 0){ return null; } return xml.substring(start + ("<"+para+">").length(),end).replace("<![CDATA[","").replace("]]>",""); } /** * 獲取ip地址 * @param request * @return */ public static String getIpAddr(HttpServletRequest request) { InetAddress addr = null; try { addr = InetAddress.getLocalHost(); } catch (UnknownHostException e) { return request.getRemoteAddr(); } byte[] ipAddr = addr.getAddress(); String ipAddrStr = ""; for (int i = 0; i < ipAddr.length; i++) { if (i > 0) { ipAddrStr += "."; } ipAddrStr += ipAddr[i] & 0xFF; } return ipAddrStr; }}
② 常量類(根據商戶信息進行設置):
public class WxPayConstants { //第三方用戶唯一ID public static String APPID = ""; //第三方用戶唯一憑證密碼 public static String APP_SECRET = ""; //商戶ID public static String MCH_ID = ""; //微信商戶平臺-賬戶設置-安全設置-api安全,配置32位key public static String KEY = ""; //交易類型 public static String TRADE_TYPE_JS = "JSAPI"; //微信支付回調url public static String NOTIFY_URL = "";}
看完了這篇文章,相信你對“如何使用java實現微信支付的公眾號支付”有了一定的了解,如果想了解更多相關知識,歡迎關注億速云行業資訊頻道,感謝各位的閱讀!
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。