Maison  >  Article  >  développement back-end  >  PHP utilise un fichier pour configurer WeChat jssdk

PHP utilise un fichier pour configurer WeChat jssdk

墨辰丷
墨辰丷original
2018-05-29 15:54:022489parcourir

Cet article présente principalement en détail comment PHP peut utiliser un fichier pour configurer WeChat jssdk. Il a une certaine valeur de référence. Les amis intéressés peuvent se référer à

PHP peut utiliser un fichier pour configurer WeChat jssdk :

Y compris le cache, y compris la communication https, l'obtention du jeton d'accès WeChat, la signature, etc. Cependant, relativement peu de programmes préventifs ont été réalisés pour une utilisation commerciale, le code doit être amélioré.

Utiliser les gestes


^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);
  }
 });
});


Serveur

GetWX.php


<?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;

 } 
?>


Cache.php

Je ne sais pas qui a écrit le code source ~


<?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
 }

}
?>


Ce qui précède est l'intégralité du contenu de cet article, j'espère qu'il sera utile à l'étude de chacun.


Recommandations associées :

Exemple de code détaillé de php pour configurer WeChat jssdk avec un seul fichier

configuration des cookies de configuration nginx de l'assembly phpmyadmin

méthode de configuration de l'environnement php et de débogageméthode


Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn