JAVA实现微信分享,朋友圈分享

编程入门 行业动态 更新时间:2024-10-17 00:26:07

JAVA实现微信分享,<a href=https://www.elefans.com/category/jswz/34/1768857.html style=朋友圈分享"/>

JAVA实现微信分享,朋友圈分享

JAVA语言部分
import com.alibaba.fastjson.JSONObject;
import com.juniorchina.serving.dao.redis1.RedisDaoApp;
import com.juniorchina.serving.entity.WinXinEntity;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;import java.io.InputStream;
import java.HttpURLConnection;
import java.URL;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;public class WeinXinUtil {private static final Logger logger = LoggerFactory.getLogger(WeinXinUtil.class);@Autowiredprivate  RedisDaoApp redisDaoApp;public  WinXinEntity getWinXinEntity(String url) {WinXinEntity wx = new WinXinEntity();//因开发管理密码改变,采用读取App的Redis//String access_token = getAccessToken();String access_token=redisDaoApp.getWebChatToken("weixin_access_token");String ticket = getTicket(access_token);Map<String, String> ret = sign(ticket, url);//调用函数//System.out.println(ret.toString());wx.setAppid(Appid);wx.setTicket(ret.get("jsapi_ticket"));wx.setSignature(ret.get("signature"));wx.setNoncestr(ret.get("nonceStr"));wx.setTimestamp(ret.get("timestamp"));return wx;}//获取tokenprivate static String getAccessToken() {String access_token = "";String grant_type = "client_credential";//获取access_token填写client_credentialString AppId=Appid;//第三方用户唯一凭证SString secret=Secret;//第三方用户唯一凭证密钥,即appsecret//这个url链接地址和参数皆不能变String url = "="+grant_type+"&appid="+AppId+"&secret="+secret;  //访问链接try {URL urlGet = new URL(url);HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();http.setRequestMethod("GET"); // 必须是get方式请求http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");http.setDoOutput(true);http.setDoInput(true);/*System.setProperty("sun.client.defaultConnectTimeout", "30000");// 连接超时30秒System.setProperty("sun.client.defaultReadTimeout", "30000"); // 读取超时30秒 */http.connect();InputStream is = http.getInputStream();int size = is.available();byte[] jsonBytes = new byte[size];is.read(jsonBytes);String message = new String(jsonBytes, "UTF-8");JSONObject demoJson = JSONObject.parseObject(message);access_token = demoJson.getString("access_token");is.close();} catch (Exception e) {e.printStackTrace();}System.out.println("access_token="+access_token);return access_token;}//获取ticketprivate static String getTicket(String access_token) {String ticket = null;String url = "="+ access_token +"&type=jsapi";//这个url链接和参数不能变try {URL urlGet = new URL(url);HttpURLConnection http = (HttpURLConnection) urlGet.openConnection();http.setRequestMethod("GET"); // 必须是get方式请求http.setRequestProperty("Content-Type","application/x-www-form-urlencoded");http.setDoOutput(true);http.setDoInput(true);System.setProperty("sun.client.defaultConnectTimeout", "30000");// 连接超时30秒System.setProperty("sun.client.defaultReadTimeout", "30000"); // 读取超时30秒http.connect();InputStream is = http.getInputStream();int size = is.available();byte[] jsonBytes = new byte[size];is.read(jsonBytes);String message = new String(jsonBytes, "UTF-8");JSONObject demoJson = JSONObject.parseObject(message);ticket = demoJson.getString("ticket");is.close();} catch (Exception e) {e.printStackTrace();}System.out.println("ticket="+ticket);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("this all url="+string1);signature = SHA1(string1);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;}public static String SHA1(String str) {try {MessageDigest digest = java.security.MessageDigest.getInstance("SHA-1"); //如果是SHA加密只需要将"SHA-1"改成"SHA"即可digest.update(str.getBytes());byte messageDigest[] = digest.digest();// Create Hex StringStringBuffer hexStr = new StringBuffer();// 字节数组转换为 十六进制 数for (int i = 0; i < messageDigest.length; i++) {String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);if (shaHex.length() < 2) {hexStr.append(0);}hexStr.append(shaHex);}return hexStr.toString();} catch (NoSuchAlgorithmException e) {e.printStackTrace();}return null;}private static String create_nonce_str() {return UUID.randomUUID().toString();}private static String create_timestamp() {return Long.toString(System.currentTimeMillis() / 1000);}

Jquery部分

$(document).ready(function () {var url = location.href.split('#').toString();//url不能写死$.ajax({type : "get",async : true,url : "/getWechatShare",dataType : "json",data:{url:url},success : function(data) {wx.config({debug: false,生产环境需要关闭debug模式appId: data.appid,//appId通过微信服务号后台查看timestamp: data.timestamp,//生成签名的时间戳nonceStr: data.noncestr,//生成签名的随机字符串signature: data.signature,//签名jsApiList: [//需要调用的JS接口列表'checkJsApi',//判断当前客户端版本是否支持指定JS接口'onMenuShareTimeline',//分享给好友'onMenuShareAppMessage'//分享到朋友圈]});},error: function(xhr, status, error) {//alert(status);//alert(xhr.responseText);}})
});
//获取标题newstitle = $("h2").html();if(newstitle==null)
{newstitle=$(".titleDate").text();
}
//获取摘要newssummary=$(".wechatsummary").text().substring(0,100).trim();
wechaticon=$(".wechaticon").text();
if (wechaticon=="" || wechaticon==null){wechaticon=".jpg";
}
//console.log(newstitle+wechaticon+newssummary);
wx.ready(function () {var link = window.location.href;var protocol = window.location.protocol;var host = window.location.host;var title= newstitle;var desc= newssummary;var imgUrl= wechaticon;//分享朋友圈wx.onMenuShareTimeline({title: title,link: link,imgUrl: imgUrl,// 自定义图标trigger: function (res) {// 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回.//alert('click shared');},success: function (res) {//alert('shared success');//some thing you should do},cancel: function (res) {//alert('shared cancle');},fail: function (res) {//alert(JSON.stringify(res));}});//分享给好友wx.onMenuShareAppMessage({title: title, // 分享标题desc: desc, // 分享描述link: link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致imgUrl: imgUrl, // 自定义图标type: 'link', // 分享类型,music、video或link,不填默认为linkdataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空success: function () {// 用户确认分享后执行的回调函数},cancel: function () {// 用户取消分享后执行的回调函数}});wx.onMenuShareQQ({title: title, // 分享标题desc: desc, // 分享描述link: link, // 分享链接imgUrl: imgUrl, // 自定义图标success: function () {// 用户确认分享后执行的回调函数},cancel: function () {// 用户取消分享后执行的回调函数}});wx.onMenuShareQZone({title: title, // 分享标题desc: desc, // 分享描述link: link, // 分享链接imgUrl: imgUrl, // 自定义图标success: function () { // 用户确认分享后执行的回调函数},cancel: function () { // 用户取消分享后执行的回调函数}});wx.onMenuShareWeibo({title: title, // 分享标题desc: desc, // 分享描述link: link, // 分享链接imgUrl: imgUrl, // 自定义图标success: function () {// 用户确认分享后执行的回调函数},cancel: function () {// 用户取消分享后执行的回调函数}});wx.error(function (res) {});
});

 

更多推荐

JAVA实现微信分享,朋友圈分享

本文发布于:2024-03-15 06:23:27,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1738282.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:朋友圈   JAVA

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!