zoukankan      html  css  js  c++  java
  • java微信分享

    先吐槽一下!!!

    哎,张小龙写的教程真差,要研究半天才能用上,大家按我的步骤12345,包你药到病除:

    1、官方参考:

    https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421141115&token=&lang=zh_CN

    2、后端参考下面后端例子,切记在WeiXinRequest类中填入自己的appid和appsecret就可以了。不过我例子中没有添加缓存大家可以用缓存加载一下。因为token的过期时间7200不需要去频繁的调用微信签名接口

    4、前端参考下面前端例子!有个分享成功和失败的方法,要放到ready()中,不能放到外面,onMenuShareAppMessage要放到ready()中!!!切记!看代码:

    签名那些都按照上面的样例来做即可;話不多説直接后端擼代碼。前端要注意的是 簽名的URL必須是完整的路徑 即 類似  http://www.baidu.com/xxx/xxx  最好用window.location.href 來取。

    前端部分代码:

    <!DOCTYPE html><html lang="en"><head><meta charset="utf-8"><meta content="initial-scale=1,minimum-scale=1,maximum-scale=2,user-scalable=no,width=device-width" name="viewport"><meta name="theme-color" content="#000000"><link rel="manifest" href="/manifest.json"><link rel="shortcut icon" href="/favicon.ico"><script src="./polyfill.js"></script><title>123</title><link rel="stylesheet" type="text/html" href="/style.css"><link href="/static/css/main.0cc44144.css" rel="stylesheet"></head><body classname="no-scroll"><noscript>You need to enable JavaScript to run this app.</noscript><div id="root"></div><script type="text/javascript" src="/static/js/common.4d193ec3.js"></script><script type="text/javascript" src="/static/js/main.bcc71316.js"></script></body></html><script>var htmls=document.getElementsByTagName("html")[0],widths=document.body.clientWidth;widths>600&&(widths=600),htmls.style.fontSize=100*widths/375+"px"</script><script src="./jweixin.js"></script><script>window.onload=function(){

    let url="域名自己写/wx/share?shareUrl="+window.location.href
    function post(token, url, params, callback){
    return fetch(url, {
    method: 'POST',
    headers: {
    'Content-Type':'application/x-www-form-urlencoded',
    },
    body:JSON.stringify(params)
    }).
    then((response) => {
    return response.json()
    }).
    then((result) => {
    console.log(result)
    if (callback) {
    callback(result)
    }

    }).catch((error) => {
    if (callback) {
    callback({
    code:90001,
    msg:'请求出错',
    data:[],
    timestamp:''
    })
    }
    });
    }

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


    wx.ready(function () {
    // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。
    alert('wechat check')
    wx.onMenuShareAppMessage({
    title: 'wjx wechat testing', // 分享标题
    imgUrl: '分享图标', // 分享图标
    dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
    success: function () {
    // 用户确认分享后执行的回调函数
    console.log(666)
    alert('wjx wechat share testing success')
    },
    cancel: function () {
    // 用户取消分享后执行的回调函数
    console.log(6663)
    }
    });

    wx.onMenuShareTimeline({
    title: 'wjx wechat testing', // 分享标题
    imgUrl: '分享图标', // 分享图标
    dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空

    success: function () {
    // 用户确认分享后执行的回调函数
    alert('wjx wechat share testing success')
    },
    cancel: function () {
    // 用户取消分享后执行的回调函数
    }
    });


    });



    wx.error(function(res){

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





    }
    } )

    }</script>

    后端完整代码如下:

    public class WeiXinController {
    @Autowired
    private WeiXinRequest weiXinRequest;


    @PostMapping(value = "/share")
    public Map<String, String> getSignForWeiXin(@RequestParam String shareUrl) {
    String ticket = weiXinRequest.getWeiXinTicket();
    Sign sign = new Sign();
    // 注意 URL 一定要动态获取,不能 hardcode
    log.debug("[shareUrl] = " + shareUrl);
    Map<String, String> ret = sign.sign(ticket, shareUrl);
    for (Map.Entry entry : ret.entrySet()) {
    System.out.println(entry.getKey() + ", " + entry.getValue());
    }
    return ret;
    }

    }






    public class WeiXinRequest {

    private static String appId = "*******";
    private static String appSecret = "***";

    public String getWeiXinTicket() {
    String access_token;
    String ticket;
    //之后做缓存
    Object act = null;
    Object apiticket = null;

    if (null == act) {

    String url = "https://api.weixin.qq.com/cgi-bin/token";
    String jsonStrToken = sendGet(url, "grant_type=client_credential&appid="+ appId + "&secret=" + appSecret);

    log.debug("[jsonStrToken] = " + jsonStrToken);

    JSONObject json = JSONObject.parseObject(jsonStrToken);

    access_token = (String) json.getString("access_token");
    if (access_token == null) {
    return null;
    }
    } else {
    access_token = (String) act;
    }

    if (null == apiticket) {
    String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket";
    String jsonStrTicket = sendGet(url, "access_token=" + access_token + "&type=jsapi");

    log.debug("[jsonStrTicket] = " + jsonStrTicket);

    JSONObject json = JSONObject.parseObject(jsonStrTicket);
    ticket = (String) json.get("ticket");

    } else {
    ticket = (String) apiticket;
    }

    return ticket;

    }


    /**
    * 向指定URL发送GET方法的请求
    *
    * @param url
    * 发送请求的URL
    * @param param
    * 请求参数,请求参数应该是 name1=value1&name2=value2 的形式。
    * @return URL 所代表远程资源的响应结果
    */
    public String sendGet(String url, String param) {
    String result = "";
    BufferedReader in = null;
    try {
    String urlNameString = url + "?" + param;
    URL realUrl = new URL(urlNameString);
    // 打开和URL之间的连接
    URLConnection connection = realUrl.openConnection();
    // 设置通用的请求属性
    connection.setRequestProperty("accept", "*/*");
    connection.setRequestProperty("connection", "Keep-Alive");
    // 建立实际的连接
    connection.connect();
    // 获取所有响应头字段
    Map<String, List<String>> map = connection.getHeaderFields();
    // 遍历所有的响应头字段
    for (String key : map.keySet()) {
    System.out.println(key + "--->" + map.get(key));
    }
    // 定义 BufferedReader输入流来读取URL的响应
    in = new BufferedReader(new InputStreamReader(
    connection.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
    result += line;
    }

    } catch (Exception e) {
    System.out.println("发送GET请求出现异常!" + e);
    e.printStackTrace();
    }
    // 使用finally块来关闭输入流
    finally {
    try {
    if (in != null) {
    in.close();
    }
    } catch (Exception e2) {
    e2.printStackTrace();
    }
    }
    return result;
    }


    }


    前端代碼略!!
  • 相关阅读:
    斐波那契数
    组合数学
    网络流
    UVA 1104 【芯片难题 Chips Challenge】
    Luogu P3181 【[HAOI2016]找相同字符】
    Luogu P4101 【[HEOI2014]人人尽说江南好 】
    Luogu P5842 【[SCOI2012]Blinker 的仰慕者】
    BZOJ 4502 串
    Luogu P5840 【[COCI2015]Divljak】
    Luogu P3295 【[SCOI2016]萌萌哒】
  • 原文地址:https://www.cnblogs.com/java-xz/p/9336845.html
Copyright © 2011-2022 走看看