微信公众号开发之分享接口实现

微信公众号开发之分享接口实现

第一步:先登录微信公众平台进行设置JS接口安全域名("域名不能包含http://")。

如图:


第二步:配置config接口权限验证

首先需要通过获取access_token凭证,然后通过获取到的access_token来请求获得jsapi_ticket
        /**
	 * 获取access_token
	 * @return
	 */
	public static String getaccess_token(String url){
		String tokenurl=url+"l&appid="+WeiXinUtil.appID
				+"&secret="+WeiXinUtil.appsecret;
		String resultStr="";
		try {
			resultStr=HttpUploadFile.getUrlCon(tokenurl);
			JSONObject objec=JSONObject.parseObject(resultStr);
			System.out.println("返回结果>>>>>>>>>:"+resultStr);
			if(!StringUtils.isEmpty(objec.getString("access_token"))){
				resultStr=objec.getString("access_token");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取token异常");
		}
		System.out.println("获取token值为>>>>>>>>:"+resultStr);
		return resultStr;
	}


try {
			resultStr=HttpUploadFile.getUrlCon(url);
			JSONObject objec=JSONObject.parseObject(resultStr);
			System.out.println("返回结果>>>>>>>>>:"+resultStr);
			if(objec!=null){
				resultStr=objec.getString("ticket");
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			System.out.println("获取ticket异常");
		}

然后验证签名

    @ResponseBody
    public Map<String, String> share(String url) throws Exception {
        Map<String, String> map = new HashMap<String, String>();
        String jsapi_ticket = WeiXinInterface.getjsapiTicket();//jsapi_ticket
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);//时间戳
        String nonceStr = UUID.randomUUID().toString();
        String signature = SignUtil.getSignature(
            jsapi_ticket, nonceStr, timestamp,
            url);//验证签名
        map.put("url", url);
        map.put("jsapi_ticket", jsapi_ticket);
        map.put("nonceStr", nonceStr);
        map.put("timestamp", timestamp);
        map.put("signature", signature);
        map.put("appid",WeiXinUtil.appID);
        return map;
    }

SginUtil工具类

package com.hlkj.utils;
import java.security.MessageDigest;
/**
 * 微信签名工具类
 * @author 楪祈
 *
 */
public class SignUtil {
	 /**
     * 获得分享链接的签名。
     * @param ticket
     * @param nonceStr
     * @param timeStamp
     * @param url
     * @return
     * @throws Exception
     */
    public static String getSignature(String ticket, String nonceStr, String timeStamp, String url) throws Exception {
        String sKey = "jsapi_ticket=" + ticket
                + "&noncestr=" + nonceStr + "×tamp=" + timeStamp
                + "&url=" + url;
        System.out.println(sKey);
        return getSignature(sKey);
    }


 /**
     * 验证签名。
     * 
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public static String getSignature(String sKey) throws Exception {
        String ciphertext = null;
        MessageDigest md = MessageDigest.getInstance("SHA-1");
        byte[] digest = md.digest(sKey.toString().getBytes());
        ciphertext = byteToStr(digest);
        return ciphertext.toLowerCase();
    }

 /** 
     * 将字节数组转换为十六进制字符串 
     *  
     * @param byteArray 
     * @return 
     */ 
    private static String byteToStr(byte[] byteArray) {  
        String strDigest = "";  
        for (int i = 0; i < byteArray.length; i++) {  
            strDigest += byteToHexStr(byteArray[i]);  
        }  
        return strDigest;  
    }  
  /** 
     * 将字节转换为十六进制字符串 
     *  
     * @param mByte 
     * @return 
     */ 
    private static String byteToHexStr(byte mByte) {  
        char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };  
        char[] tempArr = new char[2];  
        tempArr[0] = Digit[(mByte >>> 4) & 0X0F];  
        tempArr[1] = Digit[mByte & 0X0F];  

        String s = new String(tempArr);  
        return s;  
    }
}

第三步:需要进行分享功能的页面编写(需要导入微信提供的js)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%
	String path = request.getContextPath();
	String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/static/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>微信分享页面</title>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript" src="<%=path %>/js/jquery-1.11.1.min.js"></script>
<script type="text/javascript">
	$(function(){
		$.ajax({
			url:"<%=path%>/share",
			type:"post",
			data:{
				"url":window.location.href// 获取页面当前链接
			},
			dataType:"json",
			success: function(data){
				 wx.config({
				    debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
				    appId:data["appid"], // 必填,公众号的唯一标识
				    timestamp: data["timestamp"], // 必填,生成签名的时间戳
				    nonceStr: data["nonceStr"], // 必填,生成签名的随机串
				    signature: data["signature"],// 必填,签名
				    jsApiList: ["onMenuShareTimeline"
				                ,"onMenuShareQQ"
				                ,"onMenuShareAppMessage"] // 必填,需要使用的JS接口列表
				});

			}

		});

		wx.ready(function () {
			//分享到朋友
			wx.onMenuShareAppMessage({
	    	    title: '来自安然失笑i的分享', // 分享标题
	    	    desc: '测试分享功能', // 分享描述
	    	    link: window.location.href, // 分享链接
	    	    imgUrl: 'http://lhf.free.ngrok.cc<%=path%>/img/ico_tip.png', // 分享图标
	    	    type: 'link', // 分享类型,music、video或link,不填默认为link
	    	    success: function () { 
	    	        alert("分享成功");
	    	    },
	    	    cancel: function () { 
	    	        alert("未分享!");
	    	    }
			});
			//分享到QQ
			wx.onMenuShareQQ({
				title: '来自安然失笑i的分享', // 分享标题
				desc: '测试分享功能', // 分享描述
				link: window.location.href, // 分享链接
				imgUrl: 'http://lhf.free.ngrok.cc<%=path%>/img/ico_tip.png', // 分享图标
				success: function () {
					// 用户确认分享后执行的回调函数
				},
				cancel: function () {
					// 用户取消分享后执行的回调函数
				}
			});
		});
		
	});
</script>
</head>
<body>
		暂时没有内容
</body>
</html>

在开发中遇到 config:invalid url domain的原因


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值