国产 无码 综合区,色欲AV无码国产永久播放,无码天堂亚洲国产AV,国产日韩欧美女同一区二区

微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼

這篇具有很好參考價(jià)值的文章主要介紹了微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼。希望對(duì)大家有所幫助。如果存在錯(cuò)誤或未考慮完全的地方,請(qǐng)大家不吝賜教,您也可以點(diǎn)擊"舉報(bào)違法"按鈕提交疑問。

首先來看看官方支付文檔的一些相關(guān)信息?

微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼

1、用戶在商戶側(cè)完成下單,使用微信支付進(jìn)行支付

2、由商戶后臺(tái)向微信支付發(fā)起下單請(qǐng)求(調(diào)用統(tǒng)一下單接口)注:交易類型trade_type=MWEB

3、統(tǒng)一下單接口返回支付相關(guān)參數(shù)給商戶后臺(tái),如支付跳轉(zhuǎn)url(參數(shù)名“mweb_url”),商戶通過mweb_url調(diào)起微信支付中間頁

4、中間頁進(jìn)行H5權(quán)限的校驗(yàn),安全性檢查(此處常見錯(cuò)誤請(qǐng)見下文)

5、如支付成功,商戶后臺(tái)會(huì)接收到微信側(cè)的異步通知

6、用戶在微信支付收銀臺(tái)完成支付或取消支付,返回商戶頁面(默認(rèn)為返回支付發(fā)起頁面)

7、商戶在展示頁面,引導(dǎo)用戶主動(dòng)發(fā)起支付結(jié)果的查詢

8,9、商戶后臺(tái)判斷是否接到收微信側(cè)的支付結(jié)果通知,如沒有,后臺(tái)調(diào)用我們的訂單查詢接口確認(rèn)訂單狀態(tài)

10、展示最終的訂單支付結(jié)果給用戶

常見問題

一、回調(diào)頁面

正常流程用戶支付完成后會(huì)返回至發(fā)起支付的頁面,如需返回至指定頁面,則可以在MWEB_URL后拼接上redirect_url參數(shù),來指定回調(diào)頁面。

如,您希望用戶支付完成后跳轉(zhuǎn)至https://www.wechatpay.com.cn,則可以做如下處理:

假設(shè)您通過統(tǒng)一下單接口獲到的MWEB_URL= https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096

?

則拼接后的地址為MWEB_URL= https://wx.tenpay.com/cgi-bin/mmpayweb-bin/checkmweb?prepay_id=wx20161110163838f231619da20804912345&package=1037687096&redirect_url=https%3A%2F%2Fwww.wechatpay.com.cn

注意:

??1.需對(duì)redirect_url進(jìn)行urlencode處理

??2.由于設(shè)置redirect_url后,回跳指定頁面的操作可能發(fā)生在:1,微信支付中間頁調(diào)起微信收銀臺(tái)后超過5秒 2,用戶點(diǎn)擊“取消支付“或支付完成后點(diǎn)“完成”按鈕。因此無法保證頁面回跳時(shí),支付流程已結(jié)束,所以商戶設(shè)置的redirect_url地址不能自動(dòng)執(zhí)行查單操作,應(yīng)讓用戶去點(diǎn)擊按鈕觸發(fā)查單操作?;靥撁嬲故拘Ч蓞⒖枷聢D

?

微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼

?

?

二、其它常見錯(cuò)誤

?

序號(hào) 問題 錯(cuò)誤描述 解決方法
1 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 網(wǎng)絡(luò)環(huán)境未能通過安全驗(yàn)證,請(qǐng)稍后再試 1. 商戶側(cè)統(tǒng)一下單傳的終端IP(spbill_create_ip)與用戶實(shí)際調(diào)起支付時(shí)微信側(cè)檢測(cè)到的終端IP不一致導(dǎo)致的,這個(gè)問題一般是商戶在統(tǒng)一下單時(shí)沒有傳遞正確的終端IP到spbill_create_ip導(dǎo)致,詳細(xì)可參見客戶端ip獲取指引
?

2. 統(tǒng)一下單與調(diào)起支付時(shí)的網(wǎng)絡(luò)有變動(dòng),如統(tǒng)一下單時(shí)是WIFI網(wǎng)絡(luò),下單成功后切換成4G網(wǎng)絡(luò)再調(diào)起支付,這樣可能會(huì)引發(fā)我們的正常攔截,請(qǐng)保持網(wǎng)絡(luò)環(huán)境一致的情況下重新發(fā)起支付流程

2 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 商家參數(shù)格式有誤,請(qǐng)聯(lián)系商家解決

1. 當(dāng)前調(diào)起H5支付的referer為空導(dǎo)致,一般是因?yàn)橹苯釉L問頁面調(diào)起H5支付,請(qǐng)按正常流程進(jìn)行頁面跳轉(zhuǎn)后發(fā)起支付,或自行抓包確認(rèn)referer值是否為空

?

2. 如果是APP里調(diào)起H5支付,需要在webview中手動(dòng)設(shè)置referer,如(
Map?extraHeaders = new HashMap();
extraHeaders.put("Referer", "商戶申請(qǐng)H5時(shí)提交的授權(quán)域名");//例如 http://www.baidu.com ))

3 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 商家存在未配置的參數(shù),請(qǐng)聯(lián)系商家解決 1,當(dāng)前調(diào)起H5支付的域名(微信側(cè)從referer中獲?。┡c申請(qǐng)H5支付時(shí)提交的授權(quán)域名不一致,如需添加或修改授權(quán)域名,請(qǐng)登陸商戶號(hào)對(duì)應(yīng)的商戶平臺(tái)--"產(chǎn)品中心"--"開發(fā)配置"自行配置

2,如果設(shè)置了回跳地址redirect_url,請(qǐng)確認(rèn)設(shè)置的回跳地址的域名與申請(qǐng)H5支付時(shí)提交的授權(quán)域名是否一致
4 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 支付請(qǐng)求已失效,請(qǐng)重新發(fā)起支付 統(tǒng)一下單返回的MWEB_URL生成后,有效期為5分鐘,如超時(shí)請(qǐng)重新生成MWEB_URL后再發(fā)起支付
6 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 請(qǐng)?jiān)谖⑿磐獯蜷_訂單,進(jìn)行支付 H5支付不能直接在微信客戶端內(nèi)調(diào)起,請(qǐng)?jiān)谕獠繛g覽器調(diào)起
7 微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼 IOS:簽名驗(yàn)證失敗

?

下面的我實(shí)際開發(fā)的代碼??

1:WxPayController? 控制器前端請(qǐng)求傳遞相應(yīng)的參數(shù) 調(diào)用微信統(tǒng)一下單接口 生成訂單消息和調(diào)用微信支付?

package com.xinjue.web.smallprogram; 

import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xinjue.common.Globals;
import com.xinjue.common.JsonData;
import com.xinjue.meta.Tb_OrderReport;
import com.xinjue.meta.Tb_OrderReport_log;
import com.xinjue.meta.Tb_purchase;
import com.xinjue.meta.Users;
import com.xinjue.service.Tb_OrderReportService;
import com.xinjue.util.DateUtils;
import com.xinjue.util.IpUtils;
import com.xinjue.util.PayUtils;
import com.xinjue.util.StringUtils;
import com.xinjue.util.WxPayConfig;
import com.xinjue.web.BaseController;

/** 
 * @author tqf
 * @version 創(chuàng)建時(shí)間:2019-4-10 上午10:54:46 
 * 類說明   微信小程序支付 H5支付
 */
@Controller
public class WxPayController extends BaseController{
	
		@Resource Tb_OrderReportService orderReportService;
		/**
		 * @Description: 發(fā)起微信支付 統(tǒng)一下單 返回調(diào)起支付需要的參數(shù)值
		 * @param request
		 */
		@RequestMapping(value="/wxPay",method = RequestMethod.POST)
		public void  wxPay(HttpServletRequest request,HttpServletResponse response)throws IOException{
			response.setCharacterEncoding("UTF-8");
			response.setContentType("text/html");
			Users users = (Users) request.getSession().getAttribute(Globals.SSESION_USER);
			JsonData jsonData = new JsonData();
			PrintWriter out = null;
			if(users == null){
				response.getWriter().write("{\"return_msg\":\"請(qǐng)先登錄\"}");
				return;
			}
			try{
				out = response.getWriter();
				
				String openid = request.getParameter("openid");  //"oirgo491UCy5mBcyv7ldQe2RyDtE"
				String total_fee = request.getParameter("total_fee"); //支付金額
				String new_total_fee = "1";//String.valueOf((Integer.parseInt(total_fee)*100)); //金額是以分為單位的  乘以100換算成元  正式區(qū)放開
				String from = request.getParameter("from");// 來源  0--H5	1--小程序
				String paytype = request.getParameter("paytype");  //支付類型  0--微信  1--支付寶
				String title = request.getParameter("title");// 購買標(biāo)題
				String type = request.getParameter("type"); //購買類型   0--精簡(jiǎn)版   1--專業(yè)版
				//商品名稱  微信支付訂單展示使用
				String body_name = "0".equals(type)?"精簡(jiǎn)版":"專業(yè)版";
				String body = "購買報(bào)告-"+body_name;//request.getParameter("body");//"購買報(bào)告-"+body_name;//"測(cè)試支付商品名稱";
				
				//生成的隨機(jī)字符串
				String nonce_str = StringUtils.getRandomStringByLength(32);
				//獲取客戶端的ip地址
				String spbill_create_ip = IpUtils.getIpAddr(request); //request.getRemoteHost();
				
				//商戶訂單號(hào)
				String out_trade_no = "";
				String random = String.valueOf(Math.random()).substring(2,8);
				out_trade_no =DateUtils.dateToString(new Date(), "yyyyMMddhhmmssSSS")+random;
				out_trade_no = out_trade_no.substring(out_trade_no.length()-16, out_trade_no.length());
				
				//組裝參數(shù),用戶生成統(tǒng)一下單接口的簽名
				Map<String, String> packageParams = new HashMap<String, String>();
				
				packageParams.put("mch_id", WxPayConfig.mch_id);
				packageParams.put("nonce_str", nonce_str);
				packageParams.put("body", body);
				packageParams.put("out_trade_no", out_trade_no);//商戶訂單號(hào)
				packageParams.put("total_fee", new_total_fee);//支付金額,這邊需要轉(zhuǎn)成字符串類型,否則后面的簽名會(huì)失敗
				packageParams.put("spbill_create_ip", spbill_create_ip);
				packageParams.put("notify_url", WxPayConfig.notify_url);//支付成功后的回調(diào)地址
				if("0".equals(from)){ //H5參數(shù)
					packageParams.put("appid", WxPayConfig.GZH_appid);
					packageParams.put("trade_type", WxPayConfig.GZH_TRADETYPE);
					packageParams.put("scene_info", WxPayConfig.scene_info);
				}else{ //小程序
					packageParams.put("openid", openid);
					packageParams.put("appid", WxPayConfig.appid);
					packageParams.put("trade_type", WxPayConfig.TRADETYPE);//支付方式  trade_type=JSAPI,openid此參數(shù)必傳,用戶在商戶appid下的唯一標(biāo)識(shí)
				}
				
				packageParams = PayUtils.paraFilter(packageParams);
	        	String prestr = PayUtils.createLinkString(packageParams); // 把數(shù)組所有元素,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串 
	        
	        	//MD5運(yùn)算生成簽名,這里是第一次簽名,用于調(diào)用統(tǒng)一下單接口
	        	String mysign = PayUtils.sign(prestr, WxPayConfig.key, "utf-8").toUpperCase();
	        	
	        	
	        	String xmlString ="";
	        	if("0".equals(from)){ //H5請(qǐng)求參數(shù)
	        		 xmlString += "<scene_info>"+WxPayConfig.scene_info+"</scene_info>"
                 	           + "<trade_type>" + WxPayConfig.GZH_TRADETYPE + "</trade_type>"
                 	           + "<appid>" + WxPayConfig.GZH_appid + "</appid>";
                }else{//小程序
                	 xmlString+= "<trade_type>" + WxPayConfig.TRADETYPE + "</trade_type>"
                			  + "<openid>" + openid + "</openid>" 
                	 		  + "<appid>" + WxPayConfig.appid + "</appid>";
                }
		        //拼接統(tǒng)一下單接口使用的xml數(shù)據(jù),要將上一步生成的簽名一起拼接進(jìn)去
		        String xml =  
		        		"<xml>" + "<body><![CDATA[" + body + "]]></body>" 
			                    + "<mch_id>" + WxPayConfig.mch_id + "</mch_id>" 
			                    + "<nonce_str>" + nonce_str + "</nonce_str>" 
			                    + "<notify_url>" + WxPayConfig.notify_url + "</notify_url>"  
			                    + "<out_trade_no>" + out_trade_no + "</out_trade_no>" 
			                    + "<spbill_create_ip>" + spbill_create_ip + "</spbill_create_ip>" 
			                    + "<total_fee>"+new_total_fee+"</total_fee>"
			                    + xmlString
			                    + "<sign>" + mysign + "</sign>"
			                    + "</xml>";
        		/*packageParams.put("sign", mysign);
        		genXml(packageParams);*//**/
		        
		        System.out.println("調(diào)試模式_統(tǒng)一下單接口 請(qǐng)求XML數(shù)據(jù):" + xml);
		        
		       
		        
		        //調(diào)用統(tǒng)一下單接口,并接受返回的結(jié)果
		        String result = PayUtils.httpRequest(WxPayConfig.pay_url, "POST", xml);
		        
		        System.out.println("調(diào)試模式_統(tǒng)一下單接口 返回XML數(shù)據(jù):" + result);
		        
		        // 將解析結(jié)果存儲(chǔ)在HashMap中   
		        Map map = PayUtils.doXMLParse(result);
		        
		        String return_code = (String) map.get("return_code");//返回狀態(tài)碼
		        String return_msg = (String) map.get("return_msg");
		        
			    Map<String, Object> mapParams = new HashMap<String, Object>();//返回給小程序端需要的參數(shù)
			    mapParams.put("return_code", return_code);
			    mapParams.put("return_msg", return_msg);
		        if(return_code.equals("SUCCESS")){     //生成自己的訂單信息
		        	 //生成訂單記錄
			        Tb_OrderReport orderReport = new Tb_OrderReport();
			        orderReport.setAddTime(new Date());
			        orderReport.setFrom(Integer.parseInt(from));
			        orderReport.setOut_trade_no(out_trade_no);
			        orderReport.setPaytype(Integer.parseInt(paytype));
			        orderReport.setStatus(0);
			        orderReport.setTitle(title);
			        orderReport.setTotal_fee(new Double(total_fee));
			        orderReport.setType(Integer.parseInt(type));
			        orderReport.setUserId(users.getUserId());
			        orderReportService.insert(orderReport);
			        
		        	//小程序端使用     H5下單和小程序下單 都會(huì)返回這些參數(shù)
		        	String prepay_id = (String) map.get("prepay_id");//返回的預(yù)付單信息   小程序端使用
		            mapParams.put("nonceStr", nonce_str);
		            mapParams.put("package", "prepay_id=" + prepay_id);
		            Long timeStamp = new Date().getTime();//System.currentTimeMillis() / 1000;   
		            mapParams.put("timeStamp", timeStamp + "");//這邊要將返回的時(shí)間戳轉(zhuǎn)化成字符串,不然小程序端調(diào)用wx.requestPayment方法會(huì)報(bào)簽名錯(cuò)誤
		            //拼接簽名需要的參數(shù)
		            String stringSignTemp = "appId=" + WxPayConfig.appid + "&nonceStr=" + nonce_str + "&package=prepay_id=" + prepay_id+ "&signType=MD5&timeStamp=" + timeStamp;   
		            //再次簽名,這個(gè)簽名用于小程序端調(diào)用wx.requesetPayment方法
		            String paySign = PayUtils.sign(stringSignTemp, WxPayConfig.key, "utf-8").toUpperCase();
		            mapParams.put("paySign", paySign);
		            mapParams.put("appid", WxPayConfig.appid);
		            
		            //H5端支付 特有參數(shù)  支付跳轉(zhuǎn)地址
		            if("0".equals(from)){
		            	String mweb_url = (String) map.get("mweb_url"); //支付跳轉(zhuǎn)鏈接  H5端使用
			            String redirect_url  = "http://m.xinjuenet.cn/presentation"; //支付完成回調(diào)跳轉(zhuǎn)地址  自定義
			            mweb_url = mweb_url+"&redirect_url="+URLEncoder.encode(redirect_url,"UTF-8");
			            mapParams.put("mweb_url", mweb_url);
		            }
		            jsonData = new JsonData(Globals.SUCCESS, "", mapParams);
		        }else{
		        	jsonData = new JsonData(Globals.SYSTEM_BUSY,"",mapParams);
		        }
			}catch(Exception e){
				e.printStackTrace();
			}
			out.write(jsonData.toJsonString());
		}	


	/**
     * @Description:微信小程序支付回調(diào)通知地址
     * @return
     * @throws Exception
     */
    @RequestMapping(value="/wxNotify",method = RequestMethod.GET)
    public void wxNotify(HttpServletRequest request,HttpServletResponse response) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader((ServletInputStream)request.getInputStream()));
        String line = null;
        StringBuilder sb = new StringBuilder();
        while((line = br.readLine()) != null){
            sb.append(line);
        }

        br.close();
        //sb為微信返回的xml
        String notityXml = sb.toString();
        String resXml = "";
        System.out.println("接收到的報(bào)文:" + notityXml);
 
        Map map = PayUtils.doXMLParse(notityXml);
 
        String returnCode = (String) map.get("return_code");
        String total_fee  = (String) map.get("total_fee"); //支付金額
        String trade_state = (String) map.get("trade_state"); //支付狀態(tài)
        if("SUCCESS".equals(returnCode)){
            //驗(yàn)證簽名是否正確
            Map<String, String> validParams = PayUtils.paraFilter(map);  //回調(diào)驗(yàn)簽時(shí)需要去除sign和空值參數(shù)
            String validStr = PayUtils.createLinkString(validParams);//把數(shù)組所有元素,按照“參數(shù)=參數(shù)值”的模式用“&”字符拼接成字符串
            String sign = PayUtils.sign(validStr, WxPayConfig.key, "utf-8").toUpperCase();//拼裝生成服務(wù)器端驗(yàn)證的簽名
            //根據(jù)微信官網(wǎng)的介紹,此處不僅對(duì)回調(diào)的參數(shù)進(jìn)行驗(yàn)簽,還需要對(duì)返回的金額與系統(tǒng)訂單的金額進(jìn)行比對(duì)等
            //商戶系統(tǒng)對(duì)于支付結(jié)果通知的內(nèi)容一定要做簽名驗(yàn)證,并校驗(yàn)返回的訂單金額是否與商戶側(cè)的訂單金額一致,防止數(shù)據(jù)泄漏導(dǎo)致出現(xiàn)“假通知”,造成資金損失
            if(sign.equals(map.get("sign"))){
                /**此處添加自己的業(yè)務(wù)邏輯代碼start**/
            	if(trade_state != null && "SUCCESS".equals(trade_state)){
            	String out_trade_no = (String) map.get("out_trade_no"); //返回的商戶訂單號(hào)  根據(jù)這個(gè)改變訂單支付狀態(tài)
            	String time_end = (String) map.get("time_end"); //支付完成時(shí)間
            	String result = map.toString(); //返回的所有字段保存支付日志文件
            	
            	//時(shí)間格式化
            	SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmss");
            	Date date = (Date) sdf.parse(time_end);
            	SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            	String time =sdf2.format(date);
            	
            
            	//1:更新訂單狀態(tài)和支付時(shí)間
            	Tb_OrderReport orderReport = new Tb_OrderReport();
            	orderReport.setOut_trade_no(out_trade_no);
            	orderReport.setTime_end(DateUtils.stringToDate(time, "yyyy-MM-dd HH:mm:ss"));
            	orderReport.setStatus(1);
            	orderReportService.updateStatus(orderReport);
            	
            	//2:添加支付回調(diào)記錄
            	Tb_OrderReport_log orderReport_log = new Tb_OrderReport_log();
            	orderReport_log.setAddTime(new Date());
            	orderReport_log.setType(0);
            	orderReport_log.setMessage(result);
            	orderReport_log.setOut_trade_no(out_trade_no);
            	orderReportService.insertOrderReportlog(orderReport_log);
            	
            	//3生成唯一購買記錄地址 用戶通過地址訪問購買之后的完整版本報(bào)告
            	String key = StringUtils.getRandomStringByLength(32);
            	Tb_OrderReport orderReport2 = new Tb_OrderReport();
            	//orderReport2.setUserId(users.getUserId());
            	orderReport2.setOut_trade_no(out_trade_no);
            	orderReport2 = orderReportService.selectByOut_trade_no(orderReport2);
            	
            	String linkUrl = "";
            	if(orderReport2.getType() == 0){
            		linkUrl = "presentationStreamlining";//精簡(jiǎn)版
            	}else{
            		linkUrl = "presentationmajor"; //專業(yè)版
            	}
            	
            	Tb_purchase purchase = new Tb_purchase();
            	purchase.setUserId(orderReport2.getUserId());
            	purchase.setKey(key);
            	purchase.setAddTime(new Date());
            	purchase.setType(orderReport2.getType());
            	purchase.setLinkUrl(linkUrl);
            	purchase.setOut_trade_no(out_trade_no);
            	orderReportService.insert_purchase(purchase);
            	
                /**此處添加自己的業(yè)務(wù)邏輯代碼end**/
                //通知微信服務(wù)器已經(jīng)支付成功
                resXml = "<xml>" + "<return_code><![CDATA[SUCCESS]]></return_code>"
                        + "<return_msg><![CDATA[OK]]></return_msg>" + "</xml> ";
            	}
            }
        }else{
            resXml = "<xml>" + "<return_code><![CDATA[FAIL]]></return_code>"
                    + "<return_msg><![CDATA[報(bào)文為空]]></return_msg>" + "</xml> ";
        }
        System.out.println(resXml);
        System.out.println("微信支付回調(diào)數(shù)據(jù)結(jié)束");
 
 
        BufferedOutputStream out = new BufferedOutputStream(
                response.getOutputStream());
        out.write(resXml.getBytes());
        out.flush();
        out.close();
    }

	/**
	 * 生成xml
	 * @return
	 */
	public static String genXml(Map<String,String> map)throws Exception{
		StringBuffer sb=new StringBuffer();
		sb.append("<xml>");
		for(String k:map.keySet()){
			Object value=map.get(k);
			sb.append("<"+k+">"+value+"</"+k+">");
		}
		sb.append("</xml>");
		return sb.toString();//new String(sb.toString().getBytes("ISO8859-1"),"UTF-8");
	}
	
	/**
	 * 跳轉(zhuǎn)到支付頁面
	 * @param request
	 * @param response
	 * @return
	 * @throws IOException
	 */
	@RequestMapping(value="/wxpaypage",method = RequestMethod.GET)
	public String  wxpaypage(HttpServletRequest request,HttpServletResponse response)throws IOException{
		response.setCharacterEncoding("utf-8");
		response.setContentType("text/html");
		Users users = (Users) request.getSession().getAttribute(Globals.SSESION_USER);
		if(users == null){
			try {
				response.sendRedirect("login");
			} catch (Exception e) {
				e.printStackTrace();
			}
			return null;
		}
		String title = request.getParameter("title");
		String money = request.getParameter("money");
		String type = request.getParameter("type");
		String type_name = type.equals("0")?"精簡(jiǎn)版":"專業(yè)版";
		request.setAttribute("title", title);
		request.setAttribute("money", money);
		request.setAttribute("type", type);
		request.setAttribute("type_name", type_name);
		return "wxpaypage";
	}

}
 

2:IpUtils? 獲取實(shí)際的IP地址工具類?

package com.xinjue.util; 

import java.net.InetAddress;
import java.net.UnknownHostException;

import javax.servlet.http.HttpServletRequest;

/** 
 * @author tqf
 * @version 創(chuàng)建時(shí)間:2019-4-10 上午11:32:52 
 * 類說明 
 */
public class IpUtils {
		
	/**
	 * IpUtils工具類方法
	 * 獲取真實(shí)的ip地址
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request) { 
		InetAddress addr = null;
		try { 
			 addr = InetAddress.getLocalHost(); 
		} catch (UnknownHostException e) { 
			 return request.getRemoteAddr(); 
		}
		System.out.println(addr.getHostAddress());
		return addr.getHostAddress();
	}
}
 

3:PayUtils? 有請(qǐng)求接口方法? 簽名 xml解析等..方法?

package com.xinjue.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.apache.commons.codec.digest.DigestUtils;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class PayUtils
{
  public static String sign(String text, String key, String input_charset)
  {
    text = text + "&key=" + key;
    return DigestUtils.md5Hex(getContentBytes(text, input_charset));
  }
  
  public static boolean verify(String text, String sign, String key, String input_charset)
  {
    text = text + key;
    String mysign = DigestUtils.md5Hex(getContentBytes(text, input_charset));
    if (mysign.equals(sign)) {
      return true;
    }
    return false;
  }
  
  public static byte[] getContentBytes(String content, String charset)
  {
    if ((charset == null) || ("".equals(charset))) {
      return content.getBytes();
    }
    try {
      return content.getBytes(charset);
    } catch (UnsupportedEncodingException e) {
      throw new RuntimeException("MD5簽名過程中出現(xiàn)錯(cuò)誤,指定的編碼集不對(duì),您目前指定的編碼集是:" + charset);
    }
  }
  
  private static boolean isValidChar(char ch) {
    if (((ch >= '0') && (ch <= '9')) || ((ch >= 'A') && (ch <= 'Z')) || ((ch >= 'a') && (ch <= 'z')))
      return true;
    if (((ch >= '一') && (ch <= '翿')) || ((ch >= 32768) && (ch <= 38191)))
      return true;
    return false;
  }
  
  public static Map<String, String> paraFilter(Map<String, String> sArray)
  {
    Map<String, String> result = new HashMap();
    if ((sArray == null) || (sArray.size() <= 0)) {
      return result;
    }
    for (String key : sArray.keySet()) {
      String value = (String)sArray.get(key);
      if ((value != null) && (!value.equals("")) && (!key.equalsIgnoreCase("sign")) && 
        (!key.equalsIgnoreCase("sign_type")))
      {
        result.put(key, value); }
    }
    return result;
  }
  
  public static String createLinkString(Map<String, String> params)
  {
    List<String> keys = new ArrayList(params.keySet());
    Collections.sort(keys);
    String prestr = "";
    for (int i = 0; i < keys.size(); i++) {
      String key = (String)keys.get(i);
      String value = (String)params.get(key);
      if (i == keys.size() - 1) {
        prestr = prestr + key + "=" + value;
      } else {
        prestr = prestr + key + "=" + value + "&";
      }
    }
    return prestr;
  }
  
  public static String httpRequest(String requestUrl, String requestMethod, String outputStr)
  {
    StringBuffer buffer = null;
    try {
      URL url = new URL(requestUrl);
      HttpURLConnection conn = (HttpURLConnection)url.openConnection();
      conn.setRequestMethod(requestMethod);
      conn.setDoOutput(true);
      conn.setDoInput(true);
      conn.connect();
      
      if (outputStr != null) {
        OutputStream os = conn.getOutputStream();
        os.write(outputStr.getBytes("utf-8"));
        os.close();
      }
      
      InputStream is = conn.getInputStream();
      InputStreamReader isr = new InputStreamReader(is, "utf-8");
      BufferedReader br = new BufferedReader(isr);
      buffer = new StringBuffer();
      String line = null;
      while ((line = br.readLine()) != null) {
        buffer.append(line);
      }
      br.close();
    } catch (Exception e) {
      e.printStackTrace();
    }
    return buffer.toString();
  }
  
  public static String urlEncodeUTF8(String source) { String result = source;
    try {
      result = URLEncoder.encode(source, "UTF-8");
    }
    catch (UnsupportedEncodingException e) {
      e.printStackTrace();
    }
    return result;
  }
  
  public static Map doXMLParse(String strxml)
    throws Exception
  {
    if ((strxml == null) || ("".equals(strxml))) {
      return null;
    }
    try
    {
      Map<String, String> data = new HashMap();
      
      DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
      documentBuilderFactory.setFeature("http://apache.org/xml/features/disallow-doctype-decl", true);
      documentBuilderFactory.setFeature("http://xml.org/sax/features/external-general-entities", false);
      documentBuilderFactory.setFeature("http://xml.org/sax/features/external-parameter-entities", false);
      documentBuilderFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
      documentBuilderFactory.setFeature("http://javax.xml.XMLConstants/feature/secure-processing", true);
      documentBuilderFactory.setXIncludeAware(false);
      documentBuilderFactory.setExpandEntityReferences(false);
      
      InputStream stream = new ByteArrayInputStream(strxml.getBytes("UTF-8"));
      Document doc = documentBuilderFactory.newDocumentBuilder().parse(stream);
      doc.getDocumentElement().normalize();
      NodeList nodeList = doc.getDocumentElement().getChildNodes();
      for (int idx = 0; idx < nodeList.getLength(); idx++) {
        Node node = nodeList.item(idx);
        if (node.getNodeType() == 1) {
          org.w3c.dom.Element element = (org.w3c.dom.Element)node;
          data.put(element.getNodeName(), element.getTextContent());
        }
      }
      try {
        stream.close();
      }
      catch (Exception localException1) {}
      
      return data;
    } catch (Exception ex) {
      throw ex;
    }
  }
  
  public static String getChildrenText(List children)
  {
    StringBuffer sb = new StringBuffer();
    if (!children.isEmpty()) {
      Iterator it = children.iterator();
      while (it.hasNext()) {
        org.jdom.Element e = (org.jdom.Element)it.next();
        String name = e.getName();
        String value = e.getTextNormalize();
        List list = e.getChildren();
        sb.append("<" + name + ">");
        if (!list.isEmpty()) {
          sb.append(getChildrenText(list));
        }
        sb.append(value);
        sb.append("</" + name + ">");
      }
    }
    
    return sb.toString();
  }
  
  public static InputStream String2Inputstream(String str) { return new ByteArrayInputStream(str.getBytes()); }
}

4:WxPayConfig? 微信支付請(qǐng)求的一些基本參數(shù) 靜態(tài)的 實(shí)體類?

package com.xinjue.util; 
/** 
 * @author tqf
 * @version 創(chuàng)建時(shí)間:2019-4-10 上午11:13:33 
 * 類說明    小程序微信支付的配置文件
 */
public class WxPayConfig {
	
		//小程序appid
		public static final String appid = "";
		// 公眾號(hào)ID
		public static final String GZH_appid = "";
		//微信支付的商戶id
		public static final String mch_id = "";
		//微信支付的商戶密鑰
		public static final String key = "";
		//支付成功后的服務(wù)器回調(diào)url
		//public static final String notify_url = ""; //正式區(qū)
		public static final String notify_url = ""; //測(cè)試區(qū)
		//簽名方式,固定值
		public static final String SIGNTYPE = "MD5";
		//交易類型,小程序支付的固定值為JSAPI
		public static final String TRADETYPE = "JSAPI";
		//交易類型 wap H5端
		public static final String GZH_TRADETYPE = "MWEB";
		//微信統(tǒng)一下單接口地址
		public static final String pay_url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
		
		// H5端 場(chǎng)景信息   scene_info
		public static final String scene_info = "{\"h5_info\": {\"type\":\"WAP\",\"wap_url\": \"\",\"wap_name\": \"心覺咨詢\"}}";
}
 

測(cè)試的話 需要在商戶的H5支付設(shè)置微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼文章來源地址http://www.zghlxwxcb.cn/news/detail-711217.html

到了這里,關(guān)于微信支付 H5端 和小程序端 統(tǒng)一下單接口 4個(gè)JAVA源碼文件代碼的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!

本文來自互聯(lián)網(wǎng)用戶投稿,該文觀點(diǎn)僅代表作者本人,不代表本站立場(chǎng)。本站僅提供信息存儲(chǔ)空間服務(wù),不擁有所有權(quán),不承擔(dān)相關(guān)法律責(zé)任。如若轉(zhuǎn)載,請(qǐng)注明出處: 如若內(nèi)容造成侵權(quán)/違法違規(guī)/事實(shí)不符,請(qǐng)點(diǎn)擊違法舉報(bào)進(jìn)行投訴反饋,一經(jīng)查實(shí),立即刪除!

領(lǐng)支付寶紅包贊助服務(wù)器費(fèi)用

相關(guān)文章

覺得文章有用就打賞一下文章作者

支付寶掃一掃打賞

博客贊助

微信掃一掃打賞

請(qǐng)作者喝杯咖啡吧~博客贊助

支付寶掃一掃領(lǐng)取紅包,優(yōu)惠每天領(lǐng)

二維碼1

領(lǐng)取紅包

二維碼2

領(lǐng)紅包