Home > Backend Development > PHP Tutorial > PHP implements the WeChat JS-SDK interface method of selecting photo albums and taking pictures and uploading them

PHP implements the WeChat JS-SDK interface method of selecting photo albums and taking pictures and uploading them

墨辰丷
Release: 2023-03-28 12:04:02
Original
2045 people have browsed it

This article mainly introduces the method of implementing the WeChat JS-SDK interface in PHP to select albums, take pictures and upload them. It involves the calling skills of the PHP WeChat interface. It has certain reference value. Friends in need can refer to it

Understanding: The WeChat upload interface is to take a photo, or select a local photo, upload it to the WeChat server, get an ID, get the picture through the token and this ID, and save it to the server.

Rendering:

Call the underlying program through the WeChat js interface.
Need to introduce js files and configure them.

<script src="http://res.wx.qq.com/open/js/jweixin-1.0.0.js"></script>
wx.config({
  debug: false,
  appId: &#39;wxed7996e9ad58345d&#39;,
  timestamp: 1449717454,
  nonceStr: &#39;asdfasdfasdf&#39;,
  signature: &#39;b74fb4ab4790172d2ab7e58f0051a1523aaa4803&#39;,
  jsApiList: [
    &#39;chooseImage&#39;,
    &#39;uploadImage&#39;
  ]
});
Copy after login

where appId is the WeChat public platform id, timestamp is the current timestamp, nonceStr is a random string, and signature is the signature.

signature is the most important parameter. It takes many steps to get it.

First obtain the access_token, which can survive for two hours and is allowed to be obtained 2,000 times per day. If it exceeds, it cannot be obtained.

// 获取access_token 两小时有效
private function get_access_token(){
    $appid = C(&#39;oauth_config.appid&#39;);
    $appsecret = C(&#39;oauth_config.appsecret&#39;);
    $url = &#39;https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=&#39;.$appid.&#39;&secret=&#39;.$appsecret;
    $rurl = file_get_contents($url);
    $rurl = json_decode($rurl,true);
    if(array_key_exists(&#39;errcode&#39;,$rurl)){
      return false;
    }else{
      $access_token = $rurl[&#39;access_token&#39;];
      return $access_token;
    }
}
Copy after login

Then get the jsticket

// 获取jsticket 两小时有效
private function getjsticket(){ // 只允许本类调用,继承的都不可以调用,公开调用就更不可以了
    $access_token = $this->get_access_token();
    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=".$access_token."&type=jsapi"; // 两小时有效
    $rurl = file_get_contents($url);
    $rurl = json_decode($rurl,true);
    if($rurl[&#39;errcode&#39;] != 0){
      return false;
    }else{
      $jsticket = $rurl[&#39;ticket&#39;];
      return $jsticket;
    }
}
Copy after login

Then get the signature, which is composed of multiple It is formed by parameter splicing and encryption and is effective.

// 获取 signature
private function getsignature(){
    $noncestr = &#39;&#39;;
    $jsapi_ticket = $this->getjsticket();
    $timestamp = time();
    $url = &#39;http://zhudianbao.diandodo.com/index.php?g=Opener&m=Merchant&a=open&#39;;
    $string1 = &#39;jsapi_ticket=&#39;.$jsapi_ticket.&#39;&noncestr=&#39;.$noncestr.&#39;&timestamp=&#39;.$timestamp.&#39;&url=&#39;.$url;
    $signature = sha1($string1);
    return $signature;
}
Copy after login

After configuration, you can use it. I used two functions, one is to select photos and the other is to upload photos.

function chooseImage(obj){
  // 选择张片
  wx.chooseImage({
    count: 1, // 默认9
    sizeType: [&#39;original&#39;, &#39;compressed&#39;], // 可以指定是原图还是压缩图,默认二者都有
    sourceType: [&#39;album&#39;, &#39;camera&#39;], // 可以指定来源是相册还是相机,默认二者都有
    success: function(res) {
      var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片
      $(obj).attr(&#39;src&#39;, localIds);
      // 上传照片
      wx.uploadImage({
        localId: &#39;&#39; + localIds,
        isShowProgressTips: 1,
        success: function(res) {
          serverId = res.serverId;
          $(obj).next().val(serverId); // 把上传成功后获取的值附上
        }
      });
    }
  });
}
Copy after login

The localIds returned by selecting the photo are very interesting. They can be used for uploading and can be placed in the src attribute of img to display the image.

After the upload is successful, obtain a serverId. Through this ID, you can download the image file uploaded to the WeChat server and save it to your own server.

// 获取图片地址
private function getmedia($access_token,$media_id,$foldername){
    $url = "http://file.api.weixin.qq.com/cgi-bin/media/get?access_token=".$access_token."&media_id=".$media_id;
    if (!file_exists("./Uploads/User_cert/".$foldername)) {
      mkdir("./Uploads/User_cert/".$foldername, 0777, true);
    }
    $targetName = &#39;./Uploads/User_cert/&#39;.$foldername.&#39;/&#39;.date(&#39;YmdHis&#39;).rand(1000,9999).&#39;.jpg&#39;;
    $ch = curl_init($url); // 初始化
    $fp = fopen($targetName, &#39;wb&#39;); // 打开写入
    curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_exec($ch);
    curl_close($ch);
    fclose($fp);
    return $targetName;
}
Copy after login

To prevent the pictures from having the same name, add a rand random number, because multiple photos may be uploaded at the same second.

$targetName = &#39;./Uploads/User_cert/&#39;.$foldername.&#39;/&#39;.date(&#39;YmdHis&#39;).rand(1000,9999).&#39;.jpg&#39;;
Copy after login

This serverId is submitted to the server in the form of a form, then written to a file, obtains the address, and saves the address to the server.

WeChat’s js and jquery do not conflict and can be used together.

Attached is the awesome JSSDK class

<?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[&#39;HTTPS&#39;]) && $_SERVER[&#39;HTTPS&#39;] !== &#39;off&#39; || $_SERVER[&#39;SERVER_PORT&#39;] == 443) ? "https://" : "http://";
  $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
  $timestamp = time();
  $nonceStr = $this->createNonceStr();
  // 这里参数的顺序要按照 key 值 ASCII 码升序排序
  $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr&timestamp=$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);
  // 为保证第三方服务器与微信服务器之间数据传输的安全性,所有微信接口采用https方式调用,必须使用下面2行代码打开ssl安全校验。
  // 如果在部署过程中代码在此处验证失败,请到 http://curl.haxx.se/ca/cacert.pem 下载新的证书判别文件。
  curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
  curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true);
  curl_setopt($curl, CURLOPT_URL, $url);
  $res = curl_exec($curl);
  curl_close($curl);
  return $res;
 }
}
Copy after login

The above is the entire content of this article, I hope it will help everyone learn Helps.


Related recommendations:

PHP How to use sending emails

PHP Knowledge and use of cookies

##PHP Knowledge and use of file upload

PHP Session understanding and application of cache-related knowledge

##

The above is the detailed content of PHP implements the WeChat JS-SDK interface method of selecting photo albums and taking pictures and uploading them. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template