当前位置:网站首页>Wechat official account web page authorization
Wechat official account web page authorization
2022-07-04 03:36:00 【Cancri e】
Overall process
Official wechat documents : Web page authorization | Wechat open documents
Preparation 
ad locum , We don't need to apply for a real official account , The wechat team provides a test account for the majority of developers . This account does not need a public account , Quickly apply for interface test , Directly experience and test all advanced interfaces of the public platform . Address : WeChat public platform , Scan the QR code of test number , And pay attention to the official account . We will get appID and appsecret( It will be used in subsequent development ).
Because we need to interact with wechat server , The website of the program we developed is 127.0.0.1:8080, Therefore, we need to expose our access address on the public network first , What I'm using here is NATAPP.( Registration requires real name verification )
Official website :NATAPP- Intranet through be based on ngrok Domestic high-speed intranet mapping tool .
Intranet penetration steps
First step : After successful login, it is on the left My tunnel Choose from Buy tunnels , The following figure takes the free tunnel as an example .
The second step : After successful purchase, it is on the left My tunnel Choose from My tunnel , As shown in the figure below .
The third step : Show success after , download NATAPP client .
Step four : double-click natapp.exe, Enter at the command line natapp -authtoken=xxx ( among ,xxx For my tunnel in the web authtoken), The successful interface is shown in the figure below .
The mosaic in the red box is the address on your public network . ( Because it's a free tunnel , The address is not fixed , It will change after a period of time ).
Step five : Send the address Get rid of http:// fill WeChat public platform -> Web Services -> In the web account .
Wechat public platform test number interface configuration
URL Fill in Wechat server Access the development program Address of the interface , The mosaic is the public network address configured in front ;Token It needs to be consistent with the code , Here I set it to wxtoken .
Code writing
Project structure
WeixinOauthController
@Controller
@RequestMapping("weixin")
public class WeixinOauthCotroller {
@RequestMapping("oauth")
public void oauth(HttpServletResponse response) throws IOException {
String path = MenuManager.REAL_URL + "weixin/invoke";
try {
path = URLEncoder.encode(path, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
String url = "https://open.weixin.qq.com/connect/oauth2/authorize?" +
"appid=" + MenuManager.APP_ID +
"&redirect_uri=" + path +
"&response_type=code" +
"&scope=snsapi_base" +
"&state=STATE" +
"#wechat_redirect";
response.sendRedirect(url);
}
@ResponseBody
@RequestMapping("invoke")
public JSONObject oauthInvoke(HttpServletRequest request) throws JSONException {
// get code
String code = request.getParameter("code");
String state = request.getParameter("state");
// adopt code Website authorization access_token
// Authentication server
String url = "https://api.weixin.qq.com/sns/oauth2/access_token?" +
"appid=" + MenuManager.APP_ID +
"&secret=" + MenuManager.APP_SECRET +
"&code=" + code +
"&grant_type=authorization_code";
// Authentication server With code Send a request obtain access_token
JSONObject jsonObjectPost = new JSONObject(Send.sendPost(url));
System.out.println(jsonObjectPost);
String accessToken = jsonObjectPost.getString("access_token");
String openid = jsonObjectPost.getString("openid");
// With openid and access_token Get resource information
String urlInfo = "https://api.weixin.qq.com/sns/userinfo?" +
"access_token=" + accessToken +
"&openid=" + openid +
"&lang=zh_CN";
JSONObject jsonObjectGet = new JSONObject(Send.sendGet(urlInfo));
System.out.println(jsonObjectGet);
System.out.println(jsonObjectGet.getString("nickname"));
return jsonObjectGet;
}
}
WxSignatureCheckController
@RestController
public class WxSignatureCheckController {
@Autowired
private WxSignatureCheckService wxSignatureCheckService;
@RequestMapping("/wxCheck")
public String wxSignatureCheck(
@RequestParam(value = "signature") String signature,
@RequestParam(value = "timestamp") String timestamp,
@RequestParam(value = "nonce") String nonce,
@RequestParam(value = "echostr") String echostr
){
return wxSignatureCheckService.wxSignatureCheck(signature, timestamp, nonce, echostr);
}
}
WxSignatureCheckService(token It needs to be consistent with the wechat public platform )
@Service
public class WxSignatureCheckService {
//token The value must be completely consistent with that configured in wechat official account !!!
private final String token = "wxtoken";
public String wxSignatureCheck(String signature, String timestamp, String nonce, String echostr) {
ArrayList<String> array = new ArrayList<String>();
array.add(signature);
array.add(timestamp);
array.add(nonce);
// Sort
String sortString = sort(token, timestamp, nonce);
// encryption
String mytoken = Decript.SHA1(sortString);
// Verify signature
if (mytoken != null && mytoken != "" && mytoken.equals(signature)) {
System.out.println(" Signature verification passed .");
return echostr; // If the verification is successful, output echostr, Wechat server receives this output , To confirm that the inspection is complete .
} else {
System.out.println(" Signature verification failed .");
return null;
}
}
/**
* Sorting method
* @param token
* @param timestamp
* @param nonce
* @return
*/
public static String sort(String token, String timestamp, String nonce) {
String[] strArray = { token, timestamp, nonce };
Arrays.sort(strArray);
StringBuilder sbuilder = new StringBuilder();
for (String str : strArray) {
sbuilder.append(str);
}
return sbuilder.toString();
}
}
Decript
/**
* Encryption method
*/
public class Decript {
public static String SHA1(String decript) {
try {
MessageDigest digest = MessageDigest
.getInstance("SHA-1");
digest.update(decript.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuffer hexString = new StringBuffer();
// Byte array converted to Hexadecimal Count
for (int i = 0; i < messageDigest.length; i++) {
String shaHex = Integer.toHexString(messageDigest[i] & 0xFF);
if (shaHex.length() < 2) {
hexString.append(0);
}
hexString.append(shaHex);
}
return hexString.toString();
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return "";
}
}
MenuManager( You need to modify it to your own information )
public class MenuManager {
public static final String APP_ID = On wechat public platform appID;
public static final String APP_SECRET = On wechat public platform appsecret;
public static final String REAL_URL = Public address ( contain http://);
}
Send
public class Send {
/**
* Assign to URL send out POST Method request
* @param url Send requested URL
* @return Response result of the remote resource represented
*/
public static String sendPost(String url) {
PrintWriter out = null;
BufferedReader in = null;
String result = "";
try {
URL realUrl = new URL(url);
// Open and URL Connection between
URLConnection conn = realUrl.openConnection();
// Set common request properties
conn.setRequestProperty("accept", "*/*");
conn.setRequestProperty("connection", "Keep-Alive");
conn.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
conn.setRequestProperty("Content-Type", "application/json;charset=UTF-8");
// send out POST The request must be set to the following two lines
conn.setDoOutput(true);
conn.setDoInput(true);
// obtain URLConnection Object corresponding output stream
out = new PrintWriter(conn.getOutputStream());
// flush Buffering of output streams
out.flush();
// Definition BufferedReader Input stream to read URL Response
in = new BufferedReader(
new InputStreamReader(conn.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" send out POST Exception in request !" + e);
e.printStackTrace();
}
// Use finally Block to close the output stream 、 Input stream
finally {
try {
if (out != null) {
out.close();
}
if (in != null) {
in.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
return result;
}
/**
* Assign to URL send out GET Method request
* @param url Send requested URL
* @return URL Response result of the remote resource represented
*/
public static String sendGet(String url) {
String result = "";
BufferedReader in = null;
try {
String urlNameString = url;
URL realUrl = new URL(urlNameString);
// Open and URL Connection between
URLConnection connection = realUrl.openConnection();
// Set common request properties
connection.setRequestProperty("accept", "*/*");
connection.setRequestProperty("connection", "Keep-Alive");
connection.setRequestProperty("user-agent",
"Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
// Establish the actual connection
connection.connect();
// Definition BufferedReader Input stream to read URL Response
in = new BufferedReader(new InputStreamReader(
connection.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
result += line;
}
} catch (Exception e) {
System.out.println(" send out GET Exception in request !" + e);
e.printStackTrace();
}
// Use finally Block to close the input stream
finally {
try {
if (in != null) {
in.close();
}
} catch (Exception e2) {
e2.printStackTrace();
}
}
return result;
}
}
result
There is no front-end interface , Only the console can output user information .
Reference material :NATAPP Use the tutorial ( Intranet through )_Willing Kaka's blog -CSDN Blog _natapp Use the tutorial
WeChat official account OAuth2.0 Web page authorization _ Bili, Bili _bilibili
边栏推荐
- Monitoring - Prometheus introduction
- CSCI 2134
- PMP 考試常見工具與技術點總結
- Learning video website
- Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
- 7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
- Third party login initial version
- [untitled]
- How to use STR function of C language
- Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
猜你喜欢
Katalon框架测试web(二十六)自动发邮件
Zhihu million hot discussion: why can we only rely on job hopping for salary increase? Bosses would rather hire outsiders with a high salary than get a raise?
Webhook triggers Jenkins for sonar detection
MySQL data query optimization -- data structure of index
The 37 year old programmer was laid off, and he didn't find a job for 120 days. He had no choice but to go to a small company. As a result, he was confused
Unity controls the selection of the previous and next characters
Tsinghua University product: penalty gradient norm improves generalization of deep learning model
Want to do something in production? Then try these redis commands
Nbear introduction and use diagram
Dare to climb here, you're not far from prison, reptile reverse actual combat case
随机推荐
Value transfer communication between components (parent to child, child to parent, brother component to value)
数据库SQL语句汇总,持续更新......
Lichuang EDA learning notes 14: PCB board canvas settings
Constantly changing harmonyos custom JS components during the Spring Festival - Smart Koi
PID of sunflower classic
warning: LF will be replaced by CRLF in XXXXXX
Record a problem that soft deletion fails due to warehouse level error
Rhcsa day 3
Résumé des outils communs et des points techniques de l'examen PMP
What is the difference between enterprise wechat applet and wechat applet
system information
Why is it recommended that technologists write blogs?
JSON string conversion in unity
[latex] production of complex tables: excel2latex and detail adjustment
JVM family -- monitoring tools
2006 translation
If you have just joined a new company, don't be fired because of your mistakes
Zlmediakit compilation and webrtc push-pull flow testing
Summary of Chinese remainder theorem
Sword finger offer:55 - I. depth of binary tree