微信開發一(與自己的後臺互動)
阿新 • • 發佈:2019-01-07
在進入微信開發前,首先我們要將我們的ip對映成url訪問地址,這裡我用的是natapp,感覺還是挺穩定的,只不過對映的地址擱一段時間會被替換掉
接下來進入到微信的公眾號平臺裡面去,如果還沒申請的話可以進行申請,微信的公眾號分為三種:訂閱號,服務號,企業號,由於這裡是屌絲的聚集地,所以只能用訂閱號來玩一玩。
公眾號平臺地址:
https://mp.weixin.qq.com/cgi-bin/home
接著我們點選開發-》基本配置-》伺服器配置上點選啟動,輸入我們的後臺網址,令牌,接著點選確定就可以了,如果提示錯誤,說明後臺和微信平臺沒對接成功,需要檢查一下傳入的引數是否正確。如下是我的ip地址
記得啟動的natapp服務,以下是我用springmvc搭建的伺服器程式碼,如下:
@Controller
@RequestMapping("wechat")
public class WeChatController {
@RequestMapping(value = "/hello")
public String index(){
return "index";
}
@RequestMapping(value = "/detail")
public String detail(){
return "detailpage" ;
}
@RequestMapping(value = "/home",method= RequestMethod.GET)
@ResponseBody
public void valid(HttpServletRequest request, HttpServletResponse response) throws IOException {
boolean isGet = request.getMethod().toLowerCase().equals("get");
String code = request.getParameter("code" );
if (isGet) {
// 微信加密簽名
String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機數
String nonce = request.getParameter("nonce");
// 隨機字串
String echostr = request.getParameter("echostr");
PrintWriter out = response.getWriter();
// 通過檢驗signature對請求進行校驗,若校驗成功則原樣返回echostr,表示接入成功,否則接入失敗
if (SignUtil.checkSignature(signature, timestamp, nonce)) {
out.print(echostr);
}
out.close();
out = null;
}else{
userpost(request,response);
}
}
@RequestMapping(value = "/home",method= RequestMethod.POST)
public void userpost(HttpServletRequest request, HttpServletResponse response) throws IOException {
request.setCharacterEncoding("UTF-8");
PrintWriter out = response.getWriter();
String str = null;
String code = request.getParameter("code");
try {
Map<String, String> message = MessageUtil.xmlToMap(request);
String fromUser = message.get("FromUserName");
String toUser = message.get("ToUserName");
String content = message.get("Content");
String msgType = message.get("MsgType");
String msgId = message.get("MsgId");
Message ms = new Message();
ms.setContent(content);
ms.setFromUserName(toUser);
ms.setToUserName(fromUser);
ms.setMsgType(msgType);
str = MessageUtil.textMessageToXml(ms).replace("\n","").replace(" ","");
out.print(str);
out.close();
out = null;
}catch (Exception e){
e.printStackTrace();
}
}
簽名認證
/**
* 請求校驗工具類
*
* @author liufeng
* @date 2013-05-18
*/
public class SignUtil {
// 與介面配置資訊中的Token要一致
private static String token = "chenmianhai";
/**
* 驗證簽名
*
* @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;
}
}
pojo轉換為xml
/**
* 基於JAXB的XML生成器: 用於pojo與xml檔案的相互轉換
* @author wuwz
* @ClassName XmlBuilder
* @DateTime 2016年3月29日 上午10:50:17
*/
public abstract class XmlBuilder {
private final static Logger log= Logger.getLogger(XmlBuilder.class);
/**
* 將pojo轉換為XML字串
* @param object
* @return
*/
public static String convertToXml(Object object) {
Writer sw = new StringWriter();
try {
// 利用jdk中自帶的轉換類實現
JAXBContext context = JAXBContext.newInstance(object.getClass());
Marshaller marshaller = context.createMarshaller();
// 格式化xml輸出的格式
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
// 將物件轉換成輸出流形式的xml
marshaller.marshal(object, sw);
log.debug("XML字串生成成功!");
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if(sw != null) {
try {
sw.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sw.toString().replace("standalone=\"yes\"", "");
}
/**
* 將pojo轉換為XML檔案
* @param obj
* @param savePath
*/
public static File convertToXmlFile(Object obj,String savePath) {
File file = null;
String xmlStr = convertToXml(obj);
if(xmlStr != null && !"".equals(xmlStr)) {
file = new File(savePath);
if(!file.exists() && file.isFile()) {
try {
file.createNewFile();
} catch (IOException e) {
e.printStackTrace();
}
}
if(file.isDirectory()) {
System.out.println(MessageFormat.format("{0}不是有效的檔案路徑.", savePath));
return null;
}
Writer writer = null;
try {
writer = new FileWriter(file);
writer.write(xmlStr);
writer.flush();
log.debug("XML檔案生成成功!");
} catch (IOException e) {
e.printStackTrace();
} finally {
if(writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
return file;
}
/**
* 將XML檔案轉換為指定型別的pojo
* @param clazz
* @param xmlPath
* @return
*/
public static Object xmlFileToObject(Class<?> clazz, String xmlPath) {
Object xmlObject = null;
Reader fr = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
Unmarshaller unmarshaller = context.createUnmarshaller();
fr = new FileReader(xmlPath);
xmlObject = unmarshaller.unmarshal(fr);
} catch (JAXBException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} finally {
if (null != fr) {
try {
fr.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return xmlObject;
}
/**
* 將XML字串轉換為指定型別的pojo
*
* @param clazz
* @param xmlStr
* @return
*/
public static Object xmlStrToObject(Class<?> clazz, String xmlStr) {
Object xmlObject = null;
Reader reader = null;
try {
JAXBContext context = JAXBContext.newInstance(clazz);
// 進行將Xml轉成物件的核心介面
Unmarshaller unmarshaller = context.createUnmarshaller();
reader = new StringReader(xmlStr);
xmlObject = unmarshaller.unmarshal(reader);
} catch (JAXBException e) {
e.printStackTrace();
} finally {
if (null != reader) {
try {
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return xmlObject;
}
}