微信相关工具类

发送红包的工具类:

package com.activity.common.utils.wxInterface;


import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;


import javax.net.ssl.SSLContext;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.activity.common.controller.moblie.shareBargain.ShareBargainController;
import com.jfinal.kit.PropKit;


/**
 * 微信发放红包
 * @author 唐
 *
 */
public class WxRedPackageUitils {
private final Logger log = LoggerFactory.getLogger(ShareBargainController.class);
private static WxRedPackageUitils WxRedPackageUitils = new WxRedPackageUitils();;
private WxRedPackageUitils() {
}
public static WxRedPackageUitils getWxRedPackageUitils() {
return WxRedPackageUitils;
}
// 工具类
WxConfigUitils wxConfigUitils = WxConfigUitils.getWxConfigUitils();

/**
* 企业付款至微信个人账户
* @param mch_billno
* @param mchId
* @param appid
* @param sendName
* @param openid
* @param totalAmount
* @param totalNum
* @param redWishing
* @param activityName
* @param redRemark
* @param payKey
* @return
*/
public Map<String, String> enterprisePayment(String mch_billno,String mchId,String appid,String sendName,String openid,String totalAmount,String totalNum,
String redWishing,String activityName,String redRemark,String payKey){
Map<String, String> map = new HashMap<String, String>();
Map<String, String> redOk = new HashMap<String, String>();
try {
//微信分配的公众账号ID(企业号corpid即为此appId)
String mch_appid = appid.trim();
log.error("发送现金红包-公众账号ID="+mch_appid);
//微信支付分配的商户号
String mchid = mchId.trim();
log.error("发送现金红包-商户号="+mchid);
//随机字符串,不长于32位
String nonce_str  = WxConfigUitils.create_nonce_str32();
log.error("发送现金红包-随机字符串="+nonce_str);
//商户订单号
String partner_trade_no = mch_billno;
//用户在wxappid下的openid
log.error("发送现金红包-接受红包的用户="+openid);
//校验用户姓名选项 ,NO_CHECK:不校验真实姓名  FORCE_CHECK:强校验真实姓名
String check_name = "NO_CHECK";
//付款金额,单位分
String total_amount = totalAmount;
// 支付金额
BigDecimal re1 = new BigDecimal(total_amount);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float aa = re1.multiply(re2).floatValue();
String total_fee = String.valueOf(aa);
String[] smill = total_fee.split("\\.");
int amount = Integer.parseInt(smill[0]);
//企业付款描述信息
String desc = "恭喜获奖!";
String spbill_create_ip = PropKit.use("system.properties").get("client_ip").trim();
//支付密钥
String key = payKey.trim();
log.error("发送企业付款-支付密钥="+key);
map.put("mch_appid", mch_appid);
map.put("mchid", mchid);
map.put("nonce_str", nonce_str);
map.put("partner_trade_no", partner_trade_no);
map.put("openid", openid);
map.put("check_name", check_name);
map.put("amount", amount+"");
map.put("desc", desc);
map.put("spbill_create_ip", spbill_create_ip);
//获取签名
String sign = WxConfigUitils.getPayCustomSign(map, key);
log.error("企业付款-签名是="+sign);
map.put("sign", sign);
String xml = WxConfigUitils.ArrayToXml(map);
log.error("企业付款-请求前封装XML="+xml);
//发送普通红包请求路径
String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/promotion/transfers";
String xmlStr = ssl(url, xml,mchid);
log.error("发送现金红包-请求返回XMLString="+xmlStr);
//String xmlStr = HttpKit.post(url, xml);
//判读是否成功    indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
if (xmlStr.indexOf("SUCCESS") != -1) {
redOk = WxConfigUitils.doXMLParse(xmlStr);
redOk.put("state", "OK");
log.error("企业付款-请求返回XMLString="+redOk);
}else{
redOk.put("state", "NoMoney");
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return redOk;
}


/**
* 发送普通红包
* @param mchId  微信支付分配的商户号
* @param appid  微信分配的公众账号ID(企业号corpid即为此appId)
* @param sendName  红包发送者名称
* @param openid   接受红包的用户,用户在wxappid下的openid
* @param totalAmount  付款金额,单位分
* @param totalNum  红包发放总人数total_num=1
* @param redWishing  红包祝福语
* @param activityName  活动名称
* @param redRemark  备注信息   猜越多得越多,快来抢!
* @param payKey  支付密钥
* @return
*/
public Map<String, String> ordinaryRedPackage(String mch_billno,String mchId,String appid,String sendName,String openid,String totalAmount,String totalNum,
String redWishing,String activityName,String redRemark,String payKey){
Map<String, String> map = new HashMap<String, String>();
Map<String, String> redOk = new HashMap<String, String>();
try {
//随机字符串,不长于32位
String nonce_str  = WxConfigUitils.create_nonce_str32();
log.error("发送现金红包-随机字符串="+nonce_str);
//商户订单号(每个订单号必须唯一。取值范围:0~9,a~z,A~Z)
//String mch_billno = "wly"+RandomNumber();//WxConfigUitils.MchBillno().trim();
log.error("发送现金红包-商户订单号="+mch_billno);
//微信支付分配的商户号
String mch_id = mchId.trim();
log.error("发送现金红包-商户号="+mch_id);
//微信分配的公众账号ID(企业号corpid即为此appId)
String wxappid = appid.trim();
log.error("发送现金红包-公众账号ID="+wxappid);
//红包发送者名称
String send_name = sendName.trim();
log.error("发送现金红包-红包发送者名称="+send_name);
//接受红包的用户,用户在wxappid下的openid
String re_openid = openid;
log.error("发送现金红包-接受红包的用户="+re_openid);
//付款金额,单位分
String total_amount = totalAmount;
// 支付金额
BigDecimal re1 = new BigDecimal(total_amount);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float aa = re1.multiply(re2).floatValue();
String total_fee = String.valueOf(aa);
String[] smill = total_fee.split("\\.");
total_amount = smill[0];
log.error("发送现金红包-支付金额="+total_amount);
//红包发放总人数total_num=1
String total_num = totalNum.trim();
log.error("发送现金红包-红包发放总人数="+total_num);
//红包祝福语
String wishing = redWishing.trim();
log.error("发送现金红包-红包祝福语="+wishing);
//调用接口的机器Ip地址
String client_ip = PropKit.use("system.properties").get("client_ip").trim();
log.error("发送现金红包-调用接口的机器Ip地址="+client_ip);
//活动名称
String act_name = activityName.trim();
log.error("发送现金红包-活动名称="+act_name);
//备注信息   猜越多得越多,快来抢!
String remark = redRemark.trim();
log.error("发送现金红包-备注信息="+remark);
//支付密钥
String key = payKey.trim();
log.error("发送现金红包-支付密钥="+key);
map.put("wxappid", wxappid);
map.put("mch_id", mch_id);
map.put("nonce_str", nonce_str);
map.put("mch_billno", mch_billno);
map.put("send_name", send_name);
map.put("re_openid", re_openid);
map.put("total_amount", total_amount);
map.put("total_num", total_num);
map.put("wishing", wishing);
map.put("client_ip", client_ip);
map.put("act_name", act_name);
map.put("remark", remark);
//获取签名
String sign = WxConfigUitils.getPayCustomSign(map, key);
log.error("发送现金红包-签名是="+sign);
map.put("sign", sign);
String xml = WxConfigUitils.ArrayToXml(map);
log.error("发送现金红包-请求前封装XML="+xml);
//发送普通红包请求路径
String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
String xmlStr = ssl(url, xml,mch_id);
log.error("发送现金红包-请求返回XMLString="+xmlStr);
//String xmlStr = HttpKit.post(url, xml);
//判读是否成功    indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
if (xmlStr.indexOf("SUCCESS") != -1) {
redOk = WxConfigUitils.doXMLParse(xmlStr);
redOk.put("state", "OK");
log.error("发送现金红包-请求返回XMLString="+redOk);
}else{
redOk.put("state", "NoMoney");
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return redOk;
}

private String ssl(String url,String data,String mch_id){
        StringBuffer message = new StringBuffer();
        try {
            KeyStore keyStore  = KeyStore.getInstance("PKCS12");
            //FileInputStream instream = new FileInputStream(new File("E:/cert/apiclient_cert.p12"));
            log.error("发送红包--SSL方法--准备读取文件");
            //FileInputStream instream = new FileInputStream(new File("D:/cert-3/apiclient_cert.p12"));
            FileInputStream instream = new FileInputStream(new File(PropKit.get("p12Path")));
            log.error("发送红包--SSL方法--找到文件发送="+instream.toString());
            log.error("抢红包发送红包--SSL方法--商户号="+mch_id);
            keyStore.load(instream, mch_id.toCharArray());
            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, mch_id.toCharArray())
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[] { "TLSv1" },
                    null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            HttpPost httpost = new HttpPost(url);


            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        message.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } 


        return message.toString();
    }

//10位随机数
public static String RandomNumber(){
int a[] = new int[10];
String number ="";
      for(int i=0;i<a.length;i++ ) {
          a[i] = (int)(10*(Math.random()));
          number += a[i]+"";
      }
     return number+"";
}
}















import java.io.ByteArrayInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.UUID;
import java.util.Map.Entry;


import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import org.xmlpull.v1.XmlPullParserFactory;


import com.activity.common.model.bigDataPlatform.ProductInfo;
import com.activity.common.model.centerObjcet.wx.WxConfig;
import com.activity.common.model.centerObjcet.wx.WxUserInfo;
import com.activity.common.model.publicNumber.SellerPublicNumber;
import com.activity.common.model.shareBargain.ShareBargain;
import com.activity.common.model.shareBargain.ShareBargainPrize;
import com.activity.common.model.shareBargain.ShareBargainWxuser;
import com.activity.common.service.system.ProductInfoService;
import com.activity.common.utils.date.DateUitils;
import com.activity.common.utils.http.HttpRequest;
import com.jfinal.core.JFinal;
import com.jfinal.json.Jackson;
import com.jfinal.kit.HttpKit;
import com.jfinal.kit.PropKit;
import com.jfinal.weixin.sdk.api.*;
import com.jfinal.weixin.sdk.utils.HttpUtils;


/**

  * 微信工具类  

  *

*/

public class WxConfigUitils {
private final Logger log = LoggerFactory.getLogger(WxConfigUitils.class);
private static WxConfigUitils wxConfigUitils = new WxConfigUitils();
// 工具类
DateUitils uitils = DateUitils.getUitils();


private WxConfigUitils() {
}


public static WxConfigUitils getWxConfigUitils() {
return wxConfigUitils;
}


// 微信配置对象
WxConfig wxConfig = new WxConfig();
// http请求
HttpRequest httpRequest = new HttpRequest();


/**
* 添加微信公众号配置获取配置
*/
public static ApiConfig getApiConfig(String Token, String AppId, String AppSecret) {
ApiConfig ac = new ApiConfig();
// 配置微信 API 相关常量
ac.setToken(Token);
ac.setAppId(AppId);
ac.setAppSecret(AppSecret);
/**
* 是否对消息进行加密,对应于微信平台的消息加解密方式: 1:true进行加密且必须配置 encodingAesKey
* 2:false采用明文模式,同时也支持混合模式
*/
ac.setEncryptMessage(PropKit.getBoolean("encryptMessage", false));
ac.setEncodingAesKey(PropKit.get("encodingAesKey", "setting it in config file"));
return ac;
}


/**
* 产生随机串--由程序自己随机产生
* 
* @return
*/
public static String create_nonce_str() {
return UUID.randomUUID().toString();
}


/**
* 产生随机串--由程序自己随机产生 32位
* 
* @return
*/
public static String create_nonce_str32() {
return UUID.randomUUID().toString().substring(0, 32);
}


/**
* 调用微信分享接口微信所需时间
*/
public String getDate() {
Date dete = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
return formatter.format(dete);
}


/**
* 由程序自己获取当前时间 时间戳
* 
* @return
*/
public String create_timestamp() {
return Long.toString(System.currentTimeMillis() / 1000);
}


/**
* 随机加密
* 
* @param hash
* @return
*/
public String byteToHex(final byte[] hash) {
Formatter formatter = new Formatter();
for (byte b : hash) {
formatter.format("%02x", b);
}
String result = formatter.toString();
formatter.close();
return result;
}


/**
* 微信js-sdk基本配置参数
* 
* @param url
* @return
*/
public Map<String, String> WxConfigApi(String url) {
// jsapi_ticket
JsTicket jsapi_ticket = JsTicketApi.getTicket(JsTicketApi.JsApiType.jsapi);
// 随机串
String nonce_str = create_nonce_str();
// 时间戳
String timestamp = create_timestamp();
// 签名
String signature = "";
// 拼接字符串进行加密,获取签名
String sha1 = "jsapi_ticket=" + jsapi_ticket.getTicket() + "&noncestr=" + nonce_str + "&timestamp=" + timestamp
+ "&url=" + url;
try {
MessageDigest crypt = MessageDigest.getInstance("SHA-1");
crypt.reset();
crypt.update(sha1.getBytes("UTF-8"));
signature = byteToHex(crypt.digest());
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
Map<String, String> configMap = new HashMap<String, String>();
String appId = ApiConfigKit.getApiConfig().getAppId();
configMap.put("url", url);
configMap.put("appId", appId);
configMap.put("jsapi_ticket", jsapi_ticket.getTicket());
configMap.put("nonceStr", nonce_str);
configMap.put("timestamp", timestamp);
configMap.put("signature", signature);
return configMap;
}


/**
* 获取公众号用户信息
*/
public WxUserInfo getPublicUser(String accessToken, String openid) {
// 读取用户基本信息
String token = HttpUtils.post("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken
+ "&openid=" + openid + "&lang=zh_CN", "");
log.error("token"+token);
// JSON字符串转为实体对象
WxUserInfo wxuser = Jackson.getJson().parse(token, WxUserInfo.class);
return wxuser;

}

//*********************分割线*****

//这里插入WxUserInfo类属性

private String subscribe;// 是否关注0未关注
private String openid;// 唯一标识
private String nickname;// 昵称
private String sex;// 性别 1男 2女 0未知
private String language;// 用户的语言,简体中文为zh_CN
private String city;// 用户所在城市
private String province;// 用户所在省份
private String country;// 用户所在国家
private String headimgurl;// 用户头像
private String subscribe_time;// 用户关注时间,为时间戳。
private String remark;// 公众号运营者对粉丝的备注,
private String groupid;// 用户所在的分组ID(兼容旧的用户分组接口)

private String[] tagid_list;// 用户被打上的标签ID列表

//*********************分割线*****






/**
* 分享砍价中奖 中奖 aAmrKzgYCDBsYTgwGJn_a04O8l_2OgcZ94_CnvHN8MY 推送消息
*/
public void wxInformation(String openid, String templateId, String appid, String http, String token,
ShareBargainWxuser sbw, ShareBargain sb, ShareBargainPrize sbp, SellerPublicNumber spn) {
List<ProductInfo> piList = ProductInfoService.getService().getProductInfoById(sbp.getProductId());
ProductInfo pi = new ProductInfo();
for (ProductInfo piErgodic : piList) {
pi = piErgodic;
}
log.error("用户Openid="+openid+"推送模板消息ID="+templateId);
DateUitils.getUitils();
String json = " {\"touser\":\""+openid+"\","+"\"template_id\":\""+templateId+"\","
+ "\"url\":\"http://open.weixin.qq.com/connect/oauth2/authorize?appid=" + appid
+ "&redirect_uri=http%3a%2f%2f" + http + JFinal.me().getContextPath()
+ "%2fShareBargain%2fPrizeAddress%3fsbw%3d" + sbw.getId() + "%26jpn%3d" + spn.getId()
+ "&response_type=code&scope=snsapi_userinfo&state=wx#wechat_redirect\"," + "\"topcolor\":\"#FF0000\","
+ "\"data\":{" + "\"first\": {" + "\"value\":\"亲~您本次分享砍价已经砍至最低价格\"," + "\"color\":\"#ca2426" + "\"},"
+ "\"keyword1\":{" + "\"value\":\"" + sb.getActivityName() + "\"," + "\"color\":\"#ca2426" + "\"},"
+ "\"keyword2\":{" + "\"value\":\"" + pi.getProductName() + "\"," + "\"color\":\"#ca2426" + "\"},"
+ "\"keyword3\":{" + "\"value\":\"" + uitils.newDate() + "\"," + "\"color\":\"#ca2426" + "\"},"
+ "\"remark\":{" + "\"value\":\"请前往填写地址和支付最低金额\"," + "\"color\":\"#ca2426\"}}}";
String ps = HttpUtils.post("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=" + token,
json);
System.out.println("发送推送消息" + ps);
}


/**
* 微信公众号支付
* 
* @return
*/
public Map<String, String> wxPay(String openid, String appid, String key, String mch_id, String money, String ip,
String outTradeNo) {
System.out.println("调用微信支付*****************appid>"+appid);
// 商品描述
String body = "en";
// 订单号
String out_trade_no = outTradeNo;
// 支付金额
BigDecimal re1 = new BigDecimal(money);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float aa = re1.multiply(re2).floatValue();
String total_fee = String.valueOf(aa);
String[] smill = total_fee.split("\\.");
total_fee = smill[0];
// 终端IP
String spbill_create_ip = ip;
// 异步接收微信支付结果通知的回调地址
String notify_url = "http://"+PropKit.use("system.properties").get("http")+JFinal.me().getContextPath()+"/wxpayxml/analysisXml";
// 交易类型
String trade_type = "JSAPI";
// 随机串
String nonce_str = UUID.randomUUID().toString().substring(0, 32);
// 时间戳
String timestamp = create_timestamp();
// 签名类型
String signType = "MD5";
Map<String, String> map = new HashMap<String, String>();
map.put("appid", appid);
log.error("微信支付-微信APPID="+appid);
map.put("mch_id", mch_id);
log.error("微信支付-商户号="+mch_id);
map.put("nonce_str", nonce_str);
log.error("微信支付-随机串="+nonce_str);
map.put("body", body);
log.error("微信支付-商品描述="+body);
map.put("out_trade_no", out_trade_no);
log.error("微信支付-订单号="+out_trade_no);
map.put("total_fee", total_fee);
log.error("微信支付-需要支付金额(换算后)="+total_fee);
map.put("spbill_create_ip", spbill_create_ip);
log.error("微信支付-终端IP="+spbill_create_ip);
map.put("notify_url", notify_url);
log.error("微信支付-异步接收微信支付结果通知的回调地址="+notify_url);
map.put("trade_type", trade_type);
log.error("微信支付-交易类型="+trade_type);
map.put("openid", openid);
log.error("微信支付-用户OPENID="+openid);
// 支付签名
String paySign = null;
// 预付商品id
String prepayid = "";
try {
paySign = getPayCustomSign(map, key);
map.put("sign", paySign);
log.error("微信支付-统一下单签名="+paySign);
String xml = ArrayToXml(map);
log.error("微信支付-统一下单转XML="+xml);
// 统一下单
String url = "https://api.mch.weixin.qq.com/pay/unifiedorder";
String xmlStr = HttpKit.post(url, xml);
log.error("微信支付-统一下单="+xmlStr);
if (xmlStr.indexOf("SUCCESS") != -1) {
Map<String, String> map2 = doXMLParse(xmlStr);
prepayid = (String) map2.get("prepay_id");
}
log.error("微信支付-预付商品id="+prepayid);
} catch (Exception e) {
e.printStackTrace();
}
// 封装h5页面调用参数
Map<String, String> signMap = new HashMap<String, String>();
signMap.put("appId", appid);
signMap.put("timeStamp", timestamp + "");
signMap.put("package", "prepay_id=" + prepayid);
signMap.put("signType", "MD5");
signMap.put("nonceStr", nonce_str);
String paySigntwo = null;
try {
paySigntwo = getPayCustomSign(signMap, key);
log.error("微信支付-支付密钥="+key);
log.error("微信支付-支付签名="+paySigntwo);
} catch (Exception e) {
e.printStackTrace();
}
Map<String, String> paymap = new HashMap<String, String>();
paymap.put("timestamp", timestamp);
paymap.put("nonceStr", nonce_str);
paymap.put("prepay_id", "prepay_id=" + prepayid);
paymap.put("signType", signType);
paymap.put("paySign", paySigntwo);
return paymap;
}


/**
* 获取支付所需签名
* 
* @param ticket
* @param timeStamp
* @param card_id
* @param code
* @return
* @throws Exception
*/
public static String getPayCustomSign(Map<String, String> bizObj, String key) throws Exception {
String bizString = FormatBizQueryParaMap(bizObj, false);
return sign(bizString, key);
}


/**
* 商户订单号
* @return
*/
public static String MchBillno(){
Random r = new Random(1000);
String mchBillno = "wly" + (r.nextInt() * 100) + newDateByYMD();
return mchBillno;
}

/**
* 新建时间并格式转换 年月日
*/
public static String newDateByYMD() {
Date date = new Date();
SimpleDateFormat time = new SimpleDateFormat("yyyyMMddHHmmss");
return time.format(date);
}

/**
* 字典排序
* 
* @param paraMap
* @param urlencode
* @return
* @throws Exception
*/
public static String FormatBizQueryParaMap(Map<String, String> paraMap, boolean urlencode) throws Exception {
String buff = "";
try {
List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(paraMap.entrySet());
Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
public int compare(Map.Entry<String, String> o1, Map.Entry<String, String> o2) {
return (o1.getKey()).toString().compareTo(o2.getKey());
}
});
for (int i = 0; i < infoIds.size(); i++) {
Map.Entry<String, String> item = infoIds.get(i);
if (item.getKey() != "") {
String key = item.getKey();
String val = item.getValue();
if (urlencode) {
val = URLEncoder.encode(val, "utf-8");
}
buff += key + "=" + val + "&";
}
}
if (buff.isEmpty() == false) {
buff = buff.substring(0, buff.length() - 1);
}
} catch (Exception e) {
throw new Exception(e.getMessage());
}
return buff;
}


public static String sign(String content, String key) throws Exception {
String signStr = "";
signStr = content + "&key=" + key;
return MD5(signStr).toUpperCase();
}


public final static String MD5(String s) {
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
try {
byte[] btInput = s.getBytes("utf-8");
MessageDigest mdInst = MessageDigest.getInstance("MD5");
mdInst.update(btInput);
byte[] md = mdInst.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}


public static String ArrayToXml(Map<String, String> arr) {
String xml = "<xml>";
Iterator<Entry<String, String>> iter = arr.entrySet().iterator();
while (iter.hasNext()) {
Entry<String, String> entry = iter.next();
String key = entry.getKey();
String val = entry.getValue();
if (IsNumeric(val)) {
xml += "<" + key + ">" + val + "</" + key + ">";
} else
xml += "<" + key + "><![CDATA[" + val + "]]></" + key + ">";
}
xml += "</xml>";
return xml;
}


public static boolean IsNumeric(String str) {
if (str.matches("\\d *")) {
return true;
} else {
return false;
}
}


public static Map<String, String> doXMLParse(String xml) throws XmlPullParserException, IOException {
InputStream inputStream = new ByteArrayInputStream(xml.getBytes());
Map<String, String> map = null;
XmlPullParser pullParser = XmlPullParserFactory.newInstance().newPullParser();
pullParser.setInput(inputStream, "UTF-8");// 为xml设置要解析的xml数据
int eventType = pullParser.getEventType();
while (eventType != XmlPullParser.END_DOCUMENT) {
switch (eventType) {
case XmlPullParser.START_DOCUMENT:
map = new HashMap<String, String>();
break;
case XmlPullParser.START_TAG:
String key = pullParser.getName();
if (key.equals("xml"))
break;
String value = pullParser.nextText();
map.put(key, value);
break;
case XmlPullParser.END_TAG:
break;
}
eventType = pullParser.next();
}
return map;
}


public static void main(String[] args) {
WxConfigUitils ss = new WxConfigUitils();
System.out.println(ss.create_timestamp());
}



}







//***********************发红包

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;


import javax.net.ssl.SSLContext;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;


import com.activity.common.controller.moblie.shareBargain.ShareBargainController;
import com.jfinal.kit.PropKit;


/**
 * 微信发放红包
 *
 */
public class WxRedPackageUitils {
private final Logger log = LoggerFactory.getLogger(ShareBargainController.class);
private static WxRedPackageUitils WxRedPackageUitils = new WxRedPackageUitils();;
private WxRedPackageUitils() {
}
public static WxRedPackageUitils getWxRedPackageUitils() {
return WxRedPackageUitils;
}
// 工具类
WxConfigUitils wxConfigUitils = WxConfigUitils.getWxConfigUitils();

/**
* 发送普通红包
* @param mchId  微信支付分配的商户号
* @param appid  微信分配的公众账号ID(企业号corpid即为此appId)
* @param sendName  红包发送者名称
* @param openid   接受红包的用户,用户在wxappid下的openid
* @param totalAmount  付款金额,单位分
* @param totalNum  红包发放总人数total_num=1
* @param redWishing  红包祝福语
* @param activityName  活动名称
* @param redRemark  备注信息   猜越多得越多,快来抢!
* @param payKey  支付密钥
* @return
*/
public Map<String, String> ordinaryRedPackage(String mch_billno,String mchId,String appid,String sendName,String openid,String totalAmount,String totalNum,
String redWishing,String activityName,String redRemark,String payKey){
Map<String, String> map = new HashMap<String, String>();
Map<String, String> redOk = new HashMap<String, String>();
try {
//随机字符串,不长于32位
String nonce_str  = WxConfigUitils.create_nonce_str32();
log.error("发送现金红包-随机字符串="+nonce_str);
//商户订单号(每个订单号必须唯一。取值范围:0~9,a~z,A~Z)
//String mch_billno = "wly"+RandomNumber();//WxConfigUitils.MchBillno().trim();
log.error("发送现金红包-商户订单号="+mch_billno);
//微信支付分配的商户号
String mch_id = mchId.trim();
log.error("发送现金红包-商户号="+mch_id);
//微信分配的公众账号ID(企业号corpid即为此appId)
String wxappid = appid.trim();
log.error("发送现金红包-公众账号ID="+wxappid);
//红包发送者名称
String send_name = sendName.trim();
log.error("发送现金红包-红包发送者名称="+send_name);
//接受红包的用户,用户在wxappid下的openid
String re_openid = openid;
log.error("发送现金红包-接受红包的用户="+re_openid);
//付款金额,单位分
String total_amount = totalAmount;
// 支付金额
BigDecimal re1 = new BigDecimal(total_amount);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float aa = re1.multiply(re2).floatValue();
String total_fee = String.valueOf(aa);
String[] smill = total_fee.split("\\.");
total_amount = smill[0];
log.error("发送现金红包-支付金额="+total_amount);
//红包发放总人数total_num=1
String total_num = totalNum.trim();
log.error("发送现金红包-红包发放总人数="+total_num);
//红包祝福语
String wishing = redWishing.trim();
log.error("发送现金红包-红包祝福语="+wishing);
//调用接口的机器Ip地址
String client_ip = PropKit.use("system.properties").get("client_ip").trim();
log.error("发送现金红包-调用接口的机器Ip地址="+client_ip);
//活动名称
String act_name = activityName.trim();
log.error("发送现金红包-活动名称="+act_name);
//备注信息   猜越多得越多,快来抢!
String remark = redRemark.trim();
log.error("发送现金红包-备注信息="+remark);
//支付密钥
String key = payKey.trim();
log.error("发送现金红包-支付密钥="+key);
map.put("wxappid", wxappid);
map.put("mch_id", mch_id);
map.put("nonce_str", nonce_str);
map.put("mch_billno", mch_billno);
map.put("send_name", send_name);
map.put("re_openid", re_openid);
map.put("total_amount", total_amount);
map.put("total_num", total_num);
map.put("wishing", wishing);
map.put("client_ip", client_ip);
map.put("act_name", act_name);
map.put("remark", remark);
//获取签名
String sign = WxConfigUitils.getPayCustomSign(map, key);
log.error("发送现金红包-签名是="+sign);
map.put("sign", sign);
String xml = WxConfigUitils.ArrayToXml(map);
log.error("发送现金红包-请求前封装XML="+xml);
//发送普通红包请求路径
String url = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";
String xmlStr = ssl(url, xml,mch_id);
log.error("发送现金红包-请求返回XMLString="+xmlStr);
//String xmlStr = HttpKit.post(url, xml);
//判读是否成功    indexOf 方法返回一个整数值,指出 String 对象内子字符串的开始位置。如果没有找到子字符串,则返回-1。
if (xmlStr.indexOf("SUCCESS") != -1) {
redOk = WxConfigUitils.doXMLParse(xmlStr);
redOk.put("state", "OK");
log.error("发送现金红包-请求返回XMLString="+redOk);
}else{
redOk.put("state", "NoMoney");
}

} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return redOk;
}

private String ssl(String url,String data,String mch_id){
        StringBuffer message = new StringBuffer();
        try {
            KeyStore keyStore  = KeyStore.getInstance("PKCS12");
            //FileInputStream instream = new FileInputStream(new File("E:/cert/apiclient_cert.p12"));
            log.error("发送红包--SSL方法--准备读取文件");
            //FileInputStream instream = new FileInputStream(new File("D:/cert-3/apiclient_cert.p12"));
            FileInputStream instream = new FileInputStream(new File(PropKit.get("p12Path")));
            log.error("发送红包--SSL方法--找到文件发送="+instream.toString());
            log.error("抢红包发送红包--SSL方法--商户号="+mch_id);
            keyStore.load(instream, mch_id.toCharArray());
            SSLContext sslcontext = SSLContexts.custom()
                    .loadKeyMaterial(keyStore, mch_id.toCharArray())
                    .build();
            SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
                    sslcontext,
                    new String[] { "TLSv1" },
                    null,
            SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
            CloseableHttpClient httpclient = HttpClients.custom()
                    .setSSLSocketFactory(sslsf)
                    .build();
            HttpPost httpost = new HttpPost(url);


            httpost.addHeader("Connection", "keep-alive");
            httpost.addHeader("Accept", "*/*");
            httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
            httpost.addHeader("Host", "api.mch.weixin.qq.com");
            httpost.addHeader("X-Requested-With", "XMLHttpRequest");
            httpost.addHeader("Cache-Control", "max-age=0");
            httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
            httpost.setEntity(new StringEntity(data, "UTF-8"));
            CloseableHttpResponse response = httpclient.execute(httpost);
            try {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(entity.getContent(),"UTF-8"));
                    String text;
                    while ((text = bufferedReader.readLine()) != null) {
                        message.append(text);
                    }
                }
                EntityUtils.consume(entity);
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                response.close();
            }
        } catch (Exception e1) {
            e1.printStackTrace();
        } 


        return message.toString();
    }

//10位随机数
public static String RandomNumber(){
int a[] = new int[10];
String number ="";
     for(int i=0;i<a.length;i++ ) {
         a[i] = (int)(10*(Math.random()));
         number += a[i]+"";
     }
    return number+"";
}

}

//外部发红包直接调用**********************

/**
* 发送普通红包
* @param mchId  微信支付分配的商户号
* @param appid  微信分配的公众账号ID(企业号corpid即为此appId)
* @param sendName  红包发送者名称
* @param openid   接受红包的用户,用户在wxappid下的openid
* @param totalAmount  付款金额,单位分
* @param totalNum  红包发放总人数total_num=1
* @param redWishing  红包祝福语
* @param activityName  活动名称
* @param redRemark  备注信息   猜越多得越多,快来抢!
* @param payKey  支付密钥
*/
log.error("抢红包-提现-准备发送红包");
Map<String, String> paymap = WxRedPackageUitils.getWxRedPackageUitils().ordinaryRedPackage(mch_billno,spn.getShopNumber(), spn.getAppId(), spn.getSenderName(), openid, extractMoney, "1", 
spn.getWish(), spn.getSenderName()+"的活动", spn.getRemarks(), spn.getPayKey());
map.putAll(paymap);







//************w微信退款**********

import java.io.FileInputStream;
import java.security.KeyStore;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;


import javax.net.ssl.SSLContext;


import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.SSLContexts;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;


import com.activity.common.model.publicNumber.SellerPublicNumber;
import com.activity.common.utils.wxInterface.WxConfigUitils;


public class RefundUtil {
/**
* 退款函数,该方法可以对曾经部分退款的订单进行再次退款
* 
* @param out_trade_no
*            商户订单号
* @param total_fee1
*            退款对应的订单的总金额(以“元”为单位)
* @param refund_fee1
*            计划退款的金额(以“元”为单位)
* @return
*/
public static void wechatRefund1(SellerPublicNumber sellerPublicNumber, String out_trade_no, double total_fee1,
double refund_fee1) {
String out_refund_no = UUID.randomUUID().toString().substring(0, 32);// 退款单号,随机生成
// ,但长度应该跟文档一样(32位)(卖家信息校验不一致,请核实后再试)
int total_fee = (int) total_fee1 ;// 订单的总金额,以分为单位(填错了貌似提示:同一个out_refund_no退款金额要一致)
int refund_fee = (int) refund_fee1;// 退款金额,以分为单位(填错了貌似提示:同一个out_refund_no退款金额要一致)
String nonce_str = UUID.randomUUID().toString().substring(0, 32);// 随机字符串
// 微信公众平台文档:“基本配置”--》“开发者ID”
String appid = sellerPublicNumber.getAppId();
// 微信公众平台文档:“基本配置”--》“开发者ID”
String appsecret = sellerPublicNumber.getAppSecret();
System.out.println("支付密要*****" + appsecret);
// 商户号
// 微信公众平台文档:“微信支付”--》“商户信息”--》“商户号”,将该值赋值给partner
String mch_id = sellerPublicNumber.getShopNumber();
// 微信公众平台:"微信支付"--》“商户信息”--》“微信支付商户平台”(登录)--》“API安全”--》“API密钥”--“设置密钥”(设置之后的那个值就是partnerkey,32位)
String partnerkey = sellerPublicNumber.getPayKey();
Map<String, String> map = new HashMap<String, String>();
map.put("appid", appid);
map.put("mch_id", mch_id);
map.put("nonce_str", nonce_str);
map.put("out_refund_no", out_refund_no);
map.put("out_trade_no", out_trade_no);
map.put("refund_fee", refund_fee + "");
map.put("total_fee", total_fee + "");
String sign = null;
try {
sign = WxConfigUitils.getPayCustomSign(map, partnerkey);
} catch (Exception e1) {
e1.printStackTrace();
}
map.put("sign", sign);
String xml = WxConfigUitils.ArrayToXml(map);
String createOrderURL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
System.out.println("**********partnerkey>" + partnerkey);
System.out.println("**********createOrderURL>" + createOrderURL);
System.out.println("**********xml>" + xml);
try {
String refundResult = doRefund(mch_id, createOrderURL, xml);
System.out.println("退款产生的json字符串:" + refundResult);
} catch (Exception e) {
e.printStackTrace();
}
}


/**
* 该方法默认全额退款,但如果该订单曾经退款一部分,那么就不可使用该方法
* 
* @param out_trade_no
*            商户订单号
* @param total_fee1
*            总的退款金额(以“元”为单位)
*/
public static void wechatRefund(SellerPublicNumber sellerPublicNumber, String out_trade_no, double total_fee1) {
wechatRefund1(sellerPublicNumber, out_trade_no, total_fee1, total_fee1);
}


public static String doRefund(String partner, String url, String data) throws Exception {
KeyStore keyStore = KeyStore.getInstance("PKCS12");
/*
* URL url2 = ClientCustomSSL.class.getClassLoader().getResource(
* apiclient_certLocation); URI uri = url2.toURI();
*/
FileInputStream instream = new FileInputStream("E:/cert/apiclient_cert.p12");// P12文件目录
try {
keyStore.load(instream, partner.toCharArray());
} finally {
instream.close();
}
SSLContext sslcontext = SSLContexts.custom().loadKeyMaterial(keyStore, partner.toCharArray())// 这里也是写密码的
.build();
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslcontext, new String[] { "TLSv1" }, null,
SSLConnectionSocketFactory.BROWSER_COMPATIBLE_HOSTNAME_VERIFIER);
CloseableHttpClient httpclient = HttpClients.custom().setSSLSocketFactory(sslsf).build();
try {
HttpPost httpost = new HttpPost(url); // 设置响应头信息
httpost.addHeader("Connection", "keep-alive");
httpost.addHeader("Accept", "*/*");
httpost.addHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
httpost.addHeader("Host", "api.mch.weixin.qq.com");
httpost.addHeader("X-Requested-With", "XMLHttpRequest");
httpost.addHeader("Cache-Control", "max-age=0");
httpost.addHeader("User-Agent", "Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0) ");
httpost.setEntity(new StringEntity(data, "UTF-8"));
CloseableHttpResponse response = httpclient.execute(httpost);
try {
HttpEntity entity = response.getEntity();


String jsonStr = EntityUtils.toString(response.getEntity(), "UTF-8");
EntityUtils.consume(entity);
return jsonStr;
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
}

//外面直接调用***// 没有中奖的 还需要退款
                              //执行退款
String payOutNo = oneMoneyGroupWxUser.getPayOutNo(); //支付的订单号
String payMoney = oneMoneyGroupWxUser.getPayMoney(); //支付的金额
// 支付金额
BigDecimal re1 = new BigDecimal(payMoney);
BigDecimal re2 = new BigDecimal(Float.toString(100.00f));
Float total_fee = re1.multiply(re2).floatValue();
// 没有中奖的 还需要退款  sellerPublicNumber:公众号对象

RefundUtil.wechatRefund(sellerPublicNumber,payOutNo, total_fee);

//这里插入公众号对象 根据需要修改对象

import com.jfinal.plugin.activerecord.IBean;
import com.jfinal.plugin.activerecord.Model;


/**
 * 经销商公众号表
 * 
 * @author 小石潭记丶
 *
 *         2017年8月9日
 */
@SuppressWarnings("serial")
public class BaseSellerPublicNumber<M extends BaseSellerPublicNumber<M>> extends Model<M> implements IBean {
public void setId(java.lang.String ID) {
set("ID", ID);
}


public java.lang.String getId() {
return get("ID");
}


/**
* 公众号名称
*/
public void setPublicNumberName(java.lang.String PUBLICNUMBER_NAME) {
set("PUBLICNUMBER_NAME", PUBLICNUMBER_NAME);
}


public java.lang.String getPublicNumberName() {
return get("PUBLICNUMBER_NAME");
}


/**
* 开发者ID
*/
public void setAppId(java.lang.String APPID) {
set("APPID", APPID);
}


public java.lang.String getAppId() {
return get("APPID");
}


/**
* 开发者密码
*/
public void setAppSecret(java.lang.String APPSECRET) {
set("APPSECRET", APPSECRET);
}


public java.lang.String getAppSecret() {
return get("APPSECRET");
}


/**
* 公众号二维码图片
*/
public void setPublicNumberQrcodeImg(java.lang.String PUBLICNUMBER_QRCODE_IMG) {
set("PUBLICNUMBER_QRCODE_IMG", PUBLICNUMBER_QRCODE_IMG);
}


public java.lang.String getPublicNumberQrcodeImg() {
return get("PUBLICNUMBER_QRCODE_IMG");
}


/**
* 商户号
*/
public void setShopNumber(java.lang.String SHOP_NUMBER) {
set("SHOP_NUMBER", SHOP_NUMBER);
}


public java.lang.String getShopNumber() {
return get("SHOP_NUMBER");
}


/**
* 支付密钥
*/
public void setPayKey(java.lang.String PAY_KEY) {
set("PAY_KEY", PAY_KEY);
}


public java.lang.String getPayKey() {
return get("PAY_KEY");
}


/**
* 中奖模板消息ID
*/
public void setWinningNewId(java.lang.String WINNING_NEWS_ID) {
set("WINNING_NEWS_ID", WINNING_NEWS_ID);
}


public java.lang.String getWinningNewId() {
return get("WINNING_NEWS_ID");
}


/**
* 经销商userCode
*/
public void setSellerUserCode(java.lang.String SELLER_USERCODE) {
set("SELLER_USERCODE", SELLER_USERCODE);
}


public java.lang.String getSellerUserCode() {
return get("SELLER_USERCODE");
}

/**
* 经销商userID
*/
public void setSellerUserId(java.lang.String SELLER_USERID) {
set("SELLER_USERID", SELLER_USERID);
}


public java.lang.String getSellerUserId() {
return get("SELLER_USERID");
}


/**
* 备用字段一
*/
public void setSpareOne(java.lang.String SPARE_ONE) {
set("SPARE_ONE", SPARE_ONE);
}


public java.lang.String getSpareOne() {
return get("SPARE_ONE");
}


/**
* 备用字段二
*/
public void setSpareTwo(java.lang.String SPARE_TWO) {
set("SPARE_TWO", SPARE_TWO);
}


public java.lang.String getSpareTwo() {
return get("SPARE_TWO");
}


/**
* ToKen
*/
public void setToKen(java.lang.String TOKEN) {
set("TOKEN", TOKEN);
}


public java.lang.String getToKen() {
return get("TOKEN");
}


/**
* 红包发送者名称
*/
public void setSenderName(java.lang.String SENDERNAME) {
set("SENDERNAME", SENDERNAME);
}


public java.lang.String getSenderName() {
return get("SENDERNAME");
}

/**
* 祝福语
*/
public void setWish(java.lang.String WISH) {
set("WISH", WISH);
}


public java.lang.String getWish() {
return get("WISH");
}

/**
* 红包备注
*/
public void setRemarks(java.lang.String REMARKS) {
set("REMARKS", REMARKS);
}


public java.lang.String getRemarks() {
return get("REMARKS");
}
}



//这里就是微信支付了  直接调用上面微信工具类里面的方法

Map<String, String> map = WxConfigUitils.getWxConfigUitils().wxPay(openid, appId, spn.getPayKey(), mchId,

oneMoneyWxUser.getPayMoney(), getRequest().getRemoteAddr(), out_trade_no);



//微信分享java后台代码

//进入页面只需要给页面传递一个url 就是分享进入的链接 自己根据需要配置链接



//该方法是js后面访问的方法 配置微信参数



String locationUrl = getPara("locationUrl");

                //这个方法上面的微信工具类里面有

Map<String, String> wxConfigApi = WxConfigUitils.getWxConfigUitils().WxConfigApi(locationUrl);

renderJson(wxConfigApi);



//微信分享页面的js

/* 分享 */
$(".inviting-teammate").click(function() {
$(".share").show();
var shareTitle = $("#shareTitle").val();
var shareDetail = $("#shareDetail").val();
var shareImg = $("#shareImg").val();
$.ajax({
type: "GET",
url: "${basePath}/oneMoneyShop/WxShareConfig",
async: true,
dataType: "json",
data: {
"locationUrl": location.href
},
success: function(config) {
wx.config({
debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
appId: config.appId, // 必填,公众号的唯一标识
timestamp: config.timestamp, // 必填,生成签名的时间戳
nonceStr: config.nonceStr, // 必填,生成签名的随机串
signature: config.signature, // 必填,签名,见附录1
jsApiList: ['onMenuShareAppMessage', 'onMenuShareTimeline']
// 必填,需要使用的JS接口列表,所有JS接口列表见附录2
});
wx.ready(function() {
//分享朋友
wx.onMenuShareAppMessage({
title: shareTitle, // 分享标题
desc: shareDetail, // 分享描述
link: '${url}', // 分享链接
imgUrl: 'http://${systemHttp}${basePath}' + shareImg, // 分享图标
trigger: function(res) {


},
success: function() {
// 用户确认分享后执行的回调函数
},
cancel: function() {
// 用户取消分享后执行的回调函数
//alert("分享失败");
$(".shibai").css({
"display": "block"
})
}
});
//分享朋友圈
wx.onMenuShareTimeline({
title: shareTitle, // 分享标题
link: '${url}', // 分享链接
imgUrl: 'http://${systemHttp}${basePath}' + shareImg, // 分享图标
success: function() {
//alert("分享成功");
$(".chnegg").css({
"display": "block"
})
},
cancel: function() {
// 用户取消分享后执行的回调函数
//alert("分享失败");
$(".shibai").css({
"display": "block"
})
}
});
});
}
});
})





//至此微信分享、微信支付、退款完成







//最后也是第一步 微信登录获取openid 和用户信息

/**
* 获取openid和返回openid
*/
public synchronized String getOpenid(SellerPublicNumber spn) {
//获取当前线程
//Thread th=Thread.currentThread();
String code = getPara("code");
logger.error("获取code**************code>"+code);
String openid = (String) this.getSession().getAttribute(spn.getAppId());
logger.error("获取Session中的Openid="+openid+"公众号APPID="+spn.getAppId());
if(openid == null || openid.equals("")){
if (!StringUtils.isEmpty(code)) {
logger.error("*****************进来开始获取openID**********************");
//将Code放入缓存 15秒内再次处理该code认为微信中转
String wxCode = CacheKit.get("wxCode", code);
logger.error("访问时的code="+code+"缓存中是否存在="+wxCode);
//是否存在当前记录
if(!code.equals(wxCode)){
CacheKit.put("wxCode", code, code);
String appid = spn.getAppId();
String appSecret = spn.getAppSecret();
SnsAccessToken snsAccessToken = SnsAccessTokenApi.getSnsAccessToken(appid, appSecret, code);
openid = snsAccessToken.getOpenid();
getSession().setAttribute(appid, openid);
if (StringUtils.isEmpty(openid)) {
openid = getRequest().getRemoteAddr();
getSession().setAttribute(appid, openid);
}
}else{
renderError(404);
}
}else{
renderError(404);
}
}
// 判读openid是否包含英文字母。ip地址不包含英文字母
if (openid.matches(".*[a-zA-z].*")) {
} else {
// 不包含英文字母
getSession().setAttribute(spn.getAppId(), "");
}
return openid;
}


/**
* 获取AccessToken对象中的accessToken
*/
public String getAccessToken() {
String accessToken = AccessTokenApi.getAccessToken().getAccessToken();
return accessToken;

}



/**
* 获取公众号用户信息
*/
public WxUserInfo getPublicUser(String accessToken, String openid) {
// 读取用户基本信息
String token = HttpUtils.post("https://api.weixin.qq.com/cgi-bin/user/info?access_token=" + accessToken
+ "&openid=" + openid + "&lang=zh_CN", "");
log.error("token"+token);
// JSON字符串转为实体对象
WxUserInfo wxuser = Jackson.getJson().parse(token, WxUserInfo.class);
return wxuser;
}



//文章杂乱  哈哈 第一次写  干货  哈哈

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值