子webview中使用地图
5+的demo中介绍了如何使用内置地图,方式是单webview,即延时初始化map,并调用webview的show函数。
当我想在tabbar的某个子页面(非首页)中使用地图时,我发现,如果子页面按5+的demo写(调用show),那么地图页会覆盖首页;如果不调用子webview的show函数,虽然不覆盖首页,但切换后,地图不显示。上述现象只出现在android上。
似乎地图只能在单webview下使用才合适。
经过大量测试,暂时找到了规避方法(不知道算不算解决方法,有人提过类似的问题,但不知道是不屑还是讳莫如深,没人回答),即在创建子webview后,在自己的plusready中调用hide函数。
plus.webview.currentWebview().hide();
注意:只能是自己的plusready,在父页面中创建子webview后,调用hide函数无效。
这种规避方法只是在目前官方没有解答的情况下使用,期待官方的正式解决方案或者说使用指南。
5+的demo中介绍了如何使用内置地图,方式是单webview,即延时初始化map,并调用webview的show函数。
当我想在tabbar的某个子页面(非首页)中使用地图时,我发现,如果子页面按5+的demo写(调用show),那么地图页会覆盖首页;如果不调用子webview的show函数,虽然不覆盖首页,但切换后,地图不显示。上述现象只出现在android上。
似乎地图只能在单webview下使用才合适。
经过大量测试,暂时找到了规避方法(不知道算不算解决方法,有人提过类似的问题,但不知道是不屑还是讳莫如深,没人回答),即在创建子webview后,在自己的plusready中调用hide函数。
plus.webview.currentWebview().hide();
注意:只能是自己的plusready,在父页面中创建子webview后,调用hide函数无效。
这种规避方法只是在目前官方没有解答的情况下使用,期待官方的正式解决方案或者说使用指南。
收起阅读 »h5+教程、mui教程、各类app开发实战教程更新中,一起努力共同进步!!
mui
hcoder 一直致力于奉献高质量的视频教程,官网上 mui、h5 等免费教程播放量已经达到10万+。
教程汇总
实战 : HUI APP实战教程 - 仿《京东优选》电商项目
知识点 : JavaScript 快速提高视频教程
实战: MUI、H5 APP 实战教程 - 仿《有道词典》
知识点 : HBuilder 8.0.1 APP开发 - 新功能全接触
知识点 : APP开发教程 - 启动动画
知识点 : APP开发实例教程 - 窗口切换
知识点 : 移动端图片剪裁、上传视频教程
知识点 : app开发教程-用户注册、登录
实战 : APP开发实战 - 新闻客户端
知识点 : HTML 5 开发教程
知识点 : mui 全套教程、 H5+ 沉浸式状态栏详解 、h5+ 地图api
mui
hcoder 一直致力于奉献高质量的视频教程,官网上 mui、h5 等免费教程播放量已经达到10万+。
教程汇总
实战 : HUI APP实战教程 - 仿《京东优选》电商项目
知识点 : JavaScript 快速提高视频教程
实战: MUI、H5 APP 实战教程 - 仿《有道词典》
知识点 : HBuilder 8.0.1 APP开发 - 新功能全接触
知识点 : APP开发教程 - 启动动画
知识点 : APP开发实例教程 - 窗口切换
知识点 : 移动端图片剪裁、上传视频教程
知识点 : app开发教程-用户注册、登录
实战 : APP开发实战 - 新闻客户端
知识点 : HTML 5 开发教程
知识点 : mui 全套教程、 H5+ 沉浸式状态栏详解 、h5+ 地图api
教程地址
http://www.hcoder.net/course/index/cate/4
pullRefresh 安卓无法滑动,iOS正常
正在写一个设备列表的下拉刷新页面,base的代码是从别的页面copy过来。加上下拉刷新后,下拉刷新正常使用,但是在Android手机上列表滑动时候感觉move事件被谁给吃了,列表滑动很是费力。iOS正常,经过与demo相比,发现一个大坑,给小伙伴们提个醒:
mui.init({
pullRefresh: {
container: '#pullrefresh',
down: {
contentdown: "下拉可以刷新",
contentover: "释放立即刷新",
contentrefresh: "正在TM刷新",
callback: refreshDeviceList
}
}
});
mui.plusReady(function() {
//注意:列表的自动滑动属性会影响滑动效果,必须注释掉
//mui('.mui-scroll-wrapper').scroll();
if(mui.os.android) {
setTimeout('refreshDeviceList()', 800);
} else {
refreshDeviceList();
}
});
注意mui('.mui-scroll-wrapper').scroll();这句话,会影响下拉刷新嵌套的列表的滑动效果,直接去掉,一切正常了。
正在写一个设备列表的下拉刷新页面,base的代码是从别的页面copy过来。加上下拉刷新后,下拉刷新正常使用,但是在Android手机上列表滑动时候感觉move事件被谁给吃了,列表滑动很是费力。iOS正常,经过与demo相比,发现一个大坑,给小伙伴们提个醒:
mui.init({
pullRefresh: {
container: '#pullrefresh',
down: {
contentdown: "下拉可以刷新",
contentover: "释放立即刷新",
contentrefresh: "正在TM刷新",
callback: refreshDeviceList
}
}
});
mui.plusReady(function() {
//注意:列表的自动滑动属性会影响滑动效果,必须注释掉
//mui('.mui-scroll-wrapper').scroll();
if(mui.os.android) {
setTimeout('refreshDeviceList()', 800);
} else {
refreshDeviceList();
}
});
注意mui('.mui-scroll-wrapper').scroll();这句话,会影响下拉刷新嵌套的列表的滑动效果,直接去掉,一切正常了。
收起阅读 »git 的 "Push to Upstream" 变灰无法使用的解决方法
使用HBuilder 在本地创建项目后,当分享到git云端时,往往会出现无法提交到远程服务的问题(应该是git插件的原因)。
解决方法:
到该项目的根目录中的 ".git" 文件夹中找到 "config" 文件,打开并添加以下代码,已有的代码不用重复覆盖,填上你的git地址。
[core]
repositoryformatversion = 0
filemode = false
logallrefupdates = true
[remote "origin"]
url = 你的git地址
fetch = +refs/heads/:refs/remotes/origin/
[branch "master"]
remote = origin
merge = refs/heads/master
rebase = false
如果依然不能提交到远程服务,可参考该文章:http://blog.csdn.net/chenshun123/article/details/46756087
使用HBuilder 在本地创建项目后,当分享到git云端时,往往会出现无法提交到远程服务的问题(应该是git插件的原因)。
解决方法:
到该项目的根目录中的 ".git" 文件夹中找到 "config" 文件,打开并添加以下代码,已有的代码不用重复覆盖,填上你的git地址。
[core]
repositoryformatversion = 0
filemode = false
logallrefupdates = true
[remote "origin"]
url = 你的git地址
fetch = +refs/heads/:refs/remotes/origin/
[branch "master"]
remote = origin
merge = refs/heads/master
rebase = false
如果依然不能提交到远程服务,可参考该文章:http://blog.csdn.net/chenshun123/article/details/46756087
收起阅读 »纯jsp实现微信支付,无需Java程序,完整绿色版复制即可用!
本代码优点:无需依赖java程序,两个jsp文件走天下,方便多个项目复制使用,完整绿色无污染!
吐槽一下腾讯,给的示例代码太复杂不好调试,直接给个简单能跑通的多好,先能跑通再加复杂逻辑才是王道!
1、先要有微信开放平台的账号,并创建应用,审核通过。并且获取微信支付能力。
2、创建应用在填写Android的签名的时候要去掉冒号,并且小写(备注: 签名是用的md5 )
3、微信支付,一定要打包为apk 格式的文件,并且需要用到自己的keystore证书
4、打包好的apk文件,安装在手机测试
废话不多说,上代码:
1、HBuilder端js代码,放个按钮调用doWxPay()方法即可:
var channels = null;
mui.plusReady(function() {
// 获取支付通道
plus.payment.getChannels(function(cs) {
channels = cs;
}, function(e) {
alert("获取支付通道失败:" + e.message);
});
});
var w=null;
function doWxPay() {
if (w) return;
w = plus.nativeUI.showWaiting();
//获取支付通道
var channel;
for(var i in channels) {
if(channels[i].id == "wxpay") {
channel = channels[i];
}
}
mui.ajax('http://www.mywebsitexxx.com/pay_wx.jsp', {
data: {
total: "1", //支付金额1分
body: "Test", //支付界面标题
out_trade_no: "123456789" //订单编号
},
type: 'post',
dataType: 'text',
timeout:20000,
success: function(data) {
w.close();
w = null;
data=data.replace(/\r\n/g,"").trim();
console.log(data);
plus.payment.request(channel, data, saveSuccess, saveFail);
},
error: function(xhr, errorType, error) {
w.close();
w = null;
alert(" error:"+error);
}
});
}
function saveSuccess(){
mui.toast("支付成功!");
}
function saveFail(error){
alert("支付失败!"+JSON.stringify(error));
}
2、服务端jsp代码pay_wx.jsp,放在网站根目录:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="javax.xml.parsers.*"%>
<%@page import="javax.xml.transform.stream.*"%>
<%@page import="javax.xml.transform.*"%>
<%@page import="javax.xml.transform.dom.*"%>
<%@page import="java.security.MessageDigest"%>
<%@page import="org.apache.http.util.EntityUtils"%>
<%@page import="org.apache.http.client.HttpClient"%>
<%@page import="org.apache.http.*"%>
<%@page import="org.apache.http.entity.StringEntity"%>
<%@page import="org.apache.http.client.config.RequestConfig"%>
<%@page import="org.apache.http.client.methods.HttpPost"%>
<%@page import="org.apache.http.impl.client.HttpClientBuilder"%>
<%@page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory"%>
<%@page import="org.apache.http.conn.socket.PlainConnectionSocketFactory"%>
<%@page import="org.apache.http.conn.socket.ConnectionSocketFactory"%>
<%@page import="org.apache.http.config.RegistryBuilder"%>
<%@page import="org.apache.http.impl.conn.BasicHttpClientConnectionManager"%>
<%!
public static String AppID="wxea521866668888";//
public static String MchID="13866668888";//商户id
public static String Key="UNaaaaabbbb87349866668888";//支付秘钥key
public String httpsPost(String url, String data) throws Exception {
BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager)
.build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).build();
httpPost.setConfig(requestConfig);
StringEntity postEntity = new StringEntity(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(postEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
public static String randomStr(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
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();
}
public static String generateSignature(final Map<String, String> data, String key) 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) {
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
return MD5(sb.toString());
}
public static String mapToXml(Map<String, String> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.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;
}
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.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) {
}
return data;
} catch (Exception ex) {
throw ex;
}
}
%>
<%
HashMap<String, String> reqData = new HashMap<String, String>();
reqData.put("appid", AppID);
reqData.put("mch_id", MchID);
reqData.put("body", request.getParameter("body"));// 商品描述
reqData.put("out_trade_no", request.getParameter("out_trade_no")); // 商户订单号
reqData.put("total_fee", request.getParameter("total"));//支付金额
reqData.put("fee_type", "CNY");// 币种
reqData.put("spbill_create_ip", request.getRemoteAddr());
reqData.put("notify_url", "http://www.mywebsitexxx.com/webhook_wx.jsp");//微信回调notify页面
reqData.put("trade_type", "APP");
reqData.put("nonce_str",randomStr(20));
String sign = generateSignature(reqData, Key);
reqData.put("sign", sign);//打包签名
String reqBody = mapToXml(reqData);
String result = httpsPost("https://api.mch.weixin.qq.com/pay/unifiedorder", reqBody);
//System.out.println(result);
Map map = xmlToMap(result);
String prepay_id = (String) map.get("prepay_id");
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonce_str = randomStr(20);
String str = "appid=" + AppID + "&noncestr=" + nonce_str
+ "&package=Sign=WXPay" + "&partnerid=" + MchID
+ "&prepayid=" + prepay_id + "×tamp=" + timestamp
+ "&key=" + Key;
String newSign = MD5(str);
StringBuffer json = new StringBuffer();
json.append("{\"appid\":\"");
json.append(AppID);
json.append("\",\"noncestr\":\"");
json.append(nonce_str);
json.append("\",\"package\":\"");
json.append("Sign=WXPay");
json.append("\",\"partnerid\":\"");
json.append(MchID);
json.append("\",\"prepayid\":\"");
json.append(prepay_id);
json.append("\",\"timestamp\":");
json.append(timestamp);
json.append(",\"sign\":\"");
json.append(newSign);
json.append("\"}");
//System.out.println(json.toString());
out.print(json.toString());
%>
3、微信回调notify页面jsp代码webhook_wx.jsp,放在网站根目录:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="javax.xml.parsers.*"%>
<%!
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.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) {
}
return data;
} catch (Exception ex) {
throw ex;
}
}
%>
<%
StringBuffer xmlStr = new StringBuffer();
String line = null;
try {
request.setCharacterEncoding("utf-8");
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
xmlStr.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("微信支付:"+xmlStr);
Map data = xmlToMap(xmlStr.toString());
if("SUCCESS".equals(data.get("return_code"))
&& "SUCCESS".equals(data.get("result_code"))){
Double totalFee = new Double(data.get("total_fee").toString())/100;
//TODO:这里加判断逻辑,编写更新订单状态的代码,或直接调用写好的Java类
System.out.println(totalFee );
out.println("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
} catch (Exception e) {
e.printStackTrace();
}
}else{
out.println("ERROR");
}
%>
完毕,打包apk即可测试。
注:各种依赖jar包还得自行去下载。
本代码优点:无需依赖java程序,两个jsp文件走天下,方便多个项目复制使用,完整绿色无污染!
吐槽一下腾讯,给的示例代码太复杂不好调试,直接给个简单能跑通的多好,先能跑通再加复杂逻辑才是王道!
1、先要有微信开放平台的账号,并创建应用,审核通过。并且获取微信支付能力。
2、创建应用在填写Android的签名的时候要去掉冒号,并且小写(备注: 签名是用的md5 )
3、微信支付,一定要打包为apk 格式的文件,并且需要用到自己的keystore证书
4、打包好的apk文件,安装在手机测试
废话不多说,上代码:
1、HBuilder端js代码,放个按钮调用doWxPay()方法即可:
var channels = null;
mui.plusReady(function() {
// 获取支付通道
plus.payment.getChannels(function(cs) {
channels = cs;
}, function(e) {
alert("获取支付通道失败:" + e.message);
});
});
var w=null;
function doWxPay() {
if (w) return;
w = plus.nativeUI.showWaiting();
//获取支付通道
var channel;
for(var i in channels) {
if(channels[i].id == "wxpay") {
channel = channels[i];
}
}
mui.ajax('http://www.mywebsitexxx.com/pay_wx.jsp', {
data: {
total: "1", //支付金额1分
body: "Test", //支付界面标题
out_trade_no: "123456789" //订单编号
},
type: 'post',
dataType: 'text',
timeout:20000,
success: function(data) {
w.close();
w = null;
data=data.replace(/\r\n/g,"").trim();
console.log(data);
plus.payment.request(channel, data, saveSuccess, saveFail);
},
error: function(xhr, errorType, error) {
w.close();
w = null;
alert(" error:"+error);
}
});
}
function saveSuccess(){
mui.toast("支付成功!");
}
function saveFail(error){
alert("支付失败!"+JSON.stringify(error));
}
2、服务端jsp代码pay_wx.jsp,放在网站根目录:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="javax.xml.parsers.*"%>
<%@page import="javax.xml.transform.stream.*"%>
<%@page import="javax.xml.transform.*"%>
<%@page import="javax.xml.transform.dom.*"%>
<%@page import="java.security.MessageDigest"%>
<%@page import="org.apache.http.util.EntityUtils"%>
<%@page import="org.apache.http.client.HttpClient"%>
<%@page import="org.apache.http.*"%>
<%@page import="org.apache.http.entity.StringEntity"%>
<%@page import="org.apache.http.client.config.RequestConfig"%>
<%@page import="org.apache.http.client.methods.HttpPost"%>
<%@page import="org.apache.http.impl.client.HttpClientBuilder"%>
<%@page import="org.apache.http.conn.ssl.SSLConnectionSocketFactory"%>
<%@page import="org.apache.http.conn.socket.PlainConnectionSocketFactory"%>
<%@page import="org.apache.http.conn.socket.ConnectionSocketFactory"%>
<%@page import="org.apache.http.config.RegistryBuilder"%>
<%@page import="org.apache.http.impl.conn.BasicHttpClientConnectionManager"%>
<%!
public static String AppID="wxea521866668888";//
public static String MchID="13866668888";//商户id
public static String Key="UNaaaaabbbb87349866668888";//支付秘钥key
public String httpsPost(String url, String data) throws Exception {
BasicHttpClientConnectionManager connManager = new BasicHttpClientConnectionManager(
RegistryBuilder.<ConnectionSocketFactory>create()
.register("http", PlainConnectionSocketFactory.getSocketFactory())
.register("https", SSLConnectionSocketFactory.getSocketFactory())
.build(),
null,
null,
null
);
HttpClient httpClient = HttpClientBuilder.create()
.setConnectionManager(connManager)
.build();
HttpPost httpPost = new HttpPost(url);
RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(200000).setConnectTimeout(200000).build();
httpPost.setConfig(requestConfig);
StringEntity postEntity = new StringEntity(data, "UTF-8");
httpPost.addHeader("Content-Type", "text/xml");
httpPost.setEntity(postEntity);
HttpResponse httpResponse = httpClient.execute(httpPost);
HttpEntity httpEntity = httpResponse.getEntity();
return EntityUtils.toString(httpEntity, "UTF-8");
}
public static String randomStr(int length) {
String base = "abcdefghijklmnopqrstuvwxyz0123456789";
Random random = new Random();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < length; i++) {
int number = random.nextInt(base.length());
sb.append(base.charAt(number));
}
return sb.toString();
}
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();
}
public static String generateSignature(final Map<String, String> data, String key) 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) {
sb.append(k).append("=").append(data.get(k).trim()).append("&");
}
sb.append("key=").append(key);
return MD5(sb.toString());
}
public static String mapToXml(Map<String, String> data) throws Exception {
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder= documentBuilderFactory.newDocumentBuilder();
org.w3c.dom.Document document = documentBuilder.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;
}
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.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) {
}
return data;
} catch (Exception ex) {
throw ex;
}
}
%>
<%
HashMap<String, String> reqData = new HashMap<String, String>();
reqData.put("appid", AppID);
reqData.put("mch_id", MchID);
reqData.put("body", request.getParameter("body"));// 商品描述
reqData.put("out_trade_no", request.getParameter("out_trade_no")); // 商户订单号
reqData.put("total_fee", request.getParameter("total"));//支付金额
reqData.put("fee_type", "CNY");// 币种
reqData.put("spbill_create_ip", request.getRemoteAddr());
reqData.put("notify_url", "http://www.mywebsitexxx.com/webhook_wx.jsp");//微信回调notify页面
reqData.put("trade_type", "APP");
reqData.put("nonce_str",randomStr(20));
String sign = generateSignature(reqData, Key);
reqData.put("sign", sign);//打包签名
String reqBody = mapToXml(reqData);
String result = httpsPost("https://api.mch.weixin.qq.com/pay/unifiedorder", reqBody);
//System.out.println(result);
Map map = xmlToMap(result);
String prepay_id = (String) map.get("prepay_id");
String timestamp = String.valueOf(System.currentTimeMillis() / 1000);
String nonce_str = randomStr(20);
String str = "appid=" + AppID + "&noncestr=" + nonce_str
+ "&package=Sign=WXPay" + "&partnerid=" + MchID
+ "&prepayid=" + prepay_id + "×tamp=" + timestamp
+ "&key=" + Key;
String newSign = MD5(str);
StringBuffer json = new StringBuffer();
json.append("{\"appid\":\"");
json.append(AppID);
json.append("\",\"noncestr\":\"");
json.append(nonce_str);
json.append("\",\"package\":\"");
json.append("Sign=WXPay");
json.append("\",\"partnerid\":\"");
json.append(MchID);
json.append("\",\"prepayid\":\"");
json.append(prepay_id);
json.append("\",\"timestamp\":");
json.append(timestamp);
json.append(",\"sign\":\"");
json.append(newSign);
json.append("\"}");
//System.out.println(json.toString());
out.print(json.toString());
%>
3、微信回调notify页面jsp代码webhook_wx.jsp,放在网站根目录:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<%@page import="java.net.HttpURLConnection"%>
<%@page import="java.net.URL"%>
<%@page import="java.util.*"%>
<%@page import="java.io.*"%>
<%@page import="org.w3c.dom.*"%>
<%@page import="javax.xml.parsers.*"%>
<%!
public static Map<String, String> xmlToMap(String strXML) throws Exception {
try {
Map<String, String> data = new HashMap<String, String>();
DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder documentBuilder = documentBuilderFactory.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) {
}
return data;
} catch (Exception ex) {
throw ex;
}
}
%>
<%
StringBuffer xmlStr = new StringBuffer();
String line = null;
try {
request.setCharacterEncoding("utf-8");
BufferedReader reader = request.getReader();
while ((line = reader.readLine()) != null) {
xmlStr.append(line);
}
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("微信支付:"+xmlStr);
Map data = xmlToMap(xmlStr.toString());
if("SUCCESS".equals(data.get("return_code"))
&& "SUCCESS".equals(data.get("result_code"))){
Double totalFee = new Double(data.get("total_fee").toString())/100;
//TODO:这里加判断逻辑,编写更新订单状态的代码,或直接调用写好的Java类
System.out.println(totalFee );
out.println("<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
} catch (Exception e) {
e.printStackTrace();
}
}else{
out.println("ERROR");
}
%>
完毕,打包apk即可测试。
注:各种依赖jar包还得自行去下载。
快捷键混乱,设置无效
添加/取消缩进的快捷键和tab 切换的快捷键混乱在一起了,来提交BUG还说积分不够。。。尼玛真纠结被浪费的时间。。。
添加/取消缩进的快捷键和tab 切换的快捷键混乱在一起了,来提交BUG还说积分不够。。。尼玛真纠结被浪费的时间。。。
Hbuilder+MUI远程获取服务器数据显示出来
MUI前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.min.js"></script>
<link href="css/mui.min.css" rel="stylesheet"/>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<h1 class="mui-title">内容展示页</h1>
</header>
<div class="mui-content">
<div id="con">在这里就是我们要插入的远程数据内容(html)</div>
</div>
<script type="text/javascript">
/*
* @auth:韦小宝
* @weixin:8788981
* @qq:8788981
*/
mui.init();
mui.post('http://localhost/ThinkPHPAPI/',{
nid:'1'//这里通过POST发送数据到PHP服务器用以验证
},function(data){
//服务器返回响应,根据响应结果,分析是否登录成功;
var d=eval(data); //转换成javascript对象
var c=document.getElementById('con');
for(var i in d){
c.innerHTML=d[i].content;
}
},'json');
</script>
</body>
</html>
PHP接口实现代码:
代码基于thinkphp
<?php
/*
- @qq/weixin:8788981
-
@auth:weixiaobao
/
class IndexAction extends Action {
public function index(){
header("Content-Type:text/html; charset=utf-8");
header('Content-type:text/json');//输出为json格式页
header("Access-Control-Allow-Origin: "); // 允许任意域名发起的跨域请求
header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');/* 判断手机端发过来的信息(预先存储手机硬件信息)再进行数据的查询判断 * 这里只是通过明文的查询,不作动态的优化 * 希望大家发挥自己的想象力,做相应的远程判断,开发更快、更安全的APP */ if($_POST['nid']==1){ $Con=M("News_content"); $list=$Con->where("nid=1")->select(); echo json_encode($list); //输出json }}
}
?>
MUI前端代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
<title></title>
<script src="js/mui.min.js"></script>
<link href="css/mui.min.css" rel="stylesheet"/>
</head>
<body>
<header class="mui-bar mui-bar-nav">
<h1 class="mui-title">内容展示页</h1>
</header>
<div class="mui-content">
<div id="con">在这里就是我们要插入的远程数据内容(html)</div>
</div>
<script type="text/javascript">
/*
* @auth:韦小宝
* @weixin:8788981
* @qq:8788981
*/
mui.init();
mui.post('http://localhost/ThinkPHPAPI/',{
nid:'1'//这里通过POST发送数据到PHP服务器用以验证
},function(data){
//服务器返回响应,根据响应结果,分析是否登录成功;
var d=eval(data); //转换成javascript对象
var c=document.getElementById('con');
for(var i in d){
c.innerHTML=d[i].content;
}
},'json');
</script>
</body>
</html>
PHP接口实现代码:
代码基于thinkphp
<?php
/*
- @qq/weixin:8788981
-
@auth:weixiaobao
/
class IndexAction extends Action {
public function index(){
header("Content-Type:text/html; charset=utf-8");
header('Content-type:text/json');//输出为json格式页
header("Access-Control-Allow-Origin: "); // 允许任意域名发起的跨域请求
header('Access-Control-Allow-Headers: X-Requested-With,X_Requested_With');/* 判断手机端发过来的信息(预先存储手机硬件信息)再进行数据的查询判断 * 这里只是通过明文的查询,不作动态的优化 * 希望大家发挥自己的想象力,做相应的远程判断,开发更快、更安全的APP */ if($_POST['nid']==1){ $Con=M("News_content"); $list=$Con->where("nid=1")->select(); echo json_encode($list); //输出json }}
}
?>
带右侧按钮的搜索栏的实现
目前mui官方只有一个搜索栏示例供参考,但是只是一个输入框而已,很多时候这并不是我们想要的。
我们有时只是想要一个常规的搜索栏:左边输入框,右边紧接一个确定按钮。
在这里分享一下,我个人的代母,效果图如下:
实现的代码:
<!-- 搜索栏 -->
<div style="display:inline-flex; width:100%; padding-left:1px; padding-right:1px;">
<div class="mui-input-row" style="height:40px; flex-grow:4;">
<input type="text" class="mui-input-clear s_font-size2" placeholder="医院名称" maxlength="100" style="height:100%; padding-right:32px;"/>
</div>
<div style="height:40px; flex-grow:1;">
<input type="button" value="搜索" class="u_btn" style="width:100%; height:100%;"/>
</div>
</div>
目前mui官方只有一个搜索栏示例供参考,但是只是一个输入框而已,很多时候这并不是我们想要的。
我们有时只是想要一个常规的搜索栏:左边输入框,右边紧接一个确定按钮。
在这里分享一下,我个人的代母,效果图如下:
实现的代码:
<!-- 搜索栏 -->
<div style="display:inline-flex; width:100%; padding-left:1px; padding-right:1px;">
<div class="mui-input-row" style="height:40px; flex-grow:4;">
<input type="text" class="mui-input-clear s_font-size2" placeholder="医院名称" maxlength="100" style="height:100%; padding-right:32px;"/>
</div>
<div style="height:40px; flex-grow:1;">
<input type="button" value="搜索" class="u_btn" style="width:100%; height:100%;"/>
</div>
</div>
一种更柔和的底部消息提醒控件示例
一图胜千言:
相对中间弹框的方式,这是一种更柔和的提醒方式,不打断用户在主界面的操作过程;
实现方式很简单,生成一个固定底部的DIV即可,DOM结构如下:
<div class="message bottom">
<div class="icon">
<span class="mui-icon mui-icon-info"></span>
</div>
<p class="content">应用当前版本过低,存在安全漏洞,请升级至最新版</p>
<div class="action">
<button type="button" class="mui-btn mui-btn-blue mui-btn-link">取消</button>
<button id="install" type="button" class="mui-btn mui-btn-blue">立即升级</button>
</div>
</div>
其余就是css代码,定义组件布局
.message {
background-color: #fff;
z-index: 99;
box-shadow: 0px -5px 5px 0px rgba(150, 150, 150, .2);
}
.message.bottom {
position: fixed;
padding: 15px;
bottom: 0;
left: 0px;
right: 0px;
}
.message .icon {
width: 42px;
height: 42px;
float: left;
text-align: center;
}
.message .content {
padding-left: 55px;
font-size: 13px;
}
.icon .mui-icon {
font-weight: 28px;
font-weight: 700;
line-height: 42px;
color: #007AFF;
}
.action {
text-align: right;
padding-right: 2px;
margin-top: 18px;
}
完整代码示例参考github源码
一图胜千言:
相对中间弹框的方式,这是一种更柔和的提醒方式,不打断用户在主界面的操作过程;
实现方式很简单,生成一个固定底部的DIV即可,DOM结构如下:
<div class="message bottom">
<div class="icon">
<span class="mui-icon mui-icon-info"></span>
</div>
<p class="content">应用当前版本过低,存在安全漏洞,请升级至最新版</p>
<div class="action">
<button type="button" class="mui-btn mui-btn-blue mui-btn-link">取消</button>
<button id="install" type="button" class="mui-btn mui-btn-blue">立即升级</button>
</div>
</div>
其余就是css代码,定义组件布局
.message {
background-color: #fff;
z-index: 99;
box-shadow: 0px -5px 5px 0px rgba(150, 150, 150, .2);
}
.message.bottom {
position: fixed;
padding: 15px;
bottom: 0;
left: 0px;
right: 0px;
}
.message .icon {
width: 42px;
height: 42px;
float: left;
text-align: center;
}
.message .content {
padding-left: 55px;
font-size: 13px;
}
.icon .mui-icon {
font-weight: 28px;
font-weight: 700;
line-height: 42px;
color: #007AFF;
}
.action {
text-align: right;
padding-right: 2px;
margin-top: 18px;
}
完整代码示例参考github源码
收起阅读 »vue与刷新组件冲突问题
在vue与刷新组件共同使用时,pullrefresh组件会阻止事件冒泡,导致无法点击的问题。
注释
if (e.touches && e.touches.length && e.touches[0].clientX > 30) {
e.target && !this._preventDefaultException(e.target, this.options.preventDefaultException) && e.preventDefault();
} 在vue与刷新组件共同使用时,pullrefresh组件会阻止事件冒泡,导致无法点击的问题。
注释
if (e.touches && e.touches.length && e.touches[0].clientX > 30) {
e.target && !this._preventDefaultException(e.target, this.options.preventDefaultException) && e.preventDefault();
} 收起阅读 »





