The recent public platform development Project encountered a functional requirement: Generate a specific URL of the QR code, the user scanned the QR code to jump to the URL specified page, and on this page to get the user's OpenID. This function mainly involves two aspects of the technology: generate two-dimensional code, Web page authorization.
1. Generate two-dimensional code:
The simple way to generate QR codes is to use the Phpqrcode package directly (which can be downloaded online).
To get thinkphp support, put the package in the Thinkphp/extend/vendor directory, let it be referenced in the program, and the code is as follows:
Vendor ("Phpqrcode.phpqrcode");
To generate the data for the two-dimensional code
$text = "URL of the page to jump after scanning code";
Error correction level, the higher the error correction level, the larger the image will be generated
L Loadline of level 7% can be modified
Loadline of M level 15% can be corrected
Q-level 25% loadline can be corrected
H-level 30% Loadline can be modified
$level = "L";
The pixels of each black dot in the picture.
$size = "10";
Generate picture The second parameter: whether to save the file as a file, the second parameter is changed to a file name, such as: ' Qrcode.png '
QRCode::p ng ($text, False, $level, $size);
2. Website authorization:
To obtain the user's OpenID, a Web page authorization is required. First the QR code URL is set to:
$text = "Https://open.weixin.qq.com/connect/oauth2/authorize?"
Appid= Public appid&
Redirect_uri= sweep code after the page to jump url&
response_type=code&
scope=snsapi_base&
State=1#wechat_redirect ";
Where AppID is the public number Appid,redirect_uri is to jump after the page Url,response_type designated as code, in exchange for Access_token (to obtain the user's basic information of the credentials), scope here is designated as Snsapi _base, because only need to obtain the user's openid,state can pass the parameter which other developer needs, if can not fill in freely, #wechat_redirect表示直接在中打开页面.
In this way, the user sweeps the QR code and jumps to the specified URL, and passes the parameters over. Then you can get code in the jump page, in exchange for Access_token, because the acquisition of Access_token and also acquired OpenID, so if only to obtain the user ID, to this step has been implemented, the code is as follows:
$appid = "public number AppID";
$secret = "public number Appsecret";
$code = $_get["code"];
$get _token_url = ' https://api.weixin.qq.com/sns/oauth2/access_token?appid= '. $appid. ' &secret= '. $secret. ' &code= '. $code. ' &grant_type=authorization_code ';
$res =file_get_contents ($get _token_url);
$json _obj = Json_decode ($res, true);
$openid = $json _obj[' OpenID ');
$openid is the OpenID of the user who scanned the code.
Web page authorization--sweep QR code to get OpenID