微信支付H5调用支付详解(java版)

网友投稿 421 2023-06-26


微信支付H5调用支付详解(java版)

比如:支付js页面的地址为 http://xxx.com/shop/pay/

那此处配置xxx.com/shop/pay/

二、开发流程

三、向微信服务器端下订单

调用统一下单接口,这样就能获取微信支付的prepay_id(http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=9_1)。

在调用该接口前有几个字段是H5支付必须填写的openid

3.1 获取openid

可以通过网页授权形式(http://mp.weixin.qq.com/wiki/17/c0f37d5704f0b64713d5d2c37b468d75.html)

在微信中发送如下链接

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx520c15f417810387&redirect_uri=要跳转的下订单的url&response_type=code&scope=snsapi_base&state=123#wechat_redirect

3.2 下订单获取prepay_id

代码如下,实际上是通过post发送一个xml 文件,获取微信服务器端发送过来的prepay_id。

import java.io.ByteArrayInputStream;

import javaioIOException;

import javaioInputStream;

import javaioUnsupportedEncodingException;

import javautilDate;

import javautilHashMap;

import javautilIterator;

import javautilMap;

import javautilMapEntry;

import javautilRandom;

import javaxservlethttpHttpServletRequest;

import javaxservlethttpHttpServletResponse;

import orgapachecommonscodecdigestDigestUtils;

import orgspringframeworkstereotypeController;

import orgspringframeworkwebbindannotationRequestMapping;

import orgxmlpullvXmlPullParser;

import orgxmlpullvXmlPullParserException;

import orgxmlpullvXmlPullParserFactory;

import comfasterxmljacksondatabindJsonNode;

import comgsonoauthOauth;

import comgsonoauthPay;

import comgsonutilHttpKit;

import comsyutilDatetimeUtil;

import comsyutilJsonUtil;

@Controller

@RequestMapping("/pay")

public class WXPayController {

@RequestMapping(value = "wxprepaydo")

public void jspay(HttpServletRequest request, HttpServletResponse response, String callback) throws Exception {

// 获取openid

String openId = SessionUtilgetAtt(request, "openId");

if (openId == null) {

openId = getUserOpenId(request);

}

String appid = "wx16691fcb0523c1a4";

String paternerKey = "ININGFENG1234567fdfwfdfd1ss234567";

String out_trade_no = getTradeNo();

Map paraMap = new HashMap();

paraMapput("appid", appid);

paraMapput("attach", "测试");

paraMapput("body", "测试购买支付");

paraMapput("mch_id", "10283271");

paraMapput("nonce_str", create_nonce_str());

paraMapput("openid", openId);

paraMapput("out_trade_no", out_trade_no);

paraMapput("spbill_create_ip", getAddrIp(request));

paraMapput("total_fee", "1");

paraMapput("trade_type", "JSAPI");

paraMapput("notify_url", "http://wwwxxxco/bank/page/wxnotify");

String sign = getSign(paraMap, paternerKey);

paraMapput("sign", sign);

// 统一下单 https://apimchweixinqqcom/pay/unifiedorder

String url = "https://apimchweixinqqcom/pay/unifiedorder";

String xml = ArrayToXml(paraMap);

String xmlStr = HttpKitpost(url, xml);

// 预付商品id

String prepay_id = "";

if (xmlStrindexOf("SUCCESS") != -1) {

Map map = doXMLParse(xmlStr);

prepay_id = (String) mapget("prepay_id");

}

Map payMap = new HashMap();

payMapput("appId", appid);

payMapput("timeStamp", create_timestamp());

payMapput("nonceStr", create_nonce_str());

payMapput("signType", "MD5");

payMapput("package", "prepay_id=" + prepay_id);

String paySign = getSign(payMap, paternerKey);

payMapput("pg", prepay_id);

payMapput("paySign", paySign);

WebUtilresponse(response, WebUtilpackJsonp(callback, JsonUtilwarpJsonNodeResponse(JsonUtilobjectToJsonNode(payMap))toString()));

}

/**

* map转成xml

*

* @param arr

* @return

*/

public String ArrayToXml(Map arr) {

String xml = "";

Iterator> iter = arrentrySet()iterator();

while (iterhasNext()) {

Entry entry = iternext();

String key = entrygetKey();

String val = entrygetValue();

xml += "<" + key + ">" + val + "" + key + ">";

}

xml += "";

return xml;

}

// 获取openId

private String getUserOpenId(HttpServletRequest request) throws Exception {

String code = requestgetParameter("code");

if (code == null) {

String openId = requestgetParameter("openId");

return openId;

}

Oauth o = new Oauth();

String token = ogetToken(code);

JsonNode node = JsonUtilStringToJsonNode(token);

String openId = nodeget("openid")asText();

return openId;

}

private String create_nonce_str() {

String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";

String res = "";

for (int i = 0; i < 16; i++) {

Random rd = new Random();

res += charscharAt(rdnextInt(charslength() - 1));

}

return res;

}

private String getAddrIp(HttpServletRequest request){

return requestgetRemoteAddr();

}

private String create_timestamp() {

return LongtoString(SystemcurrentTimeMillis() / 1000);

}

private String getTradeNo(){

String timestamp = DatetimeUtilformatDate(new Date(), DatetimeUtilDATETIME_PATTERN);

return "HZNO" + timestamp;

}

private String getSign(Map params, String paternerKey )

throws UnsupportedEncodingException {

String string1 = PaycreateSign(params, false);

String stringSignTemp = string1 + "&key=" + paternerKey;

String signValue = DigestUtilsmd5Hex(stringSignTemp)toUpperCase();

return signValue;

}

private Map doXMLParse(String xml)

throws XmlPullParserException, IOException {

InputStream inputStream = new ByteArrayInputStream(xmlgetBytes());

Map map = null;

XmlPullParser pullParser = XmlPullParserFactorynewInstance()

newPullParser();

pullParsersetInput(inputStream, "UTF-8"); // 为xml设置要解析的xml数据

int eventType = pullParsergetEventType();

while (eventType != XmlPullParserEND_DOCUMENT) {

switch (eventType) {

case XmlPullParserSTART_DOCUMENT:

map = new HashMap();

break;

case XmlPullParserSTART_TAG:

String key = pullParsergetName();

if (keyequals("xml"))

break;

String value = pullParsernextText();

mapput(key, value);

break;

case XmlPullParserEND_TAG:

break;

}

eventType = pullParsernext();

}

return map;

}

}

四、H5支付

H5支付其实很简单,只需要调用微信内嵌浏览器的js方法就行(http://pay.weixin.qq.com/wiki/doc/api/index.php?chapter=7_7)

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>

<%@ taglib prefix="spring" uri="http://wwwspringframeworkorg/tags" %>

<%

String path = requestgetContextPath();

String basePath = requestgetScheme() + "://" + requestgetServerName() + ":" + requestgetServerPort() + path + "/";

%>

立即支付

效果如下


版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:UrlRewrite 重写url详解及实例
下一篇:DOM 事件的深入浅出(二)
相关文章

 发表评论

暂时没有评论,来抢沙发吧~