WeixinJsSDK.class.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. <?php
  2. namespace Cas\Controller;
  3. use KIF\Cache\Memcached;
  4. use KIF\Core\Controller;
  5. use KIF\Core\Request;
  6. use Cas\Module\RefreshAccessToken;
  7. use KIF\Core\Config;
  8. /**
  9. * WeixinJsSDK 用于微信 js 调用 
  10. * 吐出相应数据
  11. * 可查看:http://mp.weixin.qq.com/wiki/7/aaa137b55fb2e0456bf8dd9148dd613f.html
  12. *
  13. * @author lihuanchun
  14. *
  15. */
  16. class WeixinJsSDK extends Controller {
  17. private $objMemache;
  18. public function __construct() {
  19. $this->objMemache = new Memcached ();
  20. }
  21. /**
  22. * ajax 返回微信所需js配置信息
  23. * http://cas.lishuy.com/?c=WeixinJsSDK&a=AjaxConfigData
  24. */
  25. public function doAjaxConfigData() {
  26. $thisPageUrl = Request::g ( 'thisPageUrl' );
  27. $returnData = $this->getSignPackage ( $thisPageUrl );
  28. $this->ajax_success_exit ( $returnData );
  29. }
  30. /**
  31. * getSignPackage
  32. */
  33. private function getSignPackage($url = null) {
  34. $wechat_cfg = Config::getInstance ()->get ( 'wechat_cfg' );
  35. $appid = $wechat_cfg ['appId'];
  36. $jsapiTicket = $this->getJsApiTicket ();
  37. if ($url == null) {
  38. $url = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  39. } else {
  40. $url = htmlspecialchars_decode ( $url );
  41. }
  42. $timestamp = time ();
  43. $nonceStr = $this->createNonceStr ();
  44. $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$timestamp&url=$url";
  45. $signature = sha1 ( $string );
  46. $signPackage = array (
  47. "appId" => $appid,
  48. "nonceStr" => $nonceStr,
  49. "timestamp" => $timestamp,
  50. "url" => $url,
  51. "signature" => $signature,
  52. "rawString" => $string
  53. );
  54. return $signPackage;
  55. }
  56. /**
  57. * createNonceStr
  58. */
  59. private function createNonceStr($length = 16) {
  60. $chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
  61. $str = "";
  62. for($i = 0; $i < $length; $i ++) {
  63. $str .= substr ( $chars, mt_rand ( 0, strlen ( $chars ) - 1 ), 1 );
  64. }
  65. return $str;
  66. }
  67. /**
  68. * getJsApiTicket
  69. */
  70. private function getJsApiTicket() {
  71. $ticket = $this->objMemache->get ( RefreshAccessToken::JSAPI_TICKET_KEY );
  72. return $ticket;
  73. }
  74. /*
  75. * (non-PHPdoc)
  76. * @see \KIF\Core\Controller::run()
  77. */
  78. public function run() {
  79. $action = $this->action;
  80. $this->$action ();
  81. }
  82. }