微信公众平台消息接口校验与消息接口响应例子

 更新时间:2016年11月25日 17:23  点击:1403
开发微信公众平台消息接口过程中,我们首先需要验证消息接口的有效性,验证通过后,才可以进行其他开发。首先我们来看一下微信公众平台给我的 PHP SDK

1、需要设置一个 TOKEN 信息

 代码如下 复制代码

efine("TOKEN", "weixin");

这个 TOKEN 信息可以由开发者自行设定。
2、有个 wechatCallbackapiTest 类,该类中含有3个方法:valid、responseMsg、checkSignature,其中方法valid、checkSignature是用作验证接口URL有效性用的,responseMsg是我们使用最多的方法,后续大部分的开发工作都会在这里完成。

在我们对接口进行有效性验证通过后,就不再需要进行验证了,这时我们就需要使用到 responseMsg 方法。那么如何保证接口验证通过后,不需要去切换其中的方法或修改其中的代码呢?

我是这样做的:

 代码如下 复制代码

public function indexAction()
{
 if(isset($_GET['echostr']))
 {
  $echoStr = $_GET["echostr"];

  //valid signature , option
  if($this->checkSignatureAction())
  {
   echo $echoStr;
   exit;
  }
 }
 else
 {
  $this->responseMsgAction();
 }

 return FALSE;
}

讲解一下:

因为在验证接口有效性时传递了个 echostr 参数,而在消息接口响应过程中没有这个参数,所有我们这里用这个参数来判断是验证接口还是接口响应:

 代码如下 复制代码

isset($_GET['echostr'])

很多时候需要输出一些 “纯” 字符串,也就是去除任何杂质(例如 Html 标签、空格之类的文本),输出的摘要就是如此,下面的这个函数可以帮你实现着一点:


例子

 代码如下 复制代码

function Bing_string_cleanr( $string ){
 $string = trim( $string );
 $string = strip_tags( $string );
 $string = htmlspecialchars( $string, ENT_QUOTES, 'UTF-8' );
 $string = str_replace( "n", "", $string );
 $string = trim( $string );
 return $string;
}

使用方法:

 

 代码如下 复制代码
echo Bing_string_cleanr( '内 容 <br> <html> asdfeiuonsdfje' );

删除空白

 代码如下 复制代码

<?php
$str = " This line containstliberal rn use of whitespace.nn";

// First remove the leading/trailing whitespace
//去掉开始和结束的空白
$str = trim($str);

// Now remove any doubled-up whitespace
//去掉跟随别的挤在一块的空白
$str = preg_replace('/s(?=s)/', '', $str);

// Finally, replace any non-space whitespace, with a space
//最后,去掉非space 的空白,用一个空格代替
$str = preg_replace('/[nrt]/', ' ', $str);

// Echo out: 'This line contains liberal use of whitespace.'
echo "<pre>{$str}</pre>";
?>

因为公司要做一个项目活动在微信中要有这一样款游戏活动了,但自己不会写于是网上找到了一个作者写的方案下面我整理了一下可以用同时也分享给大家。

本来是不想写这篇博文的,但又怕网友被坑,我还是写一下。

下载 jquery扩展wScratchPad.js, 原站的页面打不开,我这里提供一个下载地址 http://file.111cn.net/upload/2014/4/wScratchPad-1.4.4.zip
然后(冷静),一些没节操的博主,直接转别人的文章,验证的过程都省了,应该坑了不是小白。我这里修正一下

在这个扩展里面,怎么才能过去用户的刮开的面积

$("#wScratchPad3").wScratchPad({
 cursor:'',  //设置鼠标的样式
 color:'gray' ,  //设置覆盖物的颜色,跟image2功能相斥
 width:"300",
 height:"100",
 image: "" //顶部的图片
// 更多配置相关的选项请看源码
 scratchUp: function(e, percent){
 if(percent > 60)
 {
 alert("sss");
 }
 }
 });

从上面的代码,看的出来,这个跟网上所谓的教程不一样,这里获取刮开的范围用到函数不是

scratchMove()
而是
scratchUp()

为嘛?看源码

 
scratchFunc: function(e, $this, event)
        {
            e.pageX = Math.floor(e.pageX - $this.canvas_offset.left);
            e.pageY = Math.floor(e.pageY - $this.canvas_offset.top);
 
            $this['scratch' + event](e, $this);
 
            if(this.settings.realtimePercent || event == "Up") {
                if($this.settings['scratch' + event]) $this.settings['scratch' + event].apply($this, [e, $this.scratchPercentage($this)]);
            }
        }

这里这个获取函数绑定的UP 而不是move
注意这里的wScratchPad是1.4.4最新版。

最近,一个项目要求做交通银行在线支付,ecshop本身没有这方面的接口,于是通过一些时间的专研,做了一个插件出来。有好的东西,当然要分享,在此特地分享出来,希望能够帮助到跟我一样有需要的人,为大家减轻一下开发的负担,也多请大家指出一些好的方法和建议,相互的学习、进步!

在使用插件之前,请配置好交通银行在线支付的环境(具体安装方法,交行提供的demo会有,也不是很难,注意好细节就行)。安装好之后,请将includes文件夹和languages文件夹拷贝到ecshop站点的根目录覆盖(最下面有源码下载),最后进入后台的支付模块安装即可。


以下是调用的范例:

 代码如下 复制代码


include_once(ROOT_PATH . 'includes/modules/payment/bankcomm.php');

$order_['orderid'] = $order['order_sn'];

$order_['amount'] = $order['yd_price'];

$order_['orderMono'] = '测试'; //商家备注

$order_['goodsURL'] = "http://".$_SERVER['HTTP_HOST'].'/respond.php?code=bankcomm'; //取货URL

$pay_code = new bankcomm;

$pay_button = $pay_code->get_code($order_);

$order['pay_button'] = $pay_button; //即此时已经生成了一个支付按钮


源码(includes/modules/payment/bankcomm.php):

 

 代码如下 复制代码

<?php


/**

 * 交通银行在线支付插件 For Ecshop

 * Author: Reson

 * Date: 2014/03/31

 */


if (!defined('IN_ECS'))

{

die('Hacking attempt');

}


$payment_lang = ROOT_PATH . 'languages/' .$GLOBALS['_CFG']['lang']. '/payment/bankcomm.php';


if (file_exists($payment_lang))

{

global $_LANG;

include_once($payment_lang);

}


/* 模块的基本信息 */

if (isset($set_modules) && $set_modules == TRUE)

{

$i = isset($modules) ? count($modules) : 0;


/* 代码 */

$modules[$i]['code']    = basename(__FILE__, '.php');


/* 描述对应的语言项 */

$modules[$i]['desc']    = 'bankcomm_desc';


/* 是否支持货到付款 */

$modules[$i]['is_cod']  = '0';


/* 是否支持在线支付 */

$modules[$i]['is_online']  = '1';


/* 支付费用,由配送决定 */

$modules[$i]['pay_fee'] = '0';


/* 作者 */

$modules[$i]['author']  = 'Reson';


/* 网址 */

$modules[$i]['website'] = 'http://www.daixiaorui.com';


/* 版本号 */

$modules[$i]['version'] = '1.0.0.0';


/* 配置信息 */

$modules[$i]['config']  = array();

return;

}


/**

 * 类

 */

class bankcomm

{

/**

* 构造函数

*

* @return void

*/

function bankcomm()

{

}


function __construct()

{

$this->bankcomm();

}


/**

* 提交函数

*/

function get_code($order)

{

//获得表单传过来的数据

$param['interfaceVersion'] = '1.0.0.0'; //消息版本号*

$param['merID'] = '301310063009501'; //商户号 (测试号,后期可自行更改)

$param['orderid'] = $order['orderid']; //订单号*

$param['orderDate'] = local_date("Ymd",gmtime()); //商户订单日期* yyyyMMdd

$param['orderTime'] = local_date("His",gmtime()); //商户订单时间* HHmmss

$param['tranType'] = 0; //交易类别* 0:B2C

$param['amount'] = $order['amount']; //订单金额*

$param['curType'] = 'CNY'; //交易币种* 默认CNY

$param['orderContent'] = '';

$param['orderMono'] = $order['orderMono']; //商家备注

$param['phdFlag'] = ''; //物流配送标志

$param['notifyType'] = 1; //通知方式* 1 通知

$param['merURL'] = ''; 

$param['goodsURL'] = $order['goodsURL']; //取货URL

$param['jumpSeconds'] = '';

$param['payBatchNo'] = '';

$param['proxyMerName'] = '';

$param['proxyMerType'] = '';

$param['proxyMerCredentials'] = '';

$param['netType'] = 0; //渠道编号* 0:html渠道

$param['issBankNo'] = '';

$tranCode = "cb2200_sign";


htmlentities($param['orderMono'],"ENT_QUOTES","utf-8");

//连接字符串

$source = '';

foreach($param as $key=>$val){

if($key != 'issBankNo')

$source .= $val.'|';

}

$source = substr($source,0,strlen($source)-1);


//连接地址 www.111cn.net

$socketUrl = "tcp://127.0.0.1:8080"; //这里的端口根据自己配置的情况

$fp = stream_socket_client($socketUrl, $errno, $errstr, 30);

$retMsg="";

//

if (!$fp) {

echo "$errstr ($errno)<br /> ";

} else

{

$in  = "<?xml version='1.0' encoding='UTF-8'?>";

$in .= "<Message>";

$in .= "<TranCode>".$tranCode."</TranCode>";

$in .= "<MsgContent>".$source."</MsgContent>";

$in .= "</Message>";

fwrite($fp, $in);

while (!feof($fp)) {

$retMsg =$retMsg.fgets($fp, 1024); 

}

fclose($fp);

//解析返回xml

$dom = new DOMDocument;

$dom->loadXML($retMsg);

$retCode = $dom->getElementsByTagName('retCode');

$retCode_value = $retCode->item(0)->nodeValue;

$errMsg = $dom->getElementsByTagName('errMsg');

$errMsg_value = $errMsg->item(0)->nodeValue;

$signMsg = $dom->getElementsByTagName('signMsg');

$signMsg_value = $signMsg->item(0)->nodeValue;

$orderUrl = $dom->getElementsByTagName('orderUrl');

$orderUrl_value = $orderUrl->item(0)->nodeValue;

$MerchID = $dom->getElementsByTagName('MerchID');

$merID = $MerchID->item(0)->nodeValue;

//echo "retMsg=".$retMsg;

//echo $retCode_value." ".$errMsg_value." ".$signMsg_value." ".$orderUrl_value;

if($retCode_value != "0"){

//echo "交易返回码:".$retCode_value."<br>";

//echo "交易错误信息:" .$errMsg_value."<br>";

return "交易错误信息:" .$errMsg_value."<br>";

}else{

$param['signMsg_value'] = $signMsg_value;

$param['orderUrl_value'] = $orderUrl_value;

$form_code = $this->create_html($param); //创建提交表单

return $form_code;

}

}

/**

* 创建提交表单

*/

function create_html($param){

$pay_html ='<form name = "form1" method = "post" action = "'.$param['orderUrl_value'].'">

<input type = "hidden" name = "interfaceVersion" value = "'.$param['interfaceVersion'].'">

<input type = "hidden" name = "merID" value = "'.$param['merID'].'">

<input type = "hidden" name = "orderid" value = "'.$param['orderid'].'">

<input type = "hidden" name = "orderDate" value = "'.$param['orderDate'].'">

<input type = "hidden" name = "orderTime" value = "'.$param['orderTime'].'">

<input type = "hidden" name = "tranType" value = "'.$param['tranType'].'">

<input type = "hidden" name = "amount" value = "'.$param['amount'].'">

<input type = "hidden" name = "curType" value = "'.$param['curType'].'">

<input type = "hidden" name = "orderContent" value = "'.$param['orderContent'].'">

<input type = "hidden" name = "orderMono" value = "'.$param['orderMono'].'">

<input type = "hidden" name = "phdFlag" value = "'.$param['phdFlag'].'">

<input type = "hidden" name = "notifyType" value = "'.$param['notifyType'].'">

<input type = "hidden" name = "merURL" value = "'.$param['merURL'].'">

<input type = "hidden" name = "goodsURL" value = "'.$param['goodsURL'].'">

<input type = "hidden" name = "jumpSeconds" value = "'.$param['jumpSeconds'].'">

<input type = "hidden" name = "payBatchNo" value = "'.$param['payBatchNo'].'">

<input type = "hidden" name = "proxyMerName" value = "'.$param['proxyMerName'].'">

<input type = "hidden" name = "proxyMerType" value = "'.$param['proxyMerType'].'">

<input type = "hidden" name = "proxyMerCredentials" value = "'.$param['proxyMerCredentials'].'">

<input type = "hidden" name = "netType" value = "'.$param['netType'].'">

<input type = "hidden" name = "merSignMsg" value = "'.$param['signMsg_value'].'">

<input type = "hidden" name = "issBankNo" value = "'.$param['issBankNo'].'">

<input type="submit" value=" " class="pay_button" />

</form>';

return $pay_html;

}


/**

* 处理函数

*/

function respond()

$tranCode = "cb2200_verify";

$notifyMsg = $_REQUEST["notifyMsg"];  

$lastIndex = strripos($notifyMsg,"|");

$signMsg = substr($notifyMsg,$lastIndex+1); //签名信息

$srcMsg = substr($notifyMsg,0,$lastIndex+1);//原文

//连接地址

$socketUrl = "tcp://127.0.0.1:8080";

$fp = stream_socket_client($socketUrl, $errno, $errstr, 30);

$retMsg="";

if (!$fp) {

//echo "$errstr ($errno)<br /> ";

return false;

}else{

$in  = "<?xml version='1.0' encoding='UTF-8'?>";

$in .= "<Message>";

$in .= "<TranCode>".$tranCode."</TranCode>";

$in .= "<MsgContent>".$notifyMsg."</MsgContent>";

$in .= "</Message>";

fwrite($fp, $in);

while (!feof($fp)) {

$retMsg =$retMsg.fgets($fp, 1024); 

}

fclose($fp);

//解析返回xml

$dom = new DOMDocument;

$dom->loadXML($retMsg);

$retCode = $dom->getElementsByTagName('retCode');

$retCode_value = $retCode->item(0)->nodeValue;

$errMsg = $dom->getElementsByTagName('errMsg');

$errMsg_value = $errMsg->item(0)->nodeValue;

$signMsg = $dom->getElementsByTagName('signMsg');

$signMsg_value = $signMsg->item(0)->nodeValue;

if($retCode_value != ''){

//echo "交易返回码:".$retCode_value."<br>";

//echo "交易错误信息:" .$errMsg_value."<br>";

return false;

}else{

$arr = preg_split("/|{1,}/",$srcMsg); 

$pay_id = $arr[1];

$action_note = base64_decode($arr[16]);

// 完成订单。

order_paid($pay_id, PS_PAYED, $action_note);

//告诉用户交易完成

return true; 

}

///////////////// respond END ///////////////

}

}


?>


源码(languages/zh_cn/payment/bankcomm.php):


<?php


/**

 * 交通银行语言文件

 * by: Reson www.111cn.net

 * 2014/03/31

 */


global $_LANG;


$_LANG['bankcomm'] = '交通银行在线支付';

$_LANG['bankcomm_desc'] = '交通银行在线支付';

$_LANG['pay_button'] = '交通银行支付';


?>

 原文件址:http://www.daixiaorui.com/read/80.html

原文下载:http://file.111cn.net/upload/2014/4/13962827995368.zip

 

这是一个可以获取网页的html代码以及css,js,font和img资源的小工具,主要用来快速获取模板。如果你来不及设计UI或者看到不错的模板,则可以使用这个工具来抓取网页和提取资源文件。提取的内容会按相对路径来保存资源,因此你不必担心资源文件的错误url导入

首页 index.php:

 代码如下 复制代码

<!DOCTYPE html>
<html>
<head>
<meta name="author" content="flute" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>网页抓取器</title>
<link rel="stylesheet" href="main.css" media="all" />
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<h1>Web Grabber</h1>
<hr />
<div class="box">
  <h2>Url</h2>
  <div class="form">
    <input type="text" id="project" value="projectname" />
    <input type="text" id="url" value="http://" size="60" />
    <button class="submit" type="button">Get</button><span id="tip"></span>
  </div> www.111cn.net
</div>
<div class="box">
  <span class="all" id="saveall">Save All</span>
  <h2>List</h2>
  <ul id="list">
  </ul>
</div>
</body>
</html>

抓取页面代码 grab.php:

 代码如下 复制代码

<?PHP
 /*
 * flute
 * 2014/03/31
 */

 if(isset($_POST['url'])) {
  if(isset($_POST['project']) && !is_dir($_POST['project'])) mkdir($_POST['project'], 0777);
  echo json_encode(grab($_POST['url']));
 }

 function grab($url) {
  //$url = 'http://ldixing-wordpress.stor.sinaapp.com/uploads/leaves/test.html';
  $data = array();
  $file = preg_replace('/^.*//', '', $url);

  if(($content = file_get_contents($url)) !== false) {

   if(isset($_POST['project'])) file_put_contents($_POST['project'].'/'.$file, $content);

   $pattern = '/<link.*?href=('|")(.*?.css)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['css'] = $matches[2];
   }

   $pattern = '/<script.*?src=('|")(.*?.js)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['js'] = $matches[2];
   }

   $pattern = '/<img.*?src=('|")(.*?)1.*?>/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['img'] = $matches[2];
   }

   $pattern = '/url(('|"|s)(.*?)1)/i';
   if(preg_match_all($pattern, $content, $matches)) {
    $data['src'] = $matches[2];
   }
  }

  return $data;
 }

www.111cn.net

 function vardump($obj) {
  echo '<pre>';
  print_r($obj);
  echo '</pre>';
 }
?>

保存css,js,img等资源的页面 save.php:

 代码如下 复制代码

<?PHP
 /*
 *  flute
 *  2014/03/31
 */

 if(isset($_POST['url']) && isset($_POST['project']) && isset($_POST['domain'])) {
  extract($_POST);
  $url = preg_replace('/?.*$/', '', $url);
  $file = $url;
  $arr = explode('/', $file);
  $length = sizeof($arr);
  $filename = $arr[$length - 1];
  $root = $project;
  $dir = $root;

  if($domain == 'http') {
   $dir = $root.'/http';
   if(!is_dir($dir)) mkdir($dir, 0777);
  } else {
   $file = $domain.'/'.$url;
   for($i = 0; $i < $length -1; $i++) {
    if(!empty($arr[$i])) {
     $dir .= '/'.$arr[$i];
     if(!is_dir($dir)) mkdir($dir, 0777);
    }
   }
  }
  if(!file_exists($dir.'/'.$filename) || filesize($dir.'/'.$filename) == 0) {
   $content = file_get_contents($file);
   file_put_contents($dir.'/'.$filename, $content);
  }
 }
?>

使用方法:
1. 打开index页,输入项目名和要抓取的网址,网址必须是文件名结尾,如index.html;
2. 点Get按钮,得到当前页面所有的css,js,img等资源列表;
3. 点击css链接会获取css文件中的背景资源图片,附加在列表后头;
4. 点击Save All即可保存列表中所有的文件,并按相对路径生成;
5. 如果网页上有http远程文件,将会直接保存在http文件夹下;
6. Get和Save有时会失败,没关系重试几次即可。

[!--infotagslink--]

相关文章

  • c# 三种方法调用WebService接口

    这篇文章主要介绍了c# 三种方法调用WebService接口的相关资料,文中示例代码非常详细,帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-07
  • vue接口请求加密实例

    这篇文章主要介绍了vue接口请求加密实例,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-12
  • SpringBoot接口接收json参数解析

    这篇文章主要介绍了SpringBoot接口接收json参数解析,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-10-19
  • C#简单了解接口(Interface)使用方法

    这篇文章主要介绍了C#简单了解接口(Interface)使用方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-12-08
  • Feign接口方法返回值设置方式

    这篇文章主要介绍了Feign接口方法返回值设置方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教...2021-07-08
  • C# Rx的主要接口深入理解

    这篇文章主要介绍了C# Rx的主要接口深入理解的相关资料,需要的朋友可以参考下...2020-06-25
  • vue设置全局访问接口API地址操作

    这篇文章主要介绍了vue设置全局访问接口API地址操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-14
  • 如何设计一个安全的API接口详解

    在日常开发中,总会接触到各种接口,前后端数据传输接口,第三方业务平台接口,下面这篇文章主要给大家介绍了关于如何设计一个安全的API接口的相关资料,需要的朋友可以参考下...2021-08-12
  • php怎么写api接口?php写api接口的实例代码

    php怎么写api接口?本文介绍了php写api接口的实例代码,有兴趣的同学可以参考一下。 http://localhost/openUser.php?act=get_user_list&type=json在这里openUser.php...2017-07-06
  • vue配置多代理服务接口地址操作

    这篇文章主要介绍了vue配置多代理服务接口地址操作,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-09-08
  • C#处理和对接HTTP接口请求的方法

    下面通过四步给大家介绍了c#处理和对接http接口请求的方法,分步骤介绍的非常详细,具有参考借鉴价值,感兴趣的朋友一起看下吧...2020-06-25
  • Java接口DAO模式代码原理及应用详解

    这篇文章主要介绍了Java接口DAO模式代码原理及应用详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-11-03
  • C#实现两接口中同名方法实例分析

    这篇文章主要介绍了C#实现两接口中同名方法,涉及C#接口与方法的相关操作技巧,需要的朋友可以参考下...2020-06-25
  • c# 接口使用实例

    这篇文章主要介绍了c#接口使用的实例,文中讲解非常细致,代码帮助大家更好的理解和学习,感兴趣的朋友可以了解下...2020-07-17
  • SpringData Repository接口用法解析

    这篇文章主要介绍了SpringData Repository接口用法解析,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下...2020-08-27
  • 微信小程序通过api接口将json数据展现到小程序示例

    这篇文章主要介绍了微信小程序通过api接口将json数据展现到小程序示例,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧...2017-01-23
  • 详解c# 接口IDisposable的用法

    这篇文章主要介绍了详解c# 接口IDisposable的用法,帮助大家更好的理解和学习c#,感兴趣的朋友可以了解下...2020-12-08
  • 深入浅析Restful接口的两种使用方式

    restful接口常用的两种方式是get和post.接下来通过本文给大家介绍Restful接口的两种使用方式,本文给大家介绍的非常详细,需要的朋友参考下吧...2020-06-25
  • Python优化列表接口进行分页示例实现

    最近,在做测试开发平台的时候,需要对测试用例的列表进行后端分页,在实际去写代码和测试的过程中,发现这里面还是有些细节的,故想复盘一下...2021-09-29
  • vue 接口请求地址前缀本地开发和线上开发设置方式

    这篇文章主要介绍了vue 接口请求地址前缀本地开发和线上开发设置方式,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧...2020-08-13