0210220总结 微信h5分享解析

4 篇文章 0 订阅

今天用到了微信的h5分享,自定义图片和描述

好久没使用了,有点生疏之前都是使用的框架直接生成的,今天单独分出来这一块,方便使用

下面列出主要的代码

使用到的主要函数

//curl获取请求文本内容
function get_curl_contents($url, $method ='GET', $data = array()) {
    if ($method == 'POST') {
      //使用crul模拟
      $ch = curl_init();
      curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
      //允许请求以文件流的形式返回
      curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
      curl_setopt($ch, CURLOPT_POST, 1);
      curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
      curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
      curl_setopt($ch, CURLOPT_DNS_CACHE_TIMEOUT, 30);
      curl_setopt($ch, CURLOPT_URL, $url);
      $result = curl_exec($ch); //执行发送
      curl_close($ch);
    }else {
      if (ini_get('allow_fopen_url') == '1') {
        $result = file_get_contents($url);
      }else {
        //使用crul模拟
        $ch = curl_init();
        //允许请求以文件流的形式返回
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //禁用https
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_URL, $url);
        $result = curl_exec($ch); //执行发送
        curl_close($ch);
      }
    }
    return $result;
  }
  //获取微信公从号access_token
  function wx_get_token() {
    $AppID = 'wxc9dc74da0aac5eb2';//AppID(应用ID)   //  wx11ca4d1dafc98df5
    $AppSecret = '03bf5766ca7cedf6af650e3e7677d13e';//AppSecret(应用密钥)   f8602841ec6c540e0aae2d732d0beae9
    $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$AppID.'&secret='.$AppSecret;
    $res = get_curl_contents($url);
    $res = json_decode($res, true);
    //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s
    return $res['access_token'];
  }
  //获取微信公从号ticket
  function wx_get_jsapi_ticket() {
    $url = sprintf("https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=%s&type=jsapi", wx_get_token());
    $res = get_curl_contents($url);
    $res = json_decode($res, true);
    //这里应该把access_token缓存起来,至于要怎么缓存就看各位了,有效期是7200s
    return $res['ticket'];
  }
  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;
  }

控制器方面:

$wx = array();
//生成签名的时间戳
$wx['timestamp'] = time();
$wx['appid'] = 'wxc9dc74da0aac5eb2';   //     wxc9dc74da0aac5eb2
//生成签名的随机串
$wx['noncestr'] = createNonceStr();
//jsapi_ticket是公众号用于调用微信JS接口的临时票据。正常情况下,jsapi_ticket的有效期为7200秒,通过access_token来获取。
$wx['jsapi_ticket'] = wx_get_jsapi_ticket();
//分享的地址,注意:这里是指当前网页的URL,我这里直接用了当前域名报错63002,invalid signature
// $wx['url'] = 'http://lt.cnseen.com/detail/75';
$wx['url'] = 'http://'.request()->host().request()->url();
$string = sprintf("jsapi_ticket=%s&noncestr=%s&timestamp=%s&url=%s", $wx['jsapi_ticket'], $wx['noncestr'], $wx['timestamp'], $wx['url']);
// dd($string);
//生成签名
$wx['signature'] = sha1($string);
// dd($wx);
$this->assign('wx',$wx);

页面方面

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
<script>
    //通过config接口注入权限验证配置
    wx.config({
      debug : false,
      appId : '<?php echo $wx["appid"];?>',
      timestamp : '<?php echo $wx["timestamp"];?>',
      nonceStr : '<?php echo $wx["noncestr"];?>',
      signature : '<?php echo $wx["signature"];?>',
      jsApiList : [
      'checkJsApi',  
        'onMenuShareTimeline',  
        'onMenuShareAppMessage'  
      ]
    });
    wx.ready(function(){
        var
            s_title = "{$content['title']}",  // 分享标题
            s_link = "<?php echo 'http://'.request()->host().'/detail/'.$content['id'].'.html'; ?>",  // 分享链接
            s_desc = "{$content['summary']}",  //分享描述
            s_imgUrl = "<?php echo 'http://'.request()->host(); ?>{$content['pic']}"; // 分享图标
       wx.checkJsApi({
            jsApiList: [
                'getLocation',
                'onMenuShareTimeline',
                'onMenuShareAppMessage'
            ],
            success: function (res) {
            //alert(JSON.stringify(res));
            }
        });
        wx.onMenuShareTimeline({
            title:s_title, // 分享标题
            desc: s_desc, // 分享描述
            link: s_link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: s_imgUrl, // 分享图标
            success: function () {
                //alert('分享成功');
            // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                //alert('分享失败1');
            // 用户取消分享后执行的回调函数
            }
        });
        wx.onMenuShareAppMessage({
            title:s_title, // 分享标题
            desc: s_desc, // 分享描述
            link: s_link, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
            imgUrl: s_imgUrl, // 分享图标
            success: function () {
                //alert('分享成功');
            // 用户确认分享后执行的回调函数
            },
            cancel: function () {
                //alert('分享失败1');
            // 用户取消分享后执行的回调函数
            }
        });
        wx.error(function (res) {  
            //alert("error: " + res.errMsg);  
        });  
    });
    </script>

在使用的过程中,遇到一个问题总是报错报错63002,invalid signature
之后发现的问题是,分享的js中的link必须是当前的url地址,当时不记得有这个问题了,报错了,尴尬

好了今天就分享下这个,避免下次出错

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

程序员子枫

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值