PHP implementation of WeChat JS-SDK interface selection and photo album and upload method, js-sdk album

Source: Internet
Author: User

PHP implementation of JS-SDK interface selection and photo album and upload method, js-sdk album

This article describes the PHP implementation of the JS-SDK interface to select the album and photo upload method. We will share this with you for your reference. The details are as follows:

Understanding: the upload interface is to take a photo, or select a local photo, upload it to the server, get an id, get the image through the token and the id, and save it to the server.

:

Call the underlying program through the js interface.
You need to introduce and configure the js file.

<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'  ]});

AppId is the public platform id, timestamp is the current timestamp, nonceStr is a random string, and signature is the signature.

Signature is the most important parameter. You need to perform many steps to obtain it.

First, get the access_token. It can survive for two hours and can be obtained 2000 times a day. If the value is exceeded, it cannot be obtained.

// Get access_token valid for two hours private function get_access_token () {$ appid = C ('oauth _ config. appid '); $ appsecret = C ('oss _ 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 valid private function getjsticket () {// only calls of this class are allowed, and none of the inherited functions can be called, public call can not be more than $ access_token = $ this-> get_access_token (); $ url = "https://api.weixin.qq.com/cgi-bin/ticket/getticket? Access_token = ". $ access_token. "& type = jsapi"; // valid for two hours $ rurl = file_get_contents ($ url); $ rurl = json_decode ($ rurl, true ); if ($ rurl ['errcode']! = 0) {return false;} else {$ jsticket = $ rurl ['ticket ']; return $ jsticket ;}}

Then obtain signature, which is encrypted by splicing multiple parameters and is effective.

// Obtain the signatureprivate function getsignature () {$ noncestr = ''; $ jsapi_ticket = $ this-> getjsticket (); $ timestamp = time (); $ url = 'HTTP: // zhudianbao.diandodo.com/index.php? G = Opener & m = Merchant & a = open'; $ string1 = 'jsapi _ ticket = '. $ jsapi_ticket. '& noncestr = '. $ noncestr. '& timestamp = '. $ timestamp. '& url = '. $ url; $ signature = sha1 ($ string1); return $ signature ;}

After configuration, you can use it. I used two functions: select a photo and upload a photo.

Function chooseImage (obj) {// select a piece of wx. chooseImage ({count: 1, // default 9 sizeType: ['original', 'compressed '], // you can specify whether the source image or the compressed image is used. Both have sourceType by default: ['alipay', 'camera '], // you can specify whether the source is an album or a camera. Both have success: function (res) {var localIds = res by default. localIds; // return the local ID list of the selected image. localId can be used as the src attribute of the img label to display the image $ (obj ). attr ('src', localIds); // upload the image wx. uploadImage ({localId: ''+ localIds, isShowProgressTips: 1, success: function (res) {serverId = res. serverId; $ (obj ). next (). val (serverId); // attach the value obtained after the upload is successful }});}});}

It is very interesting to select the localIds returned from the image. It can be used for upload and placed in the src attribute of img to display the image.

After the upload is successful, obtain a serverId. You can use this id to download the image file uploaded to the server and save it to your server.

// Get the image 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'hangzhou.rand(1000,990000.'.jpg'; $ ch = curl_init ($ url); // initialize $ fp = fopen ($ targetName, 'wb'); // open and write curl_setopt ($ ch, CURLOPT_FILE, $ fp); // sets the location of the output file. The value is a resource type, curl_setopt ($ ch, CURLOPT_HEADER, 0); curl_exec ($ ch ); curl_close ($ ch); fclose ($ fp); return $ targetName ;}

Add an rand random number to avoid the same image name, 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 in the form of a form. Then, it is written to a file, obtained the address, and saved to the server.

Js and jquery are not in conflict and can be used together.

Attach the awesome JSSDK class

<? Phpclass JSSDK {private $ appId; private $ appSecret; public function _ construct ($ appId, $ appSecret) {$ this-> appId = $ appId; $ this-> appSecret = $ appSecret;} public function getSignPackage () {$ jsapiTicket = $ this-> getJsApiTicket (); // note that the URL must be dynamically obtained 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 parameters here should be sorted by the key value ASCII code in ascending order $ string = "jsapi_ticket = $ jsapiTicket & noncestr = $ nonceStr & timestamp = $ timestamp & url = $ url "; $ signature = sha1 ($ string); $ signPackage = array ("appId" => $ this-> appId, "nonceStr" => $ nonceStr, "timestamp" => $ timestamp, "url" => $ u Rl, "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 should be stored and updated globally. The following code is written to the file for display. Example $ data = json_decode (file_get_contents ("jsapi_ticket.json"); if ($ data-> expire_time <time () {$ accessToken = $ this-> getAccessToken (); // get ticket with the following URL for the enterprise ID // $ 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 should be stored and updated globally. The following code uses Example $ data = json_decode (file_get_contents ("access_token.json"); if ($ data-> expire_time <time ()) {// get access_token with the following URL for the enterprise ID // $ url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken? Corpid = $ this-> appId & Cortana cret = $ 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 the security of data transmission between a third-party server and the server, all interfaces are called using https. The following two lines of code must be used to enable ssl security verification. // If the Code fails to be verified here during deployment, download the new certificate identification file from the http://curl.haxx.se/ca/cacert.pem. Curl_setopt ($ curl, CURLOPT_SSL_VERIFYPEER, true); curl_setopt ($ curl, expires, true); curl_setopt ($ curl, CURLOPT_URL, $ url); $ res = curl_exec ($ curl ); curl_close ($ curl); return $ res ;}}

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.