Home Backend Development PHP Tutorial Detailed explanation of php WeChat browser sharing settings and callbacks_php example

Detailed explanation of php WeChat browser sharing settings and callbacks_php example

Aug 17, 2016 pm 01:02 PM

The function of sharing to friends/sharing to Moments in WeChat should be relatively common. Take sharing to Moments as an example. The shared content is displayed in Moments with a small picture + a simple introduction. The form is for friends to see, and the details are revealed after clicking. In this way, this small picture and this small introduction directly become the top priority of the click-through rate of the shared content. By default, this image will load as the first large image in the topic section of the content, while the introduction will only load a URL. This kind of display method is still quite unsatisfactory, so let’s take a look at how these contents are set up. Take PHP as an example:

First we need to have a public account and obtain the appid and appsecret.

Then, we can exchange the access_token from the WeChat platform through the appid and appsecret.

define("APPID", $appid);
define("APPSECRET", $appsecret);
 
// 获取access_token
$token_access_url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
$res = file_get_contents($token_access_url); //获取文件内容或获取网络请求的内容
$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
$access_token = $result['access_token'];

Copy after login

Through access_token, we can request a jsapi_ticket from the WeChat platform:

 // 获取jsapi_ticket
$ticket_url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=TOKEN";

$res = file_get_contents($ticket_url); //获取文件内容或获取网络请求的内容
$result = json_decode($res, true); //接受一个 JSON 格式的字符串并且把它转换为 PHP 变量
$ticket = $result['ticket']; 

Copy after login

Okay, the preparations are ready, we can start our settings.

WeChat sharing settings are set through wx.config.

<script>
wx.config({
  debug: false, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。
  appId: '<&#63;php echo APPID;&#63;>', // 必填,公众号的唯一标识
  timestamp: <&#63;php echo $timestamp;&#63;>, // 必填,生成签名的时间戳
  nonceStr: '<&#63;php echo $noncestr;&#63;>', // 必填,生成签名的随机串
  signature: '<&#63;php echo $signature;&#63;>',// 必填,签名
  jsApiList: ['onMenuShareTimeline','onMenuShareAppMessage'] // 必填,需要使用的JS接口列表
});
</script>
Copy after login

The middle appid is the appid of our WeChat official account, timestamp is the current timestamp, noncestr is a random string used to generate signatures, signature is the generated signature, jsapilist is the WeChat interface we need to use, here we Just use the two interfaces of sharing to friends and sharing to Moments.

Briefly list the generation process of timestamp, noncestr, and signature:

// 生成签名
 // 生成随机字符串
class RandChar{
 function getRandChar($length){
  $str = null;
  $strPol = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789abcdefghijklmnopqrstuvwxyz";
  $max = strlen($strPol)-1;

  for($i=0;$i<$length;$i++){
  $str.=$strPol[rand(0,$max)];//rand($min,$max)生成介于min和max两个数之间的一个随机整数
  }
  return $str;
 }
}
$randCharObj = new RandChar();
$noncestr = $randCharObj->getRandChar(16);


$timestamp = time();
if ($_SERVER['QUERY_STRING']){
  $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'].'&#63;'.$_SERVER['QUERY_STRING'];
}else{
  $url = 'http://'.$_SERVER['HTTP_HOST'].$_SERVER['PHP_SELF'];
}

$parameters = array("noncestr" => $noncestr,
            "jsapi_ticket" => $ticket,
            "timestamp" => $timestamp,
            "url" => $url);
ksort($parameters);

$string1 = "";
foreach ($parameters as $key => $val){
  $string1 .= $key."=".$val."&";
}
$string1 = substr($string1,0,-1);
$signature = sha1($string1);

Copy after login

At this point, we have completed a configuration of wx.config. Next, we can freely set the small pictures and introduction content we just mentioned:

  wx.ready(function(){
    // 分享到朋友圈设置
    wx.onMenuShareTimeline({
      title: '测试标题', // 分享标题
      link: 'http://www.baidu.com', // 分享链接
      imgUrl: 'http://mp.weixin.qq.com/wiki/static/assets/dc5de672083b2ec495408b00b96c9aab.png', // 分享图标
      success: function () { 
        alert("分享成功");
      },
      cancel: function () { 
        alert("分享失败");
      }
    });
    // 分享给好友
    wx.onMenuShareAppMessage({
      title: '测试标题', // 分享标题
      desc: '测试分享描述', // 分享描述
      link: 'http://www.baidu.com', // 分享链接
      imgUrl: 'http://mp.weixin.qq.com/wiki/static/assets/dc5de672083b2ec495408b00b96c9aab.png', // 分享图标
      type: '', // 分享类型,music、video或link,不填默认为link
      dataUrl: '', // 如果type是music或video,则要提供数据链接,默认为空
      success: function () { 
        alert("分享成功");
      },
      cancel: function () { 
        alert("分享失败");
      }
    });
  })
Copy after login

In the middle, the values ​​​​success and cancel are also very commonly used. They represent the js callback after successful sharing and the callback after canceling sharing respectively. They are used to judge whether the user will display psychological test answers after sharing in the circle of friends. Small functions are still very useful.

The above is the entire content of this article. I hope it will be helpful to everyone’s study. I also hope that everyone will support Script Home.

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)

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

Describe the SOLID principles and how they apply to PHP development. Describe the SOLID principles and how they apply to PHP development. Apr 03, 2025 am 12:04 AM

The application of SOLID principle in PHP development includes: 1. Single responsibility principle (SRP): Each class is responsible for only one function. 2. Open and close principle (OCP): Changes are achieved through extension rather than modification. 3. Lisch's Substitution Principle (LSP): Subclasses can replace base classes without affecting program accuracy. 4. Interface isolation principle (ISP): Use fine-grained interfaces to avoid dependencies and unused methods. 5. Dependency inversion principle (DIP): High and low-level modules rely on abstraction and are implemented through dependency injection.

How to automatically set permissions of unixsocket after system restart? How to automatically set permissions of unixsocket after system restart? Mar 31, 2025 pm 11:54 PM

How to automatically set the permissions of unixsocket after the system restarts. Every time the system restarts, we need to execute the following command to modify the permissions of unixsocket: sudo...

How to debug CLI mode in PHPStorm? How to debug CLI mode in PHPStorm? Apr 01, 2025 pm 02:57 PM

How to debug CLI mode in PHPStorm? When developing with PHPStorm, sometimes we need to debug PHP in command line interface (CLI) mode...

Explain the concept of late static binding in PHP. Explain the concept of late static binding in PHP. Mar 21, 2025 pm 01:33 PM

Article discusses late static binding (LSB) in PHP, introduced in PHP 5.3, allowing runtime resolution of static method calls for more flexible inheritance.Main issue: LSB vs. traditional polymorphism; LSB's practical applications and potential perfo

How to send a POST request containing JSON data using PHP's cURL library? How to send a POST request containing JSON data using PHP's cURL library? Apr 01, 2025 pm 03:12 PM

Sending JSON data using PHP's cURL library In PHP development, it is often necessary to interact with external APIs. One of the common ways is to use cURL library to send POST�...

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

See all articles