用微信JS SDK实现分享到朋友圈和分享给朋友的功能(服务端接口开发)

版权声明:本文为博主原创文章,拒绝相同的垃圾博文。 https://blog.csdn.net/tsummerb/article/details/79181794

前端调用的接口(getInfo.php)如下,通过该接口可以获取所需的校验字段。

<?php
require_once "jssdk.php";
$url=isset($_GET['url'])? $_GET['url'] : 'no url';//动态获取前端传递的待分享页面的url
$jssdk = new JSSDK("appId",$url);
$signPackage = $jssdk->GetSignPackage();
echo json_encode($signPackage);
?>
jssdk.php如下

<?php
class JSSDK {
  private $appId;
  private $appSecret;

  public function __construct($appId, $url) {
    $this->appId = $appId;
    $this->url = $url;
  }

  public function getSignPackage() {
    $jsapiTicket = $this->getJsApiTicket();
    $cur_url=$this->url;
    $timestamp = time();
    $nonceStr = $this->createNonceStr(5);

    // 这里参数的顺序要按照 key 值 ASCII 码升序排序
    $string="jsapi_ticket=".$jsapiTicket."&noncestr=".$nonceStr."×tamp=".$timestamp."&url=".$cur_url;
    //echo $string;
    $signature = sha1($string);

    $signPackage = array(
      "appId"     => $this->appId,
      "nonceStr"  => $nonceStr,
      "timestamp" => $timestamp,
      "url"       => $cur_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() {
    $tk = file_get_contents("/var/www/keys/wx_token/appid.token");//从文件读取access_token
    $url_getjstk='https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token='.$tk.'&type=jsapi';
    $jstk = file_get_contents($url_getjstk);
    $arr_jstk=json_decode($jstk, true);
    $str_jstk=$arr_jstk["ticket"];
    return $str_jstk;
  }
}
为了方便开发,将获取access_token的程序写成了定时任务,每隔2分钟执行一次(get_token.php)

<?php
class token
{
	public function get_content()
	{
		$url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=appid&secret=secret";
		$str = file_get_contents($url); 
		return $str;
	}

	public function writet_result()
	{
		$str = $this->get_content();
		$arr = json_decode($str,true); 
		$fp=fopen("/var/www/keys/wx_token/appid.token","w");
		fputs($fp,$arr["access_token"]);
		fclose($fp);
		#$this->write_mem('token_iweicang', $str);
	}

	public function write_mem($key, $value) 
	{
		$mem = new Memcached();
		$mem->addServer('localhost', 11211);
		$mem->set($key, $value, 7200);
	}

}

$o = new token;
$o->writet_result();
?>
展开阅读全文

没有更多推荐了,返回首页