代码语言
.
CSharp
.
JS
Java
Asp.Net
C
MSSQL
PHP
Css
PLSQL
Python
Shell
EBS
ASP
Perl
ObjC
VB.Net
VBS
MYSQL
GO
Delphi
AS
DB2
Domino
Rails
ActionScript
Scala
代码分类
文件
系统
字符串
数据库
网络相关
图形/GUI
多媒体
算法
游戏
Jquery
Extjs
Android
HTML5
菜单
网页交互
WinForm
控件
企业应用
安全与加密
脚本/批处理
开放平台
其它
【
C
】
微信公众号支付
作者:
zyjason91
/ 发布于
2015/8/3
/
1309
微信公众号支付的总体其实很简单,大致就分为三步。第一步需要获取用户授权;第二步调用统一下单接口获取预支付id;第三步H5调起微信支付的内置的js。
第一步需要获取用户授权; //获取openId HttpClientUtil util = HttpClientUtil.getInstance(); Map<String, String> map = new HashMap<String, String>(); map.put("appid", WxPayConfig.APPID); map.put("secret", WxPayConfig.APPSECRET); map.put("code", code); map.put("grant_type", WxPayConfig.GRANT_TYPE); String returnStr = util.doPostRetString("https://api.weixin.qq.com/sns/oauth2/access_token", null,map); logger.info("returnStr:[" + returnStr + "]"); AccessToken at = JSON.parseObject(returnStr, AccessToken.class); AccessToken.java public class AccessToken { private String access_token; private String expires_in; private String refresh_token; private String openid; private String scope; private String unionid; public String getAccess_token() { return access_token; } public void setAccess_token(String access_token) { this.access_token = access_token; } public String getExpires_in() { return expires_in; } public void setExpires_in(String expires_in) { this.expires_in = expires_in; } public String getRefresh_token() { return refresh_token; } public void setRefresh_token(String refresh_token) { this.refresh_token = refresh_token; } public String getOpenid() { return openid; } public void setOpenid(String openid) { this.openid = openid; } public String getScope() { return scope; } public void setScope(String scope) { this.scope = scope; } public String getUnionid() { return unionid; } public void setUnionid(String unionid) { this.unionid = unionid; } @Override public String toString() { return "AccessToken [access_token=" + access_token + ", expires_in=" + expires_in + ", refresh_token=" + refresh_token + ", openid=" + openid + ", scope=" + scope + ", unionid=" + unionid + "]"; } } 第二步调用统一下单接口获取预支付id; //统一下单 WxPaySendData data = new WxPaySendData(); data.setAppid(WxPayConfig.APPID); data.setAttach("微信支付"); data.setBody("微信公众号支付"); data.setMch_id(WxPayConfig.MCHID); data.setNonce_str(nonceStr); data.setNotify_url(WxPayConfig.NOTIFY_URL); data.setOut_trade_no(tradeNo); data.setTotal_fee((int)(fee*100));//单位:分 data.setTrade_type("JSAPI"); data.setSpbill_create_ip(ip); data.setOpenid(at.getOpenid()); String returnXml = UnifiedorderService.unifiedOrder(data,WxPayConfig.KEY); WxPayReturnData reData = new WxPayReturnData(); XStream xs1 = new XStream(new DomDriver()); xs1.alias("xml", WxPayReturnData.class); reData = (WxPayReturnData) xs1.fromXML(returnXml); UnifiedorderService.java public class UnifiedorderService { private final static Logger logger = LoggerFactory.getLogger(UnifiedorderService.class); public static String unifiedOrder(WxPaySendData data,String key){ //统一下单支付 String returnXml = null; try { //生成sign签名 SortedMap<Object,Object> parameters = new TreeMap<Object,Object>(); parameters.put("appid", data.getAppid()); parameters.put("attach", data.getAttach()); parameters.put("body", data.getBody()); parameters.put("mch_id", data.getMch_id()); parameters.put("nonce_str", data.getNonce_str()); parameters.put("notify_url", data.getNotify_url()); parameters.put("out_trade_no", data.getOut_trade_no()); parameters.put("total_fee", data.getTotal_fee()); parameters.put("trade_type", data.getTrade_type()); parameters.put("spbill_create_ip", data.getSpbill_create_ip()); parameters.put("openid", data.getOpenid()); parameters.put("device_info", data.getDevice_info()); logger.info("SIGN:"+WxSign.createSign(parameters,key)); data.setSign(WxSign.createSign(parameters,key)); XStream xs = new XStream(new DomDriver("UTF-8",new XmlFriendlyNameCoder("-_", "_"))); xs.alias("xml", WxPaySendData.class); String xml = xs.toXML(data); logger.info("统一下单xml为:\n" + xml); HttpClientUtil util = HttpClientUtil.getInstance(); returnXml = util.doPostForString("https://api.mch.weixin.qq.com/pay/unifiedorder", null, xml); logger.info("返回结果:" + returnXml); } catch (Exception e) { e.printStackTrace(); } return returnXml; } } WxSign public class WxSign { private static String characterEncoding = "UTF-8"; @SuppressWarnings("rawtypes") public static String createSign(SortedMap<Object,Object> parameters,String key){ StringBuffer sb = new StringBuffer(); Set es = parameters.entrySet();//所有参与传参的参数按照accsii排序(升序) Iterator it = es.iterator(); while(it.hasNext()) { Map.Entry entry = (Map.Entry)it.next(); String k = (String)entry.getKey(); Object v = entry.getValue(); if(null != v && !"".equals(v) && !"sign".equals(k) && !"key".equals(k)) { sb.append(k + "=" + v + "&"); } } sb.append("key=" + key); String sign = MD5Util.MD5Encode(sb.toString(), characterEncoding).toUpperCase(); return sign; } public static String getNonceStr() { Random random = new Random(); return MD5Util.MD5Encode(String.valueOf(random.nextInt(10000)), "UTF-8"); } public static String getTimeStamp() { return String.valueOf(System.currentTimeMillis() / 1000); } } 第三步H5调起微信支付的内置的js //H5调起支付 attr.addAttribute("appId", reData.getAppid()); attr.addAttribute("timeStamp", WxSign.getTimeStamp()); attr.addAttribute("nonceStr", reData.getNonce_str()); attr.addAttribute("package", "prepay_id="+reData.getPrepay_id()); attr.addAttribute("signType", "MD5"); SortedMap<Object,Object> signMap = new TreeMap<Object,Object>(); signMap.put("appId", reData.getAppid()); signMap.put("timeStamp", WxSign.getTimeStamp()); signMap.put("nonceStr", reData.getNonce_str()); signMap.put("package", "prepay_id="+reData.getPrepay_id()); signMap.put("signType", "MD5"); logger.info("PaySIGN:"+WxSign.createSign(signMap,WxPayConfig.KEY)); attr.addAttribute("paySign", WxSign.createSign(signMap,WxPayConfig.KEY)); <script> function getUrlParam(name) { //构造一个含有目标参数的正则表达式对象 var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //匹配目标参数 var r = window.location.search.substr(1).match(reg); //返回参数值 if (r != null) return unescape(r[2]); return null; } function onBridgeReady() { var appId = getUrlParam('appId'); var timeStamp = getUrlParam('timeStamp'); var nonceStr = getUrlParam('nonceStr'); var Package = getUrlParam('package'); var signType = getUrlParam('signType'); var paySign = getUrlParam('paySign'); WeixinJSBridge.invoke('getBrandWCPayRequest', { "appId" : appId,//"wx2421b1c4370ec43b", //公众号名称,由商户传入 "timeStamp" : timeStamp,//"1395712654", //时间戳,自1970年以来的秒数 "nonceStr" : nonceStr,//"e61463f8efa94090b1f366cccfbbb444", //随机串 "package" : Package,//"prepay_id=u802345jgfjsdfgsdg888", "signType" : signType,//"MD5", //微信签名方式: "paySign" : paySign,//"70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 }, function(res) { // 使用以上方式判断前端返回,微信团队郑重提示:res.err_msg将在用户支付成功后返回 ok,但并不保证它绝对可靠。 //alert(res.err_msg); if (res.err_msg == "get_brand_wcpay_request:ok") { alert("支付成功"); } if (res.err_msg == "get_brand_wcpay_request:cancel") { alert("交易取消"); } if (res.err_msg == "get_brand_wcpay_request:fail") { alert("支付失败"); } }); } 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>
试试其它关键字
微信公众号支付
公众号支付
微信
同语言下
.
获取手机通讯录 iOS去除数字以外的所有字符
.
异步加载音乐等资源
.
交通罚单管理系统
.
freemark实现,简单的替换
.
计算斐波那契数列
.
base64解码 包括解码长度
.
图像显示
.
冒泡排序
.
输入十进制数,输出指定进制
.
链式栈
可能有用的
.
C#实现的html内容截取
.
List 切割成几份 工具类
.
SQL查询 多列合并成一行用逗号隔开
.
一行一行读取txt的内容
.
C#动态修改文件夹名称(FSO实现,不移动文件)
.
c# 移动文件或文件夹
.
c#图片添加水印
.
Java PDF转换成图片并输出给前台展示
.
网站后台修改图片尺寸代码
.
处理大图片在缩略图时的展示
zyjason91
贡献的其它代码
(
3
)
.
微信公众号支付
.
微信公众号支付
.
JSON转换
Copyright © 2004 - 2024 dezai.cn. All Rights Reserved
站长博客
粤ICP备13059550号-3