PHP version of the micro-letter implementation of the login authorization instance

Source: Internet
Author: User

User authorization is also a part of the advanced interface, just separate it out, so that the entire micro-letter framework is clear, but we use it first to set the OA2 URL in the micro-letter background, where the URL and tutorial a different. It is a domain name that does not start with http://.
First login to your micro-letter backstage to find the "Developer Center":


Click Modify to fill in our domain name in the following format:

Well, the most basic point of the OA2 requirements, the following we use a Wechatauth class to generate a OA2 URL format, and then from the service number, to the link or menu or text, jump to the micro-letter built-in web to achieve our OpenID or authorized to take user messages!

Example code generation Snsapi_base or Snsapi_userinfo:
$auth = new Wechatauth (Array (
wechatauth::app_id => ' wx32259fc5sd5aac12b ',
Wechatauth::app_secret => ' 7ef73d3c56fcd0d984862ff217d2c648 ',
));
$url = $auth->getloginurl (Array (
' Redirect_uri ' => ' Http://www.demo.com/wp/ken ',
' Scope ' => ' Snsapi_userinfo '//snsapi_base
));
echo $url;

Once executed, we will get the following OA2 URL:

https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx32259fc5d5aac13d&redirect_uri=http%3A%2F% 2fwww.demo.com%2fwp%2fken&response_type=code&scope=snsapi_userinfo&state=state#wechat_redirects

Then we are in the service number of the menu mentioned just now, link good click to go to the micro-trust in the browser, if your scope is Snsapi_userinfo will eject the licensing interface, base will not play the default will return to OpenID:

Well, OA2 is nothing more than let us generate a specific format URL, let us point to the past to take OpenID or user information (whether or not concerned about your service number, as long as the confirmation of authorization), you can use the site micro-letter instances have relevant OA2 application or message to me!
Wechatauth class:

<?php
/**
* Micro-letter OAuth2.0 Licensing Interface
* Class Wechatauth
*/
Class Wechatauth {

Const
JSON = ' json ',
Post = ' Post ',
get = ' get ',
app_id = ' AppID ',
App_secret = ' SECRET ',
Api_url_prefix = ' Https://api.weixin.qq.com/sns ';

Public
$_error_number = 0,
$_error,
$_appid,
$_appsecret;

Protected
$_cache = Array (),
$_options,
$_openid,
$_access_token,
$_refresh_token,
$_timeout = 30;

Static protected
$_instance;

/**
* Single case mode
* @param array $options
* @return Wechatauth
*/
static public Function getinstance (array $options = Array ()) {
if (empty (self::$_instance)) {
Self::$_instance = new Wechatauth ($options);
}

return self::$_instance;
}

/**
* @param array $options {wechatauth::app_id: "", Wechatauth::app_secret: ""}
*/
Public function __construct (array $options = Array ()) {
$this->_options = Array (
' Timeout ' => $this->_timeout,
);
$_options = Array_merge ($this->_options, $options);
$this->_appid = $_options[' APPID '];
$this->_appsecret = $_options[' secret '];
$this->_timeout = $_options[' timeout '];
}

/**
* Submit Request
* @param $url
* @param array $params
* @param string $type webchat_api::P ost| Webchat_api::get
* @return bool|mixed
*/
Public function request ($url, $params = Array (), $type = self::P ost) {
$ch = Curl_init ();
if ($type = = Self::get) {
$url = $url. Http_build_query ($params);
}
Curl_setopt_array ($ch, Array (
Curlopt_url => $url,
Curlopt_timeout => $this->_timeout,
Curlopt_useragent => ' wordpress_wechat_client/0.1. ' Rand (1,6),
Curlopt_header => 0,
Curlopt_followlocation => 1,
Curlopt_returntransfer => 1,
Curlopt_ssl_verifypeer => 0,
Curlopt_sslversion => 3,
Curlopt_verbose => 1,
));
if ($type = = self::P ost) {
curl_setopt ($ch, Curlopt_port, 1);
curl_setopt ($ch, Curlopt_postfields, $params);
}
if ($type = = Self::json) {
The broken interface of the micro-letter does not support Unicode escape characters, which violates the JSON protocol and only turns Unicode back in the JSON character
$data = Preg_replace ('/\\\\u ([a-f0-9]{4})/e ', "json_decode (' \" $0\ "', 1)", Json_encode ($params));
curl_setopt ($ch, Curlopt_postfields, $data);
curl_setopt ($ch, Curlopt_httpheader, Array (' Content-type:application/json '));
}
$res = curl_exec ($ch);
$this->_error_number = Curl_errno ($ch);
$this->_error = Curl_error ($ch);
Curl_close ($ch);

if ($this->_error_number) {
return false;
}
return $this->parseresult ($res);
}

/**
* Processing return results
* @param $res
* @return bool|mixed
*/
protected function Parseresult ($res) {
$res = Json_decode ($res, true);
if (!empty ($res)) {
if (Isset ($res [' Errcode ']) && $res [' Errcode ']) {
$this->_error_number = $res [' Errcode '];
$this->_error = $res [' errmsg '];
return false;
}

return $res;
}

return false;
}

/**
* Get current URL
* @return String
*/
static public Function Getcurrenturl () {
$pageURL = ' http ';
if (Isset ($_server["https"]) && $_server["https"] = = "on") {
$pageURL. = "S";
}
$pageURL. = "://";
if (Isset ($_server[' Server_port ')) && $_server["Server_port"]!= "80") {
$pageURL. = $_server["SERVER_NAME"]. ":" . $_server["Server_port"]. $_server["Request_uri"];
} else {
if (Isset ($_server["SERVER_NAME"]) && isset ($_server["Request_uri"))
$pageURL. = $_server["SERVER_NAME"]. $_server["Request_uri"];
}
return $pageURL;
}

/**
* Get access token
* @param bool $refresh forced flush
* @return bool|mixed
*/
Public Function Getauthaccesstoken ($refresh = False) {
$code = isset ($_get[' code ')? $_get[' Code ']: ';
$state = isset ($_get[' state ')? $_get[' state ']: ';
$cache = $this->cache (' Auth_access_token ');
if ($cache &&! $refresh) {
Return Array (' Access_token ' => $cache, ' code ' => $code, ' state ' => $state);
}
$res = $this->request (self::api_url_prefix. /oauth2/access_token ', Array (
self::app_id => $this->_appid,
Self::app_secret => $this->_appsecret,
' Code ' => $code,
' Grant_type ' => ' Authorization_code ',
), Self::get);
if ($res) {
$this->cache (' Auth_access_token ', $res [' Access_token ']);
$this->cache (' Auth_refresh_token ', $res [' Refresh_token ']);
$this->cache (' Auth_openid ', $res [' OpenID ']);
} else {
if ($this->_error_number = = 42001) {
return $this->refreshaccesstoken ();
}
}
Return Array (' Access_token ' => $res [' Access_token '], ' code ' => $code, ' state ' => $state);
}

/**
* Refresh access token
* @return Mixed
*/
Public Function Refreshaccesstoken () {
$code = isset ($_get[' code ')? $_get[' Code ']: ';
$state = isset ($_get[' state ')? $_get[' state ']: ';
$cache = $this->cache (' Auth_refresh_token ');
if ($cache) {
$this->_refresh_token = $cache;
}

$res = $this->request (self::api_url_prefix. /oauth2/refresh_token ', Array (
self::app_id => $this->_appid,
' Refresh_token ' => $this->_refresh_token,
' Grant_type ' => ' Refresh_token ',
), Self::get);

if ($res) {
$this->cache (' Auth_access_token ', $res [' Access_token ']);
$this->cache (' Auth_refresh_token ', $res [' Refresh_token ']);
$this->cache (' Auth_openid ', $res [' OpenID ']);
}
Return Array (' Access_token ' => $res [' Access_token '], ' code ' => $code, ' state ' => $state);
}

/**
* Get user Information
* @param bool $refresh forced flush
* @return bool|mixed
*/
Public Function GetUserInfo ($refresh = False) {
$this->_access_token = $this->getauthaccesstoken ($refresh);
$cache = $this->cache (' Auth_openid ');
if ($cache) {
$this->_openid = $cache;
}

$res = $this->request (self::api_url_prefix. /userinfo ', Array (
' Access_token ' => $this->_access_token,
' OpenID ' => $this->_openid,
), Self::get);


if ($res) {
return $res;
}

return false;
}

/**
* Obtain the user's authorized address
* @param array $options
* @return String
*/
Public Function Getloginurl ($options = Array ()) {
$_options = Array (
self::app_id => $this->_appid,
' Redirect_uri ' => self::getcurrenturl (),
' Response_type ' => ' code ',
' Scope ' => ' snsapi_base ',//snsapi_base | Snsapi_userinfo
' State ' => ' state ',
);
$params = Array_merge ($_options, $options);

Return ' Https://open.weixin.qq.com/connect/oauth2/authorize? '. Http_build_query ($params). ' #wechat_redirects ';
}

/**
* Cache Interface Session Implementation
* @param $key Cache index key
* @param null $value cache value
* @return bool|mixed
*/
Public Function cache ($key, $value = null) {
if (!session_id ()) {
Session_Start ();
}
if (empty ($value)) {
if (Isset ($_session[$key])) {
return $_session[$key];
}
return false;
}
$_session[$key] = $value;
return false;
}
}

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.