php一个文件搞定微信jssdk配置


Posted in PHP onDecember 12, 2016

php一个文件搞定微信jssdk配置:

包括缓存,包括https通讯,获取微信access_token,签名什么的都有。但是防范性编程做得比较少,商业用的话,需要完善下代码。

使用姿势

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

服务端

GetWX.php

<?php
 include "lib/Cache.php";
 define($APPID, "……");
 define($SECRET, "……")
 if($_GET['Type'] == "access_token"){
//  echo getAccess_token();
 }
 else if($_GET['Type'] == "jsapi_ticket"){
//  echo getJsapi_ticket();
 }
 else if($_GET['Type'] == "config"){
  $jsapi_ticket = getJsapi_ticket();
  $nonceStr = "x".rand(10000,100000)."x"; //随机字符串
  $timestamp = time(); //时间戳
  $url = $_GET['url'];
  $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."×tamp=".$timestamp."&url=".$url;
  $sha1 = sha1($string1);
  return $sha1;
 }

 function getJsapi_ticket(){
  $cache = new Cache();
  $cache = new Cache(7000, 'cache/'); //需要创建cache文件夹存储缓存文件。
  //从缓存从读取键值 $key 的数据
  $jsapi_ticket = $cache -> get("jsapi_ticket");
  $access_token = getAccess_token();
  //如果没有缓存数据
  if ($jsapi_ticket == false) {
   $access_token = getAccess_token();
   $url = 'https://api.weixin.qq.com/cgi-bin/ticket/getticket'; 
   $data = array('type'=>'jsapi','access_token'=>$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, 'cache/');
  //从缓存从读取键值 $key 的数据
  $access_token = $cache -> get("access_token");

  //如果没有缓存数据
  if ($access_token == false) {
   $url = 'https://api.weixin.qq.com/cgi-bin/token'; 
   $data = array('grant_type'=>'client_credential','appid'=>$APPID,'secret'=>$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
不知道哪位写的源代码~

<?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, 'w');
  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'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
 }

}
?>

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持三水点靠木。

PHP 相关文章推荐
使用PHP模拟HTTP认证
Oct 09 PHP
php仿微信红包分配算法的实现方法
May 13 PHP
PHP实现JS中escape与unescape的方法
Jul 11 PHP
PHP转换文本框内容为HTML格式的方法
Jul 20 PHP
PHP session会话操作技巧小结
Sep 27 PHP
SAE实时日志接口SDK用法示例
Oct 09 PHP
php socket通信简单实现
Nov 18 PHP
Laravel中的Auth模块详解
Aug 17 PHP
PHP实现深度优先搜索算法(DFS,Depth First Search)详解
Sep 16 PHP
PHP基于openssl实现的非对称加密操作示例
Jan 11 PHP
php面试中关于面向对象的相关问题
Feb 13 PHP
PHP接口类(interface)的定义、特点和应用示例
May 18 PHP
php自定义扩展名获取函数示例
Dec 12 #PHP
DWZ+ThinkPHP开发时遇到的问题分析
Dec 12 #PHP
php中引用&amp;的用法分析【变量引用,函数引用,对象引用】
Dec 12 #PHP
简单谈谈PHP中的Reload操作
Dec 12 #PHP
php的laravel框架快速集成微信登录的方法
Dec 12 #PHP
php 遍历目录,生成目录下每个文件的md5值并写入到结果文件中
Dec 12 #PHP
php+ajax+json 详解及实例代码
Dec 12 #PHP
You might like
PHP 只允许指定IP访问(允许*号通配符过滤IP)
2014/07/08 PHP
Laravel接收前端ajax传来的数据的实例代码
2017/07/20 PHP
php定期拉取数据对比方法实例
2019/09/22 PHP
基于jquery的当鼠标滚轮到最底端继续加载新数据思路分享(多用于微博、空间、论坛 )
2011/10/10 Javascript
js验证模型自我实现的具体方法
2013/06/21 Javascript
JQuery中使用Ajax赋值给全局变量失败异常的解决方法
2014/08/18 Javascript
5种处理js跨域问题方法汇总
2014/12/04 Javascript
node.js中的fs.appendFile方法使用说明
2014/12/17 Javascript
jQuery多个input求和的实现方法
2015/02/12 Javascript
JS制作手机端自适应缩放显示
2015/06/11 Javascript
简介JavaScript中的setTime()方法的使用
2015/06/11 Javascript
JS处理json日期格式化问题
2015/10/01 Javascript
深入解析Backbone.js框架的依赖库Underscore.js的作用
2016/05/07 Javascript
JS实现图片局部放大或缩小的方法
2016/08/20 Javascript
JavaScript实现的CRC32函数示例
2016/11/23 Javascript
JavaScript实现倒计时跳转页面功能【实用】
2016/12/13 Javascript
javascript设计模式之中介者模式学习笔记
2017/02/15 Javascript
深入理解Angular中的依赖注入
2017/06/26 Javascript
JS实现基于Sketch.js模拟成群游动的蝌蚪运动动画效果【附demo源码下载】
2017/08/18 Javascript
详解基于node.js的脚手架工具开发经历
2019/01/28 Javascript
使用 Element UI Table 的 slot-scope方法
2019/10/10 Javascript
[49:08]Secret vs VP 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/20 DOTA
实例讲解Python中SocketServer模块处理网络请求的用法
2016/06/28 Python
Python面向对象程序设计OOP入门教程【类,实例,继承,重载等】
2019/01/05 Python
dataframe 按条件替换某一列中的值方法
2019/01/29 Python
判断python对象是否可调用的三种方式及其区别详解
2019/01/31 Python
使用Pandas的Series方法绘制图像教程
2019/12/04 Python
用python写爬虫简单吗
2020/07/28 Python
HTML5+CSS3网页加载进度条的实现,下载进度条的代码实例
2016/12/30 HTML / CSS
CSS3 二级导航菜单的制作的示例
2018/04/02 HTML / CSS
Omio葡萄牙:全欧洲低价大巴、火车和航班搜索和比价
2019/02/09 全球购物
易程科技软件测试笔试
2013/03/24 面试题
秋冬农业生产标语
2014/10/09 职场文书
青年岗位能手事迹材料
2014/12/23 职场文书
运动会通讯稿600字
2015/07/20 职场文书
Android开发手册Chip监听及ChipGroup监听
2022/06/10 Java/Android