网页授权,获取用户头像,自定义分享图像

.php主文件(需要授权的页面)


require_once "jssdk/jssdk.php";  
require_once "jssdk/getinfo2.php";  
$jssdk = new JSSDK("id", "密钥");
$signPackage = $jssdk->GetSignPackage();
$xinxi2 = $userinfo['nickname'];//通过获取getinfo2文件里的函数获取到nickname对应的值,即用户名
?>
<script>
          
        var u="$xinxi?>";

        wx.config({
        debug:  false,  //调式模式,设置为ture后会直接在网页上弹出调试信息,用于排查问题
        appId: '',
        timestamp:  echo $signPackage["timestamp"];?>,
        nonceStr: '',
        signature: '',
        jsApiList: [  
            'onMenuShareAppMessage','onMenuShareTimeline','getLocation','openLocation'
        ]
        });
        wx.ready(function(){
        wx.onMenuShareTimeline({
            title: '我在成都等你,一起点亮中秋!',
            
            link:"http://www.funca.com.cn/visite/",
            imgUrl: u,//把分享时的图像换成了该用户头像
            //转发成功后调用的函数
            success: function () {
            //你要执行的操作
            },
            //用户取消转发后调用的函数
            cancel: function () {
            //你要执行的操作
            }
        });
        wx.onMenuShareAppMessage({
                title: "我在成都等你,一起点亮中秋!", // 分享标题
                desc: "5.18-19,西南烘焙大事件,中华月饼展 开幕!(国潮月饼展示+饼店复苏论坛)", // 分享描述
                link:"http://www.funca.com.cn/visite/",
                imgUrl: u,
                
                success: function () {
                    // 用户确认分享后执行的回调函数
                    
                },
                cancel: function () {
                    // 用户取消分享后执行的回调函数
                }
                            });
        })



</script>

getinfo2.php(授权并获取用户信息的页面)


    header("content-type:text/html;charset=utf-8");
    $code = $_GET["code"];//预定义的 $_GET 变量用于收集来自 method="get" 的表单中的值。
    if (isset($_GET['code'])){//判断code是否存在
        $userinfo = getUserInfo($code);
        $xinxi = $userinfo['headimgurl'];//获取nickname对应的值,即用户名
        // echo $xinxi;
    }else{
    //每次分享后分享的链接后边是不带code的,所以分享后会重新跳转到授权页面进行下一个用户的信息获取,然后再跳转至$redirect_uri即我们的主页面。
               	$appid='';
				$redirect_uri = 'http://www.funca.com.cn/visite/';//将字符串以 URL 编码。
				$url ="https://open.weixin.qq.com/connect/oauth2/authorize?appid=$appid&redirect_uri=$redirect_uri&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect";
				
				header("Location:".$url);//header() 函数向客户端发送原始的 HTTP 报头。

    }
    
    function getUserInfo($code)
    {
        $appid = "";
        $appsecret = "";

        //Get access_token
        $access_token_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=$appid&secret=$appsecret&code=$code&grant_type=authorization_code";
        $access_token_json = https_request($access_token_url);//自定义函数
        $access_token_array = json_decode($access_token_json,true);//对 JSON 格式的字符串进行解码,转换为 PHP 变量,自带函数
        //获取access_token
        $access_token = $access_token_array['access_token'];//获取access_token对应的值
        //获取openid
        $openid = $access_token_array['openid'];//获取openid对应的值

        //Get user info
        $userinfo_url = "https://api.weixin.qq.com/sns/userinfo?access_token=$access_token&openid=$openid";
        $userinfo_json = https_request($userinfo_url);
        $userinfo_array = json_decode($userinfo_json,ture);
        return $userinfo_array;
    }

    function https_request($url)//自定义函数,访问url返回结果
    {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($curl,  CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $data = curl_exec($curl);
        if (curl_errno($curl)){
            return 'ERROR'.curl_error($curl);
        }
        curl_close($curl);
        return $data;
    }
   
  
    
?>

access_token.php

 exit();?>
{"access_token":"","expire_time":0}

jsapi_ticket.php

 exit();?>
{"jsapi_ticket":"","expire_time":0}

jssdk.php


class JSSDK {
    private $appId;
    private $appSecret;

    public function __construct($appId, $appSecret) {
        $this->appId = $appId;
        $this->appSecret = $appSecret;
    }
    //因为url不能写死,所以我果断地把这里改成函数参数传值了
    public function getSignPackage($url) {
        $jsapiTicket = $this->getJsApiTicket();
        $timestamp = time();
        $nonceStr = $this->createNonceStr();

        // 这里参数的顺序要按照 key 值 ASCII 码升序排序
        $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url";

        $signature = sha1($string);

        $signPackage = array(
            "appId" => $this->appId,
            "nonceStr" => $nonceStr,
            "timestamp" => $timestamp,
            "url" => $url,
            "signature" => $signature,
            "rawString" => $string
        );
        return $signPackage;
    }

    private function createNonceStr($length = 16) {
        $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
        $str = "";
        for ($i = 0; $i < $length; $i++) {
            $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
        }
        return $str;
    }

    private function getJsApiTicket() {
        // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("jsapi_ticket.json"));
        if ($data->expire_time < time()) {
            $accessToken = $this->getAccessToken();
            $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken";
            $res = json_decode($this->httpGet($url));
            $ticket = $res->ticket;
            if ($ticket) {
                $data->expire_time = time() + 7000;
                $data->jsapi_ticket = $ticket;
                $fp = fopen("jsapi_ticket.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $ticket = $data->jsapi_ticket;
        }

        return $ticket;
    }

    private function getAccessToken() {
        // access_token 应该全局存储与更新,以下代码以写入到文件中做示例
        $data = json_decode(file_get_contents("access_token.json"));
        if ($data->expire_time < time()) {
            $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret";
            $res = json_decode($this->httpGet($url));
            $access_token = $res->access_token;
            if ($access_token) {
                $data->expire_time = time() + 7000;
                $data->access_token = $access_token;
                $fp = fopen("access_token.json", "w");
                fwrite($fp, json_encode($data));
                fclose($fp);
            }
        } else {
            $access_token = $data->access_token;
        }
        return $access_token;
    }

    private function httpGet($url) {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_TIMEOUT, 500);
        curl_setopt($curl, CURLOPT_URL, $url);
        $res = curl_exec($curl);
        curl_close($curl);
        return $res;
    }
}

你可能感兴趣的:(网页授权,获取用户头像,自定义分享图像)