当前位置:Gxlcms > php框架 > 微信API接口大全

微信API接口大全

时间:2021-07-01 10:21:17 帮助过:116人阅读

微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中。
微信支付、微信红包、微信卡券、微信小店。

1. [代码]index.php    

  1. <?php
  2. include_once 'lib.inc.php';
  3. $wcObj = new WeChat("YOUKUIYUAN");
  4. $wcObj->wcValid();

2. [代码]微信入口类    

  1. <?php
  2. /**
  3. * Description of wechat
  4. *
  5. * @author Administrator
  6. */
  7. class WeChat extends WxApi{
  8. public $token = "";
  9. //put your code here
  10. public function __construct($token = "") {
  11. parent::__construct();
  12. $this->token = $token;
  13. }
  14. public function wcCheckSignature(){
  15. try{
  16. if (empty($this->token)) {
  17. throw new Exception('TOKEN is not defined!');
  18. }
  19. $signature = $_GET["signature"];
  20. $timestamp = $_GET["timestamp"];
  21. $nonce = $_GET["nonce"];
  22. $token = $this->token;
  23. $tmpArr = array($token, $timestamp, $nonce);
  24. // use SORT_STRING rule
  25. sort($tmpArr, SORT_STRING);
  26. $tmpStr = implode( $tmpArr );
  27. $tmpStr = sha1( $tmpStr );
  28. if( $tmpStr == $signature ){
  29. return true;
  30. }else{
  31. return false;
  32. }
  33. }
  34. catch (Exception $e) {
  35. echo 'Message: ' .$e->getMessage();
  36. }
  37. }
  38. public function wcValid(){
  39. $echoStr = isset($_GET["echostr"]) && !empty($_GET["echostr"]) ? addslashes($_GET["echostr"]) : NULL;
  40. if(is_null($echoStr)){
  41. $this->wcMsg();
  42. }
  43. else{
  44. //valid signature , option
  45. if($this->wcCheckSignature()){
  46. echo $echoStr;
  47. exit;
  48. }
  49. else{
  50. exit();
  51. }
  52. }
  53. }
  54. public function wcMsg(){
  55. //get post data, May be due to the different environments
  56. $postStr = isset($GLOBALS["HTTP_RAW_POST_DATA"]) && !empty($GLOBALS["HTTP_RAW_POST_DATA"]) ? $GLOBALS["HTTP_RAW_POST_DATA"] : "";
  57. if(!empty($postStr)){
  58. libxml_disable_entity_loader(true);
  59. $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
  60. $this->zcLog(TRUE,$postObj);
  61. $fromUsername = $postObj->FromUserName;
  62. $toUsername = $postObj->ToUserName;
  63. $MsgType = $postObj->MsgType;
  64. if($MsgType == 'event'){//执行事件相应
  65. $Event = $postObj->Event;
  66. switch ($Event) {
  67. case 'subscribe'://关注
  68. break;
  69. case 'unsubscribe'://取消关注
  70. break;
  71. case 'SCAN'://扫描
  72. break;
  73. case 'LOCATION'://地址
  74. break;
  75. case 'CLICK'://点击时间
  76. break;
  77. case 'VIEW'://跳转
  78. break;
  79. case 'card_pass_check'://卡券审核通过
  80. break;
  81. case 'card_not_pass_check'://卡券审核失败
  82. break;
  83. case 'user_get_card'://用户领取卡券
  84. break;
  85. case 'user_del_card'://用户删除卡券
  86. break;
  87. case 'user_view_card'://用户浏览会员卡
  88. break;
  89. case 'user_consume_card'://用户核销卡券
  90. break;
  91. case 'merchant_order'://微小店用户下单付款
  92. break;
  93. default:
  94. break;
  95. }
  96. }
  97. else{
  98. switch ($MsgType) {
  99. case 'text'://文本格式
  100. break;
  101. case 'image'://图片格式
  102. break;
  103. case 'voice'://声音
  104. break;
  105. case 'video'://视频
  106. break;
  107. case 'shortvideo'://小视频
  108. break;
  109. case 'location'://上传地理位置
  110. break;
  111. case 'link'://链接相应
  112. break;
  113. default:
  114. break;
  115. }
  116. }
  117. ////////////////////////////////////////////////////////////////////
  118. $keyword = trim($postObj->Content);
  119. $time = time();
  120. $textTpl = "<xml>
  121. <ToUserName><![CDATA[%s]]></ToUserName>
  122. <FromUserName><![CDATA[%s]]></FromUserName>
  123. <CreateTime>%s</CreateTime>
  124. <MsgType><![CDATA[%s]]></MsgType>
  125. <Content><![CDATA[%s]]></Content>
  126. <FuncFlag>0</FuncFlag>
  127. </xml>";
  128. if(!empty( $keyword )){
  129. $msgType = "text";
  130. $contentStr = "Welcome to wechat world!";
  131. $resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
  132. echo $resultStr;
  133. }
  134. else{
  135. echo "Input something...";
  136. }
  137. ////////////////////////////////////////////////////////////////////
  138. }
  139. else{
  140. echo "暂时没有任何信息!";
  141. exit;
  142. }
  143. }
  144. //日志LOG
  145. public function zcLog($errcode , $errmsg){
  146. $this->returnAy = array();
  147. $this->returnAy['errcode'] = $errcode;
  148. $this->returnAy['errmsg'] = $errmsg;
  149. $this->returnAy['errtime'] = date("Y-m-d H:i:s",time());
  150. $logfile = fopen("logfile_".date("Ymd",time()).".txt", "a+");
  151. $txt = json_encode($this->returnAy)."\n";
  152. fwrite($logfile, $txt);
  153. fclose($logfile);
  154. //return $this->returnAy;
  155. }
  156. }

3. [代码]微信操作类 - 更新了自定义菜单部分    

  1. <?php
  2. /********************************************************
  3. * @author Kyler You <QQ:2444756311>
  4. * @link http://mp.weixin.qq.com/wiki/home/index.html
  5. * @version 2.0.1
  6. * @uses $wxApi = new WxApi();
  7. * @package 微信API接口 陆续会继续进行更新
  8. ********************************************************/
  9. class WxApi {
  10. //const appId = "";
  11. //const appSecret = "";
  12. const appId = "";
  13. const appSecret = "";
  14. //const mchid = ""; //商户号
  15. //const privatekey = ""; //私钥
  16. public $parameters = array();
  17. public function __construct(){
  18. }
  19. /****************************************************
  20. * 微信提交API方法,返回微信指定JSON
  21. ****************************************************/
  22. public function wxHttpsRequest($url,$data = null){
  23. $curl = curl_init();
  24. curl_setopt($curl, CURLOPT_URL, $url);
  25. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
  26. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
  27. if (!empty($data)){
  28. curl_setopt($curl, CURLOPT_POST, 1);
  29. curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
  30. }
  31. curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
  32. $output = curl_exec($curl);
  33. curl_close($curl);
  34. return $output;
  35. }
  36. /****************************************************
  37. * 微信带证书提交数据 - 微信红包使用
  38. ****************************************************/
  39. public function wxHttpsRequestPem($url, $vars, $second=30,$aHeader=array()){
  40. $ch = curl_init();
  41. //超时时间
  42. curl_setopt($ch,CURLOPT_TIMEOUT,$second);
  43. curl_setopt($ch,CURLOPT_RETURNTRANSFER, 1);
  44. //这里设置代理,如果有的话
  45. //curl_setopt($ch,CURLOPT_PROXY, '10.206.30.98');
  46. //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
  47. curl_setopt($ch,CURLOPT_URL,$url);
  48. curl_setopt($ch,CURLOPT_SSL_VERIFYPEER,false);
  49. curl_setopt($ch,CURLOPT_SSL_VERIFYHOST,false);
  50. //以下两种方式需选择一种
  51. //第一种方法,cert 与 key 分别属于两个.pem文件
  52. //默认格式为PEM,可以注释
  53. curl_setopt($ch,CURLOPT_SSLCERTTYPE,'PEM');
  54. curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/apiclient_cert.pem');
  55. //默认格式为PEM,可以注释
  56. curl_setopt($ch,CURLOPT_SSLKEYTYPE,'PEM');
  57. curl_setopt($ch,CURLOPT_SSLKEY,getcwd().'/apiclient_key.pem');
  58. curl_setopt($ch,CURLOPT_CAINFO,'PEM');
  59. curl_setopt($ch,CURLOPT_CAINFO,getcwd().'/rootca.pem');
  60. //第二种方式,两个文件合成一个.pem文件
  61. //curl_setopt($ch,CURLOPT_SSLCERT,getcwd().'/all.pem');
  62. if( count($aHeader) >= 1 ){
  63. curl_setopt($ch, CURLOPT_HTTPHEADER, $aHeader);
  64. }
  65. curl_setopt($ch,CURLOPT_POST, 1);
  66. curl_setopt($ch,CURLOPT_POSTFIELDS,$vars);
  67. $data = curl_exec($ch);
  68. if($data){
  69. curl_close($ch);
  70. return $data;
  71. }
  72. else {
  73. $error = curl_errno($ch);
  74. echo "call faild, errorCode:$error\n";
  75. curl_close($ch);
  76. return false;
  77. }
  78. }
  79. /****************************************************
  80. * 微信获取AccessToken 返回指定微信公众号的at信息
  81. ****************************************************/
  82. public function wxAccessToken($appId = NULL , $appSecret = NULL){
  83. $appId = is_null($appId) ? self::appId : $appId;
  84. $appSecret = is_null($appSecret) ? self::appSecret : $appSecret;
  85. $data = json_decode(file_get_contents("access_token.json"));
  86. if ($data->expire_time < time()) {
  87. //echo $appId,$appSecret;
  88. $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$appId."&secret=".$appSecret;
  89. $result = $this->wxHttpsRequest($url);
  90. //print_r($result);
  91. $jsoninfo = json_decode($result, true);
  92. $access_token = $jsoninfo["access_token"];
  93. if ($access_token) {
  94. $data->expire_time = time() + 7000;
  95. $data->access_token = $access_token;
  96. $fp = fopen("access_token.json", "w");
  97. fwrite($fp, json_encode($data));
  98. fclose($fp);
  99. }
  100. }
  101. else {
  102. $access_token = $data->access_token;
  103. }
  104. return $access_token;
  105. }
  106. /****************************************************
  107. * 微信获取AccessToken 返回指定微信公众号的at信息
  108. ****************************************************/
  109. public function wxJsApiTicket($appId = NULL , $appSecret = NULL){
  110. $appId = is_null($appId) ? self::appId : $appId;
  111. $appSecret = is_null($appSecret) ? self::appSecret : $appSecret;
  112. $data = json_decode(file_get_contents("jsapi_ticket.json"));
  113. if ($data->expire_time < time()) {
  114. $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?type=jsapi&access_token=".$this->wxAccessToken();
  115. $result = $this->wxHttpsRequest($url);
  116. $jsoninfo = json_decode($result, true);
  117. $ticket = $jsoninfo['ticket'];
  118. if ($ticket) {
  119. $data->expire_time = time() + 7000;
  120. $data->jsapi_ticket = $ticket;
  121. $fp = fopen("jsapi_ticket.json", "w");
  122. fwrite($fp, json_encode($data));
  123. fclose($fp);
  124. }
  125. }
  126. else {
  127. $ticket = $data->jsapi_ticket;
  128. }
  129. return $ticket;
  130. }
  131. /****************************************************
  132. * 微信通过OPENID获取用户信息,返回数组
  133. ****************************************************/
  134. public function wxGetUser($openId){
  135. $wxAccessToken = $this->wxAccessToken();
  136. $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$wxAccessToken."&openid=".$openId."&lang=zh_CN";
  137. $result = $this->wxHttpsRequest($url);
  138. $jsoninfo = json_decode($result, true);
  139. return $jsoninfo;
  140. }
  141. /****************************************************
  142. * 微信生成二维码ticket
  143. ****************************************************/
  144. public function wxQrCodeTicket($jsonData){
  145. $wxAccessToken = $this->wxAccessToken();
  146. $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$wxAccessToken;
  147. $result = $this->wxHttpsRequest($url,$jsonData);
  148. return $result;
  149. }
  150. /****************************************************
  151. * 微信通过ticket生成二维码
  152. ****************************************************/
  153. public function wxQrCode($ticket){
  154. $url = "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=" . urlencode($ticket);
  155. return $url;
  156. }
  157. /****************************************************
  158. * 发送自定义的模板消息
  159. ****************************************************/
  160. public function wxSetSend($touser, $template_id, $url, $data, $topcolor = '#7B68EE'){
  161. $template = array(
  162. 'touser' => $touser,
  163. 'template_id' => $template_id,
  164. 'url' => $url,
  165. 'topcolor' => $topcolor,
  166. 'data' => $data
  167. );
  168. $jsonData = json_encode($template);
  169. $result = $this->wxSendTemplate($jsonData);
  170. return $result;
  171. }
  172. /****************************************************
  173. * 微信设置OAUTH跳转URL,返回字符串信息 - SCOPE = snsapi_base //验证时不返回确认页面,只能获取OPENID
  174. ****************************************************/
  175. public function wxOauthBase($redirectUrl,$state = "",$appId = NULL){
  176. $appId = is_null($appId) ? self::appId : $appId;
  177. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_base&state=".$state."#wechat_redirect";
  178. return $url;
  179. }
  180. /****************************************************
  181. * 微信设置OAUTH跳转URL,返回字符串信息 - SCOPE = snsapi_userinfo //获取用户完整信息
  182. ****************************************************/
  183. public function wxOauthUserinfo($redirectUrl,$state = "",$appId = NULL){
  184. $appId = is_null($appId) ? self::appId : $appId;
  185. $url = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=".$appId."&redirect_uri=".$redirectUrl."&response_type=code&scope=snsapi_userinfo&state=".$state."#wechat_redirect";
  186. return $url;
  187. }
  188. /****************************************************
  189. * 微信OAUTH跳转指定URL
  190. ****************************************************/
  191. public function wxHeader($url){
  192. header("location:".$url);
  193. }
  194. /****************************************************
  195. * 微信通过OAUTH返回页面中获取AT信息
  196. ****************************************************/
  197. public function wxOauthAccessToken($code,$appId = NULL , $appSecret = NULL){
  198. $appId = is_null($appId) ? self::appId : $appId;
  199. $appSecret = is_null($appSecret) ? self::appSecret : $appSecret;
  200. $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$appId."&secret=".$appSecret."&code=".$code."&grant_type=authorization_code";
  201. $result = $this->wxHttpsRequest($url);
  202. //print_r($result);
  203. $jsoninfo = json_decode($result, true);
  204. //$access_token = $jsoninfo["access_token"];
  205. return $jsoninfo;
  206. }
  207. /****************************************************
  208. * 微信通过OAUTH的Access_Token的信息获取当前用户信息 // 只执行在snsapi_userinfo模式运行
  209. ****************************************************/
  210. public function wxOauthUser($OauthAT,$openId){
  211. $url = "https://api.weixin.qq.com/sns/userinfo?access_token=".$OauthAT."&openid=".$openId."&lang=zh_CN";
  212. $result = $this->wxHttpsRequest($url);
  213. $jsoninfo = json_decode($result, true);
  214. return $jsoninfo;
  215. }
  216. /****************************************************
  217. * 创建自定义菜单
  218. ****************************************************/
  219. public function wxMenuCreate($jsonData){
  220. $wxAccessToken = $this->wxAccessToken();
  221. $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $wxAccessToken;
  222. $result = $this->wxHttpsRequest($url,$jsonData);
  223. $jsoninfo = json_decode($result, true);
  224. return $jsoninfo;
  225. }
  226. /****************************************************
  227. * 获取自定义菜单
  228. ****************************************************/
  229. public function wxMenuGet(){
  230. $wxAccessToken = $this->wxAccessToken();
  231. $url = "https://api.weixin.qq.com/cgi-bin/menu/get?access_token=" . $wxAccessToken;
  232. $result = $this->wxHttpsRequest($url);
  233. $jsoninfo = json_decode($result, true);
  234. return $jsoninfo;
  235. }
  236. /****************************************************
  237. * 删除自定义菜单
  238. ****************************************************/
  239. public function wxMenuDelete(){
  240. $wxAccessToken = $this->wxAccessToken();
  241. $url = "https://api.weixin.qq.com/cgi-bin/menu/delete?access_token=" . $wxAccessToken;
  242. $result = $this->wxHttpsRequest($url);
  243. $jsoninfo = json_decode($result, true);
  244. return $jsoninfo;
  245. }
  246. /****************************************************
  247. * 获取第三方自定义菜单
  248. ****************************************************/
  249. public function wxMenuGetInfo(){
  250. $wxAccessToken = $this->wxAccessToken();
  251. $url = "https://api.weixin.qq.com/cgi-bin/get_current_selfmenu_info?access_token=" . $wxAccessToken;
  252. $result = $this->wxHttpsRequest($url);
  253. $jsoninfo = json_decode($result, true);
  254. return $jsoninfo;
  255. }
  256. /*****************************************************
  257. * 生成随机字符串 - 最长为32位字符串
  258. *****************************************************/
  259. public function wxNonceStr($length = 16, $type = FALSE) {
  260. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  261. $str = "";
  262. for ($i = 0; $i < $length; $i++) {
  263. $str .= substr($chars, mt_rand(0, strlen($chars) - 1), 1);
  264. }
  265. if($type == TRUE){
  266. return strtoupper(md5(time() . $str));
  267. }
  268. else {
  269. return $str;
  270. }
  271. }
  272. /*******************************************************
  273. * 微信商户订单号 - 最长28位字符串
  274. *******************************************************/
  275. public function wxMchBillno($mchid = NULL) {
  276. if(is_null($mchid)){
  277. if(self::mchid == "" || is_null(self::mchid)){
  278. $mchid = time();
  279. }
  280. else{
  281. $mchid = self::mchid;
  282. }
  283. }
  284. else{
  285. $mchid = substr(addslashes($mchid),0,10);
  286. }
  287. return date("Ymd",time()).time().$mchid;
  288. }
  289. /*******************************************************
  290. * 微信格式化数组变成参数格式 - 支持url加密
  291. *******************************************************/
  292. public function wxSetParam($parameters){
  293. if(is_array($parameters) && !empty($parameters)){
  294. $this->parameters = $parameters;
  295. return $this->parameters;
  296. }
  297. else{
  298. return array();
  299. }
  300. }
  301. /*******************************************************
  302. * 微信格式化数组变成参数格式 - 支持url加密
  303. *******************************************************/
  304. public function wxFormatArray($parameters = NULL, $urlencode = FALSE){
  305. if(is_null($parameters)){
  306. $parameters = $this->parameters;
  307. }
  308. $restr = "";//初始化空
  309. ksort($parameters);//排序参数
  310. foreach ($parameters as $k => $v){//循环定制参数
  311. if (null != $v && "null" != $v && "sign" != $k) {
  312. if($urlencode){//如果参数需要增加URL加密就增加,不需要则不需要
  313. $v = urlencode($v);
  314. }
  315. $restr .= $k . "=" . $v . "&";//返回完整字符串
  316. }
  317. }
  318. if (strlen($restr) > 0) {//如果存在数据则将最后“&”删除
  319. $restr = substr($restr, 0, strlen($restr)-1);
  320. }
  321. return $restr;//返回字符串
  322. }
  323. /*******************************************************
  324. * 微信MD5签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
  325. *******************************************************/
  326. public function wxMd5Sign($content, $privatekey){
  327. try {
  328. if (is_null($privatekey)) {
  329. throw new Exception("财付通签名key不能为空!");
  330. }
  331. if (is_null($content)) {
  332. throw new Exception("财付通签名内容不能为空");
  333. }
  334. $signStr = $content . "&key=" . $privatekey;
  335. return strtoupper(md5($signStr));
  336. }
  337. catch (Exception $e)
  338. {
  339. die($e->getMessage());
  340. }
  341. }
  342. /*******************************************************
  343. * 微信Sha1签名生成器 - 需要将参数数组转化成为字符串[wxFormatArray方法]
  344. *******************************************************/
  345. public function wxSha1Sign($content){
  346. try {
  347. if (is_null($content)) {
  348. throw new Exception("签名内容不能为空");
  349. }
  350. //$signStr = $content;
  351. return sha1($content);
  352. }
  353. catch (Exception $e)
  354. {
  355. die($e->getMessage());
  356. }
  357. }
  358. /*******************************************************
  359. * 微信jsApi整合方法 - 通过调用此方法获得jsapi数据
  360. *******************************************************/
  361. public function wxJsapiPackage(){
  362. $jsapi_ticket = $this->wxJsApiTicket();
  363. // 注意 URL 一定要动态获取,不能 hardcode.
  364. $protocol = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://";
  365. $url = $protocol.$_SERVER["HTTP_HOST"].$_SERVER["REQUEST_URI"];
  366. $timestamp = time();
  367. $nonceStr = $this->wxNonceStr();
  368. $signPackage = array(
  369. "jsapi_ticket" => $jsapi_ticket,
  370. "nonceStr" => $nonceStr,
  371. "timestamp" => $timestamp,
  372. "url" => $url
  373. );
  374. // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  375. $rawString = "jsapi_ticket=$jsapi_ticket&noncestr=$nonceStr×tamp=$timestamp&url=$url";
  376. //$rawString = $this->wxFormatArray($signPackage);
  377. $signature = $this->wxSha1Sign($rawString);
  378. $signPackage['signature'] = $signature;
  379. $signPackage['rawString'] = $rawString;
  380. $signPackage['appId'] = self::appId;
  381. return $signPackage;
  382. }
  383. /*******************************************************
  384. * 将数组解析XML - 微信红包接口
  385. *******************************************************/
  386. public function wxArrayToXml($parameters = NULL){
  387. if(is_null($parameters)){
  388. $parameters = $this->parameters;
  389. }
  390. if(!is_array($parameters) || empty($parameters)){
  391. die("参数不为数组无法解析");
  392. }
  393. $xml = "<xml>";
  394. foreach ($arr as $key=>$val)
  395. {
  396. if (is_numeric($val))
  397. {
  398. $xml.="<".$key.">".$val."</".$key.">";
  399. }
  400. else
  401. $xml.="<".$key."><![CDATA[".$val."]]></".$key.">";
  402. }
  403. $xml.="</xml>";
  404. return $xml;
  405. }
  406. /*******************************************************
  407. * 微信卡券:上传LOGO - 需要改写动态功能
  408. *******************************************************/
  409. public function wxCardUpdateImg() {
  410. $wxAccessToken = $this->wxAccessToken();
  411. //$data['access_token'] = $wxAccessToken;
  412. $data['buffer'] = '@D:\\workspace\\htdocs\\yky_test\\logo.jpg';
  413. $url = "https://api.weixin.qq.com/cgi-bin/media/uploadimg?access_token=".$wxAccessToken;
  414. $result = $this->wxHttpsRequest($url,$data);
  415. $jsoninfo = json_decode($result, true);
  416. return $jsoninfo;
  417. //array(1) { ["url"]=> string(121) "http://mmbiz.qpic.cn/mmbiz/ibuYxPHqeXePNTW4ATKyias1Cf3zTKiars9PFPzF1k5icvXD7xW0kXUAxHDzkEPd9micCMCN0dcTJfW6Tnm93MiaAfRQ/0" }
  418. }
  419. /*******************************************************
  420. * 微信卡券:获取颜色
  421. *******************************************************/
  422. public function wxCardColor(){
  423. $wxAccessToken = $this->wxAccessToken();
  424. $url = "https://api.weixin.qq.com/card/getcolors?access_token=".$wxAccessToken;
  425. $result = $this->wxHttpsRequest($url);
  426. $jsoninfo = json_decode($result, true);
  427. return $jsoninfo;
  428. }
  429. /*******************************************************
  430. * 微信卡券:创建卡券
  431. *******************************************************/
  432. public function wxCardCreated($jsonData) {
  433. $wxAccessToken = $this->wxAccessToken();
  434. $url = "https://api.weixin.qq.com/card/create?access_token=" . $wxAccessToken;
  435. $result = $this->wxHttpsRequest($url,$jsonData);
  436. $jsoninfo = json_decode($result, true);
  437. return $jsoninfo;
  438. }
  439. /*******************************************************
  440. * 微信卡券:JSAPI 卡券Package - 基础参数没有附带任何值 - 再生产环境中需要根据实际情况进行修改
  441. *******************************************************/
  442. public function wxCardPackage($cardId){
  443. $timestamp = time();
  444. $api_ticket = $this->wxJsApiTicket();
  445. $cardId = $cardId;
  446. $arrays = array($api_ticket,$timestamp,$cardId);
  447. sort($arrays);
  448. $string = sha1(implode("",$arrays));
  449. $resultArray['card_id'] = $cardId;
  450. $resultArray['card_ext'] = array();
  451. $resultArray['card_ext']['openid'] = 'oOmn4s9MiwqHSNNvPn0dBtU23toA';
  452. $resultArray['card_ext']['timestamp'] = $timestamp;
  453. $resultArray['card_ext']['signature'] = $string;
  454. return $resultArray;
  455. }
  456. }

4. [代码]微信JSAPI    

  1. <?php
  2. require_once 'lib.inc.php';
  3. $wx = new WxApi();
  4. //通过网页获取openid
  5. //if(!isset($_GET['code'])){
  6. // header("location:https://open.weixin.qq.com/connect/oauth2/authorize?appid=".WxApi::appId."&redirect_uri=http://".$_SERVER['SERVER_NAME'].$_SERVER['PHP_SELF']."&response_type=code&scope=snsapi_base&state=1#wechat_redirect");
  7. //}
  8. //else{
  9. // $CODE = $_GET['code'];
  10. // $Info = $wx->wxOauthAccessToken($CODE);
  11. //print_r($Info);
  12. // $openId = $Info['openid'];
  13. //}
  14. ////////////////////////////////////////////
  15. $signPackage = $wx->wxJsapiPackage();
  16. //print_r($signPackage);
  17. $kqInfo = $wx->wxCardPackage("");
  18. $listInfo = $wx->wxCardListPackage();
  19. ?>
  20. <html>
  21. <head>
  22. <title>JSAPI接口测试</title>
  23. <meta charset="UTF-8">
  24. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  25. <script src="http://code.jquery.com/jquery-1.11.2.min.js"></script>
  26. <script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
  27. </head>
  28. <body>
  29. <div>
  30. <input type="button" id="batchAddCard" name="batchAddCard" value="添加卡券" /><br />
  31. <input type="button" id="openCard" name="openCard" value="拉起卡券库" /><br />
  32. <input type="button" id="ShareTimeLine" name="ShareTimeLine" value="分享朋友圈" /><br />
  33. <div id="showInfo">
  34. </div>
  35. </div>
  36. <script>
  37. wx.config({
  38. debug: false,
  39. appId: '<?php echo $signPackage["appId"];?>',
  40. timestamp: <?php echo $signPackage["timestamp"];?>,
  41. nonceStr: '<?php echo $signPackage["nonceStr"];?>',
  42. signature: '<?php echo $signPackage["signature"];?>',
  43. jsApiList: [
  44. // 所有要调用的 API 都要加到这个列表中
  45. 'onMenuShareTimeline',
  46. 'onMenuShareAppMessage',
  47. 'addCard',
  48. 'openCard'
  49. ]
  50. });
  51. wx.ready(function () {
  52. // 在这里调用 API
  53. wx.onMenuShareAppMessage({
  54. title: '互联网之子',
  55. desc: '在长大的过程中,我才慢慢发现,我身边的所有事,别人跟我说的所有事,那些所谓本来如此,注定如此的事,它们其实没有非得如此,事情是可以改变的。更重要的是,有些事既然错了,那就该做出改变。',
  56. link: 'http://movie.douban.com/subject/25785114/',
  57. imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
  58. trigger: function (res) {
  59. // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
  60. alert('用户点击发送给朋友');
  61. },
  62. success: function (res) {
  63. alert('已分享');
  64. },
  65. cancel: function (res) {
  66. alert('已取消');
  67. },
  68. fail: function (res) {
  69. alert(JSON.stringify(res));
  70. }
  71. });
  72. document.querySelector('#ShareTimeLine').onclick = function () {
  73. wx.onMenuShareTimeline({
  74. title: '互联网之子',
  75. link: 'http://movie.douban.com/subject/25785114/',
  76. imgUrl: 'http://demo.open.weixin.qq.com/jssdk/images/p2166127561.jpg',
  77. trigger: function (res) {
  78. // 不要尝试在trigger中使用ajax异步请求修改本次分享的内容,因为客户端分享操作是一个同步操作,这时候使用ajax的回包会还没有返回
  79. alert('用户点击分享到朋友圈');
  80. },
  81. success: function (res) {
  82. alert('已分享');
  83. },
  84. cancel: function (res) {
  85. alert('已取消');
  86. },
  87. fail: function (res) {
  88. alert(JSON.stringify(res));
  89. }
  90. });
  91. };
  92. document.querySelector('#batchAddCard').onclick = function () {
  93. wx.addCard({
  94. cardList: [
  95. {
  96. cardId: 'p7G0Cj_1HGF2nijO4sTlVTzawFhI',
  97. cardExt: '{"timestamp":"<?php echo $kqInfo['cardExt']['timestamp'];?>", "signature":"<?php echo $kqInfo['cardExt']['signature'];?>"}'
  98. }
  99. ],
  100. success: function (res) {
  101. var cardList = res.cardList; // 添加的卡券列表信息
  102. alert(cardList);
  103. },
  104. cancel: function (res) {
  105. alert('已取消');
  106. },
  107. fail: function (res) {
  108. alert(JSON.stringify(res));
  109. }
  110. });
  111. };
  112. var shareData = {
  113. title: '微信JS-SDK Demo',
  114. desc: '微信JS-SDK,帮助第三方为用户提供更优质的移动web服务',
  115. link: 'http://demo.open.weixin.qq.com/jssdk/',
  116. imgUrl: 'http://mmbiz.qpic.cn/mmbiz/icTdbqWNOwNRt8Qia4lv7k3M9J1SKqKCImxJCt7j9rHYicKDI45jRPBxdzdyREWnk0ia0N5TMnMfth7SdxtzMvVgXg/0'
  117. };
  118. wx.onMenuShareAppMessage(shareData);
  119. wx.onMenuShareTimeline(shareData);
  120. });
  121. var readyFunc = function onBridgeReady() {
  122. // 绑定关注事件
  123. document.querySelector('#openCard').addEventListener('click',
  124. function(e) {
  125. WeixinJSBridge.invoke('chooseCard', {
  126. "app_id": "<?php echo $listInfo['app_id']?>",
  127. "location_id ": '',
  128. "sign_type": "SHA1",
  129. "card_sign": "<?php echo $listInfo['card_sign']?>",
  130. "card_id": "<?php echo $listInfo['card_id']?>",
  131. "card_type": "<?php echo $listInfo['card_type']?>",
  132. "time_stamp": "<?php echo $listInfo['time_stamp']?>",
  133. "nonce_str": "<?php echo $listInfo['nonce_str']?>"
  134. },
  135. function(res) {
  136. alert(res.err_msg + res.choose_card_info);
  137. $("#showInfo").empty().append(res.err_msg + res.choose_card_info);
  138. });
  139. });
  140. }
  141. if (typeof WeixinJSBridge === "undefined") {
  142. document.addEventListener('WeixinJSBridgeReady', readyFunc, false);
  143. } else {
  144. readyFunc();
  145. }
  146. </script>
  147. </body>
  148. </html>

5. [代码]创建卡券    

  1. $kqinfo = array("card" => array());
  2. $kqinfo['card']['card_type'] = 'GENERAL_COUPON';
  3. $kqinfo['card']['general_coupon'] = array('base_info' => array(), 'default_detail' => array());
  4. $kqinfo['card']['general_coupon']['base_info']['logo_url'] = 'URL';
  5. $kqinfo['card']['general_coupon']['base_info']['code_type'] = 'CODE_TYPE_QRCODE';
  6. $kqinfo['card']['general_coupon']['base_info']['brand_name'] = '';
  7. $kqinfo['card']['general_coupon']['base_info']['title'] = '测试卡券';
  8. $kqinfo['card']['general_coupon']['base_info']['color'] = 'Color030';
  9. $kqinfo['card']['general_coupon']['base_info']['notice'] = '测试测试测试';
  10. $kqinfo['card']['general_coupon']['base_info']['description'] = '这是一张优惠券';
  11. $kqinfo['card']['general_coupon']['base_info']['date_info']['type'] = 1;
  12. $kqinfo['card']['general_coupon']['base_info']['date_info']['begin_timestamp'] = time();
  13. $kqinfo['card']['general_coupon']['base_info']['date_info']['end_timestamp'] = time() + 100 * 24 * 3600;
  14. $kqinfo['card']['general_coupon']['base_info']['sku']['quantity'] = 100000;
  15. $kqinfo['card']['general_coupon']['default_detail'] = '测试数据\n测试数据\n测试数据';
  16. //var_dump($kqinfo);
  17. //$kqinfo = json_encode($kqinfo);
  18. $kqinfo = C::enJson($kqinfo);
  19. //print_r( $kqinfo);
  20. //$resultData = $wx->wxCardCreated($kqinfo);

以上所述就是本文的全部内容,希望大家能够喜欢。

人气教程排行