微信分享

1.1 JSSDK使用步骤

1.1.1 步骤一:绑定域名

步骤一:绑定域名

先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。

备注:登录后可在“开发者中心”查看对应的接口权限。


点击设置js安全域名域名,下载此文件到项目根目录,并设置一个外网域名.下载好以后启动项目,与安全域名对接.点击确认设置成功


项目中如下


1.1.2 步骤二:引入JS文件



1.1.3 步骤三:通过config接口注入权限验证配置


1:appid  下图获得


2:timestamp 时间戳

timestamp= Long.toString(System.currentTimeMillis() / 1000);

3:nonceStr 随机串

nonceStr=UUID.randomUUID().toString();

4:signature 签名

//获取access_token



String APPID=XXX;

String APPSECRET=XXX;

String tokenUrl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+APPID+"&secret="+APPSECRET;

AccessTokenDTO accessTokenDTO=new Gson().fromJson(tokenUrl,AcessTokenDTO.class);

String ACCESS_TOKEN =accessTokenDTO.getAccessToken();

String jsapiUrl="https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+ACCESS_TOKEN+"&type=jsapi";

//获取ticket

String ticketJson="";

ticketJson=HttpClientUtil.doGet(jsapiUrl);

TicketDTO ticketDTO=new Gson().fromJson(ticketJson,TicketDTO.class);

String ticket="";

ticket=ticketDTO.getTicket();


HttpClientUtil源码:

package XXX.XXXX.XX;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.net.HttpURLConnection;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.http.NameValuePair;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.ContentType;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;

public class HttpClientUtil {

   public static String doGet(String url, Map<String, String> param) {

      // 创建Httpclient对象
      CloseableHttpClient httpclient = HttpClients.createDefault();

      String resultString = "";
      CloseableHttpResponse response = null;
      try {
         // 创建uri
         URIBuilder builder = new URIBuilder(url);
         if (param != null) {
            for (String key : param.keySet()) {
               builder.addParameter(key, param.get(key));
            }
         }
         URI uri = builder.build();

         // 创建http GET请求
         HttpGet httpGet = new HttpGet(uri);

         // 执行请求
         response = httpclient.execute(httpGet);
         // 判断返回状态是否为200
         if (response.getStatusLine().getStatusCode() == 200) {
            resultString = EntityUtils.toString(response.getEntity(), "UTF-8");
         }
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            if (response != null) {
               response.close();
            }
            httpclient.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }
      return resultString;
   }

   public static String doGet(String url) {
      return doGet(url, null);
   }

   public static String doPost(String url, Map<String, String> param) {
      // 创建Httpclient对象
      CloseableHttpClient httpClient = HttpClients.createDefault();
      
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建参数列表
         if (param != null) {
            List<NameValuePair> paramList =new ArrayList<NameValuePair>();
            for (String key : param.keySet()) {
               paramList.add(new BasicNameValuePair(key, param.get(key)));
            }
            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
            httpPost.setEntity(entity);
         }
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return resultString;
   }

   public static String doPost(String url) {
      return doPost(url, null);
   }
   
   public static String doPostJson(String url, String json) {
      // 创建Httpclient对象
      CloseableHttpClient httpClient = HttpClients.createDefault();
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建请求内容
         StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
         httpPost.setEntity(entity);
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return resultString;
   }
   
   
   public static String doPostJson(String url, String json, Integer timeOut) {
      // 创建Httpclient对象
      RequestConfig requestConfig = RequestConfig.custom()  
              .setConnectTimeout(timeOut)
              .setConnectionRequestTimeout(timeOut)  
              .setSocketTimeout(timeOut)
              .build();  
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
            
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建请求内容
         StringEntity entity = new StringEntity(json, ContentType.APPLICATION_JSON);
         httpPost.setEntity(entity);
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return resultString;
   }
   
   public static String doPost(String url, Map<String, String> param, Integer timeOut) {
      // 创建Httpclient对象
      RequestConfig requestConfig = RequestConfig.custom()  
              .setConnectTimeout(timeOut)
              .setConnectionRequestTimeout(timeOut)  
              .setSocketTimeout(timeOut)
              .build();  
      CloseableHttpClient httpClient = HttpClients.custom().setDefaultRequestConfig(requestConfig).build();
      
      CloseableHttpResponse response = null;
      String resultString = "";
      try {
         // 创建Http Post请求
         HttpPost httpPost = new HttpPost(url);
         // 创建参数列表
         if (param != null) {
            List<NameValuePair> paramList =new ArrayList<NameValuePair>();
            for (String key : param.keySet()) {
               paramList.add(new BasicNameValuePair(key, param.get(key)));
            }
            // 模拟表单
            UrlEncodedFormEntity entity = new UrlEncodedFormEntity(paramList);
            httpPost.setEntity(entity);
         }
         // 执行http请求
         response = httpClient.execute(httpPost);
         resultString = EntityUtils.toString(response.getEntity(), "utf-8");
      } catch (Exception e) {
         e.printStackTrace();
      } finally {
         try {
            response.close();
         } catch (IOException e) {
            e.printStackTrace();
         }
      }

      return resultString;
   }
   
      /** 
     * 根据地址获得数据的字节流 
     * @param strUrl 网络连接地址 
     * @return 
     */  
    public static byte[] getImageFromNetByUrl(String strUrl){  
        try {  
            URL url = new URL(strUrl);  
            HttpURLConnection conn = (HttpURLConnection)url.openConnection();  
            conn.setRequestMethod("GET");  
            conn.setConnectTimeout(5 * 1000);  
            InputStream inStream = conn.getInputStream();//通过输入流获取图片数据  
            byte[] btImg = readInputStream(inStream);//得到图片的二进制数据  
            return btImg;  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return null;  
    }  
    
    /** 
     * 从输入流中获取数据 
     * @param inStream 输入流 
     * @return 
     * @throws Exception 
     */  
    public static byte[] readInputStream(InputStream inStream) throws Exception{  
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();  
        byte[] buffer = new byte[1024];  
        int len = 0;  
        while( (len=inStream.read(buffer)) != -1 ){  
            outStream.write(buffer, 0, len);  
        }  
        inStream.close();  
        return outStream.toByteArray();  
    }  
    
    
    private static String TruncateUrlPage(String strURL) {
      String strAllParam = null;
      String[] arrSplit = null;
      strURL = strURL.trim().toLowerCase();
      arrSplit = strURL.split("[?]");
      if (strURL.length() > 1) {
         if (arrSplit.length > 1) {
            if (arrSplit[1] != null) {
               strAllParam = arrSplit[1];
            }
         }
      }
      return strAllParam;
   }

    /**
     * 
     * <p>Title: URLRequest</p>
     * <p>Description: 提取URL中的值</p>
     * @param URL
     * @return
     */
   public static Map<String, String> urlRequest(String URL) {
      Map<String, String> mapRequest = new HashMap<String, String>();
      String[] arrSplit = null;
      String strUrlParam = TruncateUrlPage(URL);
      if (strUrlParam == null) {
         return mapRequest;
      }
      // 每个键值为一组 www.2cto.com
      arrSplit = strUrlParam.split("[&]");
      for (String strSplit : arrSplit) {
         String[] arrSplitEqual = null;
         arrSplitEqual = strSplit.split("[=]");
         // 解析出键值
         if (arrSplitEqual.length > 1) {
            // 正确解析
            mapRequest.put(arrSplitEqual[0], arrSplitEqual[1]);
         } else {
            if (arrSplitEqual[0] != "") {
               // 只有参数没有值,不加入
               mapRequest.put(arrSplitEqual[0], "");
            }
         }
      }
      return mapRequest;
   }
   
   /**
    * 发送HttpPost请求
    *
    * @param strURL
    *            服务地址
    * @param params
    *            json字符串,例如: "{ \"id\":\"12345\" }" ;其中属性名必须带双引号<br/>
    * @return 成功:返回json字符串<br/>
    */
   public static String post(String strURL, String params) {
      System.out.println(strURL);
      System.out.println(params);
      try {
         URL url = new URL(strURL);// 创建连接
         HttpURLConnection connection = (HttpURLConnection) url
               .openConnection();
         connection.setDoOutput(true);
         connection.setDoInput(true);
         connection.setUseCaches(false);
         connection.setInstanceFollowRedirects(true);
         connection.setRequestMethod("POST"); // 设置请求方式
         connection.setRequestProperty("Accept", "application/json"); // 设置接收数据的格式
         connection.setRequestProperty("Content-Type", "application/json"); // 设置发送数据的格式
         connection.connect();
         OutputStreamWriter out = new OutputStreamWriter(connection.getOutputStream(), "UTF-8"); // utf-8编码
         out.append(params);
         out.flush();
         out.close();
         // 读取响应
         int length = (int) connection.getContentLength();// 获取长度
         InputStream is = connection.getInputStream();
         if (length != -1) {
            byte[] data = new byte[length];
            byte[] temp = new byte[512];
            int readLen = 0;
            int destPos = 0;
            while ((readLen = is.read(temp)) > 0) {
               System.arraycopy(temp, 0, data, destPos, readLen);
               destPos += readLen;
            }
            String result = new String(data, "UTF-8"); // utf-8编码
            System.out.println(result);
            return result;
         }
      } catch (IOException e) {
         e.printStackTrace();
      }
      return "error"; // 自定义错误信息
   }
    
}
Gson pom依赖:

<dependency>
   <groupId>com.google.code.gson</groupId>
   <artifactId>gson</artifactId>
</dependency>

TicketDTO:

package xxx.xxx.xx.xx

import com.fasterxml.jackson.annotation.JsonProperty;

/**
 * 临时票据Ticket 数据封装类
 * @author xxx
 * @data 2018/5/29
 */
public class TicketDTO {

    private String errcode;
    private String errmsg;
    private String ticket;
    /**
     * 此注解用于属性上,作用是把该属性的名称序列化为另外一个名称
     */
    @JsonProperty("expires_in")
    private String expiresIn;

    public String getErrcode() {
        return errcode;
    }

    public void setErrcode(String errcode) {
        this.errcode = errcode;
    }

    public String getErrmsg() {
        return errmsg;
    }

    public void setErrmsg(String errmsg) {
        this.errmsg = errmsg;
    }

    public String getTicket() {
        return ticket;
    }

    public void setTicket(String ticket) {
        this.ticket = ticket;
    }

    public String getExpiresIn() {
        return expiresIn;
    }

    public void setExpiresIn(String expiresIn) {
        this.expiresIn = expiresIn;
    }

    @Override
    public String toString() {
        return "TicketDTO{" +
                "errcode='" + errcode + '\'' +
                ", errmsg='" + errmsg + '\'' +
                ", ticket='" + ticket + '\'' +
                ", expiresIn='" + expiresIn + '\'' +
                '}';
    }

}

@JsonProperty pom依赖

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.5.3</version>
</dependency>


String url =跳转分享的域名:自定义

String string1;

String signature = "";

string1 = "jsapi_ticket=" + jsapi_ticket +

                  "&noncestr=" + nonce_str +
                  "&timestamp=" + timestamp +
                  "&url=" + url;
        System.out.println(string1);
        try
        {
            MessageDigest crypt = MessageDigest.getInstance("SHA-1");
            crypt.reset();
            crypt.update(string1.getBytes("UTF-8"));

            signature = byteToHex(crypt.digest());

        }catch(Exception ex){}


将数据传递给前端js:wx.config接收;



1.1.4 步骤四:通过ready接口处理成功验证:wx.config验证成功以后触发事件动作

wx.ready(function(){    //放入要分享的事件});例如:

1.1.5 步骤五:通过error接口处理失败验证wx.config验证失败以后触发事件动作


1.2 接口调用说明

2 基础接口

2.1 判断当前客户端版本是否支持指定JS接口

3 分享接口

3.1 获取“分享到朋友圈”按钮点击状态及自定义分享内容接口(即将废弃)

3.2 获取“分享给朋友”按钮点击状态及自定义分享内容接口(即将废弃)

3.3 获取“分享到QQ”按钮点击状态及自定义分享内容接口

3.4 获取“分享到腾讯微博”按钮点击状态及自定义分享内容接口

3.5 获取“分享到QQ空间”按钮点击状态及自定义分享内容接口

4 图像接口

4.1 拍照或从手机相册中选图接口

4.2 预览图片接口

4.3 上传图片接口

4.4 下载图片接口

4.5 获取本地图片接口

5 音频接口

5.1 开始录音接口

5.2 停止录音接口

5.3 监听录音自动停止接口

5.4 播放语音接口

5.5 暂停播放接口

5.6 停止播放接口

5.7 监听语音播放完毕接口

5.8 上传语音接口

5.9 下载语音接口

6 智能接口

6.1 识别音频并返回识别结果接口

7 设备信息

7.1 获取网络状态接口

8 地理位置

8.1 使用微信内置地图查看位置接口

8.2 获取地理位置接口

9 摇一摇周边

9.1 开启查找周边ibeacon设备接口

9.2 关闭查找周边ibeacon设备接口

9.3 监听周边ibeacon设备接口

10 界面操作

10.1 隐藏右上角菜单接口

10.2 显示右上角菜单接口

10.3 关闭当前网页窗口接口

10.4 批量隐藏功能按钮接口

10.5 批量显示功能按钮接口

10.6 隐藏所有非基础按钮接口

10.7 显示所有功能按钮接口

11 微信扫一扫

11.1 调起微信扫一扫接口

12 微信小店

12.1 跳转微信商品页接口

13 微信卡券

13.1 获取api_ticket

13.2 拉取适用卡券列表并获取用户选择信息

13.3 批量添加卡券接口

13.4 查看微信卡包中的卡券接口

14 微信支付

14.1 发起一个微信支付请求

15 快速输入

15.1 共享微信收货地址

16 附录1-JS-SDK使用权限签名算法

17 附录2-所有JS接口列表

18 附录3-所有菜单项列表

19 附录4-卡券扩展字段及签名生成算法

20 附录5-常见错误及解决方法

21 附录6-DEMO页面和示例代码

22 附录7-问题反馈


  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值