微信js前台配置和后台实现

该博客主要介绍了微信JSAPI的配置过程,包括前端的AJAX请求获取配置信息,以及后端如何利用微信工具类生成签名。前端通过获取时间戳、nonceStr和signature来配置微信JS接口,后端通过调用微信接口获取access_token和ticket,并结合nonceStr、timestamp和url生成SHA1签名。整个流程涉及微信公众号的appid、appsecret等关键参数。
摘要由CSDN通过智能技术生成

前台配置

<script type="text/javascript">
    $(function () {
        var htmlUrl = location.href.split('#')[0];
        $.ajax({
            type: "POST",
            url: "${pageContext.request.contextPath}/test",
            data: {"code": 1, "htmlUrl": encodeURIComponent(htmlUrl)},
            dataType: "JSON",
            async: false,
            success: function (res) {
                if ('success' == res.result) {
                    wx.config({
                        beta: true,
                        appId: res.appId, // 必填,公众号的唯一标识
                        timestamp: res.timestamp, // 必填,生成签名的时间戳
                        nonceStr: res.nonceStr, // 必填,生成签名的随机串
                        signature: res.signature,// 必填,签名
                        jsApiList: ['hideMenuItems']
                    });
                    console.log('successful');
                } else {
                    alert('ticket获取失败!');
                }
            }
        });
    });


    function hideMenu() {
        wx.hideOptionMenu();
    };

</script>

后台实现
controller

package controller;

import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import utils.WXUtil;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Map;
import java.util.UUID;

/**
 * @Description TODO
 * @Author jianglun
 * @Date 2020/12/17 10:45
 * @Version 1.0
 */
@Controller
public class WXcontroller {
    @Autowired
    private WXUtil wxUtil;
    @RequestMapping(value="/test")
    @ResponseBody
    public String saveUser(@RequestParam String htmlUrl, Model model, HttpServletRequest request) throws URISyntaxException, UnsupportedEncodingException {
        String url = new URI(htmlUrl).getPath();
//        String url = new String(htmlUrl.getBytes("ISO8859-1"), "UTF-8");
        //获取timestamp
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        //获取noncestr
        String noncestr = UUID.randomUUID().toString();
        String signature = wxUtil.getSignature(url,timestamp,noncestr);
        JSONObject result = new JSONObject();
        result.put("appId","wxee8d13d392a94d00");
        result.put("timestamp",timestamp);
        result.put("nonceStr",noncestr);
        result.put("signature",signature);
        result.put("result","success");
        return result.toString();
    }
    @RequestMapping(value="/share")
    public String share(HttpServletRequest request){
        return "share";
    }
}

微信工具类WXUtil

package utils;

import net.sf.json.JSONObject;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.springframework.stereotype.Component;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.UUID;

/**
 * @Description TODO
 * @Author jianglun
 * @Date 2020/12/17 10:55
 * @Version 1.0
 */
@Component
public class WXUtil {
    public String getAccessToken(String appId , String appSecret){
        // 网页授权接口
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId+"&secret="+appSecret;

        HttpClient client = null;
        String access_token = null;
        int expires_in = 0;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            access_token = String.valueOf(OpenidJSONO.get("access_token"));//获取access_token
            expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//获取时间
        } catch (Exception e) {
            System.out.println("获取AccessToken出错!");
        } finally {
            client.getConnectionManager().shutdown();
        }
        return access_token;
    }
    public String getTicket(String accessToken) {
        // 网页授权接口
        String GetPageAccessTokenUrl = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token="+accessToken+"&type=jsapi";
        HttpClient client = null;
        String ticket = "";
        int expires_in = 0;
        try {
            client = new DefaultHttpClient();
            HttpGet httpget = new HttpGet(GetPageAccessTokenUrl);
            ResponseHandler<String> responseHandler = new BasicResponseHandler();
            String response = client.execute(httpget, responseHandler);
            JSONObject OpenidJSONO = JSONObject.fromObject(response);
            ticket = String.valueOf(OpenidJSONO.get("ticket"));//获取ticket
            expires_in = Integer.parseInt(String.valueOf(OpenidJSONO.get("expires_in")));//获取时间
        } catch (Exception e) {
            System.out.println("获取Ticket出错!");
        } finally {
            client.getConnectionManager().shutdown();
        }

        return ticket;
    }
    public 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 String
            StringBuffer 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;
    }
    public String getSignature(String url,String timestamp,String noncestr) {

        String signature = "";

        String appid = "wxee8d13d392a94d00";//微信公众号的appid
        String appsecret ="9f56cc848d905c893a87ecee49a79fa8";//微信公众号的appsecret
        //获取access_token
//        String access_token = "40_p5O9vAFblR4dPv6VijfRuNM25H2WJsMbP_VFdYM565Z1gNIJN_hR8KH3x2F0F3bYZn0Pgg4D82iHfqxyFM0GVOa4OfoSy8qmy23rnxhBj41EQHo1YdXPbbksBgr067n43xk8OEu6gcMrOH3sIWBcACAMAF";
        String access_token = getAccessToken(appid , appsecret);
        //获取jspai_ticket
        String jsapi_ticket = getTicket(access_token);
        //将四个数据进行组合,传给SHA1进行加密
        String str = "jsapi_ticket=" + jsapi_ticket +
                "&noncestr=" + noncestr +
                "&timestamp=" + timestamp +
                "&url=" + url;

        //sha1加密
        signature = SHA1(str);

        return signature ;
    }

//    public static void main(String[] args) {
//        WXUtil wx = new WXUtil();
//        wx.getSignature("","","");
//    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值