php开发解决微信公众平台 token 验证失败问题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/dreamstone_xiaoqw/article/details/98997823

刚注册公司搞了个资质,学习开发微信企业号“寻溯科技”。

在提交服务器配置时,报错 token 验证失败,在segmentfault找到了@苏生不惑的回答,经验证可以解决问题。

if($_GET[echostr]){

$wechatObj->valid();

}else {
    $wechatObj->responseMsg();//?
}

如果是静态函数调用,可以这样:

if ((new self())->checkSignature()) {
	echo $echoStr;
	exit;
} else {
	(new self())->responseMsg(); //?
}

答案原始链接:https://segmentfault.com/q/1010000003042662

附:微信公众平台文档

<?php
/**
  * wechat php test
  */

//define your token
define("TOKEN", "weixin");
$wechatObj = new wechatCallbackapiTest();

if($_GET[echostr]){

$wechatObj->valid();
    
}else {
    
}

class wechatCallbackapiTest
{
    public function valid()
    {
        $echoStr = $_GET["echostr"];

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

    public function responseMsg()
    {
        //get post data, May be due to the different environments
        $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];

        //extract post data
        if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
                $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
                            <ToUserName><![CDATA[%s]]></ToUserName>
                            <FromUserName><![CDATA[%s]]></FromUserName>
                            <CreateTime>%s</CreateTime>
                            <MsgType><![CDATA[%s]]></MsgType>
                            <Content><![CDATA[%s]]></Content>
                            <FuncFlag>0</FuncFlag>
                            </xml>";             
                if(!empty( $keyword ))
                {
                    $msgType = "text";
                    $contentStr = "Welcome to wechat world!";
                    $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                    echo $resultStr;
                }else{
                    echo "Input something...";
                }

        }else {
            echo "";
            exit;
        }
    }
        
    private function checkSignature()
    {
        // you must define TOKEN by yourself
        if (!defined("TOKEN")) {
            throw new Exception('TOKEN is not defined!');
        }
        
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
                
        $token = TOKEN;
        $tmpArr = array($token, $timestamp, $nonce);
        // use SORT_STRING rule
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode( $tmpArr );
        $tmpStr = sha1( $tmpStr );
        
        if( $tmpStr == $signature ){
            return true;
        }else{
            return false;
        }
    }
}

?>

展开阅读全文

微信公众平台填写服务器配置提示“token验证失败

03-13

配置URL:http://域名/wxapi.ashxrn配置Token:123456rn在mvc项目中添加一般处理程序代码如下:rn[code=csharp]rnpublic class wxapi : IHttpHandlerrn rnrn public void ProcessRequest(HttpContext context)rn rn context.Response.ContentType = "text/plain";rn context.Response.Write("欢迎关注!");rn string postString = string.Empty;rn if (HttpContext.Current.Request.HttpMethod.ToUpper() == "POST")rn rn using (Stream stream = HttpContext.Current.Request.InputStream)rn rn Byte[] postBytes = new Byte[stream.Length];rn stream.Read(postBytes, 0, (Int32)stream.Length);rn postString = Encoding.UTF8.GetString(postBytes);rn rnrn if (!string.IsNullOrEmpty(postString))rn rn //Execute(postString);rn rn rn elsern rn Auth(); //微信接入的测试rn rn rnrn public bool IsReusablern rn getrn rn return false;rn rn rnrn /// rn /// 成为开发者的第一步,验证并相应服务器的数据rn /// rn private void Auth()rn rn //string token = ConfigurationManager.AppSettings["WeixinToken"];//从配置文件获取Tokenrn string token = "123456";rn if (string.IsNullOrEmpty(token))rn rn //LogTextHelper.Error(string.Format("WeixinToken 配置项没有配置!"));rn rnrn string echoString = HttpContext.Current.Request.QueryString["echoStr"];rn string signature = HttpContext.Current.Request.QueryString["signature"];rn string timestamp = HttpContext.Current.Request.QueryString["timestamp"];rn string nonce = HttpContext.Current.Request.QueryString["nonce"];rnrn if (CheckSignature(token, signature, timestamp, nonce))rn rn if (!string.IsNullOrEmpty(echoString))rn rn HttpContext.Current.Response.Write(echoString);rn HttpContext.Current.Response.End();rn rn rn rnrnrn /// rn /// 验证微信签名rn /// rn public bool CheckSignature(string token, string signature, string timestamp, string nonce)rn rn string[] ArrTmp = token, timestamp, nonce ;rnrn Array.Sort(ArrTmp);rn string tmpStr = string.Join("", ArrTmp);rnrn tmpStr = FormsAuthentication.HashPasswordForStoringInConfigFile(tmpStr, "SHA1");rn tmpStr = tmpStr.ToLower();rnrn if (tmpStr == signature)rn rn return true;rn rn elsern rn return false;rn rn rn rn[/code] 论坛

关于用java 二次微信公众平台开发token 总是验证失败

01-16

我用的阿里云服务器第一次token验证通过了,后来服务器换了系统(server2008->2003),就怎么也通不过token验证,总是失败。tomcat 可以正常启动,域名也已备案,用网页打开,显示404.这个问题已经困惑了我几天了,恳请给位帮忙指教。多谢了!!rn代码如下:rnpackage service;rnrnimport java.io.IOException;rnimport java.io.PrintWriter;rnimport java.util.Date;rnimport java.util.Map;rnrnimport javax.servlet.ServletException;rnimport javax.servlet.http.HttpServlet;rnimport javax.servlet.http.HttpServletRequest;rnimport javax.servlet.http.HttpServletResponse;rnrnimport message.resp.TextMessage;rnrnrnrnimport util.ValidationUtil;rnrnpublic class LoginServlet extends HttpServletrn @Overridern protected void doGet(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn rn System.out.println(get 请求);rn String signature = request.getParameter(signature);rn String timestamp = request.getParameter(timestamp);rn String nonce= request.getParameter(nonce);rn String echostr=request.getParameter(echostr);rn PrintWriter out=response.getWriter();rn System.out.println(signature+ signature);rn System.out.println(timestamp+ timestamp);rn System.out.println(nonce+ nonce);rn System.out.println(echostr+ echostr);rn 验证请求确认成功原样返回echostr参数内容,则接入生效,成为开发者成功,否则rn if(ValidationUtil.chechSignature(signature, timestamp, nonce))rn rn out.print(echostr);rn rn out.close();rn rn接受微信服务器发过来的xml数据包(通过post)形式发过来的rn rn @Overridern protected void doPost(HttpServletRequest request, HttpServletResponse response)rn throws ServletException, IOException rn String respXml=;响应的xml串rn request.setCharacterEncoding(utf-8);rn response.setCharacterEncoding(utf-8);rn String signature = request.getParameter(signature);rn String timestamp = request.getParameter(timestamp);rn String nonce= request.getParameter(nonce);rn PrintWriter out=response.getWriter();rn if(ValidationUtil.chechSignature(signature, timestamp, nonce))rn rn 接收并解析来自用户的xml数据包中的内容rn MapString,String reqMap=MessageUtil.parseXml(request);rn String ToUserName=reqMap.get(ToUserName);rn String FromUserName=reqMap.get(FromUserName);rn String MsgType=reqMap.get(MsgType);rn String Content=reqMap.get(Content);rn System.out.println(用户给公众号发的消息+Content);rn 开始响应消息给用户rn String respContent=;要响应的文本内容rn rn 构建一条文本消息rn TextMessage textMsg=new TextMessage();rn textMsg.setFromUserName(FromUserName);rn textMsg.setFromUserName(ToUserName);rn textMsg.setCreateTime(new Date().getTime());rn textMsg.setMsgType(MessageUtil.RESP_MESSAGE_TYPE_TEXT);rn if(MsgType.equals(MessageUtil.RESP_MESSAGE_TYPE_TEXT))rn rn respContent=大家好,来自工作公众平台的测试消息!!;rn rn textMsg.setContent(respContent);rn respXml=MessageUtil.messageToXml(textMsg);rn System.out.println(respXml+respXml);rn 接受打印的字符rn out.println(respXml);rn rn out.close();rn out=null;rnrn rn rnrnrnrnpackage util;rnrnimport java.security.MessageDigest;rnimport java.security.NoSuchAlgorithmException;rnimport java.util.Arrays;rnrn/**rn * 微信请求校验工具类rn * @author yrn *rn */rnpublic class ValidationUtil rnrnprivate static String token="wlghr0479";rnpublic static boolean chechSignature(String signature,String timestamp,String nonce)rnrn //1.将token,timestamp,nonce三个参数排序rn String[] str= new String[]token,timestamp,nonce;rn Arrays.sort(str);rn //2.将三个参数字符串接成一个字符串rn StringBuilder buff=new StringBuilder();rn for (int i=0;i>>4 & 0X0F];rntemp1[1]=Digit[mByte & 0X0F];rnString str=new String(temp1);rnreturn str;rnrnrnrnrnrnrnrnrnrnrn rn rn LoginServletrn service.LoginServletrn rnrn rn LoginServletrn /api/loginrn rn rn rn rn index.jsprn rn 论坛

微信接口配置token验证失败

11-06

我在新浪sae申请了账号之后创建了一个应用作为测试微信接口使用,代码用的都是官方教程的,但是在提交服务器配置的时候不是连接失败就是token验证失败,地址和token我确认没有填写错误,实在找不出原因。rn[img=https://img-bbs.csdn.net/upload/201511/06/1446818644_192009.png][/img]rnrnrn于是我在本地进行了一下测试,把新浪sae日志中心微信发送的get请求复制过来,加在本地的地址后面模仿微信的请求。rn[img=https://img-bbs.csdn.net/upload/201511/06/1446818721_536791.png][/img]rnrnrn结果发现,程序里接收的timestamp和nonce加上token的字符串按要求排序后和链接里的signature根本不相同。 rn[img=https://img-bbs.csdn.net/upload/201511/06/1446818673_786924.png][/img]rnrn有大神遇到过这个问题吗?还是我哪里操作不对?程序是照搬官方文档的啊。求指点啊!rnrn代码都是官方的啊。rn [code=php]valid();rnrnclass wechatCallbackapiTestrnrn public function valid()rn rn $echoStr = $_GET["echostr"];rnrn //valid signature , optionrn if($this->checkSignature())rn echo $echoStr;rn exit;rn rn rnrn public function responseMsg()rn rn //get post data, May be due to the different environmentsrn $postStr = $GLOBALS["HTTP_RAW_POST_DATA"];rnrn //extract post datarn if (!empty($postStr))rn rn $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);rn $fromUsername = $postObj->FromUserName;rn $toUsername = $postObj->ToUserName;rn $keyword = trim($postObj->Content);rn $time = time();rn $textTpl = "rn %srn %srn %srn %srn %srn 0rn "; rn if(!empty( $keyword ))rn rn $msgType = "text";rn $contentStr = "Welcome to wechat world!";rn $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);rn echo $resultStr;rn elsern echo "Input something...";rn rnrn else rn echo "";rn exit;rn rn rn rn private function checkSignature()rn rn $signature = $_GET["signature"];rn $timestamp = $_GET["timestamp"];rn $nonce = $_GET["nonce"]; rn rn $token = TOKEN;rn $tmpArr = array($token, $timestamp, $nonce);rn print_r($tmpArr);rn echo " ";rn sort($tmpArr,SORT_STRING);rn print_r($tmpArr);rn echo " ";rn $tmpStr = implode( $tmpArr );rn echo $tmpStr;rn echo " ";rn $tmpStr = sha1( $tmpStr );rn echo "sha1加密后:".$tmpStr;rn echo " ";rn echo 'signature:'.$signature;rn rn if( $tmpStr == $signature )rn return true;rn elsern return false;rn rn rnrnrn?>[/code]rn 论坛

没有更多推荐了,返回首页