THINKPHP JSDK微信分享

查了很多资料。
直接上控制器代码

public function wechatJsapi(){
        // 生成签名
        // 1.获取 access_token
        $view = new View();
        $access_token = getAccessToken();
        if (Cookie::get('username','jq_') != "") {
    		$view->assign('type',1);
    		$view->assign('msg','<a class="list_a">用户:'.Cookie::get('username','jq_').'</a>');
    	}else{
    		$view->assign('type',0);
    		$view->assign('msg','<a type="button" class="am-btn am-btn-primary am-btn-block" href="/login">点我登陆</a>');
    	}
        if(empty($access_token)) halt('access_token有误');
        // 2.获取 jsapi_ticket
        $jsapi = cache('jsapi');
        $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=$access_token&type=jsapi";
	    $weixin=file_get_contents($url);//通过code换取网页授权access_token
	    $jsapi=json_decode($weixin); //对JSON格式的字符串进行编码
        cache('jsapi',$jsapi,7190);
        $jsapi_ticket = $jsapi -> ticket;
        // 3.生成签名
        $noncestr  = genRandomString();
        $timestamp = time();
        $url       = 'https://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        $signObj['noncestr']        = $noncestr;
        $signObj['jsapi_ticket']    = $jsapi_ticket;
        $signObj['timestamp']       = $timestamp;
        $signObj['url']             = $url;
        $signString = formatBizQueryParaMap($signObj, false);
        $signString = sha1($signString);

        $view->assign([
            'appId'     => 'wx04357e1fb0962a60',
            'timestamp' => $timestamp,
            'nonceStr'  => $noncestr,
            'signature' => $signString
        ]);
        return $view->fetch('share');
        // return json($jsapi);
    }

common.php

/**
 * 生成随机字符串
 * @param int $len
 * @return string
 */
function genRandomString($len = 32) {
    $chars = array(
        "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k",
        "l", "m", "n", "o", "p", "q", "r", "s", "t", "u", "v",
        "w", "x", "y", "z", "A", "B", "C", "D", "E", "F", "G",
        "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R",
        "S", "T", "U", "V", "W", "X", "Y", "Z"
    );
    $charsLen = count($chars) - 1;
    // 将数组打乱
    shuffle($chars);
    $output = "";
    for ($i = 0; $i < $len; $i++) {
        $output .= $chars[mt_rand(0, $charsLen)];
    }
    return $output;
}
/**
 * 作用:格式化参数,签名过程需要使用
 * @param $paraMap
 * @param $urlencode
 * @return bool|string
 */
 function formatBizQueryParaMap($paraMap, $urlencode)
{
    $buff = "";
    ksort($paraMap);
    foreach ($paraMap as $k => $v)
    {
        if($urlencode)
        {
            $v = urlencode($v);
        }
        $buff .= $k . "=" . $v . "&";
    }
    $reqPar = '';
    if (strlen($buff) > 0)
    {
        $reqPar = substr($buff, 0, strlen($buff)-1);
    }
    return $reqPar;
}
function getAccessToken(){
    $param = [
        'grant_type'  =>  'client_credential',
        'appid'       =>  'wx04357e1fb0962a60',
        'secret'      =>  'xxxxxxxxxxxxxxxx',
    ];
    $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".'wx04357e1fb0962a60'."&secret=". 'xxxxxxxxxxxxx';
    $weixin=file_get_contents($url);//通过code换取网页授权access_token
    $result=json_decode($weixin); //对JSON格式的字符串进行编码
    $accessToken = $result -> access_token;
    cache('accessToken',$accessToken,(($result -> expires_in )-10));
    return $accessToken;
}

前端html

先在head引入微信js:

<script type="text/javascript" src="https://res.wx.qq.com/open/js/jweixin-1.4.0.js"></script>
<script>
    wx.config({
        debug: false,
        appId: "{$appId}",
        timestamp: "{$timestamp}",
        nonceStr: "{$nonceStr}",
        signature: "{$signature}",
        jsApiList: ['scanQRCode','onMenuShareAppMessage','onMenuShareTimeline']
    });

    wx.ready(function(){
        // config信息验证后会执行ready方法,所有接口调用都必须在config接口获得结果之后,config是一个客户端的异步操作,所以如果需要在页面加载时就调用相关接口,则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口,则可以直接调用,不需要放在ready函数中。

        wx.onMenuShareAppMessage({
          title: document.title, // 分享标题
          desc: '我们整理了全部节气以及重要节日的在线图片,如果您是一个注重传统文化的人,想要在重要节日当中宣传自己及公司,可以联系我们为您制作带有您自己公司logo的图片!', // 分享描述
          link: window.location.href, // 分享链接,该链接域名或路径必须与当前页面对应的公众号JS安全域名一致
          imgUrl: 'https://jq.yunzainet.com/img/logo180.jpg', // 分享图标
          type: 'link', // 分享类型,music、video或link,不填默认为link
          dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
          trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
            // alert('用户点击分享到朋友圈');
          },
          success: function (res) {
            // alert('已分享');
            $("body").append('<div class="am-alert am-alert-success" data-am-alert><button type="button" class="am-close">×</button><p id="msg">分享成功!</p></div>')
            $('.am-alert').alert()
            $('.am-alert').css({
              'height':'47px',
              'padding':'0.625em',
            })
            $('.am-alert').animate({top:0},400)
          },
          cancel: function (res) {
            $("body").append('<div class="am-alert am-alert-warning" data-am-alert><button type="button" class="am-close">×</button><p id="msg">已取消分享!</p></div>')
            $('.am-alert').alert()
            $('.am-alert').css({
              'height':'47px',
              'padding':'0.625em',
            })
            $('.am-alert').animate({top:0},400)
          },
          fail: function (res) {
            alert(JSON.stringify(res));
          }
        });
        wx.onMenuShareTimeline({
          title: document.title,
          link: window.location.href,
          desc: '我们整理了全部节气以及重要节日的在线图片,如果您是一个注重传统文化的人,想要在重要节日当中宣传自己及公司,可以联系我们为您制作带有您自己公司logo的图片!', // 分享描述
          imgUrl: 'https://jq.yunzainet.com/img/logo180.jpg',
          trigger: function (res) {
            // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
            // alert('用户点击分享到朋友圈');
          },
          success: function (res) {
            // alert('已分享');
            $("body").append('<div class="am-alert am-alert-success" data-am-alert><button type="button" class="am-close">×</button><p id="msg">分享成功!</p></div>')
            $('.am-alert').alert()
            $('.am-alert').css({
              'height':'47px',
              'padding':'0.625em',
            })
            $('.am-alert').animate({top:0},400)
          },
          cancel: function (res) {
           $("body").append('<div class="am-alert am-alert-warning" data-am-alert><button type="button" class="am-close">×</button><p id="msg">已取消分享!</p></div>')
            $('.am-alert').alert()
            $('.am-alert').css({
              'height':'47px',
              'padding':'0.625em',
            })
            $('.am-alert').animate({top:0},1000)
          },
          fail: function (res) {
            alert(JSON.stringify(res));
          }
        });
    });
    wx.error(function(res){
      // config信息验证失败会执行error函数,如签名过期导致验证失败,具体错误信息可以打开config的debug模式查看,也可以在返回的res参数中查看,对于SPA可以在这里更新签名。
      console.log(res)
  });

</script>

把这段JS代码我做成了模板,每个页面都引入它了,这样就可以全站分享了。

效果图如下:

分享到朋友圈————

在这里插入图片描述

在这里插入图片描述

转发给朋友带描述的——————
在这里插入图片描述
在这里插入图片描述

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值