微信公众号登陆开发流程

1.首先需要获取到openId 用于返回给公众号前台,之后前台传回openId到后台做业务处理

@Autowired
    private WXAuthorizationBiz wxAuthorizationBiz;

    //获取微信openId
    @RequestMapping(value = "/getWechatOpenId", method = RequestMethod.POST)
    @ResponseBody
    public TResponse<?> getWechatOpenId(@Validated @RequestBody ReqGetWechatOpenIdDTO reqDto, BindingResult errors){
        TResponse<?> response = null;
        try {
            if(errors.hasErrors()){
                return TResponse.error(errorMsg(errors));
            }
            response = wxAuthorizationBiz.getWechatOpenId(reqDto);
        } catch (Exception e) {
            LOG.error(e);
            response = TResponse.error("访问异常");
        }
        return response;
    }
View Code

 

 1  //微信appid
 2     private String appid = "wx33777933fae68e32";
 3     //微信secret
 4     private String secret = "dcecb6ad81d86600106b3e4436f00321";
 5     //获取微信code
 6     private String getCodeUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid="+ appid + "&redirect_uri={0}&response_type=code&scope=snsapi_base&state=STATE#wechat_redirect";
 7     //获取openid接口
 8     private String getOpenIdUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid="+ appid +"&secret=" + secret + "&code={0}&grant_type=authorization_code";
 9     //获取token接口
10     private String getTokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+ appid + "&secret=" + secret;
11     //客服消息接口
12     private String sendMsgUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={0}";
13 
14 
15     public String getCodeUrl(String redirectUri) {
16         if (CommomUtil.isNullOrEmpty(redirectUri)) {
17             return null;
18         }
19         return MessageFormat.format(getOpenIdUrl, redirectUri);
20     }
21 
22 
23     public ResGetWXOpenIdDTO getOpenId(String wxCode) throws Exception {
24         try {
25             String resJson = httpClientUtil.GET(MessageFormat.format(getOpenIdUrl, wxCode));
26             if (CommomUtil.isNullOrEmpty(resJson)) {
27                 throw new Exception("获取微信OpenId失败,resJson为空");
28             }
29             LOG.info("getOpenId.resJson = " + resJson);
30             ResGetWXOpenIdDTO resDto = gson.fromJson(resJson, ResGetWXOpenIdDTO.class);
31             if (resDto == null || CommomUtil.isNullOrEmpty(resDto.getOpenid())) {
32                 throw new Exception("获取微信OpenId失败,OpenId为空");
33             }
34             return resDto;
35         } catch (Exception e) {
36             LOG.error(e);
37             throw e;
38         }
39     }
View Code

2.获取短信验证码

public TResponse<?> getWXVerifyCode(ReqGetWXVerifyCodeDTO reqDto) {
        try {
            String telphone = reqDto.getTelphone().trim();
            if (!CheckTelPhone.isTelphoneNum(telphone)) {
                return TResponse.error("手机号码格式不正确");
            }
            //发送验证码
            Random random = new Random();
            String code = random.nextInt(9999) + "";
            boolean flag = JuheSMS.sendVerifyCode(telphone, code);
            if (!flag){
                return TResponse.error("获取验证码失败");
            }
            String openId = reqDto.getOpenId().trim();
            VerifyCode verifyCode = new VerifyCode(code, System.currentTimeMillis());
            //保存
            verifyCodeMap.put(openId, verifyCode);
            return TResponse.success("获取验证码成功");
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

public class    JuheSMS {
    private static Gson gson = GsonUtil.getInstance().getGson();

    private static final String DEF_CHATSET = "UTF-8";
    private static final int DEF_CONN_TIMEOUT = 30000;
    private static final int DEF_READ_TIMEOUT = 30000;
    private static String userAgent = "Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.66 Safari/537.36";

    // 配置您申请的KEY
    private static final String APPKEY = "8790cc59919810935fa25c544a29471a";
    private static final String tpl_id = "13577";


    public static boolean sendVerifyCode(String telphone, String verifyCode) throws Exception {
        Map<String, Object> params = new HashMap<String, Object>();// 请求参数
        params.put("mobile", telphone);
        params.put("tpl_id", tpl_id);
        params.put("tpl_value", "#code#=" + verifyCode);
        params.put("key", APPKEY);
        params.put("dtype", "json");
        String result = net("http://v.juhe.cn/sms/send", params, "GET");
        if (CommomUtil.isNullOrEmpty(result)) {
            throw new Exception("发送短信验证码失败,result为空");
        }
        ResJuHeSMSDTO resJuHeSMSDTO = gson.fromJson(result, ResJuHeSMSDTO.class);
        if (resJuHeSMSDTO == null) {
            throw new Exception("发送短信验证码失败,反序列化失败");
        }
        if (resJuHeSMSDTO.getResult() != null
                && CommomUtil.isNotNullOrEmpty(resJuHeSMSDTO.getResult().getSid())) {
            return true;//发送成功
        }
        return false;
    }

    /**
     * @param strUrl 请求地址
     * @param params 请求参数
     * @param method 请求方法
     * @return 网络请求字符串
     * @throws Exception
     */
    private static String net(String strUrl, Map<String, Object> params, String method) throws Exception {
        HttpURLConnection conn = null;
        BufferedReader reader = null;
        String rs = null;
        try {
            if (method == null || method.equals("GET")) {
                strUrl = strUrl + "?" + urlencode(params);
            }
            URL url = new URL(strUrl);
            conn = (HttpURLConnection) url.openConnection();
            if (method == null || method.equals("GET")) {
                conn.setRequestMethod("GET");
            } else {
                conn.setRequestMethod("POST");
                conn.setDoOutput(true);
            }
            conn.setRequestProperty("User-agent", userAgent);
            conn.setUseCaches(false);
            conn.setConnectTimeout(DEF_CONN_TIMEOUT);
            conn.setReadTimeout(DEF_READ_TIMEOUT);
            conn.setInstanceFollowRedirects(false);
            conn.connect();
            if (params != null && method.equals("POST")) {
                try {
                    DataOutputStream out = new DataOutputStream(conn.getOutputStream());
                    out.writeBytes(urlencode(params));
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }
            }
            InputStream is = conn.getInputStream();
            reader = new BufferedReader(new InputStreamReader(is, DEF_CHATSET));
            StringBuilder strber = new StringBuilder();
            String line = null;
            while ((line = reader.readLine()) != null)
                strber.append(line + "\n");
            // 得到请求结果数据
            String ret = strber.toString();
            ret = ret.replaceAll("&", "&amp;");
            return ret;
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if (reader != null) {
                reader.close();
            }
            if (conn != null) {
                conn.disconnect();
            }
        }
    }

    // 将map型转为请求参数型
    private static String urlencode(Map<String, Object> data) {
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, Object> i : data.entrySet()) {
            try {
                sb.append(i.getKey()).append("=").append(URLEncoder.encode(i.getValue() + "", "UTF-8")).append("&");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e);
            }
        }
        return sb.toString();
    }
}
    }
View Code

 

转载于:https://www.cnblogs.com/liyiren/p/10522213.html

微信公众号的web开发流程可以简单概括为以下几个步骤: 1. 注册与认证:首先需要在微信公众平台上注册一个账号,然后进行认证,通过后方可获得开发者权限和接口调用权限。 2. 服务器搭建:在开发公众号web应用之前,需要准备一个稳定可靠的服务器,用来存放应用程序的代码和数据。 3. 开发环境准备:开发者需要安装相关的开发环境和工具,如代码编辑器、服务器软件等。 4. 开发功能:根据公众号的需求,开始进行功能开发。可以选择使用微信公众平台提供的开发接口,如获取用户信息、发送消息等,也可以根据具体业务需求自行开发相关功能。 5. 接口对接:在功能开发完成后,需要将公众号与服务器进行接口对接,实现数据的传输和交互。 6. 测试和优化:在开发完成后,需要进行测试,确保功能的稳定性和兼容性。如果存在问题,还需要进行优化和修复。 7. 发布上线:经过测试和优化后,将应用程序部署到服务器上,并在微信公众号后台设置服务器配置,确保公众号可以正常访问和使用。 8. 运营与维护:上线后,需要定期对公众号进行运营和维护,及时修复bug和添加新的功能,保证公众号的正常运行和用户体验。 总体来说,微信公众号的web开发流程包括注册与认证、服务器搭建、开发环境准备、功能开发、接口对接、测试和优化、发布上线以及运营与维护等步骤,需要开发者具备一定的技术和开发经验,并且需要不断迭代和优化,以适应不断变化的用户需求。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值