微信JS-SDK调用onMenuShareTimeline接口的问题

JaedongLee 发布于 2017/06/19 12:42
阅读 3K+
收藏 0

    我是新手,在调用微信公众平台JS-SDK接口时遇到了问题,困扰了我很久,请问应该如何解决╮(╯﹏╰)╭

    问题如下:

    wx.config配置完成后,在微信开发者工具中调用"onMenuShareTimeline"接口分享到朋友圈成功,但在Android和IOS中却失败了,如下图所示:

  在Android和IOS中,虽然显示config:ok,但却无法在分享页面显示我预设的名称和图片,如下图所示:

 

代码如下:

        请求JS-SDK的JSP页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="http://cdn.bootcss.com/jquery/3.2.1/jquery.min.js"></script>
  <script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
</head>
<body>
	中文测试
</body>
  <script>
      $(document).ready(function(){
              $.ajax({
                  type:"Get",
                  url:"./sign",
                  datatype:"json",
                  success:function(data){
                 	var obj = JSON.parse(data);
                 	var jsonstr = JSON.stringify(obj);
                 	var jsary = eval('('+jsonstr+')');
                 	alert(jsary.url)
                    wx.config({
                 	    debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                 	    appId: 'wx51b7336a2b1cd2d9', // 必填,公众号的唯一标识
                 	    timestamp: jsary.timestamp, // 必填,生成签名的时间戳
                 	    nonceStr: jsary.nonceStr, // 必填,生成签名的随机串
                 	    signature: jsary.signature,// 必填,签名,见附录1
                 	    jsApiList: [
                 	    	"onMenuShareTimeline",
                 	    	"onMenuShareQQ",
                 	    ] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2
                 	});
                 	wx.ready(function(){
                 		wx.onMenuShareTimeline({
                 		      title: '互联网之子',
                 		      link: 'http://movie.douban.com/subject/25785114/',
                 		      imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
                 		      trigger: function (res) {
                 		        // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
                 		        alert('用户点击分享到朋友圈');
                 		      },
                 		      success: function (res) {
                 		        alert('已分享');
                 		      },
                 		      cancel: function (res) {
                 		        alert('已取消');
                 		      },
                 		      fail: function (res) {
                 		        alert(JSON.stringify(res));
                 		      }
                 		    });
                 	    wx.onMenuShareQQ({
                 	       title: '互联网之子',
                 	       desc: '在长大的过程中,我才慢慢发现,我身边的所有事,别人跟我说的所有事,那些所谓本来如此,注定如此的事,它们其实没有非得如此,事情是可以改变的。更重要的是,有些事既然错了,那就该做出改变。',
                 	       link: 'http://movie.douban.com/subject/25785114/',
                 	       imgUrl: 'http://img3.douban.com/view/movie_poster_cover/spst/public/p2166127561.jpg',
                 	       trigger: function (res) {
                 	         alert('用户点击分享到QQ');
                 	       },
                 	       complete: function (res) {
                 	         alert(JSON.stringify(res));
                 	       },
                 	       success: function (res) {
                 	         alert('已分享');
                 	       },
                 	       cancel: function (res) {
                 	         alert('已取消');
                 	       },
                 	       fail: function (res) {
                 	         alert(JSON.stringify(res));
                 	       }
                 	     });
                 	});
             	  }
          	    });
       });
  </script>
</html>

    后台代码如下:

package com.tsinghua;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.*;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.io.UnsupportedEncodingException;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

    public class Sign extends HttpServlet {
        final static Gson m_gson = new GsonBuilder().setPrettyPrinting().create();


    public static Map<String, String> sign(String jsapi_ticket, String url) {
        Map<String, String> ret = new HashMap<String, String>();
        String nonce_str = create_nonce_str();
        String timestamp = create_timestamp();
        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 (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
        }
        catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }

        ret.put("url",url);
        ret.put("jsapi_ticket",jsapi_ticket);
        ret.put("nonceStr",nonce_str);
        ret.put("timestamp",timestamp);
        ret.put("signature",signature);

        return ret;
    }

    private static 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;
    }

    private static String create_nonce_str() {
        return UUID.randomUUID().toString();
    }

    private static String create_timestamp() {
        return Long.toString(System.currentTimeMillis() / 1000);
    }



    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        try {
            /*doCommon(request, response);*/
            String jsapi_ticket = "kgt8ON7yVITDhtdwci0qeXxjVFn7AZ9I21TkQnlxXoSphdHtREXQ1sdQutlFnGJWkCe7CImq7i5u_VdvhRdVmg";

            // 注意 URL 一定要动态获取,不能 hardcode
            String url = request.getHeader("Referer").toString();
            System.out.println(url);
            
    /*        String url = "http://chengchuang.cn-north-1.eb.amazonaws.com.cn/GetData.jsp";*/
            Map<String, String> ret = sign(jsapi_ticket, url);
                        sendScResponse(ret, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        try {
            /*doCommon(request, response);*/
        	this.doGet(request, response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

/*    private void doCommon(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException, SQLException {
        String jsapi_ticket = "kgt8ON7yVITDhtdwci0qeXxjVFn7AZ9I21TkQnlxXoQF3VTPc5tRORpvuB_slLD-Xua5sSwuBOrO5ZfMNGJUTA";

        // 注意 URL 一定要动态获取,不能 hardcode
        String url = request.getRequestURL().toString() + "/";
        System.out.println(url);
        String url = "http://chengchuang.cn-north-1.eb.amazonaws.com.cn/GetData.jsp";
        Map<String, String> ret = sign(jsapi_ticket, url);
                    sendScResponse(ret, response);
    }*/

    private void sendScResponse(Object obj, HttpServletResponse response) throws ServletException, IOException {
        response.setContentType("text/javascript; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        if (obj != null) {
            String responseStr = m_gson.toJson(obj);
            response.getWriter().write(responseStr);
        }
    }
}

 

加载中
0
Loveror_ahu
Loveror_ahu

腾讯为了规范分享,对分享作了同域名内分享的限制,也就是你的link不能跨域,你应该把地址

http://movie.douban.com/subject/25785114/

 放到Servlet中做跳转。

返回顶部
顶部