微信公众号“成为开发者”实践代码

1、建立一个sha1加密文件,详细代码如下:

import java.security.*;
public class SHA1Encoder
{
    //加密方法 bgy 2013-10-30
    public static String encode(String inStr)
    {
        MessageDigest md = null;
        String outStr = null;
        try
        {
            md = MessageDigest.getInstance("SHA-1");//选择SHA-1,也可以选择MD5
            byte[] bt = inStr.getBytes();
            md.update(bt);
            outStr = bytetoString(md.digest());
        }
        catch(NoSuchAlgorithmException nsae)
        {
            nsae.printStackTrace();
        }
        return outStr;
    }
   
    //将字节数组转换成16进制字符串  bgy 2013-10-30
    public static String bytetoString(byte[] b)
    {
         StringBuilder sbDes = new StringBuilder(); 
         String tmp = null; 
         for(int i = 0; i < b.length; i++)
         { 
             tmp = (Integer.toHexString(b[i] & 0xFF)); 
             if(tmp.length() == 1)
             { 
                 sbDes.append("0"); 
             } 
             sbDes.append(tmp); 
         } 
         return sbDes.toString();
    }
}

 

2、微信服务器调用接口,详细代码如下:

import java.io.IOException;
import java.io.Writer;
import java.util.Arrays;

import 1中的包;

public class WechatYxl extends CommonAction

{  

    private static String TOKEN = "88888888";//与微信的密钥 俗称token

    //接收微信服务器传过来的参数串,进行业务处理 

    public void processingData() throws IOException  

   {   

         //微信服务器传来的   

         String signature = request.getParameter("signature");//微信加密签名

         String timestamp = request.getParameter("timestamp");//时间戳

         String nonce = request.getParameter("nonce");//随机数

         String echostr = request.getParameter("echostr");//随机字符串

         //1、将token、timestamp、nonce三个参数进行字典序排序  

         String[] arrDic = {TOKEN,timestamp,nonce};   

         Arrays.sort(arrDic);    

        //2、将三个参数字符串拼接成一个字符串   

        StringBuffer str = new StringBuffer();    

        for(int i = 0; i < arrDic.length; i++)   

       {     

              str.append(arrDic[i]);   

       }         

       //3、进行sha1加密   

       String ticket = SHA1Encoder.encode(str.toString());   

       Writer out = response.getWriter();   

       if(signature==ticket || ticket.equals(signature))   

       {    

              out.write(echostr);   

       }   

       else   

       {    

              out.write("");   

       }   

       out.flush();   

       out.close();  

   }

}

posted on 2013-10-31 17:42  专注2018  阅读(608)  评论(0编辑  收藏  举报