public class HttpRequest {
/**
* 向指定URL發送GET方法的請求
* @param url 發送請求的URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return URL 所代表遠程資源的響應結果
*/
public static String sendGet(String url, String param) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url + "?" + param;
System.out.println(urlNameString);
URL realUrl = new URL(urlNameString);
// 打開和URL之間的連接
URLConnection connection = realUrl.openConnection();
// 設置通用的請求屬性
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 建立實際的連接
connection.connect();
// 獲取所有響應頭字段
Map<String, List<String>> map = connection.getHeaderFields();
// 遍歷所有的響應頭字段
for (String key : map.keySet()) {
System.out.println(key + "--->" + map.get(key));
}
// 定義 BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送GET請求出現異常!" + e);
e.printStackTrace();
}
// 使用finally塊來關閉輸入流
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
/**
* 向指定 URL 發送POST方法的請求
* @param url 發送請求的 URL
* @param param 請求參數,請求參數應該是 name1=value1&name2=value2 的形式。
* @return 所代表遠程資源的響應結果
*/
public static String sendPost(String url, String param) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// 打開和URL之間的連接
URLConnection conn = realUrl.openConnection();
// 設置通用的請求屬性
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// 發送POST請求必須設置如下兩行
conn.setDoOutput(true);
conn.setDoInput(true);
// 獲取URLConnection對象對應的輸出流
out = new PrintWriter(conn.getOutputStream());
// 發送請求參數
out.print(param);
// flush輸出流的緩沖
out.flush();
// 定義BufferedReader輸入流來讀取URL的響應
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println("發送 POST 請求出現異常!"+e);
e.printStackTrace();
}
//使用finally塊來關閉輸出流、輸入流
finally{
try{
if(out!=null){
out.close();
}
if(in!=null){
in.close();
}
}
catch(IOException ex){
ex.printStackTrace();
}
}
return result;
}
}
4、微信支付前端頁面調用
$('#btn').click(function() {
var param = { //傳入參數
.....
};
$.ajax({
type: "post",
url: 'http://XXXX.com/項目名/wechat-createInsurance',
contentType: 'application/json;charset=UTF-8',
dataType: 'json',
data: JSON.stringify(param),
success: function(result) {
if(result.code==SUCCESS){
function onBridgeReady() {
WeixinJSBridge.invoke(
'getBrandWCPayRequest', {
"appId": result.result.appId, // 公眾賬號ID
"timeStamp": result.result.timeStamp, //時間戳,自1970年以來的秒
"nonceStr": result.result.nonceStr, //隨機串
"package": result.result.package,
"signType": result.result.signType, //微信簽名方式:
"paySign": result.result.paySign //微信簽名
},
function(res) {
if (res.err_msg == "get_brand_wcpay_request:ok") {
// 使用以上方式判斷前端返回,微信團隊鄭重提示:
//res.err_msg將在用戶支付成功后返回ok,但并不保證它絕對可靠。
window.location.href = 'sucess.html' ; //成功支付后跳轉到下個頁面
}else{
alert("微信支付失敗");
}
}
);
}
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();
}
}else{
alert(result.msg);
}
},
error: function(err) {
alert("登陸失敗");
console.log(err);
}
});
});
點擊按鈕,訪問接口成功后,微信端h5頁面自動彈出微信自帶的支付頁面,支付完成后,點擊確定,微信會自動回調用戶寫微信支付回調接口。(微信支付回調接口具體實現看第五章)
5、微信支付回調接口
應用場景:
支付完成后,微信會把相關支付結果及用戶信息通過數據流的形式發送給商戶,商戶需要接收處理,并按文檔規范返回應答。
微信的通知參數格式:(具體查看微信支付結果通知)
1
微信支付回調接口的實現:
@POST
@Path(value = "wechat-notification")
public Response WeChatNotification(@Context HttpServletRequest request, @Context HttpServletResponse response)
throws IOException, DocumentException {
try {
//微信發的xml格式的數據轉為Map格式
Map<String, String> paramMap = new HashMap<String, String>();
InputStream inputStream = request.getInputStream();
SAXReader reader = new SAXReader();
Document document = reader.read(inputStream);
Element root = document.getRootElement();
List<Element> elementList = root.elements();
for (Element e : elementList) {
paramMap.put(e.getName(), e.getText());
}
inputStream.close();
inputStream = null;
if("FAIL".equals(paramMap.get("return_code"))){
throw new RuntimeException("return_code為fail, " + paramMap.get("return_msg"));
}
if("FAIL".equals(paramMap.get("result_code"))){
throw new RuntimeException("result_code為fail, " + paramMap.get("err_code_des"));
}
//...... 業務流程 ......
//響應給微信的一定是以流的方式
//告訴微信服務器收到信息了,不要在調用回調action了(回復微信服務器信息用流發送一個xml即可)
return Response.ok(" "
+ " ").build();
} catch (Exception e) {
e.printStackTrace();
return Response.ok(" "
+"+e.getMessage() +"]]> ").build();
}
}
注意:
(1)該鏈接是通過【[統一下單】中提交的參數設置,如果鏈接無法訪問,商戶將無法接收到微信通知。
(2)通知url必須為直接可訪問的url,不能攜帶參數。
(3)商戶系統對于支付結果通知的內容一定要做簽名驗證,并校驗返回的訂單金額是否與商戶側的訂單金額一致,防止數據泄漏導致出現“假通知”,造成資金損失。
(4)技術人員可登進微信商戶后臺掃描加入接口報警群,獲取接口告警信息。
(5)同樣的通知可能會多次發送給商戶系統。商戶系統必須能夠正確處理重復的通知。
(6)后臺通知交互時,如果微信收到商戶的應答不符合規范或超時微信訂單系統,微信會判定本次通知失敗,重新發送通知,直到成功為止,但微信不保證通知最終一定能成功。
(7)在訂單狀態不明或者沒有收到微信支付結果通知的情況下,建議商戶主動調用微信支付【查詢訂單】確認訂單狀態。(可查看第六章,注意可以通過輪詢查詢支付訂單來監控是否已支付)
6、查詢訂單接口
應用場景:
該接口提供所有微信支付訂單的查詢微信訂單系統,商戶可以通過查詢訂單接口主動查詢訂單狀態,完成下一步的業務邏輯。
需要調用查詢接口的情況:
(1)當商戶后臺、網絡、服務器等出現異常,商戶系統最終未接收到支付通知;
(2)調用支付接口后,返回系統錯誤或未知交易狀態情況;
(3)調用付款碼支付API,返回的狀態;
(4)調用關單或撤銷接口API之前,需確認支付狀態;
查詢訂單接口實現:
@GET
@Path(value = "wechat-orderquery")
@Produces(MediaType.APPLICATION_JSON)
public Response WechatOrderquery(@QueryParam("outTradeNo") String outTradeNo){
Map<String, Object> result = new HashMap<String, Object>();
try {
HashMap<String, String> data = new HashMap<String, String>();
data.put("out_trade_no", outTradeNo);// 商戶訂單號
data.put("mch_id", mchid);// 商戶號
data.put("nonce_str", WXPayUtil.generateNonceStr());// 隨機字符串
data.put("appid", appid);// 公眾賬號ID
String sign = WXPayUtil.generateSignature(data, paternerKey);
data.put("sign", sign);// 簽名
WXPay wxpay = new WXPay(MyConfig.getInstance()); //導入微信的下載的包
Map<String, String> resp = wxpay.orderQuery(data);
if("FAIL".equals(resp.get("return_code"))){
throw new RuntimeException("return_code為fail, " + resp.get("return_msg"));
}
if("FAIL".equals(resp.get("result_code"))){
throw new RuntimeException("result_code為fail, " + resp.get("err_code_des"));
}
if(!"SUCCESS".equals(resp.get("trade_state"))){
throw new RuntimeException("trade_state為" + resp.get("trade_state"));
}
//.......業務流程......
result.put("paperno", paperno);
result.put("code", SUCCESS);
}catch(Exception e){
e.printStackTrace();
result.put("code", ERROR);
result.put("msg", "訂單查詢異常");
}
return Response.ok(result).build();
}
微信公眾號
免責聲明:部分文章信息來源于網絡以及網友投稿,本站只負責對文章進行整理、排版、編輯,出于傳遞更多信息之目的,并不意味著贊同其觀點或證實其內容的真實性,如本站文章和轉稿涉及版權等問題,請作者在及時聯系本站,我們會盡快為您處理。