java微信支付功能实现源码
程序员文章站
2022-07-26 11:17:37
提示:仅微信支付功能模块类,可供参考,可点赞一、java后台实现源码package cn.xydx.crowdfunding.controller;import cn.xydx.crowdfundin...
提示:仅微信支付功能模块类,可供参考,可点赞
一、java后台实现源码
package cn.xydx.crowdfunding.controller; import cn.xydx.crowdfunding.util.httprequest; import cn.xydx.crowdfunding.util.wxpayutil; import org.json.jsonobject; import org.springframework.stereotype.controller; import org.springframework.web.bind.annotation.crossorigin; import org.springframework.web.bind.annotation.requestmapping; import org.springframework.web.bind.annotation.requestmethod; import org.springframework.web.bind.annotation.responsebody; import javax.servlet.http.httpservletrequest; import java.text.dateformat; import java.text.simpledateformat; import java.util.date; import java.util.hashmap; import java.util.map; import java.util.random; import static cn.xydx.crowdfunding.util.wxpayconfig.appid; import static cn.xydx.crowdfunding.util.wxpayconfig.appsecret; import static cn.xydx.crowdfunding.util.wxpayconfig.mch_id; import static cn.xydx.crowdfunding.util.wxpayconfig.key; @controller @requestmapping(value = "weixinservice") @crossorigin public class weixinpaycontroller { /** * @param request * @param code * @return map * @description 微信浏览器内微信支付/公众号支付(jsapi) */ @requestmapping(value = "orders", method = requestmethod.get) @responsebody public map orders(httpservletrequest request, string code) { try { //页面获取openid接口 string getopenid_url = "https://api.weixin.qq.com/sns/oauth2/access_token"; string param = "appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code"; // 向微信服务器发送get请求获取openidstr string openidstr = httprequest.sendget(getopenid_url, param); // jsonobject json = jsonobject.parseobject(openidstr);//转成json格式 jsonobject json = new jsonobject(openidstr); string openid = json.getstring("openid");//获取openid //拼接统一下单地址参数 map<string, string> paramap = new hashmap<string, string>(); //获取请求ip地址 string ip = request.getheader("x-forwarded-for"); if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getheader("proxy-client-ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getheader("wl-proxy-client-ip"); } if (ip == null || ip.length() == 0 || "unknown".equalsignorecase(ip)) { ip = request.getremoteaddr(); } if (ip.indexof(",") != -1) { string[] ips = ip.split(","); ip = ips[0].trim(); } paramap.put("appid", appid); paramap.put("mch_id", mch_id); paramap.put("nonce_str", wxpayutil.generatenoncestr()); paramap.put("body", "crowdfund"); paramap.put("out_trade_no", getordersn());//订单号 paramap.put("total_fee", "1"); paramap.put("spbill_create_ip", ip); paramap.put("notify_url", "http://******/index.html");// 此路径是微信服务器调用支付结果通知路径随意写 paramap.put("trade_type", "jsapi"); paramap.put("openid", openid); string sign = wxpayutil.generatesignature(paramap, key); paramap.put("sign", sign); string xml = wxpayutil.maptoxml(paramap);//将所有参数(map)转xml格式 // system.out.println("xml="+xml); // 统一下单 string unifiedorder_url = "https://api.mch.weixin.qq.com/pay/unifiedorder"; string xmlstr = httprequest.sendpost(unifiedorder_url, xml);//发送post请求"统一下单接口"返回预支付id:prepay_id system.out.println(xmlstr); //以下内容是返回前端页面的json数据 string prepay_id = "";//预支付id if (xmlstr.indexof("success") != -1) { map<string, string> map = wxpayutil.xmltomap(xmlstr); prepay_id = (string) map.get("prepay_id"); } map<string, string> paymap = new hashmap<string, string>(); paymap.put("appid", appid); paymap.put("timestamp", wxpayutil.getcurrenttimestamp() + ""); paymap.put("noncestr", wxpayutil.generatenoncestr()); paymap.put("signtype", "md5"); paymap.put("package", "prepay_id=" + prepay_id); string paysign = wxpayutil.generatesignature(paymap, key); paymap.put("paysign", paysign); // system.out.println("code="+code); system.out.println("openidstr="+openidstr); return paymap; } catch (exception e) { e.printstacktrace(); } return null; } public string getordersn() { //创建不同的日期格式 dateformat df = new simpledateformat("yyyymmddhhmmss"); random rm = new random(); // 获得随机数 double pross = (1 + rm.nextdouble()) * math.pow(10, 6); // 将获得的获得随机数转化为字符串 string fixlenthstring = string.valueof(pross); string datenum = df.format(new date()) + "wx" + fixlenthstring.substring(1,7); return datenum; } @requestmapping(value = "orderquery", method = requestmethod.get) @responsebody public string orderquery() { try { map<string, string> reqmap = new hashmap<string, string>(); reqmap.put("appid", appid); reqmap.put("mch_id", mch_id); reqmap.put("nonce_str", wxpayutil.generatenoncestr()); reqmap.put("out_trade_no", getordersn()); //商户系统内部的订单号, string sign = wxpayutil.generatesignature(reqmap, key); reqmap.put("sign", sign); string reqxmlstr = wxpayutil.maptoxml(reqmap);//将所有参数(map)转xml格式 // system.out.println("xml="+reqxmlstr); // 查询订单 https://api.mch.weixin.qq.com/pay/orderquery string orderquery = "https://api.mch.weixin.qq.com/pay/orderquery"; string xmlstr = httprequest.sendpost(orderquery, reqxmlstr); return xmlstr; } catch (exception e) { e.printstacktrace(); } return null; } }
httprequest 类
package cn.xydx.crowdfunding.util; import java.io.bufferedreader; import java.io.ioexception; import java.io.inputstreamreader; import java.io.printwriter; import java.net.url; import java.net.urlconnection; import java.util.list; import java.util.map; public class httputil { /** * 向指定url发送get方法的请求 * * @param url 发送请求的url * //@param param 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。 * @return url 所代表远程资源的响应结果 */ public static string sendget(string url) { string result = ""; bufferedreader in = null; try { string urlnamestring = url ; 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; } }
wxpayutil 类
package cn.xydx.crowdfunding.util; import cn.xydx.crowdfunding.util.wxpayconstants.signtype; import org.slf4j.logger; import org.slf4j.loggerfactory; import org.w3c.dom.node; import org.w3c.dom.nodelist; import javax.crypto.mac; import javax.crypto.spec.secretkeyspec; import javax.xml.parsers.documentbuilder; import javax.xml.transform.outputkeys; import javax.xml.transform.transformer; import javax.xml.transform.transformerfactory; import javax.xml.transform.dom.domsource; import javax.xml.transform.stream.streamresult; import java.io.bytearrayinputstream; import java.io.inputstream; import java.io.stringwriter; import java.security.messagedigest; import java.security.securerandom; import java.util.*; public class wxpayutil { private static final string symbols = "0123456789abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"; private static final random random = new securerandom(); /** * xml格式字符串转换为map * * @param strxml xml字符串 * @return xml数据转换后的map * @throws exception */ public static map<string, string> xmltomap(string strxml) throws exception { try { map<string, string> data = new hashmap<string, string>(); documentbuilder documentbuilder = wxpayxmlutil.newdocumentbuilder(); inputstream stream = new bytearrayinputstream(strxml.getbytes("utf-8")); org.w3c.dom.document doc = documentbuilder.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() == node.element_node) { org.w3c.dom.element element = (org.w3c.dom.element) node; data.put(element.getnodename(), element.gettextcontent()); } } try { stream.close(); } catch (exception ex) { // do nothing } return data; } catch (exception ex) { wxpayutil.getlogger().warn("invalid xml, can not convert to map. error message: {}. xml content: {}", ex.getmessage(), strxml); throw ex; } } /** * 将map转换为xml格式的字符串 * * @param data map类型数据 * @return xml格式的字符串 * @throws exception */ public static string maptoxml(map<string, string> data) throws exception { org.w3c.dom.document document = wxpayxmlutil.newdocument(); org.w3c.dom.element root = document.createelement("xml"); document.appendchild(root); for (string key: data.keyset()) { string value = data.get(key); if (value == null) { value = ""; } value = value.trim(); org.w3c.dom.element filed = document.createelement(key); filed.appendchild(document.createtextnode(value)); root.appendchild(filed); } transformerfactory tf = transformerfactory.newinstance(); transformer transformer = tf.newtransformer(); domsource source = new domsource(document); transformer.setoutputproperty(outputkeys.encoding, "utf-8"); transformer.setoutputproperty(outputkeys.indent, "yes"); stringwriter writer = new stringwriter(); streamresult result = new streamresult(writer); transformer.transform(source, result); string output = writer.getbuffer().tostring(); //.replaceall("\n|\r", ""); try { writer.close(); } catch (exception ex) { } return output; } /** * 生成带有 sign 的 xml 格式字符串 * * @param data map类型数据 * @param key api密钥 * @return 含有sign字段的xml */ public static string generatesignedxml(final map<string, string> data, string key) throws exception { return generatesignedxml(data, key, signtype.md5); } /** * 生成带有 sign 的 xml 格式字符串 * * @param data map类型数据 * @param key api密钥 * @param signtype 签名类型 * @return 含有sign字段的xml */ public static string generatesignedxml(final map<string, string> data, string key, signtype signtype) throws exception { string sign = generatesignature(data, key, signtype); data.put(wxpayconstants.field_sign, sign); return maptoxml(data); } /** * 判断签名是否正确 * * @param xmlstr xml格式数据 * @param key api密钥 * @return 签名是否正确 * @throws exception */ public static boolean issignaturevalid(string xmlstr, string key) throws exception { map<string, string> data = xmltomap(xmlstr); if (!data.containskey(wxpayconstants.field_sign) ) { return false; } string sign = data.get(wxpayconstants.field_sign); return generatesignature(data, key).equals(sign); } /** * 判断签名是否正确,必须包含sign字段,否则返回false。使用md5签名。 * * @param data map类型数据 * @param key api密钥 * @return 签名是否正确 * @throws exception */ public static boolean issignaturevalid(map<string, string> data, string key) throws exception { return issignaturevalid(data, key, signtype.md5); } /** * 判断签名是否正确,必须包含sign字段,否则返回false。 * * @param data map类型数据 * @param key api密钥 * @param signtype 签名方式 * @return 签名是否正确 * @throws exception */ public static boolean issignaturevalid(map<string, string> data, string key, signtype signtype) throws exception { if (!data.containskey(wxpayconstants.field_sign) ) { return false; } string sign = data.get(wxpayconstants.field_sign); return generatesignature(data, key, signtype).equals(sign); } /** * 生成签名 * * @param data 待签名数据 * @param key api密钥 * @return 签名 */ public static string generatesignature(final map<string, string> data, string key) throws exception { return generatesignature(data, key, signtype.md5); } /** * 生成签名. 注意,若含有sign_type字段,必须和signtype参数保持一致。 * * @param data 待签名数据 * @param key api密钥 * @param signtype 签名方式 * @return 签名 */ public static string generatesignature(final map<string, string> data, string key, signtype signtype) throws exception { set<string> keyset = data.keyset(); string[] keyarray = keyset.toarray(new string[keyset.size()]); arrays.sort(keyarray); stringbuilder sb = new stringbuilder(); for (string k : keyarray) { if (k.equals(wxpayconstants.field_sign)) { continue; } if (data.get(k).trim().length() > 0) // 参数值为空,则不参与签名 sb.append(k).append("=").append(data.get(k).trim()).append("&"); } sb.append("key=").append(key); if (signtype.md5.equals(signtype)) { return md5(sb.tostring()).touppercase(); } else if (signtype.hmacsha256.equals(signtype)) { return hmacsha256(sb.tostring(), key); } else { throw new exception(string.format("invalid sign_type: %s", signtype)); } } /** * 获取随机字符串 nonce str * * @return string 随机字符串 */ public static string generatenoncestr() { char[] noncechars = new char[32]; for (int index = 0; index < noncechars.length; ++index) { noncechars[index] = symbols.charat(random.nextint(symbols.length())); } return new string(noncechars); } /** * 生成 md5 * * @param data 待处理数据 * @return md5结果 */ public static string md5(string data) throws exception { java.security.messagedigest md = messagedigest.getinstance("md5"); byte[] array = md.digest(data.getbytes("utf-8")); stringbuilder sb = new stringbuilder(); for (byte item : array) { sb.append(integer.tohexstring((item & 0xff) | 0x100).substring(1, 3)); } return sb.tostring().touppercase(); } /** * 生成 hmacsha256 * @param data 待处理数据 * @param key 密钥 * @return 加密结果 * @throws exception */ public static string hmacsha256(string data, string key) throws exception { mac sha256_hmac = mac.getinstance("hmacsha256"); secretkeyspec secret_key = new secretkeyspec(key.getbytes("utf-8"), "hmacsha256"); sha256_hmac.init(secret_key); byte[] array = sha256_hmac.dofinal(data.getbytes("utf-8")); stringbuilder sb = new stringbuilder(); for (byte item : array) { sb.append(integer.tohexstring((item & 0xff) | 0x100).substring(1, 3)); } return sb.tostring().touppercase(); } /** * 日志 * @return */ public static logger getlogger() { logger logger = loggerfactory.getlogger("wxpay java sdk"); return logger; } /** * 获取当前时间戳,单位秒 * @return */ public static long getcurrenttimestamp() { return system.currenttimemillis()/1000; } /** * 获取当前时间戳,单位毫秒 * @return */ public static long getcurrenttimestampms() { return system.currenttimemillis(); } }
二、前端支付关键模块
<li><a href="https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx49bdfbb5fa7144**&redirect_uri=http://******/order.html&response_type=code&scope=snsapi_base#wechat_redirect" rel="external nofollow" >立即订购</a></li>
需要上面的连接获取code
//获取code function getquerystring(name) { var reg = new regexp("(^|&)" + name + "=([^&]*)(&|$)", "i"); var r = window.location.search.substr(1).match(reg); if (r != null) return unescape(r[2]); return null; }
var code = getquerystring("code"); if (code) { var url = "http://******/weixinservice/orders?code=" + code + ""; $.get(url, function (data) { var appid = data.appid; var timestamp = data.timestamp; var noncestr = data.noncestr; var package = data.package; var signtype = data.signtype; var paysign = data.paysign; 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(); weixinjsbridge.invoke('getbrandwcpayrequest', { "appid": appid, //公众号名称,由商户传入 "timestamp": timestamp, //时间戳,自1970年以来的秒数 "noncestr": noncestr, //随机串 "package": package, "signtype": signtype, //微信签名方式: "paysign": paysign //微信签名 }, function (res) { if (res.err_msg == "get_brand_wcpay_request:ok") { //console.log('支付成功'); // 支付成功后比如新增数据 $.post("http://******/saveuser", { username: $('#inputname').val(), useridentity: $('#inputidentity').val(), companyname: $('#inputcompany').val(), userphone: $('#inputphone').val() }, function (data, status) { alert("数据: \n你好!" + $('#inputname').val() + "\n状态: " + status); }, "json" ); //支付成功后跳转的页面 alert("支付成功!将返回首页!请分享******!"); window.history.go(-1); } else if (res.err_msg == "get_brand_wcpay_request:cancel") { //console.log('支付取消'); alert("支付取消!保证数据安全 重新参加订购!"); //weixinjsbridge.call('closewindow'); window.history.go(-1); } else if (res.err_msg == "get_brand_wcpay_request:fail") { //console.log('支付失败'); alert("支付失败!重复支付,建议稍后参加订购"); weixinjsbridge.call('closewindow'); } //使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回ok,但并不保证它绝对可靠。 }); } }, "json") } else { alert("服务器异常") }
提示:前端关键通过http连接生成code。后端最后获取reqxmlstr若不成功,可重置商户秘钥key。
总结
到此这篇关于java微信支付功能实现源码的文章就介绍到这了,更多相关java微信支付功能源码内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!