微信服务号开发-服务器配置
本期是将微信开发第一步,也就是服务器配置,以及校验。
话不多说,我们主要讲重点。既然是微信服务号开发,首先我们需要一个测试号,大家可以自己去微信公众平台申请一个。
申请完后,我们需要填写以下服务器配置信息。
这里的url我使用的是花生壳来进行内网穿透,大家也可以自行选择。
注意这边填写完URL后,微信将以你下一栏填写的Token 进行sha1加密,以get 的方式下发到你的服务器上。
两者若是比对一致,则配置成功。
下面贴一下校验代码
import com.jodoll.mall.samples.model.Signature;
import com.jodoll.mall.samples.utils.CheckUtil;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletRequest;
/**
* @fileName:WeiXinController
* @author:ccl
* @createTime:2019-05-24:08:36
*/
@RestController
@RequestMapping("/weixin")
public class WeiXinController {
@GetMapping("/validate")
public String weixinConnect(HttpServletRequest request) {
Signature sg = new Signature(
request.getParameter("signature"),
request.getParameter("timestamp"),
request.getParameter("nonce"),
request.getParameter("echostr"));
String method = request.getMethod();
if (CheckUtil.checkSignature(sg)) {
System.out.println("微信连接成功!");
return sg.getEchostr();
}
return "";
}
}
import lombok.AllArgsConstructor;
import lombok.Data;
/**
* @fileName:Signature
* @author:ccl
* @createTime:2019-05-24:08:37
*/
@Data
@AllArgsConstructor
public class Signature {
private String signature;
private String timestamp;
private String nonce;
private String echostr;
}
import com.jodoll.mall.samples.model.Signature;
import java.security.MessageDigest;
import java.util.Arrays;
/**
* @fileName:CheckUtil
* @author:ccl
* @createTime:2019-05-24:08:40
*/
public class CheckUtil {
private static final String token = "token";
public static boolean checkSignature(Signature sg) {
String[] arr = new String[] { token, sg.getTimestamp(), sg.getNonce() };
// 排序
Arrays.sort(arr);
// 生成字符串
StringBuffer content = new StringBuffer();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
// sha1加密
String temp = getSha1(content.toString());
// 比较
return temp.equals(sg.getSignature());
}
// 加密算法
public static String getSha1(String str) {
if (str == null || str.length() == 0) {
return null;
}
char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
try {
MessageDigest mdTemp = MessageDigest.getInstance("SHA1");
mdTemp.update(str.getBytes("UTF-8"));
byte[] md = mdTemp.digest();
int j = md.length;
char buf[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++) {
byte byte0 = md[i];
buf[k++] = hexDigits[byte0 >>> 4 & 0xf];
buf[k++] = hexDigits[byte0 & 0xf];
}
return new String(buf);
} catch (Exception e) {
return null;
}
}
}
以后将会陆续更新服务号的讲解。