当前位置:网站首页>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
边栏推荐
- [untitled]
- Jenkins continuous integration environment construction V (Jenkins common construction triggers)
- Tsinghua University product: penalty gradient norm improves generalization of deep learning model
- Which product is better for 2022 annual gold insurance?
- Backpropagation formula derivation [Li Hongyi deep learning version]
- Mindmanager2022 efficient and easy to use office mind map MindManager
- Sword finger offer:55 - I. depth of binary tree
- [latex] production of complex tables: excel2latex and detail adjustment
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
猜你喜欢

MySQL one master multiple slaves + linear replication

基于PHP的轻量企业销售管理系统

Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches

Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website

Dare to climb here, you're not far from prison, reptile reverse actual combat case

Webhook triggers Jenkins for sonar detection

PID of sunflower classic

National standard gb28181 protocol platform easygbs fails to start after replacing MySQL database. How to deal with it?

Lichuang EDA learning notes 14: PCB board canvas settings

Mindmanager2022 efficient and easy to use office mind map MindManager
随机推荐
JVM family -- heap analysis
Recursive structure
Don't disagree, this is the most powerful "language" of the Internet
Consul of distributed service registration discovery and unified configuration management
Learning video website
SQL语句加强练习(MySQL8.0为例)
[source code analysis] model parallel distributed training Megatron (5) -- pipestream flush
Dare to climb here, you're not far from prison, reptile reverse actual combat case
CUDA basic knowledge
Examination question bank of constructor decoration direction post skills (constructor) and examination data of constructor decoration direction post skills (constructor) in 2022
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?
Calculate the odd sum of 1~n (1~100 as an example)
Aperçu du code source futur - série juc
Object oriented -- encapsulation, inheritance, polymorphism
How much does it cost to open a futures account in China? Where is it safe to open an account at present?
Hospital network planning and design document based on GLBP protocol + application form + task statement + opening report + interim examination + literature review + PPT + weekly progress + network to
Zigzag scan
New year's first race, submit bug reward more!
Management and thesis of job management system based on SSM
MySQL is dirty
