Página web de WeChat autorizada para compartir el viaje al pozo minero

demanda

Permítanme hablar primero sobre los requisitos, que es una página HTML normal, que se muestra en el navegador WeChat. El avatar y el apodo del usuario deben mostrarse en la página, y aquí se requiere autorización web. Luego puede compartir la página con Moments o amigos, necesita personalizar el contenido para compartir

Autorización de WeChat

Cree un archivo index.php como la página que se mostrará en la página web

<?php
header("Content-type: text/html; charset=utf-8");

$appid = '66666';
$secret = '77777';
//微信授权成功后,会请求该页面,并带有code参数
$code = $_GET['code']?:'';
$userinfo = [];
if($code){
    
    
	//使用code凭证,获取access_toekn和用户openid
    $code_json = file_get_contents('https://api.weixin.qq.com/sns/oauth2/access_token?appid='.$appid.'&secret='.$secret.'&code='.$code.'&grant_type=authorization_code');
    $code_res = json_decode($code_json,true);
    //使用access_toen和openid获取用户的基本信息
    //然后,下面的html页面,可以根据userinfo的值,来展示用户的头像和昵称
    if(isset($code_res['access_token'])){
    
    
        $user_json = file_get_contents('https://api.weixin.qq.com/sns/userinfo?access_token='.$code_res['access_token'].'&openid='.$code_res['openid'].'&lang=zh_CN');
        $userinfo = json_decode($user_json,true);
    }
}


?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="content-type" content="text/html" />
    <title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
    
    
	//微信授权后的回调地址,这里设置为本页面。回调地址的域名必须在微信公众号中设置为安全域名
	var local = 'http://www.mine.com//index.php';
	//微信授权地址
    var url = 'https://open.weixin.qq.com/connect/oauth2/authorize?appid=66666&redirect_uri=' + encodeURIComponent(local) + '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
    window.location.href = url;
}
</script>
</body>
</html>

El proceso de autorización de WeChat es más simple, por lo que no lo repetiré

Compártelo

Primero, cree una página share.php para obtener la información de configuración de JSSDK

<?php
header("Content-type: text/html; charset=utf-8");

$appid = '66666';
$secret = '777777';
//获取缓存数据
$file_cache_str = file_get_contents('cache.txt');
$file_cache = [];
if($file_cache_str){
    
    
    $file_cache = json_decode($file_cache_str,true);
}
//获取access_token凭证
if($file_cache && isset($file_cache['access_token']) && $file_cache['access_token']['time'] > time()){
    
    
    $access_token = $file_cache['access_token']['value'];
}else{
    
    
    $token_json = file_get_contents('https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$appid.'&secret='.$secret);
    $token_info = json_decode($token_json,true);
    $access_token = $token_info['access_token'];
    $file_cache['access_token'] = ['value'=>$access_token,'time'=>time()+7000];
    $res = file_put_contents('cache.txt',json_encode($file_cache));
    //var_dump($res);exit;
}
//使用access_token获取jsapi_ticket凭证
if($file_cache && isset($file_cache['jsapi_ticket']) && $file_cache['jsapi_ticket']['time'] > time()){
    
    
    $jsapi_ticket = $file_cache['jsapi_ticket']['value'];
}else{
    
    
    $ticket_json =file_get_contents('https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$access_token.'&type=jsapi');
    $ticket_info = json_decode($ticket_json,true);
    $jsapi_ticket = $ticket_info['ticket'];
    $file_cache['jsapi_ticket'] = ['value'=>$jsapi_ticket,'time'=>time()+7000];
    file_put_contents('cache.txt',json_encode($file_cache));
}
//获取时间戳
$time = time();
//设置随机字符串
$rand_str = 'Wm3WZYTPz0fdfggerrtqq';
//获取分享页面完整的url地址
$host = $_POST['host'];
//获取签名字符串
$str = 'jsapi_ticket='.$jsapi_ticket.'&noncestr='.$rand_str.'&timestamp='.$time.'&url='.$host;
$signature = sha1($str);
//返回配置数据
$data = [
    'appId' => $appid,
    'timestamp' => $time,
    'nonceStr'  => $rand_str,
    'signature' => $signature
];
echo json_encode($data);
Luego configuramos el código para compartir en la página index.php

Echemos un vistazo al código para pisar el foso al principio.

<?php
............................
?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="content-type" content="text/html" />
    <!--引用微信JS-->
    <script type=" text/javascript " src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
    <title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
    
    
.....................
}
</script>
<script>
    $(function(){
    
    
        $.post('share.php',{
    
    host:location.href.split('#')[0]},function(res){
    
    
            wx.config({
    
    
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: res.appId, // 必填,公众号的唯一标识
                timestamp: res.timestamp, // 必填,生成签名的时间戳
                nonceStr: res.nonceStr, // 必填,生成签名的随机串
                signature: res.signature,// 必填,签名
                jsApiList:  ['onMenuShareAppMessage','onMenuShareTimeline'] // 必填,需要使用的JS接口列表
            });
            var share_data = {
    
    
                title: '你好吗世界', // 分享标题
                desc: '我们不能改变世界,但可以改变我们的世界', // 分享描述
                link: 'http://www.mine.com/index.php', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: 'http://www.mine.com/share_img.jpg', // 分享图标
                success: function () {
    
    
                }
            };
            wx.ready(function () {
    
       //需在用户可能点击分享按钮前就先调用
                wx.onMenuShareAppMessage(share_data);
                wx.onMenuShareTimeline(share_data);
            });
        },'json')
    })
</script>
</body>
</html>

El código se ve bien, después de abrir la depuración, también apareceráconfig: okConsejos. Cuando se comparte con amigos en el navegador WeChat en la PC, es normal y se muestran el título, la descripción y las imágenes. Pero compartir con un teléfono móvil no funciona.
Busqué en Internet durante mucho tiempo y algunos dijeron que la autorización no se puede usar como una página para compartir y requiere un segundo salto; algunos dijeron que hay un problema con el enlace para compartir. De todos modos, los probé uno por uno, pero todavía no funciona.
Consulte el documento oficial, se dice que onMenuShareAppMessage y onMenuShareTimeline están a punto de quedar obsoletos y deberían ser reemplazados por updateAppMessageShareData y updateTimelineShareData. Lo intenté, pero todavía no funciona.
Finalmente, se descubrió que se trataba de un problema con la versión del archivo js de WeChat. Para usar la última actualizaciónAppMessageShareData y updateTimelineShareData, debe usarweixin-1.4.0.js
En cuanto a por qué el código anterior se puede usar en el navegador en el lado de WeChat PC, pero no en el teléfono móvil. Se estima que debería ser el navegador en la PC o la versión anterior, y WeChat en el teléfono móvil ya es la última versión y ya no es compatible.

El siguiente es el código correcto
<?php
............................
?>
//下面是html页面
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8" />
    <meta http-equiv="content-type" content="text/html" />
    <!--引用微信JS-->
    <script type=" text/javascript " src="http://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
    <title>hell world</title>
</head>
<body>
<input type="button" value="点击获取授权" onclick="get_root();" />
<script>
function get_root(){
    
    
.....................
}
</script>
<script>
    $(function(){
    
    
        $.post('share.php',{
    
    host:location.href.split('#')[0]},function(res){
    
    
            wx.config({
    
    
                debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
                appId: res.appId, // 必填,公众号的唯一标识
                timestamp: res.timestamp, // 必填,生成签名的时间戳
                nonceStr: res.nonceStr, // 必填,生成签名的随机串
                signature: res.signature,// 必填,签名
                jsApiList:  ['updateAppMessageShareData','updateTimelineShareData'] // 必填,需要使用的JS接口列表
            });
            var share_data = {
    
    
                title: '你好吗世界', // 分享标题
                desc: '我们不能改变世界,但可以改变我们的世界', // 分享描述
                link: 'http://www.mine.com/index.php', // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
                imgUrl: 'http://www.mine.com/share_img.jpg', // 分享图标
                success: function () {
    
    
                }
            };
            wx.ready(function () {
    
       //需在用户可能点击分享按钮前就先调用
                //新版分享方法
                wx.updateAppMessageShareData(share_data);
                wx.updateTimelineShareData(share_data);
            });
        },'json')
    })
</script>
</body>
</html>

Supongo que te gusta

Origin blog.csdn.net/u012830303/article/details/107223389
Recomendado
Clasificación