关于微信开发
什么是微信openid?
某个微信账号,针对某个公众号,的唯一标示,而且不变;针对不同的公众号会有不同的openid;
openid有什么用?
用来获取用户基本信息,头像、昵称、性别、地区等
*昵称带ios图标的需要urlencode转码保存入数据库,转码出来才能显示,不然会出现字符不能识别,昵称空白乱码
****************************************************************************************************************************************
一、关于微信开发
涉及到微信开发的,基本都是获取openid来确定用户的唯一性(用户的唯一id);剩下的只是看需求处理;
例如,如何微信登陆?数据库保存openid,通过获取openid和数据库的openid做匹配,也可以写进cookie,不需要每次都通过微信获取openid;
那么如何获取openid?
首先需要AppID(应用ID)和AppSecret(应用密钥),在微信后台可以获取,因为所有调用微信端的方法都需要用到
AppID(应用ID) xxxxxxxxxxxxxxxxxxx
AppSecret(应用密钥) xxxxxxxxxxxxxxxxxxxxxxxxxx
code列如:
define("APPID", "xxxxxxxxxxxxxxxxxxx");
define("SECRET", "xxxxxxxxxxxxxxxxxxxxxxxxxx");
// 不需要授权按钮,默认授权
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode("http://www.xxxxxxxx.com/?app=appxxx&act=bx_redirect_pre")."&response_type=code&scope=snsapi_base&state=STATE&connect_redirect=1#wechat_redirect";
// 如果要获取用户的详细信息(昵称、头像、地区等) (需授权按钮,scope设置为snsapi_userinfo)
$url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".APPID."&redirect_uri=".urlencode("http://www.xxxxxxxx.com/?app=appxxx&act=bx_redirect_pre")."&response_type=code&scope=snsapi_userinfo&state=STATEconnect_redirect=1#wechat_redirect"; header("Location: ".$url);
//通过code换取网页授权,获取到网页授权access_token的同时,也获取到了openid:
https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
//微信回调方法
function bx_redirect_pre() { $code = $_GET[‘code‘]; // 1. 用get方法得到回调的code if ( $code ) { // 2. 根据code获得,用户的openid $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".SECRET."&code=".$code."&grant_type=authorization_code"; $json = file_get_contents($url); $array = json_decode($json, true); $weixin_openid = $array[‘openid‘]; //这里获取微信openid $access_token = $array[‘access_token‘]; //网页授权接口调用凭证,注意:此access_token与基础支持的access_token不同 // openid已获取,随便折腾………………………… // 如果要获取用户的详细信息(昵称、头像、地区等) (需授权按钮,scope设置为snsapi_userinfo) // http:GET(请使用https协议) // https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN if ($weixin_openid) { // 获取用户信息 $user_info_url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$access_token."&openid=".$weixin_openid."&lang=zh_CN"; $user_info_json = json_decode(file_get_contents($user_info_url), true); $headimgurl = $user_info_json[‘headimgurl‘]; $unionid = $user_info_json[‘unionid‘]; $nickname = $user_info_json[‘nickname‘]; $nickname = urlencode($nickname); $sex = $user_info_json[‘sex‘]; $language = $user_info_json[‘language‘]; $city = $user_info_json[‘city‘]; $province = $user_info_json[‘province‘]; $privilege = ""; } } }
****************************************************************************************************************************************
二、微信公众平台消息接管操作
http://mp.weixin.qq.com/wiki/10/79502792eef98d6e0c6e1739da387346.html
1.首先配置微信接口,提供url链接,验证网站是否可以处理微信消息,在微信平台填写url进行验证
2.验证通过后就可以屏蔽这个方法,写入自己的程序替代验证方法,用于处理用户输入信息(可以是语音信息)
public function valid() { $echoStr = $_GET["echostr"]; //valid signature , option if($this->checkSignature()){ echo $echoStr; exit; } } private function checkSignature() { $signature = $_GET["signature"]; $timestamp = $_GET["timestamp"]; $nonce = $_GET["nonce"]; $token = TOKEN; $tmpArr = array($token, $timestamp, $nonce); sort($tmpArr, SORT_STRING); $tmpStr = implode( $tmpArr ); $tmpStr = sha1( $tmpStr ); if( $tmpStr == $signature ){ return true; }else{ return false; } } 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)) { $postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; if ( trim($postObj->Recognition) ) { //语音 $keyword = trim($postObj->Recognition); } else { $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>"; $msgType = "text"; //关注消息推送、或其他事件自定义 // $event = $postObj->Event; if ($event=="subscribe") { $contentStr = "这些推送刚关注的消息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; exit(); } $weixin_openid = $fromUsername; if( ! empty( $keyword ) ) { $contentStr = "推送的消息"; $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr); echo $resultStr; } } else { exit; } } //微信接口数据处理 public function jiekou() { //1.判断是否已经存入红包 //$this->valid(); $this->responseMsg(); }
问题:当服务器卡,或其他原因,会出现微信重复推送消息的问题
解决方法:
根据 MsgID 或 openid+createtime 来排除重复的推送请求,重复的推送 MsgID 或 openid+createtime 会相同
$postObj = simplexml_load_string($postStr, ‘SimpleXMLElement‘, LIBXML_NOCDATA); $fromUsername = $postObj->FromUserName; $toUsername = $postObj->ToUserName; $createTime = $postObj->CreateTime; $msgId = $postObj->MsgId;
****************************************************************************************************************************************
三、微信分享html页面
<?php require_once ("jssdk.php"); $jssdk = new JSSDK("wx059077272f261fb8", "c8902a348825a64627ffa7a05be036c9"); $signPackage = $jssdk->GetSignPackage(); ?>
<script type="text/javascript" src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script> <script> /* * 注意: * 1. 所有的JS接口只能在公众号绑定的域名下调用,公众号开发者需要先登录微信公众平台进入“公众号设置”的“功能设置”里填写“JS接口安全域名”。 * 2. 如果发现在 Android 不能分享自定义内容,请到官网下载最新的包覆盖安装,Android 自定义分享接口需升级至 6.0.2.58 版本及以上。 * 3. 常见问题及完整 JS-SDK 文档地址:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html * * 开发中遇到问题详见文档“附录5-常见错误及解决办法”解决,如仍未能解决可通过以下渠道反馈: * 邮箱地址:weixin-open@qq.com * 邮件主题:【微信JS-SDK反馈】具体问题 * 邮件内容说明:用简明的语言描述问题所在,并交代清楚遇到该问题的场景,可附上截屏图片,微信团队会尽快处理你的反馈。 */ wx.config({ debug: false, appId: ‘{$signPackage["appId"]}‘, timestamp: {$signPackage["timestamp"]}, nonceStr: ‘{$signPackage["nonceStr"]}‘, signature: ‘{$signPackage["signature"]}‘, jsApiList: [ // 所有要调用的 API 都要加到这个列表中 ‘checkJsApi‘, ‘onMenuShareTimeline‘, ‘onMenuShareAppMessage‘ ] }); wx.ready(function () { //获取“分享到朋友圈” wx.onMenuShareTimeline({ title: ‘‘, // 分享标题 link: "", // 分享链接 imgUrl: "share.jpg", // 分享图标 desc: ‘‘, // 分享描述 success: function () { //分享成功操作 }, cancel: function () { } }); //获取“分享给朋友” wx.onMenuShareAppMessage({ title: ‘‘, // 分享标题 link: "", // 分享链接 imgUrl: "share.jpg", // 分享图标 desc: ‘‘, // 分享描述 success: function () { //分享成功操作 }, cancel: function () { } }); }); </script>
附录文件jssdk.php
<?php class JSSDK { private $appId; private $appSecret; public function __construct($appId, $appSecret) { $this->appId = $appId; $this->appSecret = $appSecret; } public function getSignPackage() { $jsapiTicket = $this->getJsApiTicket(); // 注意 URL 一定要动态获取,不能 hardcode. $protocol = (!empty($_SERVER[‘HTTPS‘]) && $_SERVER[‘HTTPS‘] !== ‘off‘ || $_SERVER[‘SERVER_PORT‘] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$timestamp&url=$url"; $signature = sha1($string); $signPackage = array( "appId" => $this->appId, "nonceStr" => $nonceStr, "timestamp" => $timestamp, "url" => $url, "signature" => $signature, "rawString" => $string ); return $signPackage; } private function createNonceStr($length = 16) { $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"; $str = ""; for ($i = 0; $i < $length; $i++) { $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1); } return $str; } private function getJsApiTicket() { // jsapi_ticket 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("jsapi_ticket.json")); if ($data->expire_time < time()) { $accessToken = $this->getAccessToken(); // 如果是企业号用以下 URL 获取 ticket // $url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token=$accessToken"; $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=$accessToken"; $res = json_decode($this->httpGet($url)); $ticket = $res->ticket; if ($ticket) { $data->expire_time = time() + 7000; $data->jsapi_ticket = $ticket; $fp = fopen("jsapi_ticket.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $ticket = $data->jsapi_ticket; } return $ticket; } private function getAccessToken() { // access_token 应该全局存储与更新,以下代码以写入到文件中做示例 $data = json_decode(file_get_contents("access_token.json")); if ($data->expire_time < time()) { // 如果是企业号用以下URL获取access_token // $url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken?corpid=$this->appId&corpsecret=$this->appSecret"; $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$this->appId&secret=$this->appSecret"; $res = json_decode($this->httpGet($url)); $access_token = $res->access_token; if ($access_token) { $data->expire_time = time() + 7000; $data->access_token = $access_token; $fp = fopen("access_token.json", "w"); fwrite($fp, json_encode($data)); fclose($fp); } } else { $access_token = $data->access_token; } return $access_token; } private function httpGet($url) { $curl = curl_init(); curl_setopt($curl, CURLOPT_RETURNTRANSFER, true); curl_setopt($curl, CURLOPT_TIMEOUT, 500); curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false); curl_setopt($curl, CURLOPT_URL, $url); $res = curl_exec($curl); curl_close($curl); return $res; } }
关于微信开发
原文:http://my.oschina.net/AStar/blog/516110