当前位置:网站首页>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
边栏推荐
- Third party login initial version
- PMP 考試常見工具與技術點總結
- Stm32bug [the project references devices, files or libraries that are not installed appear in keilmdk]
- 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?
- Package and download 10 sets of Apple CMS templates / download the source code of Apple CMS video and film website
- 【.NET+MQTT】.NET6 環境下實現MQTT通信,以及服務端、客戶端的雙邊消息訂閱與發布的代碼演示
- Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
- 7 * 24-hour business without interruption! Practice of applying multiple live landing in rookie villages
- Monitoring - Prometheus introduction
- PID of sunflower classic
猜你喜欢

GUI Graphical user interface programming (XIV) optionmenu - what do you want your girlfriend to wear on Valentine's day

1day vulnerability pushback skills practice (3)

Mindmanager2022 efficient and easy to use office mind map MindManager

Add token validation in swagger

Command Execution Vulnerability - command execution - vulnerability sites - code injection - vulnerability exploitation - joint execution - bypass (spaces, keyword filtering, variable bypass) - two ex

Code Execution Vulnerability - no alphanumeric rce create_ function()

MySQL query

Package details_ Four access control characters_ Two details of protected

Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram

Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
随机推荐
National standard gb28181 protocol platform easygbs fails to start after replacing MySQL database. How to deal with it?
2022 attached lifting scaffold worker (special type of construction work) free test questions and attached lifting scaffold worker (special type of construction work) examination papers 2022 attached
[untitled]
Session learning diary 1
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
CUDA basic knowledge
@Scheduled scheduled tasks
System integration meets the three business needs of enterprises
PMP 考試常見工具與技術點總結
Lichuang EDA learning notes 14: PCB board canvas settings
Is it really so difficult to learn redis? Today, a fan will share his personal learning materials!
Typical applications of minimum spanning tree
What is the difference between enterprise wechat applet and wechat applet
The first spring of the new year | a full set of property management application templates are presented, and Bi construction is "out of the box"
MySQL backup notes
[PaddleSeg 源码阅读] PaddleSeg计算Dice
[PaddleSeg 源码阅读] PaddleSeg 自定义数据类
渗透实战-SQLServer提权
Object oriented -- encapsulation, inheritance, polymorphism
What are the virtual machine software? What are their respective functions?
