PHP implementation of WeChat JS-SDK interface select album and photo and upload method

Source: Internet
Author: User
Tags sha1 ticket
This article mainly introduces the PHP implementation of JS-SDK Interface selection album and photo and upload methods, involving PHP interface call skills, with a certain reference value, the need for friends can refer to the next

Understanding: Upload interface is to take pictures, or select local photos, upload to the server, get to an ID, through token with this ID get to the picture, save to the server can.

Through the JS interface, call the underlying program.
The JS file needs to be introduced and configured.

<script src= "Http://res.wx.qq.com/open/js/jweixin-1.0.0.js" ></script>wx.config ({  debug:false,  appId: ' wxed7996e9ad58345d ',  timestamp:1449717454,  noncestr: ' asdfasdfasdf ',  signature: ' b74fb4ab4790172d2ab7e58f0051a1523aaa4803 ',  jsapilist: [    ' chooseimage ',    ' Uploadimage '  ]});

Where AppID is the public platform Id,timestamp is the current timestamp, Noncestr is a random string, signature is the signature.

Signature is the most important parameter. There are a number of steps that need to be taken.

First get Access_token, can live two hours, allow 2000 times per day. More than you can get.

Get Access_token Two-hour valid private function Get_access_token () {    $appid = C (' oauth_config.appid ');    $appsecret = C (' Oauth_config.appsecret ');    $url = ' https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid= '. $appid. ' &secret= '. $appsecret;    $rurl = file_get_contents ($url);    $rurl = Json_decode ($rurl, true);    if (array_key_exists (' Errcode ', $rurl)) {      return false;    } else{      $access _token = $rurl [' Access_token '];      return $access _token;    }}

Then get Jsticket

Get jsticket Two-hour valid private function Getjsticket () {//Allow only this class of calls, inherited can not be called, the public call is not    $access _token = $this->get_ Access_token ();    $url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket?access_token=". $access _token. " &type=jsapi "; Two hours effective    $rurl = file_get_contents ($url);    $rurl = Json_decode ($rurl, true);    if ($rurl [' errcode ']! = 0) {      return false;    } else{      $jsticket = $rurl [' ticket '];      return $jsticket;    }}

Then get signature, it is formed by multiple parameters stitching encryption, effective.

Get Signatureprivate function Getsignature () {    $noncestr = ';    $jsapi _ticket = $this->getjsticket ();    $timestamp = time ();    $url = ' Http://zhudianbao.diandodo.com/index.php?g=Opener&m=Merchant&a=open ';    $string 1 = ' jsapi_ticket= '. $jsapi _ticket. ' &noncestr= '. $noncestr. ' &timestamp= '. $timestamp. ' &url= '. $url;    $signature = SHA1 ($string 1);    return $signature;}

Once configured, you are ready to use it. I used two features, one to select photos, and one to upload photos.

function Chooseimage (obj) {  //select sheet  wx.chooseimage ({    count:1,//Default 9    sizeType: [' Original ', ' Compressed '],//can be specified as the original or compressed, by default both have    sourcetype: [' album ', ' Camera '],//You can specify whether the source is a photo album or a camera, the default is    success: Function (res) {      var localids = res.localids;//Returns a list of local IDs for the selected photo, Localid can display the picture $ (obj) as the src attribute of the img tag      . attr (' src ', Localids);      Upload Photo      wx.uploadimage ({        localid: ' + localids,        isshowprogresstips:1,        success:function (res) {          ServerID = Res.serverid;          $ (obj). Next (). Val (ServerID); Append the value of the upload to the successful Post});}  );

Selecting the Localids returned by the photo is interesting and can be used for uploading, and can be placed in the SRC attribute of img to show the image.

After the upload is successful, get a serverid that can download the image file uploaded to the server and save it to your server.

Get picture address 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 = './uploads/user_cert/'. $foldername. ' /'. Date (' Ymdhis '). Rand (1000,9999). JPG ';    $ch = Curl_init ($url); Initialize    $fp = fopen ($targetName, ' WB ');//Open Write    curl_setopt ($ch, Curlopt_file, $fp);//Set Output file location, value is a resource type    curl_setopt ($ch, Curlopt_header, 0);    Curl_exec ($ch);    Curl_close ($ch);    Fclose ($FP);    return $targetName;}

Prevent images with the same name, plus a rand random number, because multiple photos may be uploaded in the same second.

$targetName = './uploads/user_cert/'. $foldername. ' /'. Date (' Ymdhis '). Rand (1000,9999). JPG ';

This serverid is submitted to the server as a form, then writes it to the file, obtains the address, and saves the address to the server.

JS and jquery do not conflict, can be used together.

Attach the Jssdk class

<?phpclass jssdk {private $appId; private $appSecret; public function __construct ($appId, $appSecret) {$this->app  Id = $appId; $this->appsecret = $appSecret;  Public Function Getsignpackage () {$jsapiTicket = $this->getjsapiticket ();  Note that URLs must be dynamically acquired and cannot be hardcode. $protocol = (!empty ($_server[' https ") && $_server[' https ']!== ' off ' | | $_server[' server_port '] = = 443)?  "https://": "/http";  $url = "$protocol $_server[http_host]$_server[request_uri]";  $timestamp = time ();  $NONCESTR = $this->createnoncestr (); The order of the parameters here is sorted by the ASCII code of the key value in ascending order $string = "jsapi_ticket= $jsapiTicket &noncestr= $nonceStr &timestamp= $timestamp &  Amp;url= $url ";  $signature = SHA1 ($string); $signPackage = Array ("appId" = $this->appid, "noncestr" + $nonceStr, "timestamp" and "= $timestamp"  URL "=" and $url, "signature" and "rawstring", "* * *" and $string);  return $signPackage; } Private Function Createnoncestr ($length = +) {$chars ="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";  $str = "";  for ($i = 0; $i < $length; $i + +) {$str. = substr ($chars, Mt_rand (0, strlen ($chars)-1), 1); } return $STR; The Private Function Getjsapiticket () {///jsapi_ticket should be stored and updated globally, the following code is written to the file for example $data = Json_decode (file_get_contents ("JS  Api_ticket.json "));   if ($data->expire_time < Time ()) {$accessToken = $this->getaccesstoken ();   If the enterprise number is obtained ticket//$url = "https://qyapi.weixin.qq.com/cgi-bin/get_jsapi_ticket?access_token= $accessToken" with the following URL;   $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 should be stored and updated globally, the following code is written to the file for example $data = Json_decode (file_get_contents ("Access_  Token.json ")); if ($data->expire_time < Time ()) {//If it is an enterprise number get Access_token//$url = "with the following 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); To ensure that third-party servers and serversSecurity of the data transfer, all interfaces are invoked HTTPS, and SSL security checks must be turned on using the following 2 lines of code.  If the code fails to verify here during deployment, go to Http://curl.haxx.se/ca/cacert.pem to download a new certificate discriminant file.  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; }}

The above is the whole content of this article, I hope that everyone's study has helped.


Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.