直接上代码- -

  public ResponseEntity sendRedEnvelopes(SendRedEnvelopesDto sendRedEnvelopesDto) {RedEnvelopesDto redEnvelopesDto=newRedEnvelopesDto(sendRedEnvelopesDto);Map<String,String> paramMap = null;try {paramMap = WeixinUtil.convertBeanToMap(redEnvelopesDto);} catch (Exception e) {e.printStackTrace();return ResponseEntity.ok().body(ServerResponse.buildByErrorMessage("错误的参数"));}paramMap.put("sign",WeixinUtil.getSign(paramMap,Configure.getValue("mec_key")));//签名 ,默认sign_type是MD5String reqParm=WeixinUtil.arrayToXml(paramMap);
//        WxRedPackageBiz.class.getClassLoader().getResourceAsStream(L_STRING_FILE)String unifiedStr = WxstoreUtils.postSSL(WeixinUtil.SENDREDPACK, reqParm,Configure.getValue("mec_id"),Configure.getValue("mec_path"));// logger.debug("微信红包返回数据:"+unifiedStr);Map<String, String> preMap = WeixinUtil.xmltoMap(unifiedStr);RedEnvelopesInfoWithBLOBs redEnvelopesInfo=new RedEnvelopesInfoWithBLOBs();redEnvelopesInfo.setReqPram(reqParm);redEnvelopesInfo.setRespPram(unifiedStr);redEnvelopesInfo=redEnvelopesPram(redEnvelopesInfo,preMap,sendRedEnvelopesDto);Integer sign=redEnvelopesInfoService.insertSelective(redEnvelopesInfo);if(sign.intValue()==1){return ResponseEntity.ok().body(ServerResponse.buildBySuccess(preMap));}return ResponseEntity.ok().body(ServerResponse.buildByErrorMessage("失败"));}
 public RedEnvelopesDto newRedEnvelopesDto(SendRedEnvelopesDto sendRedEnvelopesDto) {RedEnvelopesDto redEnvelopesDto =new RedEnvelopesDto();redEnvelopesDto.setNonce_str(WeixinUtil.createNoncestr(32));redEnvelopesDto.setMch_billno(sendRedEnvelopesDto.getMchBillno());redEnvelopesDto.setMch_id(Configure.getValue("mec_id"));redEnvelopesDto.setWxappid(sendRedEnvelopesDto.getAppid());redEnvelopesDto.setSend_name("有车时代");redEnvelopesDto.setRe_openid(sendRedEnvelopesDto.getReOpenid());BigDecimal decimal=new BigDecimal(sendRedEnvelopesDto.getTotalMoney());BigDecimal totalMoeny = decimal.multiply(new BigDecimal(100));Integer  total= totalMoeny.setScale(0, BigDecimal.ROUND_HALF_UP).intValue();redEnvelopesDto.setTotal_amount(total);redEnvelopesDto.setTotal_num(1);redEnvelopesDto.setWishing("红包兑换");redEnvelopesDto.setClient_ip(sendRedEnvelopesDto.getClientIp());redEnvelopesDto.setAct_name("红包兑换");redEnvelopesDto.setRemark("红包兑换");redEnvelopesDto.setScene_id("PRODUCT_2");//redEnvelopesDto.setRisk_info(map.get("riskInfo"));return redEnvelopesDto;}

微信相关配置

package com.yihulian.autoshop.third;import com.yihulian.core.server.framework.utils.tools.MD5Util;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;import javax.servlet.http.HttpServletRequest;
import java.beans.BeanInfo;
import java.beans.IntrospectionException;
import java.beans.Introspector;
import java.beans.PropertyDescriptor;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.*;/*** 微信相关工具类* ClassName:WeixinUtil * Date:     2017年10月24日 下午2:05:05 * @author   sqq * @since    JDK 1.8 */
public class WeixinUtil {/** = */public static final String QSTRING_EQUAL = "=";/** & */public static final String QSTRING_SPLIT = "&";//编码方式public static final String ENCODE = "UTF-8";//微信uri-请求预支付接口public static String UNIFIED_ORDER = "https://api.mch.weixin.qq.com/pay/unifiedorder";public static String SENDREDPACK = "https://api.mch.weixin.qq.com/mmpaymkttransfers/sendredpack";/*** 对象转换成map* @param bean* @return* @throws IntrospectionException* @throws IllegalAccessException* @throws InvocationTargetException*/public static Map<String, String> convertBeanToMap(Object bean) throws IntrospectionException, IllegalAccessException, InvocationTargetException {Class type = bean.getClass();Map<String, String> returnMap = new HashMap<String, String>();BeanInfo beanInfo = Introspector.getBeanInfo(type);PropertyDescriptor[] propertyDescriptors = beanInfo.getPropertyDescriptors();for (int i = 0; i < propertyDescriptors.length; i++) {PropertyDescriptor descriptor = propertyDescriptors[i];String propertyName = descriptor.getName();if (!propertyName.equals("class")) {Method readMethod = descriptor.getReadMethod();Object result = readMethod.invoke(bean, new Object[0]);if (result != null) {returnMap.put(propertyName, result.toString());} else {returnMap.put(propertyName, "");}}}Map<String,String> map=new TreeMap<String, String>();for (String key : returnMap.keySet()) {////       System.out.println("-------------------------:" + key);//值为空不参加签名if(returnMap.get(key)!=null && !"".equals(returnMap.get(key))){//            System.out.println("-------------------------1:" + key);map.put(key,returnMap.get(key));}}return map;}/***   作用:产生随机字符串,不长于32位*/public static String createNoncestr(int length){String chars = "abcdefghijklmnopqrstuvwxyz0123456789";  String str ="";Random rand = new Random();for (int i = 0; i < length; i++) {int index = rand.nextInt(chars.length());str += chars.substring(index, index + 1);} return str;}/***  把请求要素按照“参数=参数值”的模式用“&”字符拼接成字符串* @param para 请求要素* @param sort 是否需要根据key值作升序排列* @param encode 是否需要URL编码* @return 拼接成的字符串*/public static String formatBizQueryParaMap(Map<String,String> para,boolean sort, boolean encode){List<String> keys = new ArrayList<String>(para.keySet());if (sort)Collections.sort(keys);StringBuilder sb = new StringBuilder();for (int i = 0; i < keys.size(); i++) {String key = keys.get(i);String value = para.get(key);if (encode) {try {value = URLEncoder.encode(value, ENCODE);} catch (UnsupportedEncodingException e) {}}if (i == keys.size() - 1) {//拼接时,不包括最后一个&字符sb.append(key).append(QSTRING_EQUAL).append(value);} else {sb.append(key).append(QSTRING_EQUAL).append(value).append(QSTRING_SPLIT);}}return sb.toString();}//  /**
//   *  作用:生成签名
//   */
//  public static String getSign(Map<String,String> paramMap,String merchantkey)
//  {
//  //  System.out.println("------------------bef-----------");ofr
//      Map<String,String> map=new TreeMap<>();
//      for (String key : paramMap.keySet()) {//
//  //      System.out.println("-------------------------:" + key);
//          //值为空不参加签名
//          if(paramMap.get(key)!=null && !"".equals(paramMap.get(key))){
//  //          System.out.println("-------------------------1:" + key);
//              map.put(paramMap.get(key),paramMap.get(key));
//          }
//      }
//        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
//        // 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)
//        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());
//            }
//        });
//
//      String params = formatBizQueryParaMap(map, true, false);
//      //echo '【string1】'.$String.'</br>';
//      //签名步骤二:在string后加入KEY
//      params = params + "&key=" + merchantkey;//
//      //echo "【string2】".$String."</br>";
//      //签名步骤三:MD5加密并转大写
//      params = MD5Util.encodeByMD5(params);
//      //echo "【string3】 ".$String."</br>";
//      //签名步骤四:所有字符转为大写
//      //echo "【result】 ".$result_."</br>";
//      return params;
//  }/*** 生成签名* @param paramMap* @return*/public static String getSign(Map<String, String> paramMap,String merchantkey) {String result = "";try {List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(paramMap.entrySet());// 对所有传入参数按照字段名的 ASCII 码从小到大排序(字典序)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());}});// 构造签名键值对的格式StringBuilder sb = new StringBuilder();for (Map.Entry<String, String> item : infoIds) {if (item.getKey() != null || item.getKey() != "") {String key = item.getKey();String val = item.getValue();if (!(val == "" || val == null)) {sb.append(key + "=" + val + "&");}}}sb.append("key=" + merchantkey);result = sb.toString();//签名步骤三:MD5加密并转大写result =encodeByMD5(result);//进行MD5加密// result = DigestUtils.md5Hex(result).toUpperCase();} catch (Exception e) {return null;}return result;}/*** MD5加密(UTF-8编码,32位,转大写)* @param originstr* @return*/public static String encodeByMD5(String originstr) {String result = "";try {MessageDigest md5 = MessageDigest.getInstance("MD5");md5.update(originstr.getBytes("UTF-8"));byte b[] = md5.digest();int i;StringBuffer buf = new StringBuffer("");for (int offset = 0; offset < b.length; offset++) {i = b[offset];if (i < 0) {i += 256;}if (i < 16) {buf.append("0");}buf.append(Integer.toHexString(i));}result = buf.toString().toUpperCase();} catch (NoSuchAlgorithmException e) {e.printStackTrace();} catch (UnsupportedEncodingException e) {e.printStackTrace();}return result;}/***   作用:map转xml*/public static String arrayToXml(Map<String,String> paramMap){String xml = "<xml>";for (String key : paramMap.keySet()) {////值是否只有字母和数字
//          if(paramMap.get(key).matches("^[\\da-zA-Z]*$")){
//              xml += "<" + key + ">" + paramMap.get(key) + "</" + key + ">";
//          }else{xml += "<" + key + "><![CDATA[" + paramMap.get(key) + "]]></" + key + ">";//xml += "<" + key + "><" + paramMap.get(key) + "></" + key + ">";//}}xml += "</xml>";return xml;}/*** xml 转  map* @param xml* @return*/public static Map<String,String> xmltoMap(String xml) {  try {  Map<String,String> map = new HashMap<String,String>();  Document document = DocumentHelper.parseText(xml);  Element nodeElement = document.getRootElement();  List node = nodeElement.elements();  for (Iterator it = node.iterator(); it.hasNext();) {Element elm = (Element) it.next();  String val = elm.getText();val = val.replace("<![CDATA[", "");val = val.replace("]]>", "");map.put(elm.getName(), val);  elm = null;  }  node = null;nodeElement = null;  document = null;  return map;  } catch (Exception e) {  e.printStackTrace();  }  return null;  }/*** jsonStrToMap:(json转map).* @author sqq* @param jsonStr* @return* @since JDK 1.8*/public static Map<String, Object> jsonStrToMap(String jsonStr){Map<String, Object> map = new HashMap<String, Object>();//最外层解析JSONObject json = JSONObject.fromObject(jsonStr);for(Object k : json.keySet()){Object v = json.get(k);//如果内层还是数组的话,继续解析if(v instanceof JSONArray){List<Map<String, Object>> list = new ArrayList<Map<String,Object>>();Iterator<JSONObject> it = ((JSONArray)v).iterator();while(it.hasNext()){JSONObject json2 = it.next();list.add(jsonStrToMap(json2.toString()));}map.put(k.toString(), list);} else {map.put(k.toString(), v);}}return map;}/*** 获取ip地址* getRemoteHost* @author sqq* @param request* @return* @since JDK 1.8*/public static String getRemoteHost(javax.servlet.http.HttpServletRequest request){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();}return ip.equals("0:0:0:0:0:0:0:1")?"127.0.0.1":ip;}/** * 获取精确到秒的时间戳 * @param date * @return */  public static int getTimestamp(Date date){  if (null == date) {  return 0;  }  String timestamp = String.valueOf(date.getTime()/1000);  return Integer.valueOf(timestamp);  }/*** 授权统一路径拼凑* @return* @throws Exception*/public String doWeixinRedirectUrl(HttpServletRequest request) throws Exception{//特别注意:params分享会出现code过期参数  应去掉后作为回调地址//    String server_url_name = PropertiesUtil.getValue("SERVER_URL_NAME");//服务器地址String returl = request.getScheme()+"://"+ request.getServerName() + request.getRequestURI(); Map<String,String[]> paramMap = request.getParameterMap();String params = "";int next = 0;//过滤code、statefor (String key : paramMap.keySet()) {String[] strs = paramMap.get(key);if(!key.equals("code") && !key.equals("state")){if(next == 0){params += "?";}else{params += "&";}params += key + "=" + strs[0];next ++;}}System.out.println("params:" + params);String dqurl = returl + params;dqurl = URLEncoder.encode(dqurl, "utf-8");String url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+  "&redirect_uri="+ dqurl +"&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";return url;}
}

至此  完了       公众号要想发  红包  需要公众号上关联商户号

几个特殊的字符串   mec_id  商户号ID  mec_key  商户号秘钥   mec_path 商户号中有个 apiclient_cert.p12文件  这个文件的路径  我是直接引用网上的

appid  是发放公众号的

微信开放平台-- 微信红包发放相关推荐

  1. 微信开放平台·微信公众号接口调用报错【“errcode“:48001“errmsg“:“api unauthorized...“】

    目录 问题描述 使用场景 解决方案 问题描述 使用场景 复现场景: 微信开放平台·微信公众号链接:微信开发平台 按照文档说明通过 code 获取 access_token 检验授权凭证(access_ ...

  2. 微信 开放平台 微信小商店

    最近因为一些原因开发了一份开发平台开通小商店 的代码,文档实在是太差了,以此做一些记录 开放平台帮助客户开通小商店可以免除300元认证费用,下面是需要实现的最基本的需求.另外本次使用了 微信云托过,在 ...

  3. 微信开放平台注册和添加应用操作指南

    操作步骤 1.注册/登录微信开放平台 微信开发平台网址:https://open.weixin.qq.com/ 2.申请开发者资质认证 2.1.登录以后点击账号中心->开发者资质认证 2.2.按 ...

  4. 微信公众平台与微信开放平台的区别、服务号、订阅号、企业微信的区别

    微信公众平台 vs 微信开放平台 微信公众平台是介绍公众号相关的内容,比如服务号.订阅号.企业微信,所以叫微信公众平台:公众平台也是公众号的管理端,可以编辑推送文章,通常是公众号的运营.开发登录: 微 ...

  5. 微信开放平台与微信公众平台简介

    微信开放平台地址:微信开放平台 微信公众平台地址:微信公众平台 一.微信开放平台常用功能 app: 分享与收藏 微信登录 微信支付 智能接口(具体参看文档) 网站: 微信登录 智能接口(具体参看文档) ...

  6. 微信开放平台开发(2) 网站应用微信登录

    关键字:微信公众平台 微信开放平台 微信登录 微信扫码登录 使用微信账号登录网站 作者:方倍工作室  原文:http://www.cnblogs.com/txw1958/p/weixin-qrlogi ...

  7. 微信商业闭环谈论之微信开放平台实现微信卡券投放实践(附部分JAVA源码)

    一.微信卡券及现状 先认识几个概念:微信开放平台.公众号第三方平台和微信公众平台开发者模式. 微信开放平台:简单的说,是用于微信生态平台,该平台提供各种接口,第三方App通过接口接入微信登录.微信分享 ...

  8. 微信现金红包接口实现红包发放

    微信现金红包接口实现红包发放: 一:流程:[ 流程:微信用户访问红包活动页面-->后端判断是否是微信访问的 [否:提示用微信打开连接,是:提示用户是否授权允许,获取其的用户信息[openID等信 ...

  9. python 微信支付 小程序红包 发放红包接口

    python 微信支付 小程序红包 发放红包接口 文章目录 python 微信支付 小程序红包 发放红包接口 前言 一.官方文档 二.使用步骤 1.引入,直接复制粘贴以下代码,新建wx_pay.py ...

最新文章

  1. tried to access method com.google.common.base.Stopwatch
  2. 接收xml参数_SpringBoot实战(二):接收xml请求
  3. CentOS 6 5安装Erlang/OTP 17 0
  4. 有没有办法为Node.js项目自动构建package.json文件
  5. Ros学习笔记(三)创建节点及节点之间通信
  6. Linux Cgroups详解(一)
  7. 【AllenNLP入门教程】: 1、基于Allennlp2.4版本的文本分类
  8. 学习笔记(01):2019软考网络工程师--基础知识视频教程-数据通信基础(一)
  9. wake on LAN: 三分钟实现从Linux和Windows设备上远程唤醒设备
  10. 三星固态Dell版的960g的sm863a硬盘
  11. 傻子也能看懂的弗洛伊德算法(转)
  12. 教资高中计算机科目,中学信息技术考试科目
  13. Vanishing point detection
  14. 小学三年级计算机画图工具作品,小学三年级美术下册《电脑绘画—模板帮我们作画》教案...
  15. 手机芯片性能排名天梯图2022
  16. 电信增值短信平台软件模块清单(sp专用)
  17. [Android UI] graphics
  18. 桌面存放linux文件无法删除,桌面文件无法删除怎么办【图文教程】
  19. 一文透析腾讯云云上攻防体系
  20. python 读取3D obj文件

热门文章

  1. VHDL D触发器 4位移位寄存器 例化+仿真(功能时序)
  2. mysql显示表已存在_mysql的安装与卸载
  3. java精讲_《Java核心技术精讲(李兴华)》PDF 下载
  4. win 10 电脑与 H C-05蓝牙模块连接方法集合(含k60 CRC 校验代码软件下载地址)
  5. java+selenium的入门 案例 selenium包 谷歌驱动包 火狐驱动包 IE驱动包 (一)
  6. 我说怎么flickr上不去了呢?
  7. (转)quest3D项目管理
  8. CIE RGB、CIE XYZ、 Lab空间转换
  9. [RK3288-Android8.1]cw2015驱动调试曲折
  10. 一文搞懂AWS Region, VPC, VPC endpoint,AZ, Subnet 基础篇上