Table of Contents
1. File name and location
2. Code
Background controller processing
WeChat event response
All sharing interface
Home PHP Framework ThinkPHP How ThinkPHP5 integrates JS-SDK to implement WeChat custom sharing function

How ThinkPHP5 integrates JS-SDK to implement WeChat custom sharing function

May 27, 2023 am 08:07 AM
thinkphp js-sdk

Jssdk class library

1. File name and location

Name: Jssdk.php
Location: extend\util\Jssdk.php

2. Code

<?php
namespace util;

class Jssdk {

    protected $appid = &#39;xxxx&#39;;
    protected $secret = &#39;xxxx&#39;;

    /**
     * 获取access_token方法
     */
    public function getAccessToken(){
        //定义文件名称
        $name = &#39;token_&#39; . md5($this->appid . $this->secret);
        //定义存储文件路径
        // $filename = __DIR__ . &#39;/cache/&#39; . $name . &#39;.php&#39;;
		$filename = &#39;../runtime/temp/&#39; . $name . &#39;.php&#39;;
        //判断文件是否存在,如果存在,就取出文件中的数据值,如果不存在,就向微信端请求
        if (is_file($filename) && filemtime($filename) + 7100 > time()){
            $result = include $filename;
            //定义需要返回的内容$data
            $data = $result[&#39;access_token&#39;];
        }else{
            // https请求方式: GET
			// https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=APPID&secret=APPSECRET
            // 调用curl方法完成请求
            $url = &#39;https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&#39;.$this->appid.&#39;&secret=&#39; . $this->secret;
            $result = $this->curl($url);
            //将返回得到的json数据转成php数组
            $result = json_decode($result,true);
            //将内容写入文件中
            file_put_contents($filename,"<?php\nreturn " . var_export($result,true) . ";\n?>");
            //定义需要返回的内容
            $data = $result[&#39;access_token&#39;];
        }

        //将得到的access_token的值返回
        return $data;

    }

    /**
     *
     * 获取临时票据方法
     *
     * @return mixed
     */
    public function getJsapiTicket(){
        //存入文件中,定义文件的名称和路径
        $name = &#39;ticket_&#39; . md5($this->appid . $this->secret);
        //定义存储文件路径
        //$filename = __DIR__ . &#39;/cache/&#39; . $name . &#39;.php&#39;;
		$filename = &#39;../runtime/temp/&#39; . $name . &#39;.php&#39;;
        //判断是否存在临时票据的文件,如果存在,就直接取值,如果不存在,就发送请求获取并保存
        if (is_file($filename) && filemtime($filename) + 7100 > time()){
            $result = include $filename;
        }else{
            //定义请求地址
            $url = &#39;https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=&#39;.$this
                    ->getAccessToken().&#39;&type=jsapi&#39;;
            //使用curl方法发送请求,获取临时票据
            $result = $this->curl($url);
            //转换成php数组
            $result = json_decode($result,true);
            //将获取到的值存入文件中
            file_put_contents($filename,"<?php\nreturn " . var_export($result,true) . ";\n?>");

        }
        //定义返回的数据
        $data = $result[&#39;ticket&#39;];
        //将得到的临时票据结果返回
        return $data;
    }

    /**
     * 获取签名方法
     */
    public function sign(){
        //需要定义4个参数,分别包括随机数,临时票据,时间戳和当前url地址
        $nonceStr = $this->makeStr();
        $ticket = $this->getJsapiTicket();
        $time = time();
        //组合url
		//$url = $_SERVER[&#39;REQUEST_SCHEME&#39;] . &#39;://&#39; . $_SERVER[&#39;SERVER_NAME&#39;] . $_SERVER[&#39;REQUEST_URI&#39;];
        $url = &#39;http://&#39; . $_SERVER[&#39;SERVER_NAME&#39;] . $_SERVER[&#39;REQUEST_URI&#39;];
        //将4个参数放入一个数组中
        $arr = [
            &#39;noncestr=&#39; . $nonceStr,
            &#39;jsapi_ticket=&#39; . $ticket,
            &#39;timestamp=&#39; . $time,
            &#39;url=&#39; . $url
        ];
        //对数组进行字段化排序
        sort($arr,SORT_STRING);
        //对数组进行组合成字符串
        $string = implode(&#39;&&#39;,$arr);
        //将字符串加密生成签名
        $sign = sha1($string);
        //由于调用签名方法的时候不只需要签名,还需要生成签名的时候的随机数,时间戳,所以我们应该返回由这些内容组成的一个数组
        $reArr = [
            &#39;appId&#39; => $this->appid,
            &#39;timestamp&#39; => $time,
            &#39;nonceStr&#39; => $nonceStr,
            &#39;signature&#39; => $sign,
            &#39;url&#39; => $url
        ];
        //将数组返回
        return $reArr;
    }

    /**
     *
     * 生成随机数
     *
     * @return string
     */
    protected function makeStr(){
        //定义字符串组成的种子
        $seed = &#39;www512wayanbao1qasxianrendong5tgblaochaguan8ik9500net&#39;;
        //通过循环来组成一个16位的随机字符串
        //定义一个空字符串 用来接收组合成的字符串内容
        $str = &#39;&#39;;
        for ($i = 0;$i < 16; $i++){
            //定义一个随机数
            $num = rand(0,strlen($seed) - 1);
            //循环连接随机生成的字符串
            $str .= $seed[$num];
        }
        //将随机数返回
        return $str;
    }


    /**
     *
     * 服务器之间请求的curl方法
     *
     * @param $url 请求地址
     * @param array $field post参数
     * @return string
     */
    public function curl($url,$field = []){
        //初始化curl
        $ch = curl_init();
        //设置请求的地址
        curl_setopt($ch,CURLOPT_URL,$url);
        //设置接收返回的数据,不直接展示在页面
        curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
        //设置禁止证书校验
        curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
        curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
        //判断是否为post请求方式,如果传递了第二个参数,就代表是post请求,如果么有传递,第二个参数为空,就是get请求
        if (!empty($field)){
            //设置请求超时时间
            curl_setopt($ch,CURLOPT_TIMEOUT,30);
            //设置开启post
            curl_setopt($ch,CURLOPT_POST,1);
            //传递post数据
            curl_setopt($ch,CURLOPT_POSTFIELDS,$field);
        }
        //定义一个空字符串,用来接收请求的结果
        $data = &#39;&#39;;
        if (curl_exec($ch)){
            $data = curl_multi_getcontent($ch);
        }
        //关闭curl
        curl_close($ch);
        //将得到的结果返回
        return $data;
    }

}
//测试获取access_token值的方法
//$obj = new Wx();
//$data = $obj->getAccessToken();
//echo $data;

//测试获取jsapiticket方法
//$obj = new Wx();
//$data = $obj->getJsapiTicket();
//echo $data;

//测试生成签名方法
//$obj = new Wx();
//$data = $obj->sign();
//echo &#39;<pre class="brush:php;toolbar:false">&#39;;
//print_r($data);

?>
Copy after login

Background controller processing

<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use app\admin\model\Menu;
use util\Jssdk;

class Index extends Controller {
    public function demo(){
        $id = input(&#39;id&#39;,0);//ID
        $catid = input(&#39;catid&#39;,0);//分类ID

        $modelInfo = getModInfoById($catid);

        $info = Db::name($modelInfo[&#39;tablename&#39;])->where(&#39;id&#39;,$id)->find();
        $catinfo = getCatInfoById($catid);
        $p_catname = getCatInfoById($catinfo[&#39;parentid&#39;],&#39;catname&#39;);

		$obj = new Jssdk();
		$data = $obj->sign();

        $this->assign(&#39;infos&#39;,$info);
        $this->assign(&#39;catids&#39;,$catid);
        $this->assign(&#39;catnames&#39;,$catinfo[&#39;catname&#39;]);
        $this->assign(&#39;p_catnames&#39;,$p_catname);
		$this->assign(&#39;data&#39;,$data);

        return view(&#39;../application/index/view/default/index/&#39; . $modelInfo[&#39;show_template&#39;]);
    }
}
?>
Copy after login

WeChat event response

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
	// 通过config接口注入权限验证配置
	wx.config({
		debug: false, 
		appId: &#39;{$data.appId}&#39;,
		timestamp: &#39;{$data.timestamp}&#39;,
		nonceStr: &#39;{$data.nonceStr}&#39;, 
		signature: &#39;{$data.signature}&#39;,
		jsApiList: [
			&#39;onMenuShareTimeline&#39;,
			&#39;onMenuShareAppMessage&#39;
		]
	});
	// 通过ready接口处理成功验证
	wx.ready(function(){
		// 分享到朋友圈
		wx.onMenuShareTimeline({
			title: &#39;{$info.title}&#39;,
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			success: function () {
				// 用户点击了分享后执行的回调函数
			}
		});
		// 分享给朋友
		wx.onMenuShareAppMessage({
			title: &#39;{$info.title}&#39;, 
			desc: &#39;{$info.description}&#39;, 
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			type: &#39;link&#39;, // 分享类型,music、video或link,不填默认为link
			dataUrl: &#39;&#39;, // 如果type是music或video,则要提供数据链接,默认为空
			success: function () {
				// 用户点击了分享后执行的回调函数
			}
		});
	});
</script>
Copy after login

All sharing interface

<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script type="text/javascript">
	// 通过config接口注入权限验证配置
	wx.config({
		debug: true, 
		appId: &#39;{$data.appId}&#39;,
		timestamp: &#39;{$data.timestamp}&#39;,
		nonceStr: &#39;{$data.nonceStr}&#39;, 
		signature: &#39;{$data.signature}&#39;,
		jsApiList: [
			&#39;onMenuShareTimeline&#39;,
			&#39;onMenuShareAppMessage&#39;,
			&#39;onMenuShareQQ&#39;,
			&#39;onMenuShareWeibo&#39;,
			&#39;onMenuShareQZone&#39;
		]
	});
	// 通过ready接口处理成功验证
	wx.ready(function(){
		// 分享到朋友圈
		wx.onMenuShareTimeline({
			title: &#39;{$info.title}&#39;,
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			success: function () {
				// 用户点击了分享后执行的回调函数
			}
		});
		// 分享给朋友
		wx.onMenuShareAppMessage({
			title: &#39;{$info.title}&#39;, 
			desc: &#39;{$info.description}&#39;, 
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			type: &#39;link&#39;, // 分享类型,music、video或link,不填默认为link
			dataUrl: &#39;&#39;, // 如果type是music或video,则要提供数据链接,默认为空
			success: function () {
				// 用户点击了分享后执行的回调函数
			}
		});
		// 分享到QQ
		wx.onMenuShareQQ({
			title: &#39;{$info.title}&#39;, 
			desc: &#39;{$info.description}&#39;, 
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
		// 分享到腾讯微博
		wx.onMenuShareWeibo({
			title: &#39;{$info.title}&#39;,
			desc: &#39;{$info.description}&#39;, 
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
		// 分享到QQ空间
		wx.onMenuShareQZone({
			title: &#39;{$info.title}&#39;, 
			desc: &#39;{$info.description}&#39;, 
			link: &#39;{$data.url}&#39;, 
			imgUrl: &#39;http://m.psnav.com/uploads/image/{$info.thumb}&#39;, 
			success: function () {
				// 用户确认分享后执行的回调函数
			},
			cancel: function () {
				// 用户取消分享后执行的回调函数
			}
		});
	});
</script>
Copy after login

The above is the detailed content of How ThinkPHP5 integrates JS-SDK to implement WeChat custom sharing function. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to run thinkphp project How to run thinkphp project Apr 09, 2024 pm 05:33 PM

To run the ThinkPHP project, you need to: install Composer; use Composer to create the project; enter the project directory and execute php bin/console serve; visit http://localhost:8000 to view the welcome page.

There are several versions of thinkphp There are several versions of thinkphp Apr 09, 2024 pm 06:09 PM

ThinkPHP has multiple versions designed for different PHP versions. Major versions include 3.2, 5.0, 5.1, and 6.0, while minor versions are used to fix bugs and provide new features. The latest stable version is ThinkPHP 6.0.16. When choosing a version, consider the PHP version, feature requirements, and community support. It is recommended to use the latest stable version for best performance and support.

How to run thinkphp How to run thinkphp Apr 09, 2024 pm 05:39 PM

Steps to run ThinkPHP Framework locally: Download and unzip ThinkPHP Framework to a local directory. Create a virtual host (optional) pointing to the ThinkPHP root directory. Configure database connection parameters. Start the web server. Initialize the ThinkPHP application. Access the ThinkPHP application URL and run it.

Which one is better, laravel or thinkphp? Which one is better, laravel or thinkphp? Apr 09, 2024 pm 03:18 PM

Performance comparison of Laravel and ThinkPHP frameworks: ThinkPHP generally performs better than Laravel, focusing on optimization and caching. Laravel performs well, but for complex applications, ThinkPHP may be a better fit.

Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Development suggestions: How to use the ThinkPHP framework to implement asynchronous tasks Nov 22, 2023 pm 12:01 PM

"Development Suggestions: How to Use the ThinkPHP Framework to Implement Asynchronous Tasks" With the rapid development of Internet technology, Web applications have increasingly higher requirements for handling a large number of concurrent requests and complex business logic. In order to improve system performance and user experience, developers often consider using asynchronous tasks to perform some time-consuming operations, such as sending emails, processing file uploads, generating reports, etc. In the field of PHP, the ThinkPHP framework, as a popular development framework, provides some convenient ways to implement asynchronous tasks.

How to install thinkphp How to install thinkphp Apr 09, 2024 pm 05:42 PM

ThinkPHP installation steps: Prepare PHP, Composer, and MySQL environments. Create projects using Composer. Install the ThinkPHP framework and dependencies. Configure database connection. Generate application code. Launch the application and visit http://localhost:8000.

How is the performance of thinkphp? How is the performance of thinkphp? Apr 09, 2024 pm 05:24 PM

ThinkPHP is a high-performance PHP framework with advantages such as caching mechanism, code optimization, parallel processing and database optimization. Official performance tests show that it can handle more than 10,000 requests per second and is widely used in large-scale websites and enterprise systems such as JD.com and Ctrip in actual applications.

Development suggestions: How to use the ThinkPHP framework for API development Development suggestions: How to use the ThinkPHP framework for API development Nov 22, 2023 pm 05:18 PM

Development suggestions: How to use the ThinkPHP framework for API development. With the continuous development of the Internet, the importance of API (Application Programming Interface) has become increasingly prominent. API is a bridge for communication between different applications. It can realize data sharing, function calling and other operations, and provides developers with a relatively simple and fast development method. As an excellent PHP development framework, the ThinkPHP framework is efficient, scalable and easy to use.

See all articles