1.把项目部署到 服务器
2.配置
先获取 到 APPID APPSECRET 和 token 就是令牌 (qin66)
ip地址/RepairSystem/weixindevelop 地址用来验证
源码 weixindevelop 的路径 就是 下面这个class
package com.bytech.controller;
import com.bytech.pojo.AccessToken;
import com.bytech.pojo.Button;
import com.bytech.pojo.CommonButton;
import com.bytech.pojo.ComplexButton;
import com.bytech.pojo.Menu;
import com.bytech.pojo.ViewButton;
import com.bytech.utiltool.SignUtil;
import com.bytech.utiltool.WeixinUtil;
import com.jfinal.core.Controller;
public class WeiXinServerController extends Controller {
public WeiXinServerController() {
// TODO Auto-generated constructor stub
}
public void index()
{
String method = this.getRequest().getMethod();
if("GET".equals(method))
{
WeiXinGet();
}
if("POST".equals(method))
{
WeiXinPost();
}
}
private void WeiXinGet()
{
// 微信加密签名
String signature = this.getPara("signature");
// 时间戳
String timestamp = this.getPara("timestamp");
// 随机数
String nonce = this.getPara("nonce");
// 随机字符串
String echostr = this.getPara("echostr");
// 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败
if (SignUtil.checkSignature(signature, timestamp, nonce))
{
AccessToken accessToken = WeixinUtil.getAccessToken(WeixinUtil.APPID, WeixinUtil.APPSECRET);
CommonButton b1 = new CommonButton();
b1.setName("点我试试");
b1.setType("click");
b1.setKey("1");
ViewButton b31 = new ViewButton();
ViewButton b32 = new ViewButton();
ViewButton b33 = new ViewButton();
b31.setName(" 客户登录 ");
b31.setType("view");
b31.setUrl("http://(IP地址)/RepairSystem/wx_cusmenu.html");
b32.setName(" 员工登录 ");
b32.setType("view");
b32.setUrl("http://(IP地址)/RepairSystem/wx_repmenu.html");
b33.setName(" 驻场登录 ");
b33.setType("view");
b33.setUrl("http://(IP地址)/RepairSystem/wx_boongIndex.html");
Button[] btns3 = {b31,b32,b33};
ComplexButton btn3 = new ComplexButton();
btn3.setName("登录");
btn3.setSub_button(btns3);
Button[] btns = {b1,btn3};
Menu menu = new Menu();
menu.setButton(btns);
WeixinUtil.createMenu(menu, accessToken.getToken());
this.renderText(echostr);
}
else
{
WeiXinPost();
}
}
private void WeiXinPost()
{
String respMessage = Service.processRequest(this.getRequest());
this.renderText(respMessage);
}
}
package com.bytech.utiltool;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
public class SignUtil {
// 与接口配置信息中的Token要一致
private static String token = "qin66";
/**
* 验证签名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 将token、timestamp、nonce三个参数进行字典序排序
Arrays.sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 将三个参数字符串拼接成一个字符串进行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 将sha1加密后的字符串可与signature对比,标识该请求来源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 将字节数组转换为十六进制字符串
*
* @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;
}
}
package com.bytech.utiltool;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.ConnectException;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.bytech.pojo.AccessToken;
import com.bytech.pojo.Menu;
import net.sf.json.JSONException;
import net.sf.json.JSONObject;
public class WeixinUtil {
private static Logger log = LoggerFactory.getLogger(WeixinUtil.class);
public static String APPID = "";
public static String APPSECRET = "";
/**
* 发起https请求并获取结果
*
* @param requestUrl 请求地址
* @param requestMethod 请求方式(GET、POST)
* @param outputStr 提交的数据
* @return JSONObject(通过JSONObject.get(key)的方式获取json对象的属性值)
*/
public static JSONObject httpRequest(String requestUrl, String requestMethod, String outputStr) {
JSONObject jsonObject = null;
StringBuffer buffer = new StringBuffer();
try {
// 创建SSLContext对象,并使用我们指定的信任管理器初始化
TrustManager[] tm = { new MyX509TrustManager() };
SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
sslContext.init(null, tm, new java.security.SecureRandom());
// 从上述SSLContext对象中得到SSLSocketFactory对象
SSLSocketFactory ssf = sslContext.getSocketFactory();
URL url = new URL(requestUrl);
HttpsURLConnection httpUrlConn = (HttpsURLConnection) url.openConnection();
httpUrlConn.setSSLSocketFactory(ssf);
httpUrlConn.setDoOutput(true);
httpUrlConn.setDoInput(true);
httpUrlConn.setUseCaches(false);
// 设置请求方式(GET/POST)
httpUrlConn.setRequestMethod(requestMethod);
if ("GET".equalsIgnoreCase(requestMethod))
httpUrlConn.connect();
// 当有数据需要提交时
if (null != outputStr) {
OutputStream outputStream = httpUrlConn.getOutputStream();
// 注意编码格式,防止中文乱码
outputStream.write(outputStr.getBytes("UTF-8"));
outputStream.close();
}
// 将返回的输入流转换成字符串
InputStream inputStream = httpUrlConn.getInputStream();
InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-8");
BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
String str = null;
while ((str = bufferedReader.readLine()) != null) {
buffer.append(str);
}
bufferedReader.close();
inputStreamReader.close();
// 释放资源
inputStream.close();
inputStream = null;
httpUrlConn.disconnect();
jsonObject = JSONObject.fromObject(buffer.toString());
} catch (ConnectException ce) {
ce.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return jsonObject;
}
// 获取access_token的接口地址(GET) 限200(次/天)
public final static String access_token_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET";
/**
* 获取access_token
* @param appid 凭证
* @param appsecret 密钥
* @return
*/
public static AccessToken getAccessToken(String appid, String appsecret) {
AccessToken accessToken = null;
String requestUrl = access_token_url.replace("APPID", appid).replace("APPSECRET", appsecret);
JSONObject jsonObject = httpRequest(requestUrl, "GET", null);
// 如果请求成功
if (null != jsonObject) {
try {
accessToken = new AccessToken();
accessToken.setToken(jsonObject.getString("access_token"));
accessToken.setExpiresIn(jsonObject.getInt("expires_in"));
} catch (JSONException e) {
accessToken = null;
// 获取token失败
log.error("获取token失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return accessToken;
}
// 菜单创建(POST) 限100(次/天)
public static String menu_create_url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=ACCESS_TOKEN";
/**
* 创建菜单
* @param menu 菜单实例
* @param accessToken 有效的access_token
* @return 0表示成功,其他值表示失败
*/
public static int createMenu(Menu menu, String accessToken) {
int result = 0;
// 拼装创建菜单的url
String url = menu_create_url.replace("ACCESS_TOKEN", accessToken);
// 将菜单对象转换成json字符串
String jsonMenu = JSONObject.fromObject(menu).toString();
// 调用接口创建菜单
JSONObject jsonObject = httpRequest(url, "POST", jsonMenu);
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
result = jsonObject.getInt("errcode");
log.info("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return result;
}
//删除菜单
public final static String menu_delete_url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=ACCESS_TOKEN";
/**
* 删除菜单
* @param accessToken 有效的access_token
* @return 0表示成功,其他值表示失败
*/
public static int deleteMenu(String accessToken) {
int result = 0;
// 拼装创建菜单的url
String url = menu_delete_url.replace("ACCESS_TOKEN", accessToken);
// 调用接口创建菜单
JSONObject jsonObject = httpRequest(url, "GET", null);
if (null != jsonObject) {
if (0 != jsonObject.getInt("errcode")) {
result = jsonObject.getInt("errcode");
log.info("创建菜单失败 errcode:{} errmsg:{}", jsonObject.getInt("errcode"), jsonObject.getString("errmsg"));
}
}
return result;
}
//获取素材列表 post url
public final static String get_material_list = "https://api.weixin.qq.com/cgi-bin/material/batchget_material?access_token=ACCESS_TOKEN";
/**
* 创建菜单
* @param menu 菜单实例
* @param accessToken 有效的access_token
* @return 0表示成功,其他值表示失败
*/
public static int getMaterial(String type , String count,String accessToken) {
int result = 0;
// 拼装创建菜单的url
String url = get_material_list.replace("ACCESS_TOKEN", accessToken);
// 将菜单对象转换成json字符串
String reqstr = "{\"type\":"+type+",\"offset\":0,\"count\":"+count+"}";
// 调用接口创建菜单
JSONObject jsonObject = httpRequest(url, "POST", reqstr);
if (null != jsonObject) {
if (0 != jsonObject.getInt("item_count")) {
}
}
return result;
}
}
ps:我自己能看懂。