当前位置:网站首页>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
边栏推荐
- Recursive structure
- If you have just joined a new company, don't be fired because of your mistakes
- System integration meets the three business needs of enterprises
- How much does it cost to open a futures account in China? Where is it safe to open an account at present?
- Résumé des outils communs et des points techniques de l'examen PMP
- Backpropagation formula derivation [Li Hongyi deep learning version]
- Es network layer
- [database I] database overview, common commands, view the table structure of 'demo data', simple query, condition query, sorting data, data processing function (single row processing function), groupi
- 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?
- Cache general management class + cache httpcontext Current. Cache and httpruntime Differences between caches
猜你喜欢

Setting methods, usage methods and common usage scenarios of environment variables in postman

Code Execution Vulnerability - no alphanumeric rce create_ function()

logistic regression

If you have just joined a new company, don't be fired because of your mistakes

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

@Scheduled scheduled tasks

Monitoring - Prometheus introduction

Leetcode51.n queen
![[latex] production of complex tables: excel2latex and detail adjustment](/img/39/0d448ddf006eda262de3ed75666354.jpg)
[latex] production of complex tables: excel2latex and detail adjustment

JVM family -- monitoring tools
随机推荐
Imperial cms7.5 imitation "D9 download station" software application download website source code
Solve the problems encountered by the laravel framework using mongodb
Baijia forum the founding of the Eastern Han Dynasty
Recent learning fragmentation (14)
MySQL query
MySQL one master multiple slaves + linear replication
Li Chuang EDA learning notes 13: electrical network for drawing schematic diagram
Development of digital collection trading platform development of digital collection platform
Dare to climb here, you're not far from prison, reptile reverse actual combat case
New year's first race, submit bug reward more!
MySQL data query optimization -- data structure of index
Easy to win insert sort
投资深度思考
PHP database connection succeeded, but data cannot be inserted
What are the virtual machine software? What are their respective functions?
2022 registration examination for safety production management personnel of fireworks and firecracker production units and examination skills for safety production management personnel of fireworks an
Osnabrueck University | overview of specific architectures in the field of reinforcement learning
数据库SQL语句汇总,持续更新......
Ningde times and BYD have refuted rumors one after another. Why does someone always want to harm domestic brands?
Class summation, shortest row
