频道栏目
首页 > 资讯 > 微信公众平台开发 > 正文

【微信开发】接口配置

16-07-28        来源:[db:作者]  
收藏   我要投稿

由于近期刚开始学习微信开发,在网上查询整理了php与java两个版本的微信接口对接代码。

以下是php版本

define("TOKEN", "token");
$wechatObj = new wechatCallbackapiTest();
$wechatObj->valid();
class wechatCallbackapiTest
{
    public function valid()
    {
        //随机字符串
        $echoStr = $_GET["echostr"];
        if($this->checkSignature()){
            echo $echoStr;
            exit;
        }
    }

    private function checkSignature()
    {
        //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
        $signature = $_GET["signature"];
        //时间戳
        $timestamp = $_GET["timestamp"];
        //随机数
        $nonce = $_GET["nonce"];
        $token =TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        //将token、timestamp、nonce三个参数进行字典排序
        sort($tmpArr);
        $tmpStr = implode( $tmpArr );
        //sha1加密
        $tmpStr = sha1( $tmpStr );
        //将加密后的字符串比较,验证接口
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

java版(SSM框架)

@RequestMapping(method = RequestMethod.GET)
    public void get(HttpServletRequest request, HttpServletResponse response) {

        //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
        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 (SignUtil.checkSignture(signature, timestamp, nonce)) {
                out.print(echostr);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            out.close();
            out = null;
        }
    }

SignUtil.java

 public static boolean checkSignture(String signature, String timestamp, String nonce) {
        String[] arr = new String[]{Constant.TOKEN, timestamp, nonce};
        //将token、timestamp、nonce三个参数进行字典排序
        Arrays.sort(arr);
        StringBuilder conntent = new StringBuilder();
        for (int i = 0; i < arr.length; i++) {
            conntent.append(arr[i]);
        }
        MessageDigest md = null;
        String tmpStr = null;

        try {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(conntent.toString().getBytes());
            tmpStr = byteToStr(digest);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        conntent = null;
        //将sha1加密后的字符串与signature对比
        return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
    }
相关TAG标签
上一篇:胸罩内衣突然卖不动了背后的真相究竟是什么?"
下一篇:手游业的海底捞:PokemonGo你学不会"
相关文章
图文推荐

关于我们 | 联系我们 | 广告服务 | 投资合作 | 版权申明 | 在线帮助 | 网站地图 | 作品发布 | Vip技术培训 | 举报中心

版权所有: 红黑联盟--致力于做实用的IT技术学习网站