第三方網(wǎng)站微信登錄java代碼實現(xiàn)
前兩個星期在公司中的項目加上了微信登錄、綁定的功能,在這里做個記錄!
一、開發(fā)前知識
1、微信開放平臺與微信公眾平臺的區(qū)別
1.1 微信公眾平臺:
?、?地址:https://mp.weixin.qq.com/cgi-bin/loginpage?t=wxm2-login&lang=zh_CN
?、?微信公眾平臺面向的是普通的用戶,比如自媒體和媒體,企業(yè)官方微信公眾賬號運營人員使用,當(dāng)然你所在的團(tuán)隊或者公司有實力去開發(fā)一些內(nèi)容,也可以調(diào)用公眾平臺里面的接口,比如自定義菜單,自動回復(fù),查詢功能。
1.2 微信開放平臺:
?、?地址:https://open.weixin.qq.com/
微信開放平臺:面向的是開發(fā)者和第三方軟件開發(fā)商。開放平臺的文檔似乎包含了微信開放平臺文檔里面的接口。
2、微信公眾平臺目前只支持80端口,且項目上傳到服務(wù)器上面不容易debug啊?
解決方法:ngrok 工具,可以根據(jù)本地項目映射成外網(wǎng)可以訪問的地址、端口,默認(rèn)映射為80端口。
官網(wǎng): https://dashboard.ngrok.com
存在問題: 每次重啟,域名會變化,都需要項目中、微信公眾平臺配置,付費可以固定域名。。。
使用方法: ① 注冊后獲得一個授權(quán)碼,下載 ngrok
② 》CMD 進(jìn)入 ngrok 目錄
》ngrok authtoken 授權(quán)碼
》ngrok http 8080
?、劭吹竭@個頁面,ngrok就為你分配了臨時訪問通道成功了^^

二、配置
(每個微信號可以申請成為開發(fā)者測試賬號進(jìn)行微信功能開發(fā)的。)
1、在公眾平臺中進(jìn)行配置:
地址: http://mp.weixin.qq.com/debug/cgi-bin/sandboxinfo?action=showinfo&t=sandbox/index
?、伲号渲?ldquo;接口配置信息” (Token 在項目中我是配置為"handsomeKing",沒錯,我就是King ^^)
url 改為自己映射的域名

② 配置“功能服務(wù)” 的 “網(wǎng)頁帳號”。注意,是域名

好了,可以愉快的coding 了?。?!
三、可以開發(fā)啦
1、上面的 “接口配置信息” 配置得 wechat/ownerCheck 方法是驗證 這個url 為我自己的,handsomeKing 就是這個方法中的一個參數(shù)。微信這個小朋友會用Get方法帶上4個參數(shù)給我服務(wù)器: signature(簽名)、timestamp(時間戳)、nonce(隨機(jī)數(shù))、echostr(隨機(jī)字符串),再加上咱們項目中自己配置的 token ,通過檢驗signature對請求進(jìn)行校驗,若校驗成功則原樣返回echostr,表示接入成功,否則接入失?。海╰alk is cheap, show me the code *&)
/**
* 微信消息接收和token驗證
* @param model
* @param request
* @param response
* @throws IOException
*/
@RequestMapping("/ownerCheck")
public void ownerCheck(Model model, HttpServletRequest request,HttpServletResponse response) throws IOException {
System.out.println(111);
boolean isGet = request.getMethod().toLowerCase().equals("get");
PrintWriter print;
if (isGet) {
// 微信加密簽名
String signature = request.getParameter("signature");
// 時間戳
String timestamp = request.getParameter("timestamp");
// 隨機(jī)數(shù)
String nonce = request.getParameter("nonce");
// 隨機(jī)字符串
String echostr = request.getParameter("echostr");
// 通過檢驗signature對請求進(jìn)行校驗,若校驗成功則原樣返回echostr,表示接入成功,否則接入失敗
if (signature != null && CheckoutUtil.checkSignature(signature, timestamp, nonce)) {
try {
print = response.getWriter();
print.write(echostr);
print.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class CheckoutUtil {
// 與接口配置信息中的Token要一致
private static String token = "handsomeKing";
/**
* 驗證簽名
*
* @param signature
* @param timestamp
* @param nonce
* @return
*/
public static boolean checkSignature(String signature, String timestamp, String nonce) {
String[] arr = new String[] { token, timestamp, nonce };
// 將token、timestamp、nonce三個參數(shù)進(jìn)行字典序排序
// Arrays.sort(arr);
sort(arr);
StringBuilder content = new StringBuilder();
for (int i = 0; i < arr.length; i++) {
content.append(arr[i]);
}
MessageDigest md = null;
String tmpStr = null;
try {
md = MessageDigest.getInstance("SHA-1");
// 將三個參數(shù)字符串拼接成一個字符串進(jìn)行sha1加密
byte[] digest = md.digest(content.toString().getBytes());
tmpStr = byteToStr(digest);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
content = null;
// 將sha1加密后的字符串可與signature對比,標(biāo)識該請求來源于微信
return tmpStr != null ? tmpStr.equals(signature.toUpperCase()) : false;
}
/**
* 將字節(jié)數(shù)組轉(zhuǎn)換為十六進(jìn)制字符串
*
* @param byteArray
* @return
*/
private static String byteToStr(byte[] byteArray) {
String strDigest = "";
for (int i = 0; i < byteArray.length; i++) {
strDigest += byteToHexStr(byteArray[i]);
}
return strDigest;
}
/**
* 將字節(jié)轉(zhuǎn)換為十六進(jìn)制字符串
*
* @param mByte
* @return
*/
private static String byteToHexStr(byte mByte) {
char[] Digit = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
char[] tempArr = new char[2];
tempArr[0] = Digit[(mByte >>> 4) & 0X0F];
tempArr[1] = Digit[mByte & 0X0F];
String s = new String(tempArr);
return s;
}
public static void sort(String a[]) {
for (int i = 0; i < a.length - 1; i++) {
for (int j = i + 1; j < a.length; j++) {
if (a[j].compareTo(a[i]) < 0) {
String temp = a[i];
a[i] = a[j];
a[j] = temp;
}
}
}
}
}
2、用戶用戶同意授權(quán),獲取微信服務(wù)器傳過來的倆參數(shù): code、state。其中:
APPID: 微信開發(fā)者測試賬號
REDIRECT_URI: 同意授權(quán)后跳轉(zhuǎn)的 URL
/**
* 第一步:用戶同意授權(quán),獲取code(引導(dǎo)關(guān)注者打開如下頁面:)
* 獲取 code、state
*/
public static String getStartURLToGetCode() {
String takenUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=APPID&redirect_uri=REDIRECT_URI&response_type=code&scope=SCOPE&state=STATE#wechat_redirect";
takenUrl= takenUrl.replace("APPID", Param.APPID);
takenUrl= takenUrl.replace("REDIRECT_URI", URL.encode(Param.REDIRECT_URI));
//FIXME : snsapi_userinfo
takenUrl= takenUrl.replace("SCOPE", "snsapi_userinfo");
System.out.println(takenUrl);
return takenUrl;
}
3、獲取微信用戶的 access_token、openid
APPID:微信開發(fā)者測試賬號
secret:微信開發(fā)者測試賬號密碼
code::上一步的 code
/**
* 獲取access_token、openid
* 第二步:通過code獲取access_token
* @param code url = "https://api.weixin.qq.com/sns/oauth2/access_token
* ?appid=APPID
* &secret=SECRET
* &code=CODE
* &grant_type=authorization_code"
* */
public static OAuthInfo getAccess_token(String code){
String authUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code ";
authUrl= authUrl.replace("APPID", Param.APPID);
authUrl = authUrl.replace("SECRET", Param.SECRET);
authUrl = authUrl.replace("CODE", code);
String jsonString = HTTPRequestUtil.sendPost(authUrl,"");
System.out.println("jsonString: " + jsonString);
OAuthInfo auth = null;
try {
auth = (OAuthInfo) JacksonUtil.parseJSONToObject(OAuthInfo.class, jsonString);
} catch (Exception e) {
e.printStackTrace();
}
return auth;
}
4、在數(shù)據(jù)庫中查詢 openid
我是定義了一個對象 OauthInfo,包括 openid(用戶的標(biāo)識)屬性。。。
查詢時庫中存在就直接登錄啦,不存在就先去登錄頁,將登錄賬號同 openid 綁定。
/**
* 微信引導(dǎo)頁進(jìn)入的方法
* @return
*/
@RequestMapping("/loginByWeiXin")
public String loginByWeiXin(HttpServletRequest request, Map<String, Object> map) {
// 微信接口自帶 2 個參數(shù)
String code = request.getParameter("code");
String state = request.getParameter("state");
System.out.println("code = " + code + ", state = " + state);
if(code != null && !"".equals(code)) {
// 授權(quán)成功, 微信獲取用戶openID
OAuthInfo authInfo = WeiXinUtil.getAccess_token(code);
String openid = authInfo.getOpenid();
String access_token = authInfo.getAccess_token();
if(access_token == null) {
// Code 使用過 異常
System.out.println("Code 使用過 異常.....");
return "redirect:" + WeiXinUtil.getStartURLToGetCode();
}
// 數(shù)據(jù)庫中查詢微信號是否綁定平臺賬號
SysUser sysUser = weiXinService.getUserByWeiXinID(openid);
if(sysUser == null) {
String randomStr = StringUtil.getRandomString(50);
request.getSession().setAttribute(openid, randomStr);
// 尚未綁定賬號
System.out.println("尚未綁定賬號.....");
return "redirect:/index.jsp?openid=" + openid + "&state=" + randomStr;
}
userController.doSomeLoginWorkToHomePage(sysUser.getMcid(), map);
// 登錄成功
return "homePage";
}
// 未授權(quán)
return "redirect:" + WeiXinUtil.getStartURLToGetCode();
}
四、踩過的坑
1、access_token 與普通 access_token。這是啥關(guān)系?
答:access_token: 登錄授權(quán)會得到一個 access_token, 這個是用于標(biāo)識登錄用戶(沒有使用次數(shù)限制),綁定流程中用的都是 登錄 access_token。
普通 access_token: 調(diào)用其它微信應(yīng)用接口時需要帶上的 access_token,普通 access_token時效為 2H, 每個應(yīng)用每天調(diào)用次數(shù)<= 2000次。(實際開發(fā)時必須加以處理。。我采用的是 quartz 調(diào)度^^)
2、uuid、openid。我該綁定uuid?不不不,openid?不不,到底綁哪個?
答:uuid:微信號綁定后才有的標(biāo)識,對于任何應(yīng)用該微信賬號的 uuid 均相同。同一個微信賬號不同的應(yīng)用 uuid 相同。
openid:微信號對于每個應(yīng)用均有一個不變的 openid,同一個微信賬號不同的應(yīng)用 openid 不同。
五、參考的鏈接!感謝!!
文中也許會存在我理解上的錯誤,望各位不吝賜教,小弟定會加以改正。
更多精彩內(nèi)容請點擊《java微信開發(fā)教程匯總》歡迎大家學(xué)習(xí)閱讀。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
spring?boot只需兩步優(yōu)雅整合activiti示例解析
這篇文章主要主要來教大家spring?boot優(yōu)雅整合activiti只需兩步就可完成測操作示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助祝大家多多進(jìn)步2022-03-03
Spring Boot利用JSR303實現(xiàn)參數(shù)驗證的方法實例
這篇文章主要給大家介紹了關(guān)于Spring Boot利用JSR303實現(xiàn)參數(shù)驗證的相關(guān)資料,文中通過示例代碼介紹的非常詳細(xì),對大家學(xué)習(xí)或者使用Spring Boot具有一定的參考學(xué)習(xí)價值,需要的朋友們下面來一起學(xué)習(xí)學(xué)習(xí)吧2020-05-05
java使用靜態(tài)關(guān)鍵字實現(xiàn)單例模式
這篇文章主要為大家詳細(xì)介紹了java使用靜態(tài)關(guān)鍵字實現(xiàn)單例模式,具有一定的參考價值,感興趣的小伙伴們可以參考一下2018-04-04

