Home Backend Development PHP Tutorial Detailed explanation of the example code for configuring WeChat jssdk in one PHP file

Detailed explanation of the example code for configuring WeChat jssdk in one PHP file

Feb 27, 2017 am 09:45 AM

One php file to configure WeChat jssdk:
Including cache, including https communication, obtaining WeChat access_token, signature and so on. However, relatively little preventive programming has been done. For commercial use, the code needs to be improved.
Usage posture

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

^ajax(Common.ServerUrl + "GetWX.php", {

 data: {

  Type: "config",

  url: location.href.split('#')[0]

 },

 dataType: 'json',

 type: 'get',

 timeout: 5000,

 success: function(data) {

  wx.config({

   debug: true, // 开启调试模式,调用的所有api的返回值会在客户端alert出来,若要查看传入的参数,可以在pc端打开,参数信息会通过log打出,仅在pc端时才会打印。

   appId: '……', // 必填,公众号的唯一标识

   timestamp: data.timestamp, // 必填,生成签名的时间戳

   nonceStr: data.nonceStr, // 必填,生成签名的随机串

   signature: data.signature, // 必填,签名,见附录1

   jsApiList: ["getLocation"] // 必填,需要使用的JS接口列表,所有JS接口列表见附录2

  });

 }

})

wx.ready(function() {

 wx.getLocation({

  type: 'wgs84', // 默认为wgs84的gps坐标,如果要返回直接给openLocation用的火星坐标,可传入'gcj02'

  success: function(res) {

   var latitude = res.latitude; // 纬度,浮点数,范围为90 ~ -90

   var longitude = res.longitude; // 经度,浮点数,范围为180 ~ -180。

   plus2.storage.setItem("latitude", latitude);

   plus2.storage.setItem("longitude", longitude);

  }

 });

});

Copy after login

Server
GetWX.php

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

<?php

 include "lib/Cache.php";

 define($APPID, "……");

 define($SECRET, "……")

 if($_GET[&#39;Type&#39;] == "access_token"){

//  echo getAccess_token();

 }

 else if($_GET[&#39;Type&#39;] == "jsapi_ticket"){

//  echo getJsapi_ticket();

 }

 else if($_GET[&#39;Type&#39;] == "config"){

  $jsapi_ticket = getJsapi_ticket();

  $nonceStr = "x".rand(10000,100000)."x"; //随机字符串

  $timestamp = time(); //时间戳

  $url = $_GET[&#39;url&#39;];

  $signature = getSignature($jsapi_ticket,$nonceStr, $timestamp, $url);

 

  $result = array("jsapi_ticket"=>$jsapi_ticket, "nonceStr"=>$nonceStr,"timestamp"=>$timestamp,"url"=>$url,"signature"=>$signature);

  echo json_encode($result);

 }

 

 function getSignature($jsapi_ticket,$noncestr, $timestamp, $url){

  $string1 = "jsapi_ticket=".$jsapi_ticket."&noncestr=".$noncestr."&timestamp=".$timestamp."&url=".$url;

  $sha1 = sha1($string1);

  return $sha1;

 }

 

 function getJsapi_ticket(){

  $cache = new Cache();

  $cache = new Cache(7000, &#39;cache/&#39;); //需要创建cache文件夹存储缓存文件。

  //从缓存从读取键值 $key 的数据

  $jsapi_ticket = $cache -> get("jsapi_ticket");

  $access_token = getAccess_token();

  //如果没有缓存数据

  if ($jsapi_ticket == false) {

   $access_token = getAccess_token();

   $url = &#39;https://api.weixin.qq.com/cgi-bin/ticket/getticket&#39;;

   $data = array(&#39;type&#39;=>&#39;jsapi&#39;,&#39;access_token&#39;=>$access_token);

   $header = array();

   $response = json_decode(curl_https($url, $data, $header, 5));

   $jsapi_ticket = $response->ticket;

   //写入键值 $key 的数据

   $cache -> put("jsapi_ticket", $jsapi_ticket);

  }

  return $jsapi_ticket;

 }

 

 function getAccess_token(){

  $cache = new Cache();

  $cache = new Cache(7000, &#39;cache/&#39;);

  //从缓存从读取键值 $key 的数据

  $access_token = $cache -> get("access_token");

 

  //如果没有缓存数据

  if ($access_token == false) {

   $url = &#39;https://api.weixin.qq.com/cgi-bin/token&#39;;

   $data = array(&#39;grant_type&#39;=>&#39;client_credential&#39;,&#39;appid&#39;=>$APPID,&#39;secret&#39;=>$SECRET);

   $header = array();

 

   $response = json_decode(curl_https($url, $data, $header, 5));

   $access_token = $response->access_token;

   //写入键值 $key 的数据

   $cache -> put("access_token", $access_token);

  }

  return $access_token;

 }

 

 /** curl 获取 https 请求

 * @param String $url 请求的url

 * @param Array $data 要發送的數據

 * @param Array $header 请求时发送的header

 * @param int $timeout 超时时间,默认30s

 */

 function curl_https($url, $data=array(), $header=array(), $timeout=30){

  $ch = curl_init();

  curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查

  curl_setopt($ch, CURLOPT_URL, $url);

  curl_setopt($ch, CURLOPT_HTTPHEADER, $header);

  curl_setopt($ch, CURLOPT_POST, true);

  curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));

  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

  curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);

 

  $response = curl_exec($ch);

 

  if($error=curl_error($ch)){

  die($error);

  }

 

  curl_close($ch);

 

  return $response;

 

 }

?>

Copy after login

Cache.php
I don’t know who wrote the source code~

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

<?php

class Cache {

 private $cache_path;

 //path for the cache

 private $cache_expire;

 //seconds that the cache expires

 

 //cache constructor, optional expiring time and cache path

 public function Cache($exp_time = 3600, $path = "cache/") {

  $this -> cache_expire = $exp_time;

  $this -> cache_path = $path;

 }

 

 //returns the filename for the cache

 private function fileName($key) {

  return $this -> cache_path . md5($key);

 }

 

 //creates new cache files with the given data, $key== name of the cache, data the info/values to store

 public function put($key, $data) {

  $values = serialize($data);

  $filename = $this -> fileName($key);

  $file = fopen($filename, &#39;w&#39;);

  if ($file) {//able to create the file

   fwrite($file, $values);

   fclose($file);

  } else

   return false;

 }

 

 //returns cache for the given key

 public function get($key) {

  $filename = $this -> fileName($key);

  if (!file_exists($filename) || !is_readable($filename)) {//can&#39;t read the cache

   return false;

  }

  if (time() < (filemtime($filename) + $this -> cache_expire)) {//cache for the key not expired

   $file = fopen($filename, "r");

   // read data file

   if ($file) {//able to open the file

    $data = fread($file, filesize($filename));

    fclose($file);

    return unserialize($data);

    //return the values

   } else

    return false;

  } else

   return false;

  //was expired you need to create new

 }

 

}

?>

Copy after login

The above is the detailed explanation of the example code of WeChat jssdk configuration in one PHP file. For more related content, please pay attention to the PHP Chinese website (www.php. cn)!


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)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

PHP in Action: Real-World Examples and Applications PHP in Action: Real-World Examples and Applications Apr 14, 2025 am 12:19 AM

PHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.

PHP: A Key Language for Web Development PHP: A Key Language for Web Development Apr 13, 2025 am 12:08 AM

PHP is a scripting language widely used on the server side, especially suitable for web development. 1.PHP can embed HTML, process HTTP requests and responses, and supports a variety of databases. 2.PHP is used to generate dynamic web content, process form data, access databases, etc., with strong community support and open source resources. 3. PHP is an interpreted language, and the execution process includes lexical analysis, grammatical analysis, compilation and execution. 4.PHP can be combined with MySQL for advanced applications such as user registration systems. 5. When debugging PHP, you can use functions such as error_reporting() and var_dump(). 6. Optimize PHP code to use caching mechanisms, optimize database queries and use built-in functions. 7

PHP vs. Python: Understanding the Differences PHP vs. Python: Understanding the Differences Apr 11, 2025 am 12:15 AM

PHP and Python each have their own advantages, and the choice should be based on project requirements. 1.PHP is suitable for web development, with simple syntax and high execution efficiency. 2. Python is suitable for data science and machine learning, with concise syntax and rich libraries.

PHP vs. Other Languages: A Comparison PHP vs. Other Languages: A Comparison Apr 13, 2025 am 12:19 AM

PHP is suitable for web development, especially in rapid development and processing dynamic content, but is not good at data science and enterprise-level applications. Compared with Python, PHP has more advantages in web development, but is not as good as Python in the field of data science; compared with Java, PHP performs worse in enterprise-level applications, but is more flexible in web development; compared with JavaScript, PHP is more concise in back-end development, but is not as good as JavaScript in front-end development.

The Enduring Relevance of PHP: Is It Still Alive? The Enduring Relevance of PHP: Is It Still Alive? Apr 14, 2025 am 12:12 AM

PHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.

PHP and Python: Code Examples and Comparison PHP and Python: Code Examples and Comparison Apr 15, 2025 am 12:07 AM

PHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.

PHP vs. Python: Core Features and Functionality PHP vs. Python: Core Features and Functionality Apr 13, 2025 am 12:16 AM

PHP and Python each have their own advantages and are suitable for different scenarios. 1.PHP is suitable for web development and provides built-in web servers and rich function libraries. 2. Python is suitable for data science and machine learning, with concise syntax and a powerful standard library. When choosing, it should be decided based on project requirements.

See all articles