微信分享(配置+开发)简单流程【只要配置的参数没问题,就easy】

首先网上查资料,没有和配置结合,踩了坑(又不爱看官方文档,文字太多一堆口水话)

。。。。。整理下自己完整的步骤

1、公众号【基本配置】里面的【服务器配置】

(下面必须要空降方法,不然配置验证通不过)

一、首先项目导入公众号的jar包

<!-- 微信公众号 -->
<dependency>
   <groupId>com.github.binarywang</groupId>
   <artifactId>weixin-java-mp</artifactId>
   <version>2.3.0</version>
</dependency>

二、服务中WeixinController提供如下方法

注意:weixinService需要继承WxMpServiceImpl

public class WeixinService extends WxMpServiceImpl)
weixinService.checkSignature(timestamp, nonce, signature)方法是jar包自带的方法
/**
     * 1、用于公众号【服务器配置】验证——然后才有token(坑)
     * @param signature
     * @param timestamp
     * @param nonce
     * @param echostr
     * @return
     */
    @RequestMapping(value = "/wechat/check.do", method = RequestMethod.GET, produces = "text/plain;charset=utf-8")
    public
    String authGet(@RequestParam("signature") String signature,
                   @RequestParam("timestamp") String timestamp, @RequestParam("nonce") String nonce,
                   @RequestParam("echostr") String echostr) {
        logger.info("接收到来自微信服务器的认证消息:[{},{},{},{}]", signature, timestamp, nonce, echostr);
        if (weixinService.checkSignature(timestamp, nonce, signature)) {
            return echostr;
        }
        return "非法请求";
    }

三、公众号配置自己需要做分享操作的域名

2、配置公众号的appId、secretKey等参数

 

 

wechat.AppID=wx28xxxcf239xx
wechat.AppSecret=938b579878798619542d6xxxxxf03000
wechat.ybyc.token=自定义的token,copy过来
wechat.ybyc.EncodingAESKey=随机生成的AESKey

3、获取微信JSAPI初始化所需信息

Controller代码

    @RequestMapping(value = "/wechat/config.do", method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
    public String getWXConfig(HttpServletRequest request) throws Exception {
        Map map = new HashMap<>();
        Map resultMap = new HashMap<>();        
        try {
            map.put("clientUrl", request.getParameter("clientUrl"));//当前页面所在的浏览器URL全路径,由于该支付为jssdk支付,所以需要url地址.参与后台sign签名
            /** 获取用户的微信客户端版本号,用于前端支付之前进行版本判断,微信版本低于5.0无法使用微信支付 */
            /*String userAgent = request.getHeader("user-agent");
            if (StringUtils.isNotBlank(userAgent)){
                char agent = userAgent.charAt(userAgent.indexOf("MicroMessenger") + 15);
                map.put("agent", new String(new char[]{agent}));
            }*/
			resultMap = weixinService.getConfig(map);            
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage(), e);
        }
        return new Gson().toJson(resultMap);
    }

service代码

    /**
     * 获取微信JSAPI初始化所需信息
     */
    public Map getConfig(Map requestMap) {
        String clientUrl = (String) requestMap.get("clientUrl");
        String jsapiTicket = "";
        try {
            jsapiTicket = this.getJsapiTicket();
        } catch (WxErrorException e) {
            e.printStackTrace();
        }
        String nonceStr = 生成一个UUID;
        String timeStamp = Long.toString(System.currentTimeMillis() / 1000);
        String string1 = "jsapi_ticket=" + jsapiTicket +
                "&noncestr=" + nonceStr +
                "×tamp=" + timeStamp +
                "&url=" + clientUrl;
        String signature = "";
        signature = SHA1.gen(string1);
        //logger.info("待签名的字符串为:{}, 签名后: {}", string1, signature);
        Map<String, Object> reponseMap = new HashMap<>();
        reponseMap.put("appId", 注意自己公众号的appId);
        reponseMap.put("timeStamp", timeStamp);
        reponseMap.put("nonceStr", nonceStr);
        reponseMap.put("signature", signature);
        reponseMap.put("agent", requestMap.get("agent"));
        //微信分享相关
        reponseMap.put("imgUrl", "https://www.baidu.com/img/bd_logo1.png");
        reponseMap.put("shareTitle", "来自……爸爸的测试");
        reponseMap.put("descContent", "第一次测试有点紧张,不要慌");
        reponseMap.put("lineLink", "http://www.xxx.com/jxq/index.html");
        return reponseMap;
    }

 

4、前端wechat.js工具封装的分享

 

var timeStamp,nonceStr,appId,agent;

var imgUrl,lineLink,shareTitle,descContent;

var shareType,shareId;

$(function(){
    //当前完整路径(请求后台,获取jssdk支付所需的参数,应该可以不要)
    var clientUrl = window.location.href.split('#')[0];
	
    $.ajax({
        type: 'get',
        url: 'http://www.ybycedu.com/core/wechat/config.do',
        dataType: 'json',
        data: {
            "clientUrl": clientUrl //当前页面所在的浏览器URL全路径,由于该支付为jssdk支付,所以需要url地址.参与后台sign签名
        },
        cache: false,
        error: function () {
            alert("系统错误,请稍后重试");
            return false;
        },
        success: function (data) {
            timeStamp = data.obj.timeStamp;
            nonceStr = data.obj.nonceStr;
            appId = data.obj.appId;
            agent = data.obj.agent;
            imgUrl = data.obj.imgUrl;
            lineLink = data.obj.lineLink;
            shareTitle = data.obj.shareTitle;
            descContent = data.obj.descContent;
            //JSSDK支付所需的配置参数,首先会检查signature是否合法。
            wx.config({
                debug: false, //开启debug模式,测试的时候会有alert提示
                appId: appId, //公众平台中-开发者中心-appid
                timestamp: timeStamp, //时间戳
                nonceStr: nonceStr, //随机字符串,不长于32位
                signature: data.obj.signature, //这里的signature是后台使用SHA1签名算法得出,不是MD5,与下面的wx.chooseWXPay中的paySign不同,下面的paySign是后台使用MD5加密得出
                jsApiList: [ //指定哪些JS接口有权限访问
                    'chooseWXPay','onMenuShareTimeline','onMenuShareAppMessage','getLocation','startRecord','stopRecord','onVoiceRecordEnd','playVoice','pauseVoice','stopVoice','onVoicePlayEnd','uploadVoice','downloadVoice'
                ]
            });
            //上方的config检测通过后,会执行ready方法
            wx.ready(function () {
                if (typeof WeixinJSBridge == "undefined"){
                    if( document.addEventListener ){
                        document.addEventListener('WeixinJSBridgeReady', onBridgeReady, false);
                    }else if (document.attachEvent){
                        document.attachEvent('WeixinJSBridgeReady', onBridgeReady);
                        document.attachEvent('onWeixinJSBridgeReady', onBridgeReady);
                    }
                }else{
                    onBridgeReady();
                }
            });
            wx.error(function (res) {
                alert("检测出问题:" + res.errMsg);
            });
        }
    });
});

function onBridgeReady() {
    // 发送给好友
    WeixinJSBridge.on('menu:share:appmessage', shareFriend);
    // 分享到朋友圈
    WeixinJSBridge.on('menu:share:timeline', shareTimeline);
    // 分享到微博
    WeixinJSBridge.on('menu:share:weibo', shareWeibo);
}

//分享给好友
function shareFriend() {
    WeixinJSBridge.invoke('sendAppMessage',{
        "appid": appId,
        "img_url": imgUrl,
        "img_width": "200",
        "img_height": "200",
        "link": lineLink,
        "desc": descContent,
        "title": shareTitle
    }, function(res) {
        if(res.err_msg=="send_app_msg:ok"){
            // alert("发送给好友成功");
        }
    })
}

//分享到朋友圈
function shareTimeline() {
    WeixinJSBridge.invoke('shareTimeline',{
        "img_url": imgUrl,
        "img_width": "200",
        "img_height": "200",
        "link": lineLink,
        "desc": descContent,
        "title": shareTitle
    }, function(res) {
        if(res.err_msg == 'share_timeline:ok'){
            // alert("分享成功");
        }
    });
}

//分享到微博
function shareWeibo() {
    WeixinJSBridge.invoke('shareWeibo',{
        "content": descContent,
        "url": lineLink
    }, function(res) {
        if(res.err_msg == "share_weibo:ok"){
            alert("分享到微博成功");
        }
    });
}

.

.

.

.

注意:记得在【基本设置】中【ip白名单】添加自己服务器IP

不然报错:{"errcode":40164,"errmsg":"invalid ip 120.11.26.205, not in whitelist hint: [WJWUwa08642790]"}

好的,遛遛

 

|

|

|

完美。

 

 

 

 

 

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

多来哈米

还可以打赏???来试一毛

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值