企业微信中前端需要后端提供JSConfig

背景:前端调用企业微信的SDK,需要签名,但是前端做签名不安全,所以需要放在服务端起签名

这边的API写的也很详细

直接代码,

controller:

package com.movitech.mobile.controller;

import com.movitech.mobile.Response.JSConfig;
import com.movitech.mobile.entity.AccessToken;
import com.movitech.mobile.utils.QiYeWeiXinUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;
import java.util.UUID;

@RestController
public class HelloController {

    @GetMapping("hello1")
    public JSConfig hello1(HttpServletRequest requesturl) {
        AccessToken accessToken = QiYeWeiXinUtil.access_token();
        String jsapi_ticket = QiYeWeiXinUtil.jsapi_ticket(accessToken.getAccess_token());
        String timestamp = Long.toString(System.currentTimeMillis() / 1000);
        String nonce_str = UUID.randomUUID().toString();
        //String url = requesturl.getRequestURL().toString();
        String url = "http://mp.weixin.qq.com?params=value";
        String string1 = "jsapi_ticket=" + jsapi_ticket + "&noncestr=" + nonce_str + "&timestamp=" + timestamp + "&url=" + url;
        String signature = "";
        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();
        }
        JSConfig jsConfig = new JSConfig();
        jsConfig.setBeta(true);
        jsConfig.setDebug(true);
        jsConfig.setAppId("ww3c9853412b633936");
        jsConfig.setTimestamp(timestamp);
        jsConfig.setNonceStr(nonce_str);
        jsConfig.setSignature(signature);

        return jsConfig;
    }

    public 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;
    }

}

QiYeWeiXinUtil

package com.movitech.mobile.utils;

import com.movitech.mobile.entity.AccessToken;
import com.movitech.mobile.entity.Members;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.apache.commons.io.IOUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONException;

import java.io.InputStream;
import java.util.Formatter;

/**
 * 微信企业号调用类 {"errcode":0,"errmsg":"ok"} 此结果表示调用方法成功返回
 * Created by Cerulean on 2018/8/25.
 */
@Slf4j
public class QiYeWeiXinUtil {

    //获取access_token
    public static AccessToken access_token() {
        AccessToken accessToken = null;
        String id = "ww3c9853412b633936";
        String corpsecret = "DjdwKnjlsyzwC82fzspYTOMxmN4dMtA3WHz7hCQGS2A";
        String urlNameString = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=Id&corpsecret=Secrect";
        urlNameString = urlNameString.replace("Id", id);
        urlNameString = urlNameString.replace("Secrect", corpsecret);
        String result = "";
        try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(urlNameString);//这里发送get请求
            // 获取当前客户端对象
            @SuppressWarnings({"resource", "deprecation"})
            HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    result = IOUtils.toString(instream, "utf-8");
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        accessToken = (AccessToken) JsonMapper.fromJsonString(result, AccessToken.class);
        if (accessToken != null) {
            return accessToken;
        }
        return null;
    }

    
    //获取jsapi_ticket
    public static String jsapi_ticket(String accessToken) {
        String urlNameString = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=ACCESS_TOKEN";
        urlNameString = urlNameString.replace("ACCESS_TOKEN", accessToken);
        String result = "";
        try {
            // 根据地址获取请求
            HttpGet request = new HttpGet(urlNameString);//这里发送get请求
            // 获取当前客户端对象
            @SuppressWarnings({"resource", "deprecation"})
            HttpClient httpClient = new DefaultHttpClient();
            // 通过请求对象获取响应对象
            HttpResponse response = httpClient.execute(request);

            // 判断网络连接状态码是否正常(0--200都数正常)
            if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                HttpEntity entity = response.getEntity();
                if (entity != null) {
                    InputStream instream = entity.getContent();
                    result = IOUtils.toString(instream, "utf-8");
                }
            }
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        JSONObject jsonObject = JSONObject.fromObject(result);
        return jsonObject.getString("ticket");
    }

   
}

返回bean:JSConfig 

package com.movitech.mobile.Response;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class JSConfig {
    private boolean beta;
    private boolean debug;
    private String appId;
    private String timestamp;
    private String nonceStr;
    private String signature;
}

结果:这里封装了返回包装体,只要看其中的主要数据

猜你喜欢

转载自blog.csdn.net/qq_34707991/article/details/82496096