public function getuserinfo(){
header("Content-type:text/html;charset=utf-8");
ini_set(`date.timezone`, `Asia/Shanghai`);
//引入封裝的類
// import(`Common.Lib.WxPayPubHelper.WxPayPubHelper`);
//使用jsapi介面
//$jsApi = new JsApi_pub();
/* 通過code獲得openid*/
if (!isset($_GET[`code`])) {
//觸發微信返回code碼
$url = $this->createOauthUrlForCode("http://" . $_SERVER[`HTTP_HOST`] . "/Web/Index/index.html");
header("Location: $url");
} else {
//獲取code碼,以獲取openid
$code = I(`get.code`);
if (!empty($code)) {
$this->setCode($code);
$result_wechat = $this->getWxInfomation();
if ($result_wechat) {
if (!M(`web_user`)->where(array(`openid` => $result_wechat[`openid`]))->find())
M(`web_user`)->add($result_wechat);
cookie(`openid`, $result_wechat[`openid`]);
cookie(`nickname`, $result_wechat[`nickname`]);
cookie(`wechatinfo`, $result_wechat);
}
}
}
}
***
> //其實需要一個包,但是我不知道怎麼傳檔案,我只能複製一些能用的函式了
/**
* 作用:生成可以獲得code的url
*/
function createOauthUrlForCode($redirectUrl)
{
$urlObj["appid"] = WxPayConf_pub::APPID;
$urlObj["redirect_uri"] = "$redirectUrl";
$urlObj["response_type"] = "code";
$urlObj["scope"] = "snsapi_userinfo";
$urlObj["state"] = "STATE" . "#wechat_redirect";
$bizString = $this->formatBizQueryParaMap($urlObj, false);
return "https://open.weixin.qq.com/connect/oauth2/authorize?" . $bizString;
}
/**
* 作用:格式化引數,簽名過程需要使用
*/
function formatBizQueryParaMap($paraMap, $urlencode)
{
$buff = "";
ksort($paraMap);
foreach ($paraMap as $k => $v) {
if ($urlencode) {
$v = urlencode($v);
}
//$buff .= strtolower($k) . "=" . $v . "&";
$buff .= $k . "=" . $v . "&";
}
$reqPar;
if (strlen($buff) > 0) {
$reqPar = substr($buff, 0, strlen($buff) - 1);
}
return $reqPar;
}
/**
* 作用:設定code
*/
function setCode($code_)
{
$this->code = $code_;
}
/**
* 獲取微信使用者資料
* @return mixed
*/
function getWxInfomation()
{
$url = $this->createOauthUrlForOpenid();
//初始化curl
$ch = curl_init();
//設定超時
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//執行curl,結果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res, true);
if ($data) {
$url = $this->createOauthUrlForUserInfo($data[`access_token`], $data[`openid`]);
//初始化curl
$ch = curl_init();
//設定超時
curl_setopt($ch, CURLOPT_TIMEOUT, $this->curl_timeout);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_HEADER, FALSE);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
//執行curl,結果以jason形式返回
$res = curl_exec($ch);
curl_close($ch);
//取出openid
$data = json_decode($res, true);
return $data;
}
}