Home  >  Article  >  Web Front-end  >  WeChat JS-SDK customizes WeChat sharing function

WeChat JS-SDK customizes WeChat sharing function

零到壹度
零到壹度Original
2018-04-21 14:43:512326browse

This article introduces the custom WeChat sharing function of WeChat JS-SDK, which has certain reference value. Now I share it with everyone. Friends in need can refer to it

1 Preparation

appId public account id, apply for sharing interface, ip whitelist setting, JS interface security domain name setting (must be registered)

2. Introduce js

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>

3. Inject permission verification configuration through the config interface

wx.config({    
    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。    
    appId: &#39;&#39;, // 必填,公众号的唯一标识    
    timestamp: , // 必填,生成签名的时间戳    
    nonceStr: &#39;&#39;, // 必填,生成签名的随机串    
    signature: &#39;&#39;,// 必填,签名,见附录1    
    jsApiList: [   &#39;onMenuShareTimeline&#39;,    
                 &#39;onMenuShareAppMessage&#39; ,
                 &#39;onMenuShareQQ&#39;  ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2    
});

4. Process through the ready interface Successful verification

wx.ready(function(){    
// config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,
则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。    
});

5. Handle failed verification through the error interface

wx.error(function(res){    
// config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。    
});

Page source code:

wx.config({         
        debug: false,                 
        appId: &#39;xxxxxxxxxxxxxx&#39;,                 
        timestamp: timestamp,                 
        nonceStr: nonceStr,                 
        signature: signature,                 
        jsApiList: [           
                  &#39;onMenuShareTimeline&#39;,                     
                  &#39;onMenuShareAppMessage&#39; ,                 
                  &#39;onMenuShareQQ&#39;             
         ]             
});              

wx.ready(function(){       
      // wx.hideOptionMenu();             
      wx.onMenuShareTimeline({         
              title: &#39;&#39;,                 
              link: &#39;&#39;,                 
              imgUrl: &#39;&#39;,                 
              success: function () {           
                         // 用户确认分享后执行的回调函数                      
                         //alert(&#39;分享到朋友圈成功&#39;);                 
               },                 
               cancel: function () {          
                           // 用户取消分享后执行的回调函数                      
                           //alert(&#39;你没有分享到朋友圈&#39;);                 
                }             
      });             
      wx.onMenuShareAppMessage({          
               title: &#39;&#39;,                   
               desc: &#39;&#39;,                   
               link: &#39;&#39;,                   
               imgUrl: &#39;&#39;,                   
               trigger: function (res) {           
                         // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回                   
                         },                   
                         success: function (res) {           
                                     //alert(&#39;分享给朋友成功&#39;);                   
                         },                   
                         cancel: function (res) {            
                                    //alert(&#39;你没有分享给朋友&#39;);                   
                         },                   
                         fail: function (res) {            
                                   alert(JSON.stringify(res));                   
                         }               
               });             
               wx.onMenuShareQQ({       
                      title: &#39;&#39;,                  
                      desc: &#39;&#39;,                  
                      link: &#39;&#39;,                  
                      imgUrl: &#39;&#39;,             
                      success: function () {      
                             // 用户确认分享后执行的回调函数             
                             },             
                             cancel: function () {       
                             // 用户取消分享后执行的回调函数             
                             }             
                      });         
            });

java code obtains WeChat’s signature, timestamp, and signature random string

url is your current address, WeChat generates token

@RequestMapping("/doGetWxToken")
      public RespBean<Map<String,Object>> doEditAccractMemberStatus(String url) throws Except
ion{
     RespBean<Map<String,Object>>  resp = new RespBean<Map<String,Object>> ();
     Map<String,Object> map  = new HashMap<String,Object>();
     String str = SendGET("https://api.weixin.qq.com/cgi-bin/token", "grant_type=client_
credential&appid=XX&secret=XXXX");
     String a = str.substring(str.indexOf("{"), str.indexOf("}")+1);
     JSONObject jo = JSON.parseObject(a);
     String token = jo.getString("access_token");//获取token
     String info = SendGET("https://api.weixin.qq.com/cgi-bin/ticket/getticket", "access
_token="+token+"&type=jsapi");
     JSONObject ticketO = JSON.parseObject(info);
     String ticket = ticketO.getString("ticket");//获取ticket 
     Map<String, String> ret = WxSign.sign(ticket, url);         
     for (Map.Entry entry : ret.entrySet()) {         
            System.out.println(entry.getKey() + "=" + entry.getValue());                
            map.put(entry.getKey().toString(), entry.getValue());            
     }
     resp.setBody(map);
     return resp;
     }
     //直接java访问拿对应的数据
     public static String SendGET(String url,String param){
        String result="";//访问返回结果   
        BufferedReader read=null;//读取访问结果       
        
        try {    
        //创建url    
        URL realurl=new URL(url+"?"+param);    
        //打开连接    URLConnection connection=realurl.openConnection();     
        // 设置通用的请求属性       
              connection.setRequestProperty("accept", "*/*");             
              connection.setRequestProperty("connection", "Keep-Alive");             
              connection.setRequestProperty("user-agent",           
                        "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");             
              //建立连接             
              connection.connect();          
       // 获取所有响应头字段        
              Map<String, List<String>> map = connection.getHeaderFields();             
              // 遍历所有的响应头字段,获取到cookies等             
              for (String key : map.keySet()) {         
                      System.out.println(key + "--->" + map.get(key));             
              }             
              // 定义 BufferedReader输入流来读取URL的响应             
              read = new BufferedReader(new InputStreamReader(           
                      connection.getInputStream(),"UTF-8"));             
              String line;//循环读取             
              while ((line = read.readLine()) != null) {         
                      result += line;             
              }   
      } catch (IOException e) {  
        e.printStackTrace();   
      }finally{   
        if(read!=null){//关闭流     
        try {    
          read.close();     
      } catch (IOException e) {    
        e.printStackTrace();     
      }   
    }  
 }        
  return result;  
}
through the current address

The above is the detailed content of WeChat JS-SDK customizes WeChat sharing function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn