02、微信服务器接入

注意事项:
当服务器接入开启后,微信公众号后台设置的公众号菜单和自动回复将会失效,可以使用第三方授权的进行管理(如:微软小冰等)
enter image description here

enter image description here
链接
https://mp.weixin.qq.com/wiki?t=resource/res_main&id=mp1421135319

接入微信公众平台开发,开发者需要按照如下步骤完成:
1、填写服务器配置
2、验证服务器地址的有效性
3、依据接口文档实现业务逻辑
第一步:填写服务器配置
登录微信公众平台官网后,在公众平台官网的开发-基本设置页面,勾选协议成为开发者,点击“修改配置”按钮,填写服务器地址(URL)、Token和EncodingAESKey,其中URL是开发者用来接收微信消息和事件的接口URL。Token可由开发者可以任意填写,用作生成签名(该Token会和接口URL中包含的Token进行比对,从而验证安全性)。EncodingAESKey由开发者手动填写或随机生成,将用作消息体加解密密钥。
同时,开发者可选择消息加解密方式:明文模式、兼容模式和安全模式。模式的选择与服务器配置在提交后都会立即生效,请开发者谨慎填写及选择。加解密方式的默认状态为明文模式,选择兼容模式和安全模式需要提前配置好相关加解密代码,详情请参考消息体签名及加解密部分的文档。
enter image description here
第二步:验证消息的确来自微信服务器
开发者提交信息后,微信服务器将发送GET请求到填写的服务器地址URL上(只会是GET请求,post请求在用户交互时候使用),GET请求携带参数如下表所示:

参数说明
signature微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
timestamp时间戳
nonce随机数
echostr随机字符串

开发者通过检验signature对请求进行校验(下面有校验方式)。若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,否则接入失败。加密/校验流程如下:
1)将token、timestamp、nonce三个参数进行字典序排序 2)将三个参数字符串拼接成一个字符串进行sha1加密 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信

第三步:依据接口文档实现业务逻辑
验证URL有效性成功后即接入生效,成为开发者。你可以在公众平台网站中申请微信认证,认证成功后,将获得更多接口权限,满足更多业务需求。
成为开发者后,用户每次向公众号发送消息、或者产生自定义菜单、或产生微信支付订单等情况时,开发者填写的服务器配置URL将得到微信服务器推送过来的消息和事件,开发者可以依据自身业务逻辑进行响应,如回复消息。
另请注意,微信公众号接口必须以http://或https://开头,分别支持80端口和443端口。

package com.lm.action.accessToken;

import com.lm.conf.WechatConf;
import com.lm.util.SHA1;
import com.lm.util.XmlUtil;
import org.dom4j.DocumentException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Map;

/**
 * 微信服务器接入
 * 开发者通过检验signature对请求进行校验(下面有校验方式)。
 * 若确认此次GET请求来自微信服务器,请原样返回echostr参数内容,则接入生效,成为开发者成功,
 * 否则接入失败。加密/校验流程如下:
 *
 * 1)将token、timestamp、nonce三个参数进行字典序排序
 * 2)将三个参数字符串拼接成一个字符串进行sha1加密
 * 3)开发者获得加密后的字符串可与signature对比,标识该请求来源于微信
 *
 *signature 微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
 *timestamp 时间戳
 *nonce 随机数
 *echostr   随机字符串
 */
@Controller
public class ServerConfigAction {

    @GetMapping("/wechat/server/config")
    public void get(HttpServletRequest request, HttpServletResponse response,
                    String signature, String timestamp, String nonce, String echostr) throws IOException {
        response.getWriter().write(echostr);
    }

    @PostMapping("/wechat/server/config")
    public void post(HttpServletRequest request, @RequestBody String requestBody, HttpServletResponse response,
                     String signature, String timestamp, String nonce, String echostr) throws IOException, DocumentException {
        ArrayList<String> list=new ArrayList<String>();
        list.add(nonce);
        list.add(timestamp);
        list.add(WechatConf.TOKEN);
        Collections.sort(list);
        if(checkSignature(list.get(0) + list.get(1) + list.get(2), signature)) {
            router(requestBody);
            response.getWriter().write("");
        }
    }

    /**
     * 接收提示不同路由到不同代码
     * @return
     */
    public String router(String body) throws IOException, DocumentException {
        System.out.println(body);
        Map<String, String> map = XmlUtil.xmlToMap(body);
        return "";
    }

    private boolean checkSignature(String str, String signature) {
        return SHA1.encode(str).equals(signature);
    }

}


package com.lm.util;

/*
 * 微信公众平台(JAVA) SDK
 *
 * Copyright (c) 2016, Ansitech Network Technology Co.,Ltd All rights reserved.
 * http://www.ansitech.com/weixin/sdk/
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

import java.security.MessageDigest;

/**
 * <p>Title: SHA1算法</p>
 *
 * @author levi
 */
public final class SHA1 {

    private static final char[] HEX_DIGITS = {'0', '1', '2', '3', '4', '5',
            '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /**
     * Takes the raw bytes from the digest and formats them correct.
     *
     * @param bytes the raw bytes from the digest.
     * @return the formatted bytes.
     */
    private static String getFormattedText(byte[] bytes) {
        int len = bytes.length;
        StringBuilder buf = new StringBuilder(len * 2);
        // 把密文转换成十六进制的字符串形式
        for (int j = 0; j < len; j++) {
            buf.append(HEX_DIGITS[(bytes[j] >> 4) & 0x0f]);
            buf.append(HEX_DIGITS[bytes[j] & 0x0f]);
        }
        return buf.toString();
    }

    public static String encode(String str) {
        if (str == null) {
            return null;
        }
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("SHA1");
            messageDigest.update(str.getBytes());
            return getFormattedText(messageDigest.digest());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值