參考: 1.https://www.cnblogs.com/martianShu/p/5947170.html
基本上看了這篇文章,就可以了,前提是要看一下微信開發文檔,申請微信開發公眾號等,前期準備要做好
申請微信公眾號 ,獲得公眾號的appid和秘鑰查看appid及appsecret
前臺引入相關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();})
后臺代碼
@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.完整代碼
前臺:
<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>郵 箱:
</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>微 信:
</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>姓 名:
</label> <span>${login_user.name}
</span></div><div class="text-left user-info"><label>公 司:
</label> <span style="display: inline-block;width: 325px">${login_user.company}
</span> <label>行 業:
</label> <span>${user.vocation}
</span></div><div class="text-left user-info"><label>地 區:
</label> <span>${login_user.provice} ${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號 :
</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;">頭 像
</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>
后臺
@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;}}
總結
以上是生活随笔為你收集整理的java微信绑定的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。