


PHP implements the WeChat JS-SDK interface method of selecting photo albums and taking pictures and uploading them
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: 'wxed7996e9ad58345d', timestamp: 1449717454, nonceStr: 'asdfasdfasdf', signature: 'b74fb4ab4790172d2ab7e58f0051a1523aaa4803', jsApiList: [ 'chooseImage', 'uploadImage' ] });
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('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 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['errcode'] != 0){ return false; }else{ $jsticket = $rurl['ticket']; return $jsticket; } }
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 = ''; $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.'×tamp='.$timestamp.'&url='.$url; $signature = sha1($string1); return $signature; }
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: ['original', 'compressed'], // 可以指定是原图还是压缩图,默认二者都有 sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机,默认二者都有 success: function(res) { var localIds = res.localIds; // 返回选定照片的本地ID列表,localId可以作为img标签的src属性显示图片 $(obj).attr('src', localIds); // 上传照片 wx.uploadImage({ localId: '' + localIds, isShowProgressTips: 1, success: function(res) { serverId = res.serverId; $(obj).next().val(serverId); // 把上传成功后获取的值附上 } }); } }); }
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 = './Uploads/User_cert/'.$foldername.'/'.date('YmdHis').rand(1000,9999).'.jpg'; $ch = curl_init($url); // 初始化 $fp = fopen($targetName, 'wb'); // 打开写入 curl_setopt($ch, CURLOPT_FILE, $fp); // 设置输出文件的位置,值是一个资源类型 curl_setopt($ch, CURLOPT_HEADER, 0); curl_exec($ch); curl_close($ch); fclose($fp); return $targetName; }
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 = './Uploads/User_cert/'.$foldername.'/'.date('YmdHis').rand(1000,9999).'.jpg';
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['HTTPS']) && $_SERVER['HTTPS'] !== 'off' || $_SERVER['SERVER_PORT'] == 443) ? "https://" : "http://"; $url = "$protocol$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]"; $timestamp = time(); $nonceStr = $this->createNonceStr(); // 这里参数的顺序要按照 key 值 ASCII 码升序排序 $string = "jsapi_ticket=$jsapiTicket&noncestr=$nonceStr×tamp=$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; } }
The above is the entire content of this article, I hope it will help everyone learn Helps.
Related recommendations:
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!

In PHP, you can use session_status() or session_id() to check whether the session has started. 1) Use the session_status() function. If PHP_SESSION_ACTIVE is returned, the session has been started. 2) Use the session_id() function, if a non-empty string is returned, the session has been started. Both methods can effectively check the session state, and choosing which method to use depends on the PHP version and personal preferences.

Sessionsarevitalinwebapplications,especiallyfore-commerceplatforms.Theymaintainuserdataacrossrequests,crucialforshoppingcarts,authentication,andpersonalization.InFlask,sessionscanbeimplementedusingsimplecodetomanageuserloginsanddatapersistence.

Managing concurrent session access in PHP can be done by the following methods: 1. Use the database to store session data, 2. Use Redis or Memcached, 3. Implement a session locking strategy. These methods help ensure data consistency and improve concurrency performance.

PHPsessionshaveseverallimitations:1)Storageconstraintscanleadtoperformanceissues;2)Securityvulnerabilitieslikesessionfixationattacksexist;3)Scalabilityischallengingduetoserver-specificstorage;4)Sessionexpirationmanagementcanbeproblematic;5)Datapersis

Load balancing affects session management, but can be resolved with session replication, session stickiness, and centralized session storage. 1. Session Replication Copy session data between servers. 2. Session stickiness directs user requests to the same server. 3. Centralized session storage uses independent servers such as Redis to store session data to ensure data sharing.

Sessionlockingisatechniqueusedtoensureauser'ssessionremainsexclusivetooneuseratatime.Itiscrucialforpreventingdatacorruptionandsecuritybreachesinmulti-userapplications.Sessionlockingisimplementedusingserver-sidelockingmechanisms,suchasReentrantLockinJ

Alternatives to PHP sessions include Cookies, Token-based Authentication, Database-based Sessions, and Redis/Memcached. 1.Cookies manage sessions by storing data on the client, which is simple but low in security. 2.Token-based Authentication uses tokens to verify users, which is highly secure but requires additional logic. 3.Database-basedSessions stores data in the database, which has good scalability but may affect performance. 4. Redis/Memcached uses distributed cache to improve performance and scalability, but requires additional matching

Sessionhijacking refers to an attacker impersonating a user by obtaining the user's sessionID. Prevention methods include: 1) encrypting communication using HTTPS; 2) verifying the source of the sessionID; 3) using a secure sessionID generation algorithm; 4) regularly updating the sessionID.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version
Useful JavaScript development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Dreamweaver CS6
Visual web development tools

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.
