1. Obtain apikey, appsecret and merchant number
Register a public account and a merchant account
2. Get the user's OpenId
1. Set [Authorization callback page domain name]
Official explanation: After the user agrees to authorize the official account on the web authorization page, WeChat will pass the authorization data to a callback page. The callback page needs to be under this domain name to ensure safety and reliability. The callback page domain name does not support IP addresses.
2. User agrees to authorization
I wrote this url under the WeChat menu and asked the user to agree when entering this page. Note: It seems to be authorized silently, the user does not know
1.url:
https://open.weixin.qq.com/connect/oauth/authorize?appid=appid&redirect_uri=url&response_type=code&scope=snsapi_userinfo&state= park#wechat_redirect
Parameters: appid: the unique identifier of the official account
redirect_uri: The redirected url is the page to be redirected after authorization
scope: Application authorization scope
snsapi_base: No authorization page pops up, jumps directly, can only obtain the user openid
snsapi_userinfo: The authorization page pops up, you can get the nickname, gender, and location through openid
state: parameters with redirection
2. After the user agrees, a code will be generated, with only a valid period of minutes.
String code = request.getParameter("code")3. Change code to openId
/** * Constant class* @author rory.wu * */public class Constants { // third-party user's unique credentials public static String appid = ""; // third-party user's unique credentials key public static String appsecre t = "" ; //Merchant ID public static String mch_id=""; //Get openId public static String oauth_url = "https://api.weixin.qq.com/sns/oauth/access_token?appid =APPID&secret=SECRET&code=CODE&grant_type=authorization_code ";} /** * General tool class* @author rory.wu * @version . * @since Year, Month, Day*/ public class CommonUtil { private static Logger log = Logger.getLogger(CommonUtil.class); public static JSONObject httpsRequestToJsonObject(String requestUrl , String requestMethod, String outputStr) { JSONObject jsonObject = null; try { StringBuffer buffer = httpsRequest(requestUrl, requestMethod, outputSt r); jsonObject = JSONObject.fromObject(buffer.toString()); } catch (ConnectException ce) { log.error ("Connection timeout: "+ce.getMessage()); } catch (Exception e) { log.error("https request exception: "+e.getMessage()); } return jsonObject; } private static StringB uffer httpsRequest(String requestUrl, String requestMethod, String output) throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLEx ception, IOException, ProtocolException, UnsupportedEncodingException { URL url = new URL(requestUrl); HttpsURLConnection connection = (HttpsU RLConnection) url.openConnection(); connection.setDoOutput(true) ; connection.setDoInput(true); connection.setUseCaches(false); connection.setRequestMethod(requestMethod); if (null != output) { OutputStre am outputStream = connection.getOutputStream(); outputStream.write(output.getBytes("UTF- ")); outputStream.close(); } //Return content from input stream InputStream inputStream = connection.getInputStream(); InputStreamReader inputStreamReader = new InputStreamRe ader(inputStream, "utf-"); BufferedReader bufferedReader = new BufferedReader(inputStreamReader ); String str = null; StringBuffer buffer = new StringBuffer(); while ((str = bufferedReader.readLine()) != null) { buffer.append(str); } bufferedRea der.close(); inputStreamReader.close() ; inputStream.close(); inputStream = null; connection.disconnect(); return buffer; } } /** * Get the user's openId and put the session * @param code The code returned by WeChat */ private void setOpenId(String code) { session.put("code", code); String oauth_url = Constants.oauth_url.replace("APPID", Constants.appid).replace("SECRET", Constants.appsecret ).replace("CODE", String .valueOf(session.get("code"))); log.info("oauth_url:"+oauth_url); JSONObject jsonObject = CommonUtil.httpsRequestToJsonObject(oauth_ur l, "POST", null); log.info("jsonObject:" +jsonObject); Object errorCode = jsonObject.get("errcode"); if(errorCode != null) { log.info("code is illegal"); }else{ String openId = jsonObje ct.getString("openid"); log.info("openId:"+openId); session.put("openId", openId); } }oauth_url returns the format: { "access_token":"ACCESS_TOKEN", "expires_in":, "refresh _token":" REFRESH_TOKEN", "openid":"OPENID", "scope":"SCOPE", "unionid": "o_bmasdasdsad_sgVthMZOPfL" }Code is invalid: { "errcode": ,"errmsg":"invalid co de" }The above content is the WeChat public account payment shared by the editor of Wulin.com (I) How to obtain user openId? I hope you like it.