PHP前端开发

微信开发之准备阶段的图文代码介绍

百变鹏仔 3周前 (03-13) #前端问答
文章标签 阶段

  微信开发之准备阶段


所需资源:

1、微信公众平台账号

2、百度BAE平台账号

一、    微信公众账号申请  

登录微信公众平台    在右上角有注册

填写相关资料进行注册,在此我注册的是个人订阅号,如果有公司信息可以注册服务号。另外由于个人订阅号接口有限,对于个人开发不是很有利,微信还提供了测试账号,专为开发人员使用,进入如下地址申请测试号          




测试号权限对于开发来说还是很不错的~

由于微信接入开发者模式需要提供可供微信服务器发送请求的url地址所以你的服务端必须能接入公网,可以使用花生壳等dns服务商,在此由于我用的是小区宽带不能解析,所以改用了百度的bae,没有公网ip的可以试试,初步接入测试感觉挺方便的,,用百度账号就可登陆,需要注意的是在bae使用中要用svn等管理应用,但是用户名又不支持中文所以如果百度账号是中文的朋友还是重新注册一个英文的吧,

接下来准备工作做完了就开始编写代码成为微信公众平台的开发者吧,以下代码出自柳峰老师博客

核心类:

package com.vlive.action.connector;  import java.io.IOException;  import java.io.PrintWriter;  import javax.servlet.ServletException;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import com.vlive.utils.SignUtil;  public class URlresponse extends HttpServlet{      @Override      protected void doGet(HttpServletRequest req, HttpServletResponse resp)              throws ServletException, IOException {           // 微信加密签名            String signature = req.getParameter("signature");            // 时间戳            String timestamp = req.getParameter("timestamp");            // 随机数            String nonce = req.getParameter("nonce");            // 随机字符串            String echostr = req.getParameter("echostr");            PrintWriter out = resp.getWriter();            // 通过检验signature对请求进行校验,若校验成功则原样返回echostr,表示接入成功,否则接入失败            if (SignUtil.checkSignature(signature, timestamp, nonce)) {                out.print(echostr);            }            out.close();            out = null;        }  }


此类用到 signutil的checksignature方法:      

package com.vlive.utils;  import java.security.MessageDigest;  import java.security.NoSuchAlgorithmException;  import java.util.Arrays;  public class SignUtil {      private static String token="vlive";      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 >> 4) & 0X0F];            tempArr[1] = Digit[mByte & 0X0F];            String s = new String(tempArr);            return s;        }    }

以下是web.xml

<?xml  version="1.0" encoding="UTF-8"?>  <web-app>    <display-name></display-name>     <servlet>            <servlet-name>URlresponse</servlet-name>            <servlet-class>               com.vlive.action.connector.URlresponse            </servlet-class>        </servlet>        <!-- url-pattern中配置的/coreServlet用于指定该Servlet的访问路径 -->        <servlet-mapping>            <servlet-name>URlresponse</servlet-name>            <url-pattern>/urlresponse</url-pattern>        </servlet-mapping>      <welcome-file-list>      <welcome-file>index.jsp</welcome-file>    </welcome-file-list>  </web-app>


至此接入配置就可以开始了

填写相应url和token就可以成为开发者了,祝大家顺利~