首页 > 开发 > PHP > 正文

微信API接口大全

2024-05-04 23:34:17
字体:大 中 小
来源:转载
供稿:网友

本文给大家介绍的是个人总结的一些微信API接口,包括微信支付、微信红包、微信卡券、微信小店等,十分的全面,有需要的小伙伴可以参考下。

微信入口绑定,微信事件处理,微信API全部操作包含在这些文件中。

微信支付、微信红包、微信卡券、微信小店。

1. [代码]index.php

 

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

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

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

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

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表