最近兩周實現(xiàn)了調(diào)用微信接口使用微信進(jìn)行支付的需求,包含公眾號支付及掃碼支付兩種方式,由于微信文檔寫的較為簡略,現(xiàn)將調(diào)用微信接口進(jìn)行支付流程進(jìn)行記錄及分享。
我們提供的服務(wù)有:網(wǎng)站建設(shè)、成都做網(wǎng)站、微信公眾號開發(fā)、網(wǎng)站優(yōu)化、網(wǎng)站認(rèn)證、代縣ssl等。為上千企事業(yè)單位解決了網(wǎng)站和推廣的問題。提供周到的售前咨詢和貼心的售后服務(wù),是有科學(xué)管理、有技術(shù)的代縣網(wǎng)站制作公司
本文旨在對公眾號支付的實現(xiàn)流程進(jìn)行介紹,即微信用戶從公眾號中點擊鏈接進(jìn)入商品h6頁面,選擇商品后點擊支付按鈕后彈出微信支付頁面、輸入支付密碼、支付成功后跳轉(zhuǎn)到全部商品頁面的整個過程。微信掃碼支付請參看后續(xù)文章。
1、首先,商戶需申請微信公眾號、微信商戶號及微信支付權(quán)限。開發(fā)過程中需參照公眾號及商戶平臺提供如下參數(shù):
① appid:公眾號id,登錄微信公眾號–開發(fā)–基本配置中獲得;
② mch_id:收款商家商戶號;
③ APP_SECRET:第三方唯一憑證密碼;
④ key:收款商戶后臺進(jìn)行配置,登錄微信商戶平臺–賬戶設(shè)置–安全設(shè)置–api安全,設(shè)置32位key值。
2、登錄微信公眾號,進(jìn)行開發(fā)相關(guān)設(shè)置:
① 獲取用戶基本信息(主要是openid)權(quán)限配置:微信公眾平臺–開發(fā)–接口權(quán)限–網(wǎng)頁授權(quán)–網(wǎng)頁授權(quán)域名(不接受IP地址,需通過ICP備案驗證,不帶http):
② 支付測試目錄及測試白名單設(shè)置:微信公眾平臺–微信支付–開發(fā)配置,測試授權(quán)目錄具體到最后一級。
3、獲取用戶openid,OpenID是公眾號一對一對應(yīng)用戶身份的標(biāo)識:
① 微信網(wǎng)頁授權(quán)獲取用戶信息文檔:https://developers.weixin.qq.com/miniprogram/dev/wxcloud/guide/functions/userinfo.html。根據(jù)文檔拼裝url,引導(dǎo)用戶在微信上點擊該鏈接,獲取用戶openid等基本信息;
② 引導(dǎo)用戶點擊url(例如公眾號推送該鏈接),形式如下:
https://open.weixin.qq.com/connect/oauth3/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
各個參數(shù)需替換,含義如下:
REDIRECT_URI:重定向URL,可為商品列表頁面或商品頁面,用戶授權(quán)成功即轉(zhuǎn)到該URL指向頁面
scope:snsapi_base和snsapi_userinfo兩種,snsapi_base為用戶靜默授權(quán),snsapi_userinfo需要用戶進(jìn)行授權(quán)確認(rèn),可以獲得更多用戶信息。本文選擇后者
state:重定向后會帶上此參數(shù)
③ 用戶授權(quán)后,重定向的頁面獲得code參數(shù)(若用戶禁止授權(quán),則重定向后不會帶上code參數(shù),僅會帶上state參數(shù)redirect_uri?state=STATE ),官方對于code參數(shù)的說明如下:
code作為換取access_token的票據(jù),每次用戶授權(quán)帶上的code將不一樣,code只能使用一次,5分鐘未被使用自動過期。
重定向頁面對應(yīng)controller中通過String code = getPara("code");
獲取code參數(shù)。
④ contoller中同時利用WxPayUtil中方法,調(diào)用微信接口,獲取當(dāng)前用戶openid,將該openid存入session:
setSessionAttr("openid", (WxPayUtil.getOpenIdByCode(code)).get("openid"));
4、用戶選擇商品點擊付款,在商家提供h6頁面確認(rèn)支付對應(yīng)controller中,進(jìn)行統(tǒng)一下單,獲得prepay_id(這里需要注意,訂單金額轉(zhuǎn)換成以分為單位)。統(tǒng)一下單的官方文檔地址為:https://pay.weixin.qq.com/wiki/doc/api/jsapi.php?chapter=9_1
//統(tǒng)一下單,返回xml,用return_code判斷統(tǒng)一下單結(jié)果,獲取prepay_id等預(yù)支付成功信息 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后,調(diào)用微信支付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年以來的秒數(shù) "nonceStr" : nonceStr , //隨機(jī)串 "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、用戶完成支付,后臺等待微信支付回調(diào),進(jìn)行支付成功后操作:
① 用戶輸入密碼完成支付。后臺回調(diào)地址(統(tǒng)一下單中設(shè)定的notify_url)接收微信支付結(jié)果,對支付結(jié)果進(jìn)行判斷并進(jìn)行對應(yīng)操作:
public void notify(){ System.out.print("微信支付回調(diào)獲取數(shù)據(jù)開始"); HttpServletRequest request = getRequest(); String resXml = WxPayUtil.getNotifyResult(request); //向微信輸出處理結(jié)果,如果成功(SUCCESS),微信就不會繼續(xù)調(diào)用了,否則微信會連續(xù)調(diào)用8次 renderText(resXml, "text/xml"); }
相關(guān)工具及常量類如下:
① WxPayUtil類(支付工具類):
public class WxPayUtil { private static Logger logger = Logger.getLogger(WxPayUtil.class); /** * 根據(jù)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"); //組裝請求參數(shù) 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); //設(shè)置參數(shù) httppost.setEntity(reqEntity); //設(shè)置瀏覽器 CloseableHttpClient httpclient = HttpClients.createDefault(); //發(fā)起請求 CloseableHttpResponse response = httpclient.execute(httppost); //獲得請求內(nèi)容 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; } /** * 統(tǒng)一下單 * @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 { //設(shè)置訪問路徑 HttpPost httppost = new HttpPost("https://api.mch.weixin.qq.com/pay/unifiedorder"); String nonce_str = getNonceStr().toUpperCase();//隨機(jī) //組裝請求參數(shù),按照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用于請求統(tǒng)一下單返回結(jié)果的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("統(tǒng)一下單請求:" + sb); StringEntity reqEntity = new StringEntity(new String (sb.toString().getBytes("UTF-8"),"ISO8859-1"));//這個處理是為了防止傳中文的時候出現(xiàn)簽名錯誤 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("統(tǒng)一下單返回xml:" + strResult); return strResult; } /** * 根據(jù)統(tǒng)一下單返回預(yù)支付訂單的id和其他信息生成簽名并拼裝為map(調(diào)用微信支付) * @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");//統(tǒng)一下單返回xml中prepay_id String timeStamp = String.valueOf((System.currentTimeMillis()/1000));//1970年到現(xiàn)在的秒數(shù) String nonceStr = getNonceStr().toUpperCase();//隨機(jī)數(shù)據(jù)字符串 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;//注意這里的參數(shù)要根據(jù)ASCII碼 排序 paySign = ToolMD5.MD5Encode(paySign,"").toUpperCase();//將數(shù)據(jù)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; } /** * 修改訂單狀態(tài),獲取微信回調(diào)結(jié)果 * @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("收到微信異步回調(diào):"); 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"); //根據(jù)返回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;//注意這里的參數(shù)要根據(jù)ASCII碼 排序 localSign = ToolMD5.MD5Encode(localSign,"").toUpperCase();//將數(shù)據(jù)MD5加密 System.out.println("本地簽名是:" + localSign); logger.debug("本地簽名是:" + localSign); logger.debug("微信支付簽名是:" + sign); //本地計算簽名與微信返回簽名不同||返回結(jié)果為不成功 if(!sign.equals(localSign) || !"SUCCESS".equals(result_code) || !"SUCCESS".equals(return_code)){ System.out.println("驗證簽名失敗或返回錯誤結(jié)果碼"); logger.error("驗證簽名失敗或返回錯誤結(jié)果碼"); 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位隨機(jī)字符串 * @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標(biāo)簽 * @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的參數(shù)值 * @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; } }
② 常量類(根據(jù)商戶信息進(jìn)行設(shè)置):
public class WxPayConstants { //第三方用戶唯一ID public static String APPID = ""; //第三方用戶唯一憑證密碼 public static String APP_SECRET = ""; //商戶ID public static String MCH_ID = ""; //微信商戶平臺-賬戶設(shè)置-安全設(shè)置-api安全,配置32位key public static String KEY = ""; //交易類型 public static String TRADE_TYPE_JS = "JSAPI"; //微信支付回調(diào)url public static String NOTIFY_URL = ""; }
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
新聞名稱:微信支付之公眾號支付(java實現(xiàn))
路徑分享:http://aaarwkj.com/article24/pjchje.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計、軟件開發(fā)、搜索引擎優(yōu)化、、外貿(mào)建站、移動網(wǎng)站建設(shè)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)