java微信绑定

参考: 1.https://www.cnblogs.com/martianShu/p/5947170.html
基本上看了这篇文章,就可以了,前提是要看一下微信开发文档,申请微信开发公众号等,前期准备要做好

  1. 申请微信公众号 ,获得公众号的appid和秘钥
  2. 查看appid及appsecret

  3. 前台引入相关js

<script type="text/javascript" src="${base}/theme2/plugins/jquery.qrcode.min.js"></script>

<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
 @if(login_user.wxunionid==null || login_user.wxunionid==""){
        <a  style="margin-left: -1000px;cursor: pointer" id="wxBind">【绑定微信】</a>
        @}else{
        <a style="margin-left: -1000px">已绑定</a>
        @}

  <div style="position: absolute;margin-top: -40px;margin-left: 100px;background-color: #eee" id="login_container"></div>




 var obj = new WxLogin({
        self_redirect:false,
        id:"login_container",
        appid: "wx4e5373274d806988",
        scope: "snsapi_login",
        redirect_uri: "http%3a%2f%2fwww.3dmomoda.com/zone/ucenter",
        state: "STATE",
        style: "",
        href: ""
    });

     $("#wxBind").click(function () {
            $("#login_container").toggle();
    })
  1. 后台代码
/**
     * 用户空间 个人资料
     */
    @Before(UserLoginInterceptor.class)
    public void ucenter() {
        String login_userid = CasKit.getStr("userid");
        this.setAttr("zone_navba", "ucenter");
        String code = this.getPara("code","");
        String state = this.getPara("state","");

        User user = User.dao.getById(login_userid);
        if (user != null) {
            if(!"".equals(code)){
                String result = HttpClientUtil.getForObject("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4e5373274d806988&secret=8b4f2363f85adf43aeb41c5b729731b3&code=" + code + "&grant_type=authorization_code");
                WxInfo wxInfo=JSON.parseObject(result, WxInfo.class);
                String userInfo = HttpClientUtil.getForObject("https://api.weixin.qq.com/sns/userinfo?access_token="+wxInfo.getAccess_token()+"&openid="+wxInfo.getOpenid());
                WxUserInfo wxUserInfo=JSON.parseObject(userInfo, WxUserInfo.class);
                log.error(wxUserInfo.toString());
                user.set("wxname",wxUserInfo.getNickname());
                user.set("wximg",wxUserInfo.getHeadimgurl());
                user.set("wxsex",wxUserInfo.getSex());
                user.set("wxopenid",wxUserInfo.getOpenid());
                user.set("wxunionid",wxUserInfo.getUnionid());
                user.update();
            }
            this.setAttr("self", true);
            this.setAttr("his", "我");
            this.setAttr("user", user);
            if (this.getPara("_pjax") == null && this.getPara("_ajax") == null) {
                this.render("/zone/ucenter/index.html");
            } else {
                this.render("/zone/ucenter/item.html");
            }
        } else {
            throw new RuntimeException("用户不存在啊,请重新登录");
        }
    }

6.完整代码

  1. 前台:
<script type="text/javascript" src="${base}/theme2/plugins/jquery.qrcode.min.js"></script>
<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
<div class="call-to-action">
    <div class="row">
        <div class="text-left user-info" style="width: 55%">
            <label>用户ID: </label> <span>${user.userid}</span>
        </div>
        <div class="text-left user-info" style="width: 55%;">
            <label>用户名: </label> <span>
                @if(!strutil.contain(login_user.username, "@default.default")){
                    ${login_user.username}
                @}
            </span>
        </div>
        <div class="text-left user-info" style="width: 55%;">
            <label>邮&nbsp;&nbsp;&nbsp;箱: </label> <span>
                @if(!strutil.contain(login_user.email, "@default.default")){
                    ${login_user.email}
                @}
            </span>
        </div>
        <div class="text-left user-info" style="width: 55%;">
            <label>微&nbsp;&nbsp;&nbsp;信: </label> <span>
                @if(login_user.wxunionid==null || login_user.wxunionid==""){

                @}else{
                    ${login_user.wxname}
                @}
            </span>
        </div>
        @if(login_user.wxunionid==null || login_user.wxunionid==""){
        <a  style="margin-left: -1000px;cursor: pointer" id="wxBind">【绑定微信】</a>
        @}else{
        <a style="margin-left: -1000px">已绑定</a>
        @}
        <div style="position:relative">
            <div style="position: absolute;margin-top: -40px;margin-left: 100px;background-color: #eee" id="login_container"></div>
            <div class="text-left user-info">
                <label>姓&nbsp;&nbsp;&nbsp;名:</label> <span>${login_user.name}</span>
            </div>
            <div class="text-left user-info">
                <label>公&nbsp;&nbsp;&nbsp;司:</label> <span style="display: inline-block;width: 325px">${login_user.company}</span> <label>行&nbsp;&nbsp;&nbsp;业:</label> <span>${user.vocation}</span>
            </div>
            <div class="text-left user-info">
                <label>地&nbsp;&nbsp;&nbsp;区: </label> <span>${login_user.provice}&nbsp;${user.city}</span>
            </div>
            <div class="text-left user-info">
                <label>手机号: </label> <span>${login_user.phone}</span>
            </div>
            <div class="text-left user-info">
                <label>QQ号&nbsp;: </label> <span>${login_user.qq}</span>
            </div>
        </div>
        <div style="width: 75%; margin-top: 66px;">
            <div class="btn btn-default btn-block" id="editUserInfoBtn" style="display:inline-block;width: 10%;">编辑资料
            </div>
        </div>
        <div class="info_img" style="width: 116px;height: 116px;display: inline-block;position: absolute;top:10px;right: 30%;">
            <img id="clickHeadimg" class="img-rounded" src="${has(headimg)?headimg:'/images/user/user-defalut.svg'}" onerror="imgError(this)" style="display:inline-block;width:100%;height:100%;border-radius: 50%;"/>
            <p style="font-size: 15px;font-weight: bold;color: #666666;margin-top: 10px;">头&nbsp;&nbsp;像</p>
        </div>
    </div>
</div>
<script type="text/javascript">
    $(function () {
        //进入编辑页面
        $("#editUserInfoBtn").on("click", function () {
            $.post('/zone/getEditInfoPage', '', function (data) {
                $("#user-center-body").html(data);
            });
        });

        $("#login_container").hide();
    });

    var obj = new WxLogin({
        self_redirect:false,
        id:"login_container",
        appid: "wx4e5373274d806988",
        scope: "snsapi_login",
        redirect_uri: "http%3a%2f%2fwww.3dmomoda.com/zone/ucenter",
        state: "STATE",
        style: "",
        href: ""
    });


</script>
<script>
    $("#wxBind").click(function () {
            $("#login_container").toggle();
    })
</script>
  1. 后台
/**
     * 用户空间 个人资料
     */
    @Before(UserLoginInterceptor.class)
    public void ucenter() {
        String login_userid = CasKit.getStr("userid");
        this.setAttr("zone_navba", "ucenter");
        String code = this.getPara("code","");
        String state = this.getPara("state","");

        User user = User.dao.getById(login_userid);
        if (user != null) {
            if(!"".equals(code)){
                String result = HttpClientUtil.getForObject("https://api.weixin.qq.com/sns/oauth2/access_token?appid=wx4e5373274d806988&secret=8b4f2363f85adf43aeb41c5b729731b3&code=" + code + "&grant_type=authorization_code");
                WxInfo wxInfo=JSON.parseObject(result, WxInfo.class);
                String userInfo = HttpClientUtil.getForObject("https://api.weixin.qq.com/sns/userinfo?access_token="+wxInfo.getAccess_token()+"&openid="+wxInfo.getOpenid());
                WxUserInfo wxUserInfo=JSON.parseObject(userInfo, WxUserInfo.class);
                log.error(wxUserInfo.toString());
                user.set("wxname",wxUserInfo.getNickname());
                user.set("wximg",wxUserInfo.getHeadimgurl());
                user.set("wxsex",wxUserInfo.getSex());
                user.set("wxopenid",wxUserInfo.getOpenid());
                user.set("wxunionid",wxUserInfo.getUnionid());
                user.update();
            }
            this.setAttr("self", true);
            this.setAttr("his", "我");
            this.setAttr("user", user);
            if (this.getPara("_pjax") == null && this.getPara("_ajax") == null) {
                this.render("/zone/ucenter/index.html");
            } else {
                this.render("/zone/ucenter/item.html");
            }
        } else {
            throw new RuntimeException("用户不存在啊,请重新登录");
        }
    }

3.工具类

package com.momoda.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.PostMethod;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.lang.text.StrBuilder;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

@SuppressWarnings({ "rawtypes", "unchecked" })
public class HttpClientUtil {

    public static HttpClient httpClient = new HttpClient();

    /**
     * 字符串生成Map
     */
    public static <T> T createParamasMap(Object... strs) {
        if (strs.length % 2 != 0) {
            return null;
        }

        Map ret = new HashMap();
        for (int i = 0; i < strs.length; i++) {
            ret.put(strs[i], strs[i + 1]);
            i++;
        }
        return (T) ret;
    }

    /**
     * 创建表单PostMethod
     */
    public static PostMethod createPostMethod(String url, Map<String, String> params) {
        PostMethod postMethod = new PostMethod(url);
        postMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        postMethod.setRequestHeader("Referer", "http://www.3dmomoda.com");
        String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        postMethod.setRequestHeader("User-Agent", agent);
        if (params != null) {
            List<NameValuePair> paramsData = new ArrayList<NameValuePair>();
            for (String key : params.keySet()) {
                paramsData.add(new NameValuePair(key, params.get(key)));
            }
            NameValuePair[] nvpArray = new NameValuePair[paramsData.size()];
            postMethod.setRequestBody(paramsData.toArray(nvpArray));
        }
        postMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        return postMethod;
    }

    /**
     * 创建get
     */
    public static GetMethod createGetMethod(String url) {
        GetMethod getMethod = new GetMethod(url);
        getMethod.setRequestHeader("Accept-Language", "zh-CN,zh;q=0.8,en;q=0.6");
        getMethod.setRequestHeader("Referer", "http://www.3dmomoda.com");
        String agent = "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1750.146 Safari/537.36";
        getMethod.setRequestHeader("User-Agent", agent);
        getMethod.getParams().setParameter(HttpMethodParams.HTTP_CONTENT_CHARSET, "UTF-8");
        return getMethod;
    }

    /**
     * 获取response返回的信息
     */
    public static String getResponseString(HttpMethodBase pm, String charset) {
        StringBuffer response = new StringBuffer();
        try {
            BufferedReader reader = new BufferedReader(new InputStreamReader(pm.getResponseBodyAsStream(), charset));
            String line = "";
            int linecount = 0;
            while ((line = reader.readLine()) != null) {
                if (linecount > 0 && line != null && !line.equals("")) {
                    response.append(System.getProperty("line.separator"));
                }
                response.append(line);
                linecount++;
            }
            reader.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return response.toString();
    }



    public static String getForObject(String url) {
        CloseableHttpClient client=HttpClients.createDefault();
        HttpGet get=new HttpGet(url);
        try {
            CloseableHttpResponse response=client.execute(get);
            if(response.getStatusLine().getStatusCode()==200){
                return getStringResult(response);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }


    public static String getStringResult(HttpResponse response){
        HttpEntity entity = response.getEntity();
        if(entity==null) return null;

        try {
            InputStream is = entity.getContent();
            //转换为字节输入流
            BufferedReader br = new BufferedReader(new InputStreamReader(is, Consts.UTF_8));
            StrBuilder builder = new StrBuilder();
            String body;
            while ((body = br.readLine()) != null) {
                builder.append(body);
            }

            return builder.toString();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值