Introduction to WeChat login for website applications developed by WeChat open platform

高洛峰
Release: 2017-03-09 15:06:53
Original
2569 people have browsed it

In this WeChat public platform development tutorial, we will introduce how to use the WeChat open platform interface to implement the WeChat QR code login function.

Preparation

The website application WeChat login is a WeChat OAuth2.0 authorized login system built based on the OAuth2.0 protocol standard.

Before performing WeChat OAuth2. Before performing WeChat OAuth2.0 authorized login and access, register a developer account on the WeChat open platform, have an approved website application, and obtain the corresponding AppID and AppSecret. After applying for WeChat login and passing the review, you can start the access process.

 微信开放平台开发之网站应用微信登录介绍

Authorization process description

WeChat OAuth2.0 authorized login allows WeChat users to use WeChat identities to securely log in to third-party applications or websites. After the WeChat user has authorized login After accessing the third-party application of WeChat OAuth2.0, the third party can obtain the user's interface call credential (access_token). Through the access_token, the WeChat open platform authorization relationship interface can be called, thereby obtaining the basic open information of WeChat users and helping users. Implement basic open functions, etc.

WeChat OAuth2.0 authorized login currently supports authorization_code mode, which is suitable for application authorization with server side. The overall process of this model is:

  1. 1. A third party initiates a WeChat authorized login request. After the WeChat user allows authorization of the third-party application, WeChat will launch the application or restart it. Direct to the third-party website and bring the authorization temporary ticket code parameter;

  2. 2. Add AppID and AppSecret through the code parameter, and exchange for access_token through the API;

  3. 3. Call the interface through access_token to obtain the user's basic data resources or help the user implement basic operations.

Get access_token sequence diagram:

 微信开放平台开发之网站应用微信登录介绍

Step 1: Request CODE

Log in to Fangbei Studio WeChat login website application

http://weixin.fangbei.org/login.php
Copy after login

After opening, the application will generate state parameters, jump to the following link: (please log in before Note that the corresponding web page authorization scope (scope=snsapi_login) has been obtained)

https://open.weixin.qq.com/connect/qrconnect?appid=wxed782be999f86e0e&redirect_uri=http%3A%2F%2Fweixin.fangbei.org%2Flogin.php&response_type=code&scope=snsapi_login&state=123#wechat_redirect
Copy after login

If it prompts "The link cannot be accessed", please check whether the parameters are filled in Errors, such as the domain name of redirect_uri is inconsistent with the authorized domain name filled in during review or the scope is not snsapi_login.

Parameter Description
Parameter Is it necessary Description
appid is the application unique identifier
redirect_uri is Redirect address needs to be UrlEncode
response_type is fill in code
scope is the application authorization scope, with multiple scopes separated by commas (,), web applications currently only need to fill in snsapi_login
state No Used to maintain the status of the request and callback, and bring it back to the third party intact after the request is authorized. This parameter can be used to prevent CSRF attacks (cross-site request forgery attacks). It is recommended that third parties bring this parameter. It can be set to a simple random number plus session for verification
返回说明

此时,PC网站上显示如下二维码

 微信开放平台开发之网站应用微信登录介绍

 

用户允许授权后,将会重定向到redirect_uri的网址上,并且带上code和state参数


http://weixin.fangbei.org/login.php?code=0317a2c31ccd5eadf1a7a8fffd4a7dbf&state=123
Copy after login

为了满足网站更定制化的需求,我们还提供了第二种获取code的方式,支持网站将微信登录二维码内嵌到自己页面中,用户使用微信扫码授权后通过JS将code返回给网站。

JS微信登录主要用途:网站希望用户在网站内就能完成登录,无需跳转到微信域下登录后再返回,提升微信登录的流畅性与成功率。 网站内嵌二维码微信登录JS实现办法:

步骤1:在页面中先引入如下JS文件(支持https):

<script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
Copy after login

步骤2:在需要使用微信登录的地方实例以下JS对象:


        <script>
            var obj = new WxLogin({
              id: "login_container",
              appid: "wxed782be999f86e0e",
              scope: "snsapi_login",
              redirect_uri: encodeURIComponent("http://" + window.location.host + "/login.php"),
              state: Math.ceil(Math.random()*1000),
              style: "black",
              href: ""});        </script>
Copy after login

参数说明

参数 是否必须 说明
id 第三方页面显示二维码的容器id
appid 应用唯一标识,在微信开放平台提交应用审核通过后获得
scope 应用授权作用域,拥有多个作用域用逗号(,)分隔,网页应用目前仅填写snsapi_login即可
redirect_uri 重定向地址,需要进行UrlEncode
state 用于保持请求和回调的状态,授权请求后原样带回给第三方。该参数可用于防止csrf攻击(跨站请求伪造攻击),建议第三方带上该参数,可设置为简单的随机数加session进行校验
style 提供"black"、"white"可选,默认为黑色文字描述。详见文档底部FAQ
href 自定义样式链接,第三方可根据实际需求覆盖默认样式。详见文档底部FAQ

完整代码如下


    
        
    
    
        
        <script src="http://res.wx.qq.com/connect/zh_CN/htmledition/js/wxLogin.js"></script>
        <script>
            var obj = new WxLogin({
              id: "login_container",
              appid: "wxed782be999f86e0e",
              scope: "snsapi_login",
              redirect_uri: encodeURIComponent("http://" + window.location.host + "/login.php"),
              state: Math.ceil(Math.random()*1000),
              style: "black",
              href: ""});        </script>
    
Copy after login

页面显示效果如下 

 微信开放平台开发之网站应用微信登录介绍

 

第二步:通过code获取access_token

通过code获取access_token


https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code

参数说明
参数 是否必须 说明
appid 应用唯一标识,在微信开放平台提交应用审核通过后获得
secret 应用密钥AppSecret,在微信开放平台提交应用审核通过后获得
code 填写第一步获取的code参数
grant_type 填authorization_code
返回说明

正确的返回:


{    "access_token": "OezXcEiiBSKSxW0eoylIeFy2HFC4Bxv9JvC0Sgj4Px4_8TX1ci3jF_QP_6sWjvx2rCAUjXEP1_9edZdJLf3MIwii2N8cnTooDfx7nYpFRmOSZyq4gb2FNdWJr__KUqPtcfVUvg6XBTucZZ4zH6v8VQ",    "expires_in": 7200,    "refresh_token": "OezXcEiiBSKSxW0eoylIeFy2HFC4Bxv9JvC0Sgj4Px4_8TX1ci3jF_QP_6sWjvx2lW60INlf6AK1q21rW7mJyc5yG3GZ9p1psANOKTi2EZUQXA6CnwSXxDQlJ3421tEOvCWIrJhkA8oTqjsLKYG-yg",    "openid": "oJekJs2faTQ47FGjDOEIyOPMN97s",    "scope": "snsapi_login",    "unionid": "o4wcnw02YjFUYglZxV0LwcBkVF6Y"}
Copy after login

参数说明

参数 说明
access_token 接口调用凭证
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 授权用户唯一标识
scope 用户授权的作用域,使用逗号(,)分隔
 unionid 当且仅当该网站应用已获得该用户的userinfo授权时,才会出现该字段。

错误返回样例:


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

刷新access_token有效期

access_token是调用授权关系接口的调用凭证,由于access_token有效期(目前为2个小时)较短,当access_token超时后,可以使用refresh_token进行刷新,access_token刷新结果有两种:

  1. 1. 若access_token已超时,那么进行refresh_token会获取一个新的access_token,新的超时时间;

  2. 2. 若access_token未超时,那么进行refresh_token不会改变access_token,但超时时间会刷新,相当于续期access_token。

refresh_token拥有较长的有效期(30天),当refresh_token失效的后,需要用户重新授权。

请求方法

获取第一步的code后,请求以下链接进行refresh_token:

https://api.weixin.qq.com/sns/oauth2/refresh_token?appid=APPID&grant_type=refresh_token&refresh_token=REFRESH_TOKEN

参数说明
参数 是否必须 说明
appid 应用唯一标识
grant_type 填refresh_token
refresh_token 填写通过access_token获取到的refresh_token参数
返回说明

正确的返回:


{ <br>"access_token":"ACCESS_TOKEN", <br>"expires_in":7200, <br>"refresh_token":"REFRESH_TOKEN", <br>"openid":"OPENID", <br>"scope":"SCOPE" <br>}

参数 说明
access_token 接口调用凭证
expires_in access_token接口调用凭证超时时间,单位(秒)
refresh_token 用户刷新access_token
openid 授权用户唯一标识
scope 用户授权的作用域,使用逗号(,)分隔

Error return example:


##{"errcode":40030,"errmsg":"invalid refresh_token"}

Note:


1. Appsecret is the key used by the application interface. If leaked, it may lead to application data leakage, application user data leakage and other high-risk consequences; it is stored in the client terminal, it is very likely to be maliciously stolen (such as decompiling to obtain Appsecret);

2. access_token is the credential for users to authorize third-party applications to initiate interface calls (equivalent to user login status), stored on the client, and may Behaviors such as user data leakage caused by malicious acquisition of access_token and user WeChat-related interface functions being maliciously initiated;

3. refresh_token is a long-term credential for users to authorize third-party applications. It is only used to refresh access_token, but it is leaked. The latter is equivalent to access_token leakage, the risk is the same as above.

It is recommended that the secret and user data (such as access_token) be placed on the App cloud server, and the cloud transfer interface calls the request.

Step 3: Call the interface through access_token
After obtaining the access_token, make the interface call with the following prerequisites:

  1. 1. The access_token is valid and has not expired;

  2. 2. The WeChat user has authorized the corresponding interface scope (scope) of the third-party application account.

For interface scope (scope), the interfaces that can be called are the following:

Authorization function Domain(scope)InterfaceInterface Description##snsapi_base/sns/oauth2/refresh_token/sns/authsnsapi_userinfo

其中snsapi_base属于基础接口,若应用已拥有其它scope权限,则默认拥有snsapi_base的权限。使用snsapi_base可以让移动端网页授权绕过跳转授权登录页请求用户授权的动作,直接跳转第三方网页带上授权临时票据(code),但会使得用户已授权作用域(scope)仅为snsapi_base,从而导致无法获取到需要用户授权才允许获得的数据和基础功能。

接口调用方法可查阅《微信授权关系接口调用指南》

 

下面是获取用户个人信息,并dump出来

array(10) {
  ["openid"]=>
  string(28) "oJekJs2faTQ47FGjDOEIyOPMN97s"
  ["nickname"]=>
  string(15) "方倍工作室"
  ["sex"]=>
  int(1)
  ["language"]=>
  string(5) "zh_CN"
  ["city"]=>
  string(6) "海淀"
  ["province"]=>
  string(6) "北京"
  ["country"]=>
  string(6) "中国"
  ["headimgurl"]=>
  string(139) "http://wx.qlogo.cn/mmopen/Q3auHgzwzM7zdkiaZFdM5qrwk1iaEESVjfhWVHNg22teOnfKSPpKDE0l2yfQm1hM9AeT8pO1BKElntEBZ7DxibzdteBp3H3yXESwPYUkhibNObs/0"
  ["privilege"]=>
  array(0) {
  }
  ["unionid"]=>
  string(28) "o4wcnw02YjFUYglZxV0LwcBkVF6Y"}
Copy after login

 

核心代码如下

 微信开放平台开发之网站应用微信登录介绍

 

F.A.Q
1. 什么是授权临时票据(code)?

答:第三方通过code进行获取access_token的时候需要用到,code的超时时间为10分钟,一个code只能成功换取一次access_token即失效。code的临时性和一次保障了微信授权登录的安全性。第三方可通过使用https和state参数,进一步加强自身授权登录的安全性。

2. 什么是授权作用域(scope)?

答:授权作用域(scope)代表用户授权给第三方的接口权限,第三方应用需要向微信开放平台申请使用相应scope的权限后,使用文档所述方式让用户进行授权,经过用户授权,获取到相应access_token后方可对接口进行调用。

3. 网站内嵌二维码微信登录JS代码中style字段作用?

答:第三方页面颜色风格可能为浅色调或者深色调,若第三方页面为浅色背景,style字段应提供"black"值(或者不提供,black为默认值),则对应的微信登录文字样式为黑色。相关效果如下:

 微信开放平台开发之网站应用微信登录介绍  微信开放平台开发之网站应用微信登录介绍

若提供"white"值,则对应的文字描述将显示为白色,适合深色背景。相关效果如下:

 微信开放平台开发之网站应用微信登录介绍  微信开放平台开发之网站应用微信登录介绍

4.网站内嵌二维码微信登录JS代码中href字段作用?

答:如果第三方觉得微信团队提供的默认样式与自己的页面样式不匹配,可以自己提供样式文件来覆盖默认样式。举个例子,如第三方觉得默认二维码过大,可以提供相关css样式文件,并把链接地址填入href字段


.impowerBox .qrcode {width: 200px;}<br>.impowerBox .title {display: none;}<br>.impowerBox .info {width: 200px;}<br>.status_icon {display:none}<br>.impowerBox .status {text-align: center;} <br>

相关效果如下:

 微信开放平台开发之网站应用微信登录介绍  微信开放平台开发之网站应用微信登录介绍

 

 

/sns/oauth2/access_token Exchange access_token, refresh_token and authorized scope through code
Refresh or renew access_token usage
Check access_token validity
/sns/userinfo Get user personal information

The above is the detailed content of Introduction to WeChat login for website applications developed by WeChat open platform. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!