search
HomeWeChat AppletWeChat DevelopmentWeChat official account payment (1) How to obtain user openId

1. Obtain the apikey, appsecret and merchant number

Register the public account and merchant number

2. Obtain the user’s OpenId

1. Set the [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, and the callback page needs to be here domain name to ensure safety and reliability. The callback page domain name does not support IP addresses.

WeChat official account payment (1) How to obtain user openId

## 2. User agrees to authorize


I wrote this URL under the WeChat menu, and when entering this page, the user will agree. 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: Does not pop up the authorization page, jumps directly, and can only obtain the user openid


snsapi_userinfo : The authorization page pops up, and you can get the nickname, gender, and location through openid


State: Parameters after redirection


2. A code will be generated after the user agrees , only valid for minutes.

String code = request.getParameter("code")

3. Code for openId

/**
 * 常量类
 * @author rory.wu
 *
 */
public class Constants {
 // 第三方用户唯一凭证
 public static String appid = "";
 // 第三方用户唯一凭证密钥
 public static String appsecret = "";
 //商户ID
 public static String mch_id="";
 //获取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";
}
/**
 * 通用工具类
 * @author rory.wu
 * @version .
 * @since 年月日
 */
 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, outputStr);
  jsonObject = JSONObject.fromObject(buffer.toString());
  } catch (ConnectException ce) {
  log.error("连接超时:"+ce.getMessage());
  } catch (Exception e) {
  log.error("https请求异常:"+e.getMessage());
  }
  return jsonObject;
 }
  
 private static StringBuffer httpsRequest(String requestUrl, String requestMethod, String output)
  throws NoSuchAlgorithmException, NoSuchProviderException, KeyManagementException, MalformedURLException,
  IOException, ProtocolException, UnsupportedEncodingException {
  URL url = new URL(requestUrl);
  HttpsURLConnection connection = (HttpsURLConnection) url.openConnection();
  connection.setDoOutput(true);
  connection.setDoInput(true);
  connection.setUseCaches(false);
  connection.setRequestMethod(requestMethod);
  if (null != output) {
  OutputStream outputStream = connection.getOutputStream();
  outputStream.write(output.getBytes("UTF-"));
  outputStream.close();
  }
  // 从输入流读取返回内容
  InputStream inputStream = connection.getInputStream();
  InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "utf-");
  BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
  String str = null;
  StringBuffer buffer = new StringBuffer();
  while ((str = bufferedReader.readLine()) != null) {
  buffer.append(str);
  }
  bufferedReader.close();
  inputStreamReader.close();
  inputStream.close();
  inputStream = null;
  connection.disconnect();
  return buffer;
 } }
 
   /**
 * 获取用户的openId,并放入session
 * @param code 微信返回的code
 */
 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_url, "POST", null);
  log.info("jsonObject:"+jsonObject);
  Object errorCode = jsonObject.get("errcode");
  if(errorCode != null) {
  log.info("code不合法");
  }else{
  String openId = jsonObject.getString("openid");
  log.info("openId:"+openId);
  session.put("openId", openId);
  }
 }
oauth_url返回的格式是:
  {
   "access_token":"ACCESS_TOKEN",
   "expires_in":,
 "refresh_token":"REFRESH_TOKEN",
 "openid":"OPENID", "scope":"SCOPE",
 "unionid": "o_bmasdasdsad_sgVthMZOPfL"
 }
Code无效时:
  {
   "errcode":
   ,"errmsg":"invalid code"
 }

The above content is from Script House The editor will share with you how to obtain user openId for WeChat public account payment (1). I hope you like it.

For more WeChat public account payment (1) How to obtain user openId related articles, please pay attention to the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version