java 后台服务:
@Controller
public class LoginController {
@RequestMapping(value = "/weixin/auth",method=RequestMethod.GET)
public void login(HttpServletRequest request,HttpServletResponse response){
System.out.println("success");
String signature = request.getParameter("signature");
String timestamp = request.getParameter("timestamp");
String nonce = request.getParameter("nonce");
String echostr = request.getParameter("echostr");
PrintWriter out = null;
try {
out = response.getWriter();
if(CheckUtil.checkSignature(signature, timestamp, nonce)){
out.write(echostr);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.close();
}
}
}
import java.util.Arrays;
/**
*
* 类名称: CheckUtil
* 类描述: 请求校验
* @author yuanjun
* 创建时间:2017年12月8日上午10:54:16
*/
public class CheckUtil {
private static final String token = "自己设置,要与微信页面设置的一致";
public static boolean checkSignature(String signature,String timestamp,String nonce){
String[] str = new String[]{token,timestamp,nonce};
//排序
Arrays.sort(str);
//拼接字符串
StringBuffer buffer = new StringBuffer();
for(int i =0 ;i<str.length;i++){
buffer.append(str[i]);
}
//进行sha1加密
String temp = SHA1.encode(buffer.toString());
//与微信提供的signature进行匹对
return signature.equals(temp);
}
}
import java.security.MessageDigest;
/**
*
* 类名称: SHA1
* 类描述: sha1加密
* @author yuanjun
* 创建时间:2017年12月5日上午11:10:01
*/
public final class SHA1 {
private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
'6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
/**
* Takes the raw bytes from the digest and formats them correct.
*
* @param bytes the raw bytes from the digest.
* @return the formatted bytes.
*/
private static String getFormattedText(byte[] bytes) {
int len = bytes.length;
StringBuilder buf = new StringBuilder(len * 2);
// 把密文转换成十六进制的字符串形式
for (int j = 0; j < len; j++) {
buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
}
return buf.toString();
}
public static String encode(String str) {
if (str == null) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
messageDigest.update(str.getBytes());
return getFormattedText(messageDigest.digest());
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
微信设置

网页授权


测试
将该地址对应填写,发到微信手机上,点击打开
https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect
具体参照:https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421140842
网友评论