天天看點

微信開發4——PHP實作PC掃碼授權登陸擷取使用者資訊

首先須要申請,必須企業,個體工商戶,媒體等,微信開放平台申請位址 https://open.weixin.qq.com/,要交300多的費用才能開通

1,編寫入口:微信開放平台的掃碼登陸開放的接口可以自動生成PC掃碼頁面,你得到了官方通過稽核的appid和appsecret後,先構造一個掃碼網址入口(這裡以"一号店"的掃碼登陸頁面為例子)

https://open.weixin.qq.com/connect/qrconnect?appid=wxbdc5610cc59c1631&redirect_uri=https%3A%2F%2Fpassport.yhd.com%2Fwechat%2Fcallback.do&response_type=code&scope=snsapi_login&state=3d6be0a4035d839573b04816624a415e#wechat_redirect

通路後

微信開發4——PHP實作PC掃碼授權登陸擷取使用者資訊

掃碼後手機端效果

微信開發4——PHP實作PC掃碼授權登陸擷取使用者資訊
微信開發4——PHP實作PC掃碼授權登陸擷取使用者資訊

入口代碼如下:

<?php
//-------配置
$AppID = 'wxbdc5610cc59c1631';
$AppSecret = 'd4624c36333337afxxxxxxxxxxxxxx';
$callback  =  'https://passport.yhd.com/wechat/callback.php'; //回調位址
//微信登入 login.php
session_start();
//-------生成唯一随機串防CSRF攻擊
$state  = md5(uniqid(rand(),TRUE));
$_SESSION["wx_state"]    =   $state; //存到SESSION
$callback = urlencode($callback);
$wxurl = "https://open.weixin.qq.com/connect/qrconnect?appid=".$AppID."&redirect_uri={$callback}&response_type=code&scope=snsapi_login&state={$state}#wechat_redirect";
header("Location: $wxurl");
?>
           

回調檔案callback.php

<?php
//驗證CSRF攻擊
if($_GET['state']!=$_SESSION["wx_state"]){
      exit("5001");
}
$AppID = 'wx33333333334d4';
$AppSecret = 'd4624c363333330547af5443d';
$url='https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$AppID.'&secret='.$AppSecret.'&code='.$_GET['code'].'&grant_type=authorization_code';
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json =  curl_exec($ch);
curl_close($ch);
$arr=json_decode($json,1);
//得到 access_token 與 openid
print_r($arr);    
$url='https://api.weixin.qq.com/sns/userinfo?access_token='.$arr['access_token'].'&openid='.$arr['openid'].'&;
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
curl_setopt($ch, CURLOPT_URL, $url);
$json =  curl_exec($ch);
curl_close($ch);
$arr=json_decode($json,1);
得到 使用者資料
print_r($arr);   
?>
           

PC端最終效果如下:

微信開發4——PHP實作PC掃碼授權登陸擷取使用者資訊

如有問題,請咨詢我的qq:1290851757,備注:csdn部落格問問題的

繼續閱讀