WeChat public account development series-Get WeChat OpenID, public openid

Source: Internet
Author: User
Tags openid

Public Account Development Series-Get OpenID, public openid

You need to use OpenId when interacting with message interfaces during development. The following describes how to obtain OpenID in type 2, receive event push and webpage authorization to obtain basic user information.

1. Obtain OpenId by receiving passive messages (by receiving event push). You can obtain OpenID in the following events.

Follow/cancel follow events

When you follow or remove the public account, the event is pushed to the URL entered by the developer. This allows developers to send welcome messages to users or unbind accounts.

If the server fails to receive the response within five seconds, the connection will be disconnected and the server will initiate a new request. A total of three retries will be made.

We recommend that you use FromUserName + CreateTime for message deduplication.

If the server cannot process and reply within five seconds, it can directly reply to an empty string. The server will not process the request and will not initiate a retry.

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event Type, subscribe and unsubscribe)

Use the Web debugging tool to debug this interface

Scan QR code events with Parameters

When a user scans a QR code with a scene value, the following two events may be pushed:

  1. If the user has not followed the public account, the user can follow the public account, after which the event with the scene value will be pushed to the developer.
  2. If the user has followed the public account, the event with the scene value will be pushed to the developer.

1. If you do not pay attention to it, push the following events

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[subscribe]]></Event><EventKey><![CDATA[qrscene_123123]]></EventKey><Ticket><![CDATA[TICKET]]></Ticket></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event Type, subscribe
EventKey The event KEY value. qrscene _ is the prefix, followed by the parameter value of the QR code.
Ticket Two-dimensional code ticket can be used in exchange for two-dimensional code pictures

2. Event push when the user is concerned

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[SCAN]]></Event><EventKey><![CDATA[SCENE_VALUE]]></EventKey><Ticket><![CDATA[TICKET]]></Ticket></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event Type, SCAN
EventKey Event KEY value, which is a 32-bit unsigned integer, that is, the two-dimensional code scene_id
Ticket Two-dimensional code ticket can be used in exchange for two-dimensional code pictures

Use the Web debugging tool to debug this interface

Report location events

After the user agrees to report the geographic location, each time the user enters the public account Session, the geographical location will be reported at the time of access, or once every 5 seconds after the user enters the session, the public account can be modified on the public platform website. When a location event is reported, the event is pushed to the URL entered by the developer.

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[fromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[LOCATION]]></Event><Latitude>23.137466</Latitude><Longitude>113.352425</Longitude><Precision>119.385040</Precision></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event type, LOCATION
Latitude Geographic location and latitude
Longpolling Geographic longitude
Precision Geographic location accuracy

Use the Web debugging tool to debug this interface

Custom menu events

After you click the custom menu, the click event is pushed to the developer. Note that clicking the menu to bring up the submenu will not generate reports.

Push events when you click the menu to pull messages

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[CLICK]]></Event><EventKey><![CDATA[EVENTKEY]]></EventKey></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event Type, CLICK
EventKey Event KEY value, which corresponds to the KEY value in the custom menu interface


Event push when you click the menu to jump to the link

Example of pushing XML data packets:

<xml><ToUserName><![CDATA[toUser]]></ToUserName><FromUserName><![CDATA[FromUser]]></FromUserName><CreateTime>123456789</CreateTime><MsgType><![CDATA[event]]></MsgType><Event><![CDATA[VIEW]]></Event><EventKey><![CDATA[www.qq.com]]></EventKey></xml>

Parameter description:

Parameters Description
ToUserName DeveloperNo.
FromUserName Sender account (one OpenID)
CreateTime Message creation time (integer)
MsgType Message Type, event
Event Event Type, VIEW
EventKey Event KEY value, set the jump URL

Use the Web debugging tool to debug this interface

The above information is excerpted from the "receive event push" section on the public platform. Click to view original help documentation-receive event push


2. Obtain OpenID through third-party webpage authorization and use third-party webpage authorization (OAuth2.0 authorized login)

If a user accesses a third-party webpage with a public account in the middle (excluding the Web), the public account developer can use this interface to obtain the basic information of the current user (including nickname, gender, city, and country ). Using user information, you can achieve user experience optimization, user source statistics, account binding, user identity authentication, and other functions.Note: "The interface for obtaining basic user information is used to obtain basic user information based on the user's OpenID when a message is generated between the user and the public account, and the webpage authorization method is used to obtain basic user information, message interaction is not required, but the user can access the webpage of the public account. The page requesting user authorization is displayed. After user authorization, you can obtain the basic information (this process does not even require users to pay attention to the public account .)"

OAuth2.0 authorized logon allows users to log on to a third-party application or website using their identities. After authorized users log on to a third-party application already connected to OAuth2.0, the third party can obtain the user's interface call credential (access_token ), access_token can be used to call the open platform authorization Link Interface, so as to obtain basic user open information and help users implement basic open functions.

Before requesting authorization from a user's webpage through a public account, the developer needs to configure the authorization callback domain name on the my service page of the public platform website. Please note that do not add http ://

Instructions on configuring the authorization callback Domain Name:

Authorization callback domain name configuration specification for the full domain name, such as the need for web page authorization Domain Name: www.qq.com, after the configuration of this domain name under the page http://www.qq.com/music.html, http://www.qq.com/login.html can be OAuth2.0 authentication. But http://pay.qq.com, http://music.qq.com, http://qq.com cannot perform OAuth2.0 authentication.

Specifically, the webpage authorization process is divided into four steps:

  1. Instruct the user to go to the authorization page to agree to the authorization and obtain the code
  2. Use code in exchange for webpage authorization access_token (different from access_token in Basic Support)
  3. If necessary, developers can refresh the webpage to authorize access_token to avoid expiration.
  4. Use the access_token and openid authorized on the webpage to obtain basic user information.
Directory [hide]
  • 1 Step 1: The user agrees to the authorization and obtains the code
  • 2 Step 2: Exchange code for webpage authorization access_token
  • 3 Step 3: refresh access_token (if needed)
  • 4. Step 4: Pull user information (the scope must be snsapi_userinfo)
  • 5 Appendix: Check whether the authorization credential (access_token) is valid
Step 1: The user agrees to the authorization and obtains the code

To ensure that the public account has the permission to authorize the scope (scope parameter) (after the service number obtains the advanced interface, the snsapi_base and snsapi_userinfo in the scope parameter are included by default), the publisher is guided to open the following page:

Https://open.weixin.qq.com/connect/oauth2/authorize? Appid = APPID & redirect_uri = REDIRECT_URI & response_type = code & scope = SCOPE & state = STATE # wechat_redirect, whether the permission of the scope parameter is granted.
Reference Link (please open this link on the client) Scope is snsapi_baseHttps://open.weixin.qq.com/connect/oauth2/authorize? Appid = wx520c15f415810387 & redirect_uri = http % 3A % 2F % 2Fchong.qq.com % 2 Fphp % 2Findex. php % 3Fd % 3D % 26c % 3 DwxAdapter % 26 m % 3 DmobileDeal % 26 showwxpaytitle % 3D1% 26vb2ctag % response & response_type = code & scope = snsapi_base & state = 123 # wechat_redirectScope is snsapi_userinfoHttps://open.weixin.qq.com/connect/oauth2/authorize? Appid = Response & redirect_uri = http % 3A % 2F % 2Fnba.bluewebgame.com % 2Foauth_response.php & response_type = code & scope = snsapi_userinfo & state = STATE # wechat_redirect

Parameter description

Parameters Required? Description
Appid Yes Unique public ID
Redirect_uri Yes URL of the redirection callback link after authorization. Use urlencode to process the link.
Response_type Yes Return type. Enter the code
Scope Yes Application Authorization scope, snsapi_base (the authorization page is not displayed, Jump directly, only the user's openid can be obtained), snsapi_userinfo (the authorization page is displayed, and the nickname, gender, and location can be obtained through openid. And,Even if you do not pay attention to it, you can obtain the user information as long as the user is authorized.)
State No With the state parameter, the developer can fill in the parameter value of the a-zA-Z0-9
# Wechat_redirect Yes This parameter must be included when you open the page directly or perform page 302 redirection.

Authorization page when scope is equal to snsapi_userinfo:

After the user agrees to authorize

If the user agrees to the authorization, the page will jump to redirect_uri /? Code = CODE & state = STATE. If authorization is disabled, the redirection will not contain the code parameter, but the state parameter redirect_uri? State = STATE

Code Description: the code in exchange for the access_token will be different for each user authorization. The code can only be used once and will automatically expire if it is not used for 5 minutes.
Step 2: Exchange code for webpage authorization access_token

First of all, please note that the webpage authorization access_token in exchange for code here is different from the access_token in the basic support. The public account can be used to obtain the webpage authorization access_token through the following interface. If the scope of webpage authorization is snsapi_base, The openid and snsapi_base webpage authorization processes are also obtained when the webpage authorization access_token is obtained in this step.

Request Method

After getting code, request the following link to get access_token: https://api.weixin.qq.com/sns/oauth2/access_token? Appid = APPID & secret = SECRET & code = CODE & grant_type = authorization_code

Parameter description

Parameters Required? Description
Appid Yes Unique public ID
Secret Yes Appsecret of Public Account
Code Yes Enter the code parameter obtained in step 1.
Grant_type Yes Enter authorization_code

Return description

The returned JSON data packet is as follows:

{   "access_token":"ACCESS_TOKEN",   "expires_in":7200,   "refresh_token":"REFRESH_TOKEN",   "openid":"OPENID",   "scope":"SCOPE"}
Parameters Description
Access_token Webpage authorization interface call credential. Note: This access_token is different from the access_token supported by the Basic.
Expires_in Access_token interface call credential timeout time, in seconds)
Refresh_token User refresh access_token
Openid Unique User ID. Note that when you do not pay attention to the public account, a unique OpenID is generated when you access the webpage of the public account.
Scope User-authorized scopes, separated by commas (,)


When an error occurs, the JSON data packet is returned as follows (the sample Code is invalid ):

{"errcode":40029,"errmsg":"invalid code"}

Global return code Description

Step 3: refresh access_token (if needed)

Because access_token has a short validity period, you can use refresh_token to refresh when the access_token times out. refresh_token has a long validity period (7 days, 30 days, 60 days, and 90 days ), if the refresh_token is invalid, you must re-authorize it.

Request Method

After obtaining the refresh_token in step 2, request the following link to get access_token: https://api.weixin.qq.com/sns/oauth2/refresh_token? Appid = APPID & grant_type = refresh_token & refresh_token = REFRESH_TOKEN
Parameters Required? Description
Appid Yes Unique public ID
Grant_type Yes Enter refresh_token
Refresh_token Yes Enter the refresh_token parameter obtained through access_token.

Return description

The returned JSON data packet is as follows:

{   "access_token":"ACCESS_TOKEN",   "expires_in":7200,   "refresh_token":"REFRESH_TOKEN",   "openid":"OPENID",   "scope":"SCOPE"}
Parameters Description
Access_token Webpage authorization interface call credential. Note: This access_token is different from the access_token supported by the Basic.
Expires_in Access_token interface call credential timeout time, in seconds)
Refresh_token User refresh access_token
Openid Unique User ID
Scope User-authorized scopes, separated by commas (,)


When an error occurs, the JSON data packet is returned as follows (the sample Code is invalid ):

{"errcode":40029,"errmsg":"invalid code"}

Global return code Description

Step 4: Pull user information (scope must be snsapi_userinfo)

If the webpage Authorization scope is snsapi_userinfo, the developer can pull user information through access_token and openid.

Request Method

Http: GET (Please use https protocol) https://api.weixin.qq.com/sns/userinfo? Access_token = ACCESS_TOKEN & openid = OPENID & lang = zh_CN

Parameter description

Parameters Description
Access_token Webpage authorization interface call credential. Note: This access_token is different from the access_token supported by the Basic.
Openid Unique User ID
Lang Return to the Chinese language version, zh_CN simplified, zh_TW traditional, en english

Return description

The returned JSON data packet is as follows:

{   "openid":" OPENID",   " nickname": NICKNAME,   "sex":"1",   "province":"PROVINCE"   "city":"CITY",   "country":"COUNTRY",    "headimgurl":    "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/46", "privilege":["PRIVILEGE1""PRIVILEGE2"    ]}
Parameters Description
Openid Unique User ID
Nickname User nickname
Sex Gender of the user. If the value is 1, the user is male. If the value is 2, the user is female. If the value is 0, the user is unknown.
Province Province of the user's personal data
City City for normal user Personal Data
Country Country, such as CN
Headimgurl User profile picture. The last value indicates the size of the square profile picture (optional values include 0, 46, 64, 96, and 132, and 0 indicates the size of the 640*640 square profile picture). This parameter is blank when the user does not have the profile picture.
Privilege User Privilege information, which is a json array. For example, the Waka user is (chinaunicom)


If an error occurs, a JSON packet is returned as follows (the openid is invalid in this example ):

{"errcode":40003,"errmsg":" invalid openid "}

Global return code Description

Appendix: Check whether the authorization credential (access_token) is valid

Request Method

Http: GET (Please use https protocol) https://api.weixin.qq.com/sns/auth? Access_token = ACCESS_TOKEN & openid = OPENID

Parameter description

Parameters Description
Access_token Webpage authorization interface call credential. Note: This access_token is different from the access_token supported by the Basic.
Openid Unique User ID

Return description

Correct Json return results:

{ "errcode":0,"errmsg":"ok"}

Json return example in case of an error:

{ "errcode":40003,"errmsg":"invalid openid"}
The above information is excerpted from the Section for authorizing users to obtain basic information on the webpage of the public platform. Click to view the original help documentation-webpage authorization to obtain basic user information



Ask C # How to get the public account to get the openid of the publisher

Each time a user sends a message to you or clicks the menu, there is a FromUserName. This is the OPENID, which can be obtained after parsing the sent information.
Public static string HandleXML (string postStr) {XmlDocument xmldoc = new XmlDocument (); xmldoc. load (new System. IO. memoryStream (System. text. encoding. getEncoding ("GB2312 "). getBytes (postStr); XmlNode FromUserName = xmldoc. selectSingleNode ("/xml/FromUserName"); string str = FromUserName. innerText ;}

How to obtain openid

Tools/Raw Materials
Public platform service No.
Computer
Method/step
1. To obtain the openid, you must use OAuth2.0 to complete web page authorization. After OAuth2.0 completes web page authorization, you can use the authorization page after the user permission is granted, obtain the user's openid

2. How can I use OAuth2.0 webpage authorization? You must first apply for advanced interface functions

3. After the application is approved, create an authorization page to guide the user to obtain the openid!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.