最近在作一个公众号的工具,想使用公众号的权限,第一步就是受权,官方的文档说的不是很清楚,对于一个刚接触的开发者看起来是有点吃力的。php
说下两个比较重要的域名设置node
微信服务器会向这个地址推送一些信息包括(ComponentVerifyTicket、用户取消应用受权...)数据库
用户关注公众号或发送信息对应的信息会推送到这个地址。json
微信调用任何接口都须要component_verify_ticket,这一步也是折腾我最久的,主要推送过来的信息是加密的咱们须要将信息解密,
解密出component_verify_ticket将该ticket保存
后面须要用到api
消息加解密接入指引
这个页面上能够下载对应语言解密的demo,我选择的是php,貌似有点问题,本身改了下能够用了。服务器
public function parseMess() { $data = $_REQUEST; $postStr = $GLOBALS['HTTP_RAW_POST_DATA']; $encryptMsg = $postStr; $xml_tree = new DOMDocument(); $xml_tree->loadXML($encryptMsg); $array_e = $xml_tree->getElementsByTagName('Encrypt'); $encrypt = $array_e->item(0)->nodeValue; $msg_sign = $data['msg_signature']; $format = "<xml><ToUserName><![CDATA[toUser]]></ToUserName><Encrypt><![CDATA[%s]]></Encrypt></xml>"; $from_xml = sprintf($format, $encrypt); $msg = ''; $this->load->library('openweixin/wxBizMsgCrypt'); //改文件在php的demo包里面,加载过来就行 $pc = new WXBizMsgCrypt($this->token, $this->key, $this->appid); $timeStamp = $data['timestamp']; $nonce = $data['nonce']; $errCode = $pc->decryptMsg($msg_sign, $timeStamp, $nonce, $from_xml, $msg); if ($errCode == 0) { $postObj = simplexml_load_string($msg, "SimpleXMLElement", LIBXML_NOCDATA); $data = (array)$postObj; return $data; }
component_access_token这个参数也须要保存,后面也会重复用到。
这个参数的有效期是2个小时,因此定时每2小时执行下面的程序来更新component_access_token微信
public function getToken() { $ticket = $component_verify_ticket; //component_verify_ticket以前已经保存了,从数据库中获取 $post = array( 'component_appid' => $this->appid, //应用详情中的AppID 'component_appsecret' => $this->secret, //应用详情中的AppSecret 'component_verify_ticket' => $ticket, ); $ret=send_post('https://api.weixin.qq.com/cgi-bin/component/api_component_token', $post); $result = json_decode($ret, True); $component_access_token = $result['component_access_token']; //保存component_access_token echo 'success'; }
//发送post请求 function send_post($url, $post_data) { $postdata=json_encode($post_data); $options = array( 'http' => array( 'method' => 'POST', 'header' => 'Content-type:application/x-www-form-urlencoded', 'content' => $postdata, 'timeout' => 15 * 60 // 超时时间(单位:s) ) ); $context = stream_context_create($options); $result = file_get_contents($url, false, $context); return $result; }
有限时间是10分钟,因此定时执行每过10分钟来刷新一次pre_auth_codeapp
//刷新pre_auth_code public function refresh_pre() { $info = getData('system_config', array('type' => 'component_access_token'), array(), 1); $component_access_token = $info ['value']; $url = 'https://api.weixin.qq.com/cgi-bin/component/api_create_preauthcode?component_access_token='.$component_access_token; $post = array('component_appid' => $this->appid); $ret=send_post($url, $post); $result = json_decode($ret, True); $pre_auth_code = $result['pre_auth_code']; //保存pre_auth_code echo 'success'; }
这是个人我的网站今日Tech 喜欢科技新闻的朋友能够收藏下。工具