H5网页实现微信分享,分享朋友圈功能(分享带图片,附源码)

H5网页实现微信分享,分享朋友圈功能,网上的代码基本上都过期了,特基于最新的jweixin-1.6.0版本的微信分享实现,以作备忘。

目 录

1.微信分享文档及配置

1.1微信分享官网文档

1.2 appid对应的公众号是否有分享接口权限

 1.3设置白名单和绑定域名

2 代码实现

2.1后端Java代码

2.2前端代码

2.1 idea完整项目下载

3.常见问题及解决方法

3.1wx.config初始化失败

3.2分享接口没有权限

3.3H5页面看不到“分享朋友圈”和“转发朋友”功能


1.微信分享文档及配置

1.1微信分享官网文档

地址概述 | 微信开放文档

 需要注意一下,即将废弃接口,建议不要再调用了。

1.2 appid对应的公众号是否有分享接口权限

登录公众号后,接口状态为已获得,表示有权限。如下图

 1.3设置白名单和绑定域名

分享的服务器外网ip地址,需要添加到白名单中,如下图

 绑定域名

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

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

2 代码实现

2.1后端Java代码

获取参数工具类

import org.json.JSONObject;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class SignUtil {
    public static String APP_ID="";//在controller中初始化
    public static String APP_SECRET="";
    public static void main(String[] args) {
        String url = "https://www.**.com/share";
        System.out.println(getResult(url));
    };

    public static Map<String, String> getResult(String url){

        Map<String, String> ret = sign(getTicket(), url);
        ret.put("appId", getAppId());
        return ret;
    }

    private static String getAppId(){
        return APP_ID;
    }

    private static String getToken(){
        String accessToken = "";
        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+getAppId()+"&secret="+APP_SECRET;
        try {
            String resultString =HttpUtil.get(url);
            if (null != resultString && !"".equals(resultString)) {
                System.out.println(resultString);
                JSONObject json = new JSONObject(resultString);
                accessToken = json.get("access_token").toString();

            }else{
                System.out.println("返回值为空,请检查请求报文或者请求地址是否正确");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return accessToken;
    }

    private static String getTicket(){

        String ticket = "";
        String url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+getToken()+"&type=jsapi";

        try {
            String resultString =HttpUtil.get(url);
            if (null != resultString && !"".equals(resultString)) {
                System.out.println(resultString);
                JSONObject json = new JSONObject(resultString);
                ticket = json.getString("ticket");
            }else{
                System.out.println("返回值为空,请检查请求报文或者请求地址是否正确");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return ticket;
    }

    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().replace("-","");
    }

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

controller实现

@Controller
public class ShareController {
    @Value("${wx.appid}")
    private String appid;
    @Value("${wx.appsecret}")
    private String appsecret;

    @RequestMapping("/index")
    public ModelAndView show(){
        SignUtil.APP_ID=appid;
        SignUtil.APP_SECRET=appsecret;

        ModelAndView mv=new ModelAndView();
        String url="http://localhost:8080/index";
        mv.addObject("share",SignUtil.getResult(url));
        mv.setViewName("/index");
        return mv;
    }
}

2.2前端代码

<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
<%
    String path = request.getContextPath();
    String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>分享</title>
    <script src="<%=basePath%>static/js/jquery-1.5.1.min.js" type="text/javascript"></script>
    <script src="http://res.wx.qq.com/open/js/jweixin-1.6.0.js" type="text/javascript"></script>
</head>
<body>
<form role="form" action = "" method="post">
   <img src="<%=basePath%>static/image/demo.png" alt="">
</form>
<script type="text/javascript">
    // 微信分享默认调用接口
    var $appid,$timestamp,$noncestr,$signature,$description,$title1;
    //获取当前页面的url
    var linkUrl = window.location.href;

    var data = "${share}";
    console.log(data);

    $appid = "${share.appId}";  // appid
    $timestamp = "${share.timestamp}";   // timestamp
    $noncestr = "${share.nonceStr}"; // noncestr
    $signature = "${share.signature}";  // signature
    $description = "分享描述"; // share_desc
    $title1 =  "分享标题";// share_title


    //**配置微信信息**
    wx.config ({
        debug : true,
        appId : $appid,
        timestamp : $timestamp,
        nonceStr : $noncestr,
        signature : $signature,
        jsApiList : [
            // 所有要调用的 API 都要加到这个列表中
            'updateTimelineShareData',
            'updateAppMessageShareData',
            'onMenuShareWeibo'
        ]
    });

    wx.ready (function () {
        // 微信分享的数据
        var shareData = {
            "imgUrl" : "<%=basePath%>static/image/demo.png",
            "link" : linkUrl,
            "desc" : $description,
            "title" : $title1,
            success : function () {
                // 分享成功可以做相应的数据处理
            }
        };
        //分享微信朋友圈
        wx.updateTimelineShareData (shareData);
        //分享给朋友
        wx.updateAppMessageShareData({
            title: $title1, // 分享标题
            desc: $description, // 分享描述
            link: linkUrl, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: '<%=basePath%>static/image/demo.png', // 分享图标
            success: function () {
                // 设置成功
            }
        });


        //分享到微博
        wx.onMenuShareWeibo (shareData);
    });

</script>
</body>
</html>

2.1 idea完整项目下载

基于jweixin-1.6.0.js最新版本,搭建springbootweb项目,实现微信分享,分享朋友圈,完整idea源码_H5网页实现微信分享功能-Java文档类资源-CSDN下载

3.常见问题及解决方法

3.1wx.config初始化失败

情况有很多种,主要如下:

1.Java后台前面的url与分享的url不一致,需要完全一致。例如后台是http,分享地址是https

2.参数不对

3.2分享接口没有权限

这错误有2种情况,1是参数不对;2是公众号中分享接口的状态为未获得。

3.3H5页面看不到“分享朋友圈”和“转发朋友”功能

这个是由于微信官方在2021年9月份,做了调整,只能把H5页面加在公众号中(例如加到公众号菜单中)进行访问时,才可以分享朋友圈和转发给微信朋友。

有问题,欢迎大家留言沟通。

  • 28
    点赞
  • 144
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 12
    评论
评论 12
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

秋9

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值